implement grpc api

This commit is contained in:
Maxim Merzhanov authored and Maxim committed 2019-10-25 12:18:34 +03:00
1 parent c31abb84c9
commit 9e503ab31f
45 files changed
+2351 -232

No files matched your search

+4
View File
@@ -1,3 +1,7 @@
### v2.0.0
*
### v1.1.0
* update libs
* default config handling
Generated
+9 -15
View File
@@ -164,11 +164,11 @@
[[projects]]
branch = "master"
digest = "1:793af7eb674c40d9bb472c26e2c1a2eb20407f189dd995f72f58c23bfaea18bc"
digest = "1:284a10479bed36f43fbf5809858f2e969811997eab7368e5b5fdca4a4a30fb32"
name = "github.com/hashicorp/raft"
packages = ["."]
pruneopts = "UT"
revision = "7d1d8f1e35633442c29f894aba099ac90cd04f2b"
revision = "06fcbeea879f4476af60425fc330169bcde4c85e"
[[projects]]
branch = "master"
@@ -200,8 +200,7 @@
revision = "ac5582987a2f25e8743e0ebb7259312adda05c23"
[[projects]]
branch = "master"
digest = "1:280d620c33aea271545c0b4456e1a9347a45b03aca09d2bb8923cc524864a325"
digest = "1:12bcebed6dfc45cedc650f6dce60fe6ce6d27de88d9bfa8893a5b144c010d317"
name = "github.com/integration-system/golang-socketio"
packages = [
".",
@@ -209,11 +208,12 @@
"transport",
]
pruneopts = "UT"
revision = "24b88aed7c77403c0b9b45de1f42ddc3c4fc0fb2"
revision = "7513a9b590e428674e3c22ea82f46b28890cc17a"
version = "v1.0.0"
[[projects]]
branch = "master"
digest = "1:50757af2a33b01c2ad349659740367c41739eb03e8c4010e566e0b5bd2031720"
digest = "1:70304818e3d84deb317b59a0d02fc95c4f4264b8721efa816e97f749d8cf90a1"
name = "github.com/integration-system/isp-lib"
packages = [
"backend",
@@ -229,7 +229,7 @@
"utils",
]
pruneopts = "UT"
revision = "ef90e94729c8d6fbb34b3ebf033b8d6ffecadb37"
revision = "5060d1348219abd8fad3628668b229779a5314c7"
[[projects]]
branch = "master"
@@ -242,14 +242,6 @@
pruneopts = "UT"
revision = "a22bf2e0b56a9ef47db4a98756e39f700a99b688"
[[projects]]
branch = "master"
digest = "1:9eb3b0c24935048c4097eedb3344f2f209e35bd12fa3884e54b83a1a55c22224"
name = "github.com/integration-system/jsonschema"
packages = ["."]
pruneopts = "UT"
revision = "26ce276eb6ea02881e72f7756f48796bc1f9552b"
[[projects]]
digest = "1:01ed62f8f4f574d8aff1d88caee113700a2b44c42351943fa73cc1808f736a50"
name = "github.com/jinzhu/inflection"
@@ -663,6 +655,8 @@
"github.com/sirupsen/logrus",
"github.com/spf13/cast",
"github.com/thecodeteam/goodbye",
"google.golang.org/grpc/codes",
"google.golang.org/grpc/status",
]
solver-name = "gps-cdcl"
solver-version = 1
+4
View File
@@ -36,6 +36,10 @@
name = "github.com/valyala/fasthttp"
branch = "master"
[[override]]
name = "github.com/integration-system/isp-lib"
branch = "master"
[[override]]
name = "github.com/googollee/go-socket.io"
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
-4
View File
@@ -7,7 +7,6 @@ import (
jsoniter "github.com/json-iterator/go"
"isp-config-service/codes"
"isp-config-service/raft"
"strconv"
"sync"
"time"
)
@@ -119,9 +118,6 @@ func (client *Client) listenLeader() {
}
go func(declaration structure.BackendDeclaration) {
response, err := leaderClient.SendDeclaration(declaration, defaultApplyTimeout)
if res, err := strconv.Unquote(response); err == nil {
response = res
}
if err != nil {
log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader err: %v", err)
} else if response != Ok {
+42 -2
View File
@@ -7,6 +7,7 @@ import (
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/entity"
"time"
)
const (
@@ -20,8 +21,19 @@ const (
_ = iota
UpdateBackendDeclarationCommand
DeleteBackendDeclarationCommand
UpdateConfigSchemaCommand
ModuleConnectedCommand
ModuleDisconnectedCommand
DeleteModulesCommand
ActivateConfigCommand
DeleteConfigsCommand
UpsertConfigCommand
DeleteCommonConfigsCommand
UpsertCommonConfigCommand
)
func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
@@ -32,14 +44,42 @@ func PrepareDeleteBackendDeclarationCommand(backend structure.BackendDeclaration
return prepareCommand(DeleteBackendDeclarationCommand, backend)
}
func PrepareModuleConnectedCommand(moduleName string) []byte {
return prepareCommand(ModuleConnectedCommand, ModuleConnected{ModuleName: moduleName})
func PrepareModuleConnectedCommand(module entity.Module) []byte {
return prepareCommand(ModuleConnectedCommand, module)
}
func PrepareModuleDisconnectedCommand(module entity.Module) []byte {
return prepareCommand(ModuleDisconnectedCommand, module)
}
func PrepareDeleteModulesCommand(ids []string) []byte {
return prepareCommand(DeleteModulesCommand, DeleteModules{Ids: ids})
}
func PrepareActivateConfigCommand(configId string, date time.Time) []byte {
return prepareCommand(ActivateConfigCommand, ActivateConfig{ConfigId: configId, Date: date})
}
func PrepareDeleteConfigsCommand(ids []string) []byte {
return prepareCommand(DeleteConfigsCommand, DeleteModules{Ids: ids})
}
func PrepareUpsertConfigCommand(config UpsertConfig) []byte {
return prepareCommand(UpsertConfigCommand, config)
}
func PrepareUpdateConfigSchemaCommand(schema entity.ConfigSchema) []byte {
return prepareCommand(UpdateConfigSchemaCommand, schema)
}
func PrepareDeleteCommonConfigsCommand(ids []string) []byte {
return prepareCommand(DeleteCommonConfigsCommand, DeleteModules{Ids: ids})
}
func PrepareUpsertCommonConfigCommand(config UpsertCommonConfig) []byte {
return prepareCommand(UpsertCommonConfigCommand, config)
}
func prepareCommand(command uint64, payload interface{}) []byte {
cmd := make([]byte, 8)
binary.BigEndian.PutUint64(cmd, command)
+49 -5
View File
@@ -1,10 +1,12 @@
package cluster
import json2 "encoding/json"
type ModuleConnected struct {
ModuleName string
}
import (
json2 "encoding/json"
"fmt"
"google.golang.org/grpc/codes"
"isp-config-service/entity"
"time"
)
type ApplyLogResponse struct {
ApplyError string
@@ -14,3 +16,45 @@ type ApplyLogResponse struct {
func (a ApplyLogResponse) Error() string {
return a.ApplyError
}
type DeleteModules struct {
Ids []string
}
type ActivateConfig struct {
ConfigId string
Date time.Time
}
type UpsertConfig struct {
Config entity.Config
Create bool
}
type DeleteConfigs struct {
Ids []string
}
type UpsertCommonConfig struct {
Config entity.CommonConfig
Create bool
}
type ResponseWithError struct {
Response interface{}
Error string
ErrorCode codes.Code
}
func NewResponseErrorf(code codes.Code, format string, args ...interface{}) ResponseWithError {
return ResponseWithError{
Error: fmt.Sprintf(format, args...),
ErrorCode: code,
}
}
func NewResponse(value interface{}) ResponseWithError {
return ResponseWithError{
Response: value,
}
}
+14 -5
View File
@@ -20,7 +20,12 @@ type SocketLeaderClient struct {
}
func (c *SocketLeaderClient) Send(data []byte, timeout time.Duration) (string, error) {
return c.c.Ack(ApplyCommandEvent, data, timeout)
response, err := c.c.Ack(ApplyCommandEvent, string(data), timeout)
// REMOVE after replacing socket.io
if res, err := strconv.Unquote(response); err == nil {
response = res
}
return response, err
}
func (c *SocketLeaderClient) SendDeclaration(backend structure.BackendDeclaration, timeout time.Duration) (string, error) {
@@ -29,7 +34,12 @@ func (c *SocketLeaderClient) SendDeclaration(backend structure.BackendDeclaratio
return "", err
}
if c.c.IsAlive() {
return c.c.Ack(utils.ModuleReady, data, timeout)
response, err := c.c.Ack(utils.ModuleReady, string(data), timeout)
// REMOVE after replacing socket.io
if res, err := strconv.Unquote(response); err == nil {
response = res
}
return response, err
}
return "", errors.New("SendDeclaration connection is not alive")
}
@@ -60,7 +70,7 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *
leaderDisconnectionCallback()
})
if err != nil {
panic(err) ////must never occurred, and will removed in future
panic(err) // must never occurred, and will removed in future
}
return &SocketLeaderClient{
@@ -71,7 +81,7 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *
func getSocketIoUrl(address string) string {
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) //must never occurred
panic(err) // must never occurred
}
cfg := config.Get().(*conf.Configuration)
@@ -96,5 +106,4 @@ func getSocketIoUrl(address string) string {
// TODO вынести ключи в константы в isp-lib и выпилить instance_uuid
"instance_uuid": "9d89354b-c728-4b48-b002-a7d3b229f151",
})
}
+21 -23
View File
@@ -1,38 +1,36 @@
package codes
// TODO numbers
const (
// Common
StartHttpServerError = 0
ShutdownHttpServerError = 0
ShutdownHttpServerInfo = 0
StartHttpServerError = 1001
ShutdownHttpServerError = 1002
ShutdownHttpServerInfo = 1003
SocketIoError = 0
SocketIoEmitError = 0
SocketIoError = 1004
SocketIoEmitError = 1005
DatabaseOperationError = 0
DatabaseOperationError = 1006
// Raft
InitRaftError = 0
RestoreFromRepositoryError = 0
RaftLoggerCode = 0
BootstrapClusterError = 0
RaftShutdownError = 0
RaftShutdownInfo = 0
InitRaftError = 1007
RestoreFromRepositoryError = 1008
RaftLoggerCode = 1009
BootstrapClusterError = 1010
RaftShutdownError = 1011
RaftShutdownInfo = 1012
// Raft Log
ApplyLogCommandError = 0
PrepareLogCommandError = 0
SyncApplyError = 0
ApplyLogCommandError = 1013
PrepareLogCommandError = 1014
SyncApplyError = 1015
// Raft Cluster
SendDeclarationToLeaderError = 0
LeaderClientConnectionError = 0
LeaderClientDisconnected = 0
SendDeclarationToLeaderError = 1016
LeaderClientConnectionError = 1017
LeaderClientDisconnected = 1018
// Services
DiscoveryServiceSendModulesError = 0
RoutesServiceSendRoutesError = 0
DeleteBackendDeclarationError = 0
DiscoveryServiceSendModulesError = 1019
RoutesServiceSendRoutesError = 1020
ConfigServiceBroadcastConfigError = 1021
)
+103
View File
@@ -0,0 +1,103 @@
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/store"
"isp-config-service/store/state"
)
var CommonConfig *commonConfig
type commonConfig struct {
rstore *store.Store
}
// GetConfigs godoc
// @Summary Метод получения объектов конфигурации по идентификаторам
// @Description Возвращает массив конфигураций по запрошенным идентификаторам (все, если массив пустой)
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Success 200 {array} entity.CommonConfig
// @Router /common_config/get_configs [POST]
func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
var response []entity.CommonConfig
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
if len(identities) > 0 {
response = state.CommonConfigs().GetByIds(identities)
} else {
response = state.CommonConfigs().GetAll()
}
})
return response
}
// CreateUpdateConfig godoc
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body entity.Config true "объект для сохранения"
// @Success 200 {object} entity.Config
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /common_config/create_update_config [POST]
func (c *commonConfig) CreateUpdateConfig(config entity.CommonConfig) (*entity.CommonConfig, error) {
var response entity.CommonConfig
now := state.GenerateDate()
config.CreatedAt = now
config.UpdatedAt = now
upsertConfig := cluster.UpsertCommonConfig{
Config: config,
}
if config.Id == "" {
upsertConfig.Config.Id = state.GenerateId()
upsertConfig.Create = true
}
command := cluster.PrepareUpsertCommonConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, "UpsertCommonConfigCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
// DeleteConfigs godoc
// @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если конфигурации где-то используются либо не указан объект identities"
// @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)
err := PerformSyncApplyWithError(command, "DeleteCommonConfigsCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
func NewCommonConfig(rstore *store.Store) *commonConfig {
return &commonConfig{
rstore: rstore,
}
}
+126
View File
@@ -0,0 +1,126 @@
package controller
import (
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/store"
"isp-config-service/store/state"
)
var Config *config
type config struct {
rstore *store.Store
}
// GetActiveConfigByModuleName godoc
// @Summary Метод получения объекта конфигурации по названию модуля
// @Description Возвращает активную конфиграцию по названию модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest 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) {
var response *entity.Config
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = state.Configs().GetActiveByModuleId(request.ModuleId)
})
if response == nil {
return nil, status.Error(codes.NotFound, utils.ValidationError)
}
return response, nil
}
// CreateUpdateConfig godoc
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body entity.Config true "объект для сохранения"
// @Success 200 {object} entity.Config
// @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
now := state.GenerateDate()
config.CreatedAt = now
config.UpdatedAt = now
upsertConfig := cluster.UpsertConfig{
Config: config,
}
if config.Id == "" {
upsertConfig.Config.Id = state.GenerateId()
upsertConfig.Create = true
}
command := cluster.PrepareUpsertConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, "UpsertConfigCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
// MarkConfigAsActive godoc
// @Summary Метод активации конфигурации для модуля
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
// @Success 200 {object} entity.Config "активированная конфигурация"
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/mark_config_as_active [POST]
func (c *config) MarkConfigAsActive(identity domain.ConfigIdRequest) (*entity.Config, error) {
var response entity.Config
command := cluster.PrepareActivateConfigCommand(identity.Id, state.GenerateDate())
err := PerformSyncApplyWithError(command, "ActivateConfigCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
// DeleteConfigs godoc
// @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
// @Failure 500 {object} structure.GrpcError
// @Router /config/delete_config [POST]
func (c *config) 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.PrepareDeleteConfigsCommand(identities)
err := PerformSyncApply(command, "DeleteConfigsCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
func NewConfig(rstore *store.Store) *config {
return &config{
rstore: rstore,
}
}
+66
View File
@@ -0,0 +1,66 @@
package controller
import (
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/cluster"
codes2 "isp-config-service/codes"
"isp-config-service/holder"
)
var json = jsoniter.ConfigFastest
func unknownError() error {
return status.Error(codes.Unknown, utils.ServiceError)
}
func PerformSyncApply(command []byte, commandName string, responsePtr interface{}) error {
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
log.Warnf(codes2.SyncApplyError, "apply %s: %v", commandName, err)
return unknownError()
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes2.SyncApplyError, "apply command")
return unknownError()
}
err = json.Unmarshal(applyLogResponse.Result, responsePtr)
if err != nil {
return unknownError()
}
return nil
}
func PerformSyncApplyWithError(command []byte, commandName string, responsePtr interface{}) error {
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
log.Warnf(codes2.SyncApplyError, "apply %s: %v", commandName, err)
return unknownError()
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes2.SyncApplyError, "apply command")
return unknownError()
}
clusterResp := cluster.ResponseWithError{
Response: responsePtr,
}
err = json.Unmarshal(applyLogResponse.Result, &clusterResp)
if err != nil {
return unknownError()
}
if clusterResp.Error != "" {
return status.Error(clusterResp.ErrorCode, clusterResp.Error)
}
return nil
}
+68
View File
@@ -0,0 +1,68 @@
package controller
import (
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
)
var Module *module
type module struct {
rstore *store.Store
}
// GetModulesAggregatedInfo godoc
// @Summary Метод получения полной информации о состоянии модуля
// @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
// @Tags Модули
// @Accept json
// @Produce json
// @Success 200 {array} domain.ModuleInfo
// @Failure 500 {object} structure.GrpcError
// @Router /module/get_modules_info [POST]
func (c *module) GetModulesAggregatedInfo() ([]domain.ModuleInfo, error) {
var response []domain.ModuleInfo
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = service.ModuleRegistryService.GetAggregatedModuleInfo(state)
})
return response, nil
}
// DeleteModules godoc
// @Summary Метод удаления объектов модулей по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов модулей"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} structure.GrpcError
// @Router /module/delete_module [POST]
func (*module) DeleteModules(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 deleteResponse domain.DeleteResponse
command := cluster.PrepareDeleteModulesCommand(identities)
err := PerformSyncApply(command, "DeleteCommonConfigsCommand", &deleteResponse)
if err != nil {
return nil, err
}
return &deleteResponse, err
}
func NewModule(rstore *store.Store) *module {
return &module{
rstore: rstore,
}
}
+37
View File
@@ -0,0 +1,37 @@
package controller
import (
"github.com/integration-system/isp-lib/structure"
"isp-config-service/store"
"isp-config-service/store/state"
)
var (
Routes *routes
)
type routes struct {
rstore *store.Store
}
// GetRoutes godoc
// @Summary Метод получения маршрутов
// @Description Возвращает все доступные модули
// @Tags Роуты
// @Accept json
// @Produce json
// @Success 200 {array} structure.BackendDeclaration
// @Router /routing/get_routes [POST]
func (c *routes) GetRoutes() ([]structure.BackendDeclaration, error) {
var response structure.RoutingConfig
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = state.Mesh().GetRoutes()
})
return response, nil
}
func NewRoutes(rstore *store.Store) *routes {
return &routes{
rstore: rstore,
}
}
+44
View File
@@ -0,0 +1,44 @@
package controller
import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/store"
"isp-config-service/store/state"
)
var Schema *schema
type schema struct {
rstore *store.Store
}
// GetByModuleId godoc
// @Summary Метод получения схемы конфигурации модуля
// @Description Возвращает текущую json схему конфигурации модуля
// @Tags Схема
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
// @Success 200 {object} entity.ConfigSchema
// @Failure 404 {object} structure.GrpcError "если схема для модуля не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /schema/get_by_module_id [POST]
func (c *schema) GetByModuleId(request domain.GetByModuleIdRequest) (*entity.ConfigSchema, error) {
var result []entity.ConfigSchema
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = state.Schemas().GetByModuleIds([]string{request.ModuleId})
})
if len(result) == 0 {
return nil, status.Errorf(codes.NotFound, "schema with moduleId %d not found", request.ModuleId)
}
return &result[0], nil
}
func NewSchema(rstore *store.Store) *schema {
return &schema{
rstore: rstore,
}
}
+870
View File
@@ -0,0 +1,870 @@
basePath: /api/config
definitions:
domain.ConfigIdRequest:
properties:
id:
type: string
required:
- id
type: object
domain.Connection:
properties:
address:
$ref: '#/definitions/structure.AddressConfiguration'
type: object
endpoints:
items:
$ref: '#/definitions/structure.EndpointConfig'
type: array
establishedAt:
type: string
libVersion:
type: string
version:
type: string
type: object
domain.DeleteResponse:
properties:
deleted:
type: integer
type: object
domain.GetByModuleIdRequest:
properties:
moduleId:
type: string
required:
- moduleId
type: object
domain.ModuleInfo:
properties:
active:
type: boolean
configSchema:
$ref: '#/definitions/schema.Schema'
type: object
configs:
items:
$ref: '#/definitions/entity.Config'
type: array
createdAt:
type: string
id:
type: string
lastConnectedAt:
type: string
lastDisconnectedAt:
type: string
name:
type: string
status:
items:
$ref: '#/definitions/domain.Connection'
type: array
type: object
entity.CommonConfig:
properties:
createdAt:
type: string
data:
$ref: '#/definitions/entity.ConfigData'
type: object
description:
type: string
id:
type: string
name:
type: string
updatedAt:
type: string
required:
- id
- name
type: object
entity.Config:
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
version:
type: integer
required:
- id
- moduleId
- name
type: object
entity.ConfigData:
additionalProperties:
type: object
type: object
entity.ConfigSchema:
properties:
createdAt:
type: string
id:
type: string
moduleId:
type: string
schema:
$ref: '#/definitions/schema.Schema'
type: object
updatedAt:
type: string
version:
type: string
required:
- id
type: object
jsonschema.Definitions:
additionalProperties: {}
type: object
jsonschema.Schema:
properties:
$ref:
description: section 7
type: string
$schema:
description: RFC draft-wright-json-schema-00
type: string
additionalItems:
description: section 5.9
type: integer
additionalProperties:
description: section 5.18
type: string
allOf:
description: section 5.22
items:
$ref: '#/definitions/jsonschema.Type'
type: array
anyOf:
description: section 5.23
items:
$ref: '#/definitions/jsonschema.Type'
type: array
binaryEncoding:
description: section 4.3
type: string
default:
description: section 6.2
type: object
definitions:
$ref: '#/definitions/jsonschema.Definitions'
type: object
dependencies:
description: section 5.19
type: object
description:
description: section 6.1
type: string
enum:
description: section 5.20
items:
type: object
type: array
examples:
description: section 7.4
items:
type: object
type: array
exclusiveMaximum:
description: section 5.3
type: boolean
exclusiveMinimum:
description: section 5.5
type: boolean
format:
description: section 7
type: string
items:
description: section 5.9
type: integer
maxItems:
description: section 5.10
type: integer
maxLength:
description: section 5.6
type: integer
maxProperties:
description: section 5.13
type: integer
maximum:
description: section 5.2
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
minItems:
description: section 5.11
type: integer
minLength:
description: section 5.7
type: integer
minProperties:
description: section 5.14
type: integer
minimum:
description: section 5.4
type: integer
multipleOf:
description: RFC draft-wright-json-schema-validation-00, section 5
type: integer
not:
description: section 5.25
type: integer
oneOf:
description: section 5.24
items:
$ref: '#/definitions/jsonschema.Type'
type: array
pattern:
description: section 5.8
type: string
patternProperties:
description: section 5.17
type: object
properties:
description: section 5.16
type: object
required:
description: section 5.15
items:
type: string
type: array
title:
description: RFC draft-wright-json-schema-validation-00, section 6, 7
type: string
type:
description: section 5.21
type: string
uniqueItems:
description: section 5.12
type: boolean
type: object
jsonschema.Type:
properties:
$ref:
description: section 7
type: string
$schema:
description: RFC draft-wright-json-schema-00
type: string
additionalItems:
description: section 5.9
type: integer
additionalProperties:
description: section 5.18
type: string
allOf:
description: section 5.22
items:
$ref: '#/definitions/jsonschema.Type'
type: array
anyOf:
description: section 5.23
items:
$ref: '#/definitions/jsonschema.Type'
type: array
binaryEncoding:
description: section 4.3
type: string
default:
description: section 6.2
type: object
definitions:
$ref: '#/definitions/jsonschema.Definitions'
description: section 5.26
type: object
dependencies:
description: section 5.19
type: object
description:
description: section 6.1
type: string
enum:
description: section 5.20
items:
type: object
type: array
examples:
description: section 7.4
items:
type: object
type: array
exclusiveMaximum:
description: section 5.3
type: boolean
exclusiveMinimum:
description: section 5.5
type: boolean
format:
description: section 7
type: string
items:
description: section 5.9
type: integer
maxItems:
description: section 5.10
type: integer
maxLength:
description: section 5.6
type: integer
maxProperties:
description: section 5.13
type: integer
maximum:
description: section 5.2
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
minItems:
description: section 5.11
type: integer
minLength:
description: section 5.7
type: integer
minProperties:
description: section 5.14
type: integer
minimum:
description: section 5.4
type: integer
multipleOf:
description: RFC draft-wright-json-schema-validation-00, section 5
type: integer
not:
description: section 5.25
type: integer
oneOf:
description: section 5.24
items:
$ref: '#/definitions/jsonschema.Type'
type: array
pattern:
description: section 5.8
type: string
patternProperties:
description: section 5.17
type: object
properties:
description: section 5.16
type: object
required:
description: section 5.15
items:
type: string
type: array
title:
description: RFC draft-wright-json-schema-validation-00, section 6, 7
type: string
type:
description: section 5.21
type: string
uniqueItems:
description: section 5.12
type: boolean
type: object
schema.Schema:
properties:
$ref:
description: section 7
type: string
$schema:
description: RFC draft-wright-json-schema-00
type: string
additionalItems:
description: section 5.9
type: integer
additionalProperties:
description: section 5.18
type: string
allOf:
description: section 5.22
items:
$ref: '#/definitions/jsonschema.Type'
type: array
anyOf:
description: section 5.23
items:
$ref: '#/definitions/jsonschema.Type'
type: array
binaryEncoding:
description: section 4.3
type: string
default:
description: section 6.2
type: object
definitions:
$ref: '#/definitions/jsonschema.Definitions'
type: object
dependencies:
description: section 5.19
type: object
description:
description: section 6.1
type: string
enum:
description: section 5.20
items:
type: object
type: array
examples:
description: section 7.4
items:
type: object
type: array
exclusiveMaximum:
description: section 5.3
type: boolean
exclusiveMinimum:
description: section 5.5
type: boolean
format:
description: section 7
type: string
items:
description: section 5.9
type: integer
maxItems:
description: section 5.10
type: integer
maxLength:
description: section 5.6
type: integer
maxProperties:
description: section 5.13
type: integer
maximum:
description: section 5.2
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
minItems:
description: section 5.11
type: integer
minLength:
description: section 5.7
type: integer
minProperties:
description: section 5.14
type: integer
minimum:
description: section 5.4
type: integer
multipleOf:
description: RFC draft-wright-json-schema-validation-00, section 5
type: integer
not:
description: section 5.25
type: integer
oneOf:
description: section 5.24
items:
$ref: '#/definitions/jsonschema.Type'
type: array
pattern:
description: section 5.8
type: string
patternProperties:
description: section 5.17
type: object
properties:
description: section 5.16
type: object
required:
description: section 5.15
items:
type: string
type: array
title:
description: RFC draft-wright-json-schema-validation-00, section 6, 7
type: string
type:
description: section 5.21
type: string
uniqueItems:
description: section 5.12
type: boolean
type: object
structure.AddressConfiguration:
properties:
ip:
type: string
port:
type: string
type: object
structure.BackendDeclaration:
properties:
address:
$ref: '#/definitions/structure.AddressConfiguration'
type: object
endpoints:
items:
$ref: '#/definitions/structure.EndpointConfig'
type: array
libVersion:
type: string
moduleName:
type: string
version:
type: string
type: object
structure.EndpointConfig:
properties:
ignoreOnRouter:
type: boolean
inner:
type: boolean
path:
type: string
required:
- path
type: object
structure.GrpcError:
properties:
details:
items:
type: object
type: array
errorCode:
type: string
errorMessage:
type: string
type: object
host: localhost:9003
info:
contact: {}
description: Сервис управления конфигурацией модулей ISP кластера
license:
name: GNU GPL v3.0
title: ISP configuration service
version: 2.0.0
paths:
/common_config/create_update_config:
post:
consumes:
- application/json
description: Если конфиг с таким id существует, то обновляет данные, если нет,
то добавляет данные в базу
parameters:
- description: объект для сохранения
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.Config'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Config'
"404":
description: если конфигурация не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод обновления конфигурации
tags:
- Общие конфигурации
/common_config/delete_config:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
parameters:
- description: массив идентификаторов конфигураций
in: body
name: body
required: true
schema:
items:
type: string
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"400":
description: если конфигурации где-то используются либо не указан объект
identities
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод удаления объектов конфигурации по идентификаторам
tags:
- Общие конфигурации
/common_config/get_configs:
post:
consumes:
- application/json
description: Возвращает массив конфигураций по запрошенным идентификаторам (все,
если массив пустой)
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/entity.CommonConfig'
type: array
summary: Метод получения объектов конфигурации по идентификаторам
tags:
- Общие конфигурации
/config/create_update_config:
post:
consumes:
- application/json
description: Если конфиг с таким id существует, то обновляет данные, если нет,
то добавляет данные в базу
parameters:
- description: объект для сохранения
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.Config'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Config'
"404":
description: если конфигурация не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод обновления конфигурации
tags:
- Конфигурация
/config/delete_config:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
parameters:
- description: массив идентификаторов конфигураций
in: body
name: body
required: true
schema:
items:
type: string
type: array
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:
- application/json
description: Возвращает активную конфиграцию по названию модуля
parameters:
- description: название модуля
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Config'
"404":
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: Активирует указанную конфигурацию и деактивирует остальные, возвращает
активированную конфигурацию
parameters:
- description: id конфигурации для изменения
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: активированная конфигурация
schema:
$ref: '#/definitions/entity.Config'
"404":
description: если конфигурация не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод активации конфигурации для модуля
tags:
- Конфигурация
/module/delete_module:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
parameters:
- description: массив идентификаторов модулей
in: body
name: body
required: true
schema:
items:
type: string
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод удаления объектов модулей по идентификаторам
tags:
- Модули
/module/get_modules_info:
post:
consumes:
- application/json
description: Возвращает полное состояние всех модулей в кластере (конфигурация,
схема конфигурации, подключенные экземпляры)
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/domain.ModuleInfo'
type: array
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод получения полной информации о состоянии модуля
tags:
- Модули
/routing/get_routes:
post:
consumes:
- application/json
description: Возвращает все доступные модули
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/structure.BackendDeclaration'
type: array
summary: Метод получения маршрутов
tags:
- Роуты
/schema/get_by_module_id:
post:
consumes:
- application/json
description: Возвращает текущую json схему конфигурации модуля
parameters:
- description: идентификатор модуля
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.ConfigSchema'
"404":
description: если схема для модуля не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод схемы конфигурации модуля
tags:
- Схема
swagger: "2.0"
+9
View File
@@ -0,0 +1,9 @@
package domain
type ConfigIdRequest struct {
Id string `json:"id" valid:"required~Required"`
}
type GetByModuleIdRequest struct {
ModuleId string `valid:"required~Required"`
}
+32
View File
@@ -0,0 +1,32 @@
package domain
import (
"github.com/integration-system/isp-lib/config/schema"
"github.com/integration-system/isp-lib/structure"
"isp-config-service/entity"
"time"
)
type DeleteResponse struct {
Deleted int
}
type ModuleInfo struct {
Id string
Name string
Active bool
CreatedAt time.Time
LastConnectedAt time.Time
LastDisconnectedAt time.Time
Configs []entity.Config `json:",omitempty"`
ConfigSchema *schema.Schema `json:",omitempty"`
Status []Connection `json:",omitempty"`
}
type Connection struct {
LibVersion string
Version string
Address structure.AddressConfiguration
Endpoints []structure.EndpointConfig `json:",omitempty"`
EstablishedAt time.Time
}
-1
View File
@@ -26,7 +26,6 @@ type CommonConfig struct {
Id string `json:"id" valid:"required~Required"`
Name string `json:"name" valid:"required~Required"`
Description string `json:"description"`
Version int32 `json:"version" sql:",null"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
Data ConfigData `json:"data" sql:",notnull"`
+48 -2
View File
@@ -1,5 +1,51 @@
package helper
func GetAllHandlers() []interface{} {
return nil
import (
"github.com/integration-system/isp-lib/structure"
"isp-config-service/controller"
"isp-config-service/domain"
"isp-config-service/entity"
)
type Handlers struct {
// ===== MODULE =====
DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
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"`
// ===== 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"`
// ===== ROUTING =====
GetRoutes func() ([]structure.BackendDeclaration, error) `method:"get_routes" group:"routing" inner:"true"`
// ===== SCHEMA =====
GetSchemaByModuleId func(domain.GetByModuleIdRequest) (*entity.ConfigSchema, error) `method:"get_by_module_id" group:"schema" inner:"true"`
}
func GetHandlers() *Handlers {
return &Handlers{
DeleteModules: controller.Module.DeleteModules,
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
MarkConfigAsActive: controller.Config.MarkConfigAsActive,
DeleteConfig: controller.Config.DeleteConfigs,
GetCommonConfigs: controller.CommonConfig.GetConfigs,
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
DeleteCommonConfig: controller.CommonConfig.DeleteConfigs,
GetRoutes: controller.Routes.GetRoutes,
GetSchemaByModuleId: controller.Schema.GetByModuleId,
}
}
+25 -14
View File
@@ -11,6 +11,7 @@ import (
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/conf"
"isp-config-service/controller"
"isp-config-service/helper"
"isp-config-service/holder"
"isp-config-service/model"
@@ -41,10 +42,18 @@ func init() {
config.InitConfig(&conf.Configuration{})
}
// @title ISP configuration service
// @version 2.0.0
// @description Сервис управления конфигурацией модулей ISP кластера
// @license.name GNU GPL v3.0
// @host localhost:9003
// @BasePath /api/config
func main() {
cfg := config.Get().(*conf.Configuration)
handlers := helper.GetAllHandlers()
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers...)
handlers := helper.GetHandlers()
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
declaration := structure.BackendDeclaration{
ModuleName: cfg.ModuleName,
Version: version,
@@ -54,9 +63,9 @@ func main() {
}
model.DbClient.ReceiveConfiguration(cfg.Database)
client, raftStore := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster, declaration)
initWebsocket(cfg.WS.Rest.GetAddress(), client, raftStore)
initGrpc(cfg.WS.Grpc)
_, raftStore := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster, declaration)
initWebsocket(cfg.WS.Rest.GetAddress(), raftStore)
initGrpc(cfg.WS.Grpc, raftStore)
ctx := context.Background()
defer goodbye.Exit(ctx, -1)
@@ -66,13 +75,13 @@ func main() {
<-shutdownChan
}
func initWebsocket(bindAddress string, clusterClient *cluster.Client, raftStore *store.Store) {
func initWebsocket(bindAddress string, raftStore *store.Store) {
socket, err := ws.NewWebsocketServer()
if err != nil {
// TODO уйдет при миграции
log.Fatalf(0, "init socket.io %s", err.Error())
}
subs.NewSocketEventHandler(socket, clusterClient, raftStore).SubscribeAll()
subs.NewSocketEventHandler(socket, raftStore).SubscribeAll()
mux := http.NewServeMux()
mux.HandleFunc("/socket.io/", socket.ServeHttp)
@@ -103,7 +112,7 @@ func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declarat
cfg := config.Get().(*conf.Configuration)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) //must never occured
panic(err) // must never occured
}
port := addr.Port
// TODO логика для определения порта пира, т.к всё тестируется на одной машине
@@ -119,10 +128,7 @@ func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declarat
//
addressConfiguration := structure.AddressConfiguration{Port: strconv.Itoa(port), IP: addr.IP.String()}
back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration}
err = service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(back, s)
if err != nil {
log.Warnf(codes.DeleteBackendDeclarationError, "onClientDisconnect delete backend declaration. %v", err)
}
service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(back, s)
})
})
holder.ClusterClient = clusterClient
@@ -134,8 +140,13 @@ func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declarat
return clusterClient, raftStore
}
func initGrpc(bindAddress structure.AddressConfiguration) {
defaultService := backend.GetDefaultService(moduleName, helper.GetAllHandlers()...)
func initGrpc(bindAddress structure.AddressConfiguration, raftStore *store.Store) {
controller.Routes = controller.NewRoutes(raftStore)
controller.Schema = controller.NewSchema(raftStore)
controller.Module = controller.NewModule(raftStore)
controller.Config = controller.NewConfig(raftStore)
controller.CommonConfig = controller.NewCommonConfig(raftStore)
defaultService := backend.GetDefaultService(moduleName, helper.GetHandlers())
backend.StartBackendGrpcServer(bindAddress, defaultService)
}
+6 -14
View File
@@ -2,13 +2,18 @@
DROP TABLE instances CASCADE;
DROP TRIGGER update_config_create_time ON configs;
DROP TRIGGER deactivate_config on configs;
DROP TRIGGER update_schema_create_time ON config_schemas;
DROP TRIGGER update_customer_modtime ON modules;
ALTER TABLE configs
DROP CONSTRAINT "FK_configs_moduleId_modules_id";
ALTER TABLE config_schemas
DROP CONSTRAINT "fk_module_id__module_id";
ALTER TABLE configs
ALTER COLUMN id TYPE varchar(255),
ALTER COLUMN module_id TYPE varchar(255),
@@ -23,25 +28,12 @@ ALTER TABLE modules
DROP COLUMN active,
DROP COLUMN instance_id;
-- Constraints
ALTER TABLE configs
ADD CONSTRAINT "FK_configs_moduleId_modules_id"
FOREIGN KEY ("module_id") REFERENCES modules ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE config_schemas
ADD CONSTRAINT FK_module_id__module_id FOREIGN KEY (module_id)
REFERENCES modules (id) ON UPDATE CASCADE ON DELETE CASCADE;
CREATE TABLE common_configs
(
id VARCHAR(255) NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL DEFAULT 'unnamed',
description TEXT,
version int4 NOT NULL,
created_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'),
updated_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'),
data jsonb NOT NULL DEFAULT '{}'
+6 -6
View File
@@ -8,8 +8,8 @@ import (
type CommonConfigRepository interface {
Snapshot() ([]entity.CommonConfig, error)
Upsert(config *entity.CommonConfig) (*entity.CommonConfig, error)
Delete(identities []int64) (int, error)
Upsert(config entity.CommonConfig) (*entity.CommonConfig, error)
Delete(identities []string) (int, error)
}
type commonConfigRepPg struct {
@@ -24,18 +24,18 @@ func (r *commonConfigRepPg) Snapshot() ([]entity.CommonConfig, error) {
return configs, err
}
func (r *commonConfigRepPg) Upsert(config *entity.CommonConfig) (*entity.CommonConfig, error) {
func (r *commonConfigRepPg) Upsert(config entity.CommonConfig) (*entity.CommonConfig, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(config).
_, err := db.Model(&config).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
return config, err
return &config, err
}
func (r *commonConfigRepPg) Delete(identities []int64) (int, error) {
func (r *commonConfigRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
+6 -6
View File
@@ -8,8 +8,8 @@ import (
type ConfigRepository interface {
Snapshot() ([]entity.Config, error)
Upsert(config *entity.Config) (*entity.Config, error)
Delete(identities []int64) (int, error)
Upsert(config entity.Config) (*entity.Config, error)
Delete(identities []string) (int, error)
}
type configRepPg struct {
@@ -24,18 +24,18 @@ func (r *configRepPg) Snapshot() ([]entity.Config, error) {
return configs, err
}
func (r *configRepPg) Upsert(config *entity.Config) (*entity.Config, error) {
func (r *configRepPg) Upsert(config entity.Config) (*entity.Config, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(config).
_, err := db.Model(&config).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
return config, err
return &config, err
}
func (r *configRepPg) Delete(identities []int64) (int, error) {
func (r *configRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
+2 -2
View File
@@ -9,7 +9,7 @@ import (
type ModulesRepository interface {
Snapshot() ([]entity.Module, error)
Upsert(module entity.Module) (entity.Module, error)
Delete(identities []int32) (int, error)
Delete(identities []string) (int, error)
}
type modulesRepPg struct {
@@ -35,7 +35,7 @@ func (r *modulesRepPg) Upsert(module entity.Module) (entity.Module, error) {
return module, err
}
func (r *modulesRepPg) Delete(identities []int32) (int, error) {
func (r *modulesRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
+12
View File
@@ -9,6 +9,7 @@ import (
type SchemaRepository interface {
Snapshot() ([]entity.ConfigSchema, error)
Upsert(s entity.ConfigSchema) (*entity.ConfigSchema, error)
Delete(identities []string) (int, error)
}
type schemaRepPg struct {
@@ -33,3 +34,14 @@ func (r *schemaRepPg) Upsert(s entity.ConfigSchema) (*entity.ConfigSchema, error
})
return &s, err
}
func (r *schemaRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.ConfigSchema{}).
Where("id IN (?)", pg.In(identities)).Delete()
return err
})
return res.RowsAffected(), err
}
-1
View File
@@ -26,7 +26,6 @@ func (l *LoggerAdapter) Log(level logrus.Level, msg string, args ...interface{})
metadata[k] = args[i+1]
}
isplog.WithMetadata(metadata).Log(level, codes.RaftLoggerCode, msg)
} else {
isplog.Log(level, codes.RaftLoggerCode, msg)
}
+10 -19
View File
@@ -2,10 +2,6 @@ package service
import (
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
)
@@ -15,27 +11,22 @@ var (
type clusterMeshService struct{}
func (clusterMeshService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) error {
func (clusterMeshService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
changed := state.WritableMesh().UpsertBackend(declaration)
if changed {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
RoutesService.BroadcastRoutes(state)
go func() {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
RoutesService.BroadcastRoutes(state)
}()
}
return nil
}
func (clusterMeshService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) error {
func (clusterMeshService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
deleted := state.WritableMesh().DeleteBackend(declaration)
if deleted {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
RoutesService.BroadcastRoutes(state)
module := ModuleRegistryService.updateModuleLastDisconnected(declaration.ModuleName, state.WritableModules())
if holder.ClusterClient.IsLeader() {
_, err := model.ModuleRep.Upsert(module)
if err != nil {
log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
}
}
go func() {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
RoutesService.BroadcastRoutes(state)
}()
}
return nil
}
+68
View File
@@ -0,0 +1,68 @@
package service
import (
log "github.com/integration-system/isp-log"
codes2 "google.golang.org/grpc/codes"
"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 (
CommonConfigService = commonConfigService{}
)
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")
}
deleted := state.WritableCommonConfigs().DeleteByIds(ids)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ConfigRep.Delete(ids)
if err != nil {
log.WithMetadata(map[string]interface{}{
"configIds": ids,
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
}
return cluster.NewResponse(domain.DeleteResponse{Deleted: deleted})
}
func (commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCommonConfig, state state.WritableState) cluster.ResponseWithError {
config := upsertConfig.Config
if upsertConfig.Create {
config = state.WritableCommonConfigs().Create(config)
} else {
// Update
configs := state.CommonConfigs().GetByIds([]string{config.Id})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "common config with id %s not found", config.Id)
}
config.CreatedAt = configs[0].CreatedAt
state.WritableCommonConfigs().UpdateById(config)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.CommonConfigRep.Upsert(config)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert common config: %v", err)
}
}
if !upsertConfig.Create {
configsToBroadcast := state.Configs().FilterByCommonConfigs([]string{config.Id})
ConfigService.BroadcastNewConfig(state, configsToBroadcast...)
}
return cluster.NewResponse(config)
}
+106
View File
@@ -1,8 +1,17 @@
package service
import (
"encoding/json"
"github.com/integration-system/bellows"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
codes2 "google.golang.org/grpc/codes"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
)
@@ -10,6 +19,8 @@ var (
ConfigService = configService{}
)
const ConfigWatchersRoomSuffix = "_config"
type configService struct{}
func (configService) GetCompiledConfig(moduleName string, state state.ReadonlyState) (map[string]interface{}, error) {
@@ -32,6 +43,101 @@ func (configService) GetCompiledConfig(moduleName string, state state.ReadonlySt
return resultData, nil
}
func (configService) HandleActivateConfigCommand(activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError {
configs := state.Configs().GetByIds([]string{activateConfig.ConfigId})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", activateConfig.ConfigId)
}
config := configs[0]
affected := state.WritableConfigs().Activate(config, activateConfig.Date)
if holder.ClusterClient.IsLeader() {
for _, c := range affected {
// TODO handle db errors
_, err := model.ConfigRep.Upsert(c)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert config: %v", err)
}
}
}
return cluster.NewResponse(affected[len(affected)-1])
}
func (configService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConfigs, state state.WritableState) int {
ids := deleteConfigs.Ids
deleted := state.WritableConfigs().DeleteByIds(ids)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ConfigRep.Delete(ids)
if err != nil {
log.WithMetadata(map[string]interface{}{
"configIds": ids,
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
}
return deleted
}
func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertConfig, state state.WritableState) cluster.ResponseWithError {
config := upsertConfig.Config
module := state.Modules().GetById(config.ModuleId)
if module == nil {
return cluster.NewResponseErrorf(codes2.InvalidArgument, "invalid moduleId %s", config.ModuleId)
}
if upsertConfig.Create {
config = state.WritableConfigs().Create(config)
} else {
// Update
configs := state.Configs().GetByIds([]string{config.Id})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", config.Id)
}
config.CreatedAt = configs[0].CreatedAt
state.WritableConfigs().UpdateById(config)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ConfigRep.Upsert(config)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert config: %v", err)
}
}
cs.BroadcastNewConfig(state, config)
return cluster.NewResponse(config)
}
func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) {
for _, cfg := range configs {
moduleId := cfg.ModuleId
module := state.Modules().GetById(moduleId)
moduleName := module.Name
room := moduleName + ConfigWatchersRoomSuffix
compiledConfig, err := cs.GetCompiledConfig(moduleName, state)
if err != nil {
go cs.broadcast(room, utils.ConfigError, err.Error())
continue
}
data, err := json.Marshal(compiledConfig)
if err != nil {
go cs.broadcast(room, utils.ConfigError, err.Error())
continue
}
go cs.broadcast(room, utils.ConfigSendConfigWhenConnected, string(data))
}
}
func (cs configService) broadcast(room, event, data string) {
err := holder.Socket.Broadcast(room, utils.ConfigSendConfigWhenConnected, data)
if err != nil {
log.Errorf(codes.ConfigServiceBroadcastConfigError, "broadcast %s err: %v", event, err)
}
}
func mergeNestedMaps(maps ...map[string]interface{}) map[string]interface{} {
if len(maps) == 1 {
return maps[0]
+7 -2
View File
@@ -10,10 +10,15 @@ import (
"isp-config-service/holder"
"isp-config-service/store/state"
"isp-config-service/ws"
"strings"
"sync"
"time"
)
const (
ModuleConnectionEventSuffix = "_" + utils.ModuleConnectionSuffix
)
var (
DiscoveryService = NewDiscoveryService()
)
@@ -41,8 +46,8 @@ func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state
ds.subs[conn.Id()] = events
holder.Socket.Rooms().Join(conn, events...)
for _, event := range events {
addressList := state.Mesh().GetModuleAddresses(event)
event = utils.ModuleConnected(event)
eventName := strings.TrimSuffix(event, ModuleConnectionEventSuffix)
addressList := state.Mesh().GetModuleAddresses(eventName)
err := ds.sendAddrList(conn, event, addressList)
if err != nil {
log.Errorf(codes.DiscoveryServiceSendModulesError, "send module connected %v", err)
+138 -20
View File
@@ -1,14 +1,16 @@
package service
import (
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
"time"
"sort"
)
var (
@@ -17,35 +19,151 @@ var (
type moduleRegistryService struct{}
func (s moduleRegistryService) HandleModuleConnectedCommand(moduleConnected cluster.ModuleConnected, state state.WritableState) error {
module := s.updateModuleLastConnected(moduleConnected.ModuleName, state.WritableModules())
func (s moduleRegistryService) HandleModuleConnectedCommand(module entity.Module, state state.WritableState) {
existedModule := state.WritableModules().GetByName(module.Name)
if existedModule == nil {
state.WritableModules().Create(module)
} else {
module.Id = existedModule.Id
module.CreatedAt = existedModule.CreatedAt
module.LastDisconnectedAt = existedModule.LastDisconnectedAt
state.WritableModules().UpdateByName(module)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ModuleRep.Upsert(module)
if err != nil {
log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
log.WithMetadata(map[string]interface{}{
"module": module,
}).Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
}
}
return nil
}
func (moduleRegistryService) updateModuleLastConnected(moduleName string, moduleStore state.WriteableModuleStore) entity.Module {
existedModule := moduleStore.GetByName(moduleName)
func (moduleRegistryService) HandleModuleDisconnectedCommand(module entity.Module, state state.WritableState) {
existedModule := state.WritableModules().GetByName(module.Name)
if existedModule == nil {
module := moduleStore.Create(moduleName)
return module
state.WritableModules().Create(module)
} else {
module.Id = existedModule.Id
module.CreatedAt = existedModule.CreatedAt
module.LastConnectedAt = existedModule.LastConnectedAt
state.WritableModules().UpdateByName(module)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ModuleRep.Upsert(module)
if err != nil {
log.WithMetadata(map[string]interface{}{
"module": module,
}).Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
}
}
existedModule.LastConnectedAt = time.Now()
moduleStore.Update(*existedModule)
return *existedModule
}
func (moduleRegistryService) updateModuleLastDisconnected(moduleName string, moduleStore state.WriteableModuleStore) entity.Module {
existedModule := moduleStore.GetByName(moduleName)
if existedModule == nil {
module := moduleStore.Create(moduleName)
return module
func (moduleRegistryService) HandleDeleteModulesCommand(deleteModules cluster.DeleteModules, state state.WritableState) int {
ids := deleteModules.Ids
deletedModules := state.WritableModules().DeleteByIds(ids)
configsToDelete := state.WritableConfigs().GetByModuleIds(ids)
confIds := make([]string, 0, len(configsToDelete))
for _, conf := range configsToDelete {
confIds = append(confIds, conf.Id)
}
existedModule.LastDisconnectedAt = time.Now()
moduleStore.Update(*existedModule)
return *existedModule
state.WritableConfigs().DeleteByIds(confIds)
schemasToDelete := state.WritableSchemas().GetByModuleIds(ids)
schemaIds := make([]string, 0, len(schemasToDelete))
for _, schema := range schemasToDelete {
schemaIds = append(schemaIds, schema.Id)
}
state.WritableSchemas().DeleteByIds(schemaIds)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ModuleRep.Delete(ids)
if err != nil {
log.WithMetadata(map[string]interface{}{
"moduleIds": ids,
}).Errorf(codes.DatabaseOperationError, "delete modules: %v", err)
}
_, err = model.ConfigRep.Delete(confIds)
if err != nil {
log.WithMetadata(map[string]interface{}{
"configIds": confIds,
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
_, err = model.SchemaRep.Delete(schemaIds)
if err != nil {
log.WithMetadata(map[string]interface{}{
"schemaIds": schemaIds,
}).Errorf(codes.DatabaseOperationError, "delete schemas: %v", err)
}
}
return len(deletedModules)
}
func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState) []domain.ModuleInfo {
modules := state.Modules().GetAll()
modulesLen := len(modules)
result := make([]domain.ModuleInfo, 0, modulesLen)
resMap := make(map[string]domain.ModuleInfo, modulesLen)
idList := make([]string, modulesLen)
for i, module := range modules {
idList[i] = module.Id
active := state.Mesh().BackendExist(structure.BackendDeclaration{ModuleName: module.Name})
info := domain.ModuleInfo{
Id: module.Id,
Name: module.Name,
Active: active,
CreatedAt: module.CreatedAt,
LastConnectedAt: module.LastConnectedAt,
LastDisconnectedAt: module.LastDisconnectedAt,
}
resMap[module.Id] = info
}
configs := state.Configs().GetByModuleIds(idList)
for _, cfg := range configs {
info := resMap[cfg.ModuleId]
info.Configs = append(info.Configs, cfg)
resMap[cfg.ModuleId] = info
}
schemas := state.Schemas().GetByModuleIds(idList)
for _, s := range schemas {
info := resMap[s.ModuleId]
schema := s.Schema
info.ConfigSchema = &schema
resMap[s.ModuleId] = info
}
for key := range resMap {
info := resMap[key]
backends := state.Mesh().GetBackends(info.Name)
conns := make([]domain.Connection, 0, len(backends))
for _, back := range backends {
con := domain.Connection{
Version: back.Version,
LibVersion: back.LibVersion,
Address: back.Address,
Endpoints: back.Endpoints,
}
sort.Slice(con.Endpoints, func(i, j int) bool {
return con.Endpoints[i].Path < con.Endpoints[j].Path
})
con.EstablishedAt = info.LastConnectedAt
conns = append(conns, con)
}
sort.Slice(conns, func(i, j int) bool {
return conns[i].EstablishedAt.Before(conns[j].EstablishedAt)
})
info.Status = conns
result = append(result, info)
}
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}
+8 -3
View File
@@ -1,7 +1,9 @@
package service
import (
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"isp-config-service/codes"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/model"
@@ -14,17 +16,20 @@ var (
type schemaService struct{}
func (schemaService) HandleUpdateConfigSchema(schema entity.ConfigSchema, state state.WritableState) error {
func (schemaService) HandleUpdateConfigSchemaCommand(schema entity.ConfigSchema, state state.WritableState) error {
module := state.Modules().GetById(schema.ModuleId)
if module == nil {
return errors.Errorf("module with id %s not found", schema.ModuleId)
}
schema = state.WritableSchemas().Upsert(schema)
if holder.ClusterClient.IsLeader() {
schema = state.WritableSchemas().Upsert(schema)
// TODO handle db errors
_, err := model.SchemaRep.Upsert(schema)
if err != nil {
return err
log.WithMetadata(map[string]interface{}{
"schema": schema,
}).Errorf(codes.DatabaseOperationError, "upsert schema: %v", err)
}
}
return nil
+78 -16
View File
@@ -4,6 +4,7 @@ import (
"github.com/integration-system/isp-lib/structure"
"github.com/pkg/errors"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
)
@@ -14,10 +15,7 @@ func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) (interface{},
if err != nil {
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
}
err = service.ClusterMeshService.HandleUpdateBackendDeclarationCommand(declaration, s.state)
if err != nil {
return nil, errors.WithMessage(err, "update backend declaration")
}
service.ClusterMeshService.HandleUpdateBackendDeclarationCommand(declaration, s.state)
return nil, nil
}
@@ -27,20 +25,17 @@ func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) (interface{},
if err != nil {
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
}
err = service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(declaration, s.state)
if err != nil {
return nil, errors.WithMessage(err, "delete backend declaration")
}
service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(declaration, s.state)
return nil, nil
}
func (s *Store) applyUpdateConfigSchema(data []byte) (interface{}, error) {
func (s *Store) applyUpdateConfigSchemaCommand(data []byte) (interface{}, error) {
schema := entity.ConfigSchema{}
err := json.Unmarshal(data, &schema)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal entity.ConfigSchema")
}
err = service.SchemaService.HandleUpdateConfigSchema(schema, s.state)
err = service.SchemaService.HandleUpdateConfigSchemaCommand(schema, s.state)
if err != nil {
return nil, errors.WithMessage(err, "update config schema")
}
@@ -48,14 +43,81 @@ func (s *Store) applyUpdateConfigSchema(data []byte) (interface{}, error) {
}
func (s *Store) applyModuleConnectedCommand(data []byte) (interface{}, error) {
moduleConnected := cluster.ModuleConnected{}
err := json.Unmarshal(data, &moduleConnected)
module := entity.Module{}
err := json.Unmarshal(data, &module)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.ModuleConnected")
}
err = service.ModuleRegistryService.HandleModuleConnectedCommand(moduleConnected, s.state)
if err != nil {
return nil, errors.WithMessage(err, "register module")
}
service.ModuleRegistryService.HandleModuleConnectedCommand(module, s.state)
return nil, nil
}
func (s *Store) applyModuleDisconnectedCommand(data []byte) (interface{}, error) {
module := entity.Module{}
err := json.Unmarshal(data, &module)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.ModuleConnected")
}
service.ModuleRegistryService.HandleModuleDisconnectedCommand(module, s.state)
return nil, nil
}
func (s *Store) applyDeleteModulesCommand(data []byte) (interface{}, error) {
deleteModules := cluster.DeleteModules{}
err := json.Unmarshal(data, &deleteModules)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteModules")
}
deleted := service.ModuleRegistryService.HandleDeleteModulesCommand(deleteModules, s.state)
return domain.DeleteResponse{Deleted: deleted}, nil
}
func (s *Store) applyActivateConfigCommand(data []byte) (interface{}, error) {
activateConfig := cluster.ActivateConfig{}
err := json.Unmarshal(data, &activateConfig)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteModules")
}
response := service.ConfigService.HandleActivateConfigCommand(activateConfig, s.state)
return response, nil
}
func (s *Store) applyDeleteConfigsCommand(data []byte) (interface{}, error) {
deleteConfigs := cluster.DeleteConfigs{}
err := json.Unmarshal(data, &deleteConfigs)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteConfigs")
}
deleted := service.ConfigService.HandleDeleteConfigsCommand(deleteConfigs, s.state)
return domain.DeleteResponse{Deleted: deleted}, nil
}
func (s *Store) applyUpsertConfigCommand(data []byte) (interface{}, error) {
config := cluster.UpsertConfig{}
err := json.Unmarshal(data, &config)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal entity.Config")
}
response := service.ConfigService.HandleUpsertConfigCommand(config, s.state)
return response, nil
}
func (s *Store) applyDeleteCommonConfigsCommand(data []byte) (interface{}, error) {
deleteConfigs := cluster.DeleteConfigs{}
err := json.Unmarshal(data, &deleteConfigs)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteConfigs")
}
response := service.CommonConfigService.HandleDeleteConfigsCommand(deleteConfigs, s.state)
return response, nil
}
func (s *Store) applyUpsertCommonConfigCommand(data []byte) (interface{}, error) {
config := cluster.UpsertCommonConfig{}
err := json.Unmarshal(data, &config)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal entity.CommonConfig")
}
response := service.CommonConfigService.HandleUpsertConfigCommand(config, s.state)
return response, nil
}
+44 -7
View File
@@ -1,15 +1,19 @@
package state
import "isp-config-service/entity"
import (
"isp-config-service/entity"
)
type WriteableCommonConfigStore interface {
ReadonlyCommonConfigStore
Upsert(config entity.CommonConfig)
Delete(config entity.CommonConfig)
Create(config entity.CommonConfig) entity.CommonConfig
UpdateById(config entity.CommonConfig)
DeleteByIds(ids []string) int
}
type ReadonlyCommonConfigStore interface {
GetByIds(ids []string) []entity.CommonConfig
GetAll() []entity.CommonConfig
}
type CommonConfigStore struct {
@@ -27,12 +31,45 @@ func (cs CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
return configs
}
func (cs *CommonConfigStore) Upsert(config entity.CommonConfig) {
// TODO
func (cs *CommonConfigStore) Create(config entity.CommonConfig) entity.CommonConfig {
if config.Name == "" {
config.Name = configDefaultName
}
if config.Data == nil {
config.Data = make(entity.ConfigData)
}
cs.configs = append(cs.configs, config)
return config
}
func (cs *CommonConfigStore) Delete(config entity.CommonConfig) {
// TODO
func (cs *CommonConfigStore) UpdateById(config entity.CommonConfig) {
for i := range cs.configs {
if cs.configs[i].Id == config.Id {
cs.configs[i] = config
break
}
}
}
func (cs *CommonConfigStore) DeleteByIds(ids []string) int {
idsMap := StringsToMap(ids)
var deleted int
for i := 0; i < len(cs.configs); i++ {
id := cs.configs[i].Id
if _, ok := idsMap[id]; ok {
// change configs ordering
cs.configs[i] = cs.configs[len(cs.configs)-1]
cs.configs = cs.configs[:len(cs.configs)-1]
deleted++
}
}
return deleted
}
func (cs *CommonConfigStore) GetAll() []entity.CommonConfig {
response := make([]entity.CommonConfig, len(cs.configs))
copy(response, cs.configs)
return response
}
func NewCommonConfigStore() *CommonConfigStore {
+115 -13
View File
@@ -2,18 +2,26 @@ package state
import (
"isp-config-service/entity"
"time"
)
const (
configDefaultName = "unnamed"
)
type WriteableConfigStore interface {
ReadonlyConfigStore
Upsert(config entity.Config)
Delete(config entity.Config)
Activate(config entity.Config)
Create(config entity.Config) entity.Config
UpdateById(config entity.Config)
DeleteByIds(ids []string) int
Activate(config entity.Config, date time.Time) (affected []entity.Config)
}
type ReadonlyConfigStore interface {
GetActiveByModuleId(moduleId string) *entity.Config
GetById(id int64) *entity.Config
GetByIds(ids []string) []entity.Config
GetByModuleIds(ids []string) []entity.Config
FilterByCommonConfigs(commonIds []string) []entity.Config
}
type ConfigStore struct {
@@ -29,21 +37,115 @@ func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
return nil
}
func (cs ConfigStore) GetById(id int64) *entity.Config {
// TODO
return nil
func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
idsMap := StringsToMap(ids)
result := make([]entity.Config, 0, len(ids))
for _, conf := range cs.configs {
if _, ok := idsMap[conf.Id]; ok {
result = append(result, conf)
}
}
return result
}
func (cs *ConfigStore) Upsert(config entity.Config) {
// TODO
func (cs ConfigStore) GetByModuleIds(ids []string) []entity.Config {
idsMap := StringsToMap(ids)
result := make([]entity.Config, 0, len(ids))
for _, conf := range cs.configs {
if _, ok := idsMap[conf.ModuleId]; ok {
result = append(result, conf)
}
}
return result
}
func (cs *ConfigStore) Delete(config entity.Config) {
// TODO
func (cs *ConfigStore) Create(config entity.Config) entity.Config {
config.Version = cs.calcNewVersion(config.ModuleId)
if config.Version == 1 {
config.Active = true
}
if config.Name == "" {
config.Name = configDefaultName
}
if config.Data == nil {
config.Data = make(entity.ConfigData)
}
if config.CommonConfigs == nil {
config.CommonConfigs = make([]string, 0)
}
cs.configs = append(cs.configs, config)
return config
}
func (cs *ConfigStore) Activate(config entity.Config) {
// TODO
func (cs *ConfigStore) UpdateById(config entity.Config) {
for i := range cs.configs {
if cs.configs[i].Id == config.Id {
cs.configs[i] = config
break
}
}
}
func (cs *ConfigStore) calcNewVersion(moduleId string) int32 {
var maxVersion int32 = 0
for i := range cs.configs {
if cs.configs[i].ModuleId == moduleId {
if cs.configs[i].Version > maxVersion {
maxVersion = cs.configs[i].Version
}
}
}
return maxVersion + 1
}
func (cs *ConfigStore) DeleteByIds(ids []string) int {
idsMap := StringsToMap(ids)
var deleted int
for i := 0; i < len(cs.configs); i++ {
id := cs.configs[i].Id
if _, ok := idsMap[id]; ok {
// change configs ordering
cs.configs[i] = cs.configs[len(cs.configs)-1]
cs.configs = cs.configs[:len(cs.configs)-1]
deleted++
}
}
return deleted
}
func (cs *ConfigStore) Activate(config entity.Config, date time.Time) []entity.Config {
affected := cs.deactivate(config.ModuleId, date)
config.Active = true
config.UpdatedAt = date
cs.UpdateById(config)
affected = append(affected, config)
return affected
}
func (cs *ConfigStore) deactivate(moduleId string, date time.Time) []entity.Config {
affected := make([]entity.Config, 0)
for i := range cs.configs {
if cs.configs[i].ModuleId == moduleId && cs.configs[i].Active {
cs.configs[i].Active = false
cs.configs[i].UpdatedAt = date
affected = append(affected, cs.configs[i])
}
}
return affected
}
func (cs *ConfigStore) FilterByCommonConfigs(commonIds []string) []entity.Config {
idsMap := StringsToMap(commonIds)
result := make([]entity.Config, 0)
for _, cfg := range cs.configs {
for _, commonId := range cfg.CommonConfigs {
if _, ok := idsMap[commonId]; ok {
result = append(result, cfg)
break
}
}
}
return result
}
func NewConfigStore() *ConfigStore {
+13 -2
View File
@@ -14,9 +14,12 @@ type ReadonlyMesh interface {
CheckBackendChanged(backend structure.BackendDeclaration) (changed bool)
BackendExist(backend structure.BackendDeclaration) (exist bool)
GetModuleAddresses(moduleName string) []structure.AddressConfiguration
GetBackends(module string) []structure.BackendDeclaration
GetRoutes() structure.RoutingConfig
}
type NodesMap map[string]structure.BackendDeclaration
type Mesh struct {
// { "ModuleName": { "address": BackendDeclaration, ...}, ... }
modulesMap map[string]NodesMap
@@ -32,6 +35,16 @@ func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
return
}
func (m Mesh) GetBackends(module string) []structure.BackendDeclaration {
declarations := make([]structure.BackendDeclaration, 0)
if nodes, ok := m.modulesMap[module]; ok {
for _, backend := range nodes {
declarations = append(declarations, backend)
}
}
return declarations
}
func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration {
addressList := make([]structure.AddressConfiguration, 0)
if nodes, ok := m.modulesMap[moduleName]; ok {
@@ -101,8 +114,6 @@ func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool
return
}
type NodesMap map[string]structure.BackendDeclaration
func NewMesh() *Mesh {
return &Mesh{modulesMap: make(map[string]NodesMap)}
}
+29 -14
View File
@@ -2,18 +2,19 @@ package state
import (
"isp-config-service/entity"
"time"
)
type WriteableModuleStore interface {
ReadonlyModuleStore
Update(module entity.Module)
Create(name string) entity.Module
UpdateByName(module entity.Module)
Create(entity.Module)
DeleteByIds(ids []string) (deleted []entity.Module)
}
type ReadonlyModuleStore interface {
GetByName(name string) *entity.Module
GetById(id string) *entity.Module
GetAll() []entity.Module
}
type ModuleStore struct {
@@ -38,24 +39,38 @@ func (ms ModuleStore) GetById(id string) *entity.Module {
return nil
}
func (ms *ModuleStore) Update(module entity.Module) {
func (ms *ModuleStore) UpdateByName(module entity.Module) {
for i := range ms.modules {
if ms.modules[i].Id == module.Id {
if ms.modules[i].Name == module.Name {
ms.modules[i] = module
return
}
}
}
func (ms *ModuleStore) Create(name string) entity.Module {
module := entity.Module{
Id: GenerateId(),
Name: name,
CreatedAt: time.Now(),
LastConnectedAt: time.Now(),
LastDisconnectedAt: time.Time{},
}
func (ms *ModuleStore) Create(module entity.Module) {
ms.modules = append(ms.modules, module)
return module
}
func (ms *ModuleStore) DeleteByIds(ids []string) []entity.Module {
idsMap := StringsToMap(ids)
var deleted []entity.Module
for i := 0; i < len(ms.modules); i++ {
id := ms.modules[i].Id
if _, ok := idsMap[id]; ok {
// change modules ordering
deleted = append(deleted, ms.modules[i])
ms.modules[i] = ms.modules[len(ms.modules)-1]
ms.modules = ms.modules[:len(ms.modules)-1]
}
}
return deleted
}
func (ms *ModuleStore) GetAll() []entity.Module {
response := make([]entity.Module, len(ms.modules))
copy(response, ms.modules)
return response
}
func NewModuleStore() *ModuleStore {
+25 -9
View File
@@ -7,36 +7,52 @@ import (
type WriteableSchemaStore interface {
ReadonlySchemaStore
Upsert(schema entity.ConfigSchema) entity.ConfigSchema
DeleteByIds(ids []string) int
}
type ReadonlySchemaStore interface {
GetByModuleId(moduleId int32) *entity.ConfigSchema
GetById(id int64) *entity.ConfigSchema
GetByModuleIds(ids []string) []entity.ConfigSchema
}
type SchemaStore struct {
schemas []entity.ConfigSchema
}
func (ss SchemaStore) GetByModuleId(moduleId int32) *entity.ConfigSchema {
// TODO
return nil
func (ss SchemaStore) GetByModuleIds(ids []string) []entity.ConfigSchema {
idsMap := StringsToMap(ids)
result := make([]entity.ConfigSchema, 0, len(ids))
for _, schema := range ss.schemas {
if _, ok := idsMap[schema.ModuleId]; ok {
result = append(result, schema)
}
}
return result
}
func (ss SchemaStore) GetById(id int64) *entity.ConfigSchema {
// TODO
return nil
func (ss *SchemaStore) DeleteByIds(ids []string) int {
idsMap := StringsToMap(ids)
var deleted int
for i := 0; i < len(ss.schemas); i++ {
id := ss.schemas[i].Id
if _, ok := idsMap[id]; ok {
// change schemas ordering
ss.schemas[i] = ss.schemas[len(ss.schemas)-1]
ss.schemas = ss.schemas[:len(ss.schemas)-1]
deleted++
}
}
return deleted
}
func (ss *SchemaStore) Upsert(schema entity.ConfigSchema) entity.ConfigSchema {
for key, value := range ss.schemas {
if value.ModuleId == schema.ModuleId {
schema.Id = value.Id
schema.CreatedAt = value.CreatedAt
ss.schemas[key] = schema
return schema
}
}
schema.Id = GenerateId()
ss.schemas = append(ss.schemas, schema)
return schema
}
+5
View File
@@ -2,6 +2,7 @@ package state
import (
uuid "github.com/satori/go.uuid"
"time"
)
func StringsToMap(list []string) map[string]struct{} {
@@ -16,3 +17,7 @@ func GenerateId() string {
uuidV4 := uuid.NewV4()
return uuidV4.String()
}
func GenerateDate() time.Time {
return time.Now()
}
+10 -2
View File
@@ -32,6 +32,7 @@ func (s *Store) Apply(l *raft.Log) interface{} {
log.Errorf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data)
}
command := binary.BigEndian.Uint64(l.Data[:8])
log.Debugf(0, "Apply %d command. Data: %s", command, l.Data)
var (
result interface{}
@@ -40,7 +41,7 @@ func (s *Store) Apply(l *raft.Log) interface{} {
if handler, ok := s.handlers[command]; ok {
result, err = handler(l.Data[8:])
} else {
log.Errorf(codes.ApplyLogCommandError, "unknown log command %s", command)
log.Errorf(codes.ApplyLogCommandError, "unknown log command %d", command)
}
bytes, e := json.Marshal(result)
@@ -116,7 +117,14 @@ func NewStateStore(st state.State) *Store {
cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand,
cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand,
cluster.ModuleConnectedCommand: store.applyModuleConnectedCommand,
cluster.UpdateConfigSchemaCommand: store.applyUpdateConfigSchema,
cluster.ModuleDisconnectedCommand: store.applyModuleDisconnectedCommand,
cluster.DeleteModulesCommand: store.applyDeleteModulesCommand,
cluster.UpdateConfigSchemaCommand: store.applyUpdateConfigSchemaCommand,
cluster.ActivateConfigCommand: store.applyActivateConfigCommand,
cluster.DeleteConfigsCommand: store.applyDeleteConfigsCommand,
cluster.UpsertConfigCommand: store.applyUpsertConfigCommand,
cluster.DeleteCommonConfigsCommand: store.applyDeleteCommonConfigsCommand,
cluster.UpsertCommonConfigCommand: store.applyUpsertCommonConfigCommand,
}
return store
}
+49 -8
View File
@@ -10,12 +10,15 @@ import (
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/service"
"isp-config-service/store/state"
"isp-config-service/ws"
)
func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string {
moduleName, _ := conn.Parameters() // REMOVE
log.Debugf(0, "handleModuleReady moduleName: %s", moduleName) // REMOVE
declaration := structure.BackendDeclaration{}
err := json.Unmarshal(data, &declaration)
if err != nil {
@@ -33,7 +36,7 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string
})
if changed {
command := cluster.PrepareUpdateBackendDeclarationCommand(declaration)
applyLogResponse, err := h.cluster.SyncApply(command)
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
return err.Error()
}
@@ -63,17 +66,17 @@ func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte)
}
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, state)
if declaration.RequireRoutes {
service.RoutesService.SubscribeRoutes(conn, state)
}
service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, state)
})
return Ok
}
func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) string {
moduleName, err := conn.Parameters()
log.Debugf(0, "handleModuleRequirements moduleName: %s", moduleName) // REMOVE
log.Debugf(0, "handleConfigSchema moduleName: %s", moduleName) // REMOVE
if err != nil {
return err.Error()
}
@@ -82,6 +85,19 @@ func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) strin
if err := json.Unmarshal(data, &configSchema); err != nil {
return err.Error()
}
// TODO Костыль. Дважды посылаем ModuleConnected, т.к с момента первой отправки в handleConnect,
// состояние к конкретной ноде кластера может не успеть примениться
now := state.GenerateDate()
newModule := entity.Module{
Id: state.GenerateId(),
Name: moduleName,
CreatedAt: now,
LastConnectedAt: now,
}
command := cluster.PrepareModuleConnectedCommand(newModule)
SyncApplyCommand(command, "ModuleConnectedCommand")
// />
module := new(entity.Module)
h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
module = readState.Modules().GetByName(moduleName)
@@ -91,17 +107,42 @@ func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) strin
}
schema := entity.ConfigSchema{
ModuleId: module.Id,
Version: configSchema.Version,
Schema: configSchema.Schema,
Id: state.GenerateId(),
Version: configSchema.Version,
ModuleId: module.Id,
Schema: configSchema.Schema,
CreatedAt: now,
UpdatedAt: now,
}
command := cluster.PrepareUpdateConfigSchemaCommand(schema)
i, err := h.cluster.SyncApply(command)
command = cluster.PrepareUpdateConfigSchemaCommand(schema)
i, err := holder.ClusterClient.SyncApply(command)
if err != nil {
log.WithMetadata(map[string]interface{}{
"answer": i,
}).Warnf(codes.SyncApplyError, "apply ModuleSendConfigSchemaCommand %v", err)
}
var configs []entity.Config
h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
configs = readState.Configs().GetByModuleIds([]string{module.Id})
})
if len(configs) == 0 {
config := entity.Config{
Id: state.GenerateId(),
Name: module.Name,
ModuleId: module.Id,
Data: configSchema.DefaultConfig,
CreatedAt: now,
UpdatedAt: now,
}
upsertConfig := cluster.UpsertConfig{
Config: config,
Create: true,
}
command := cluster.PrepareUpsertConfigCommand(upsertConfig)
SyncApplyCommand(command, "UpsertConfigCommand")
}
return Ok
}
+2 -1
View File
@@ -4,11 +4,12 @@ import (
log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/holder"
"isp-config-service/ws"
)
func (h *socketEventHandler) applyCommandOnLeader(conn ws.Conn, cmd []byte) string {
obj, err := h.cluster.SyncApplyOnLeader(cmd)
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmd)
if err != nil {
var logResponse cluster.ApplyLogResponse
logResponse.ApplyError = err.Error()
+4 -3
View File
@@ -3,6 +3,7 @@ package subs
import (
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/holder"
"isp-config-service/ws"
)
@@ -15,14 +16,14 @@ func EmitConn(conn ws.Conn, event string, args ...interface{}) {
}
}
func (h *socketEventHandler) SyncApplyCommand(command []byte, commandName string) {
applyLogResponse, err := h.cluster.SyncApply(command)
func SyncApplyCommand(command []byte, commandName string) {
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
log.Warnf(codes.SyncApplyError, "apply %s: %v", commandName, err)
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
log.WithMetadata(map[string]interface{}{
"result": applyLogResponse.Result,
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes.SyncApplyError, "apply command")
+34 -10
View File
@@ -6,6 +6,7 @@ import (
jsoniter "github.com/json-iterator/go"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/service"
"isp-config-service/store"
@@ -23,9 +24,8 @@ var (
)
type socketEventHandler struct {
socket *ws.WebsocketServer
cluster *cluster.Client
store *store.Store
socket *ws.WebsocketServer
store *store.Store
}
func (h *socketEventHandler) SubscribeAll() {
@@ -44,12 +44,21 @@ func (h *socketEventHandler) handleConnect(conn ws.Conn) {
holder.Socket.Rooms().Join(conn, followersRoom)
}
moduleName, err := conn.Parameters()
log.Debugf(0, "handleConnect: %s", moduleName) // REMOVE
if err != nil {
EmitConn(conn, utils.ErrorConnection, err.Error())
return
}
command := cluster.PrepareModuleConnectedCommand(moduleName)
h.SyncApplyCommand(command, "ModuleConnectedCommand")
holder.Socket.Rooms().Join(conn, moduleName+service.ConfigWatchersRoomSuffix)
now := state.GenerateDate()
module := entity.Module{
Id: state.GenerateId(),
Name: moduleName,
CreatedAt: now,
LastConnectedAt: now,
}
command := cluster.PrepareModuleConnectedCommand(module)
SyncApplyCommand(command, "ModuleConnectedCommand")
var config map[string]interface{}
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
@@ -71,12 +80,28 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) {
if conn.IsConfigClusterNode() {
holder.Socket.Rooms().Leave(conn, followersRoom)
}
moduleName, _ := conn.Parameters()
log.Debugf(0, "handleDisconnect: %s", moduleName) // REMOVE
if moduleName != "" {
holder.Socket.Rooms().Leave(conn, moduleName+service.ConfigWatchersRoomSuffix)
now := state.GenerateDate()
module := entity.Module{
Id: state.GenerateId(),
Name: moduleName,
CreatedAt: now,
LastConnectedAt: now,
LastDisconnectedAt: now,
}
command := cluster.PrepareModuleDisconnectedCommand(module)
SyncApplyCommand(command, "ModuleDisconnectedCommand")
}
service.DiscoveryService.HandleDisconnect(conn.Id())
service.RoutesService.HandleDisconnect(conn.Id())
backend := conn.GetBackendDeclaration()
if backend != nil {
command := cluster.PrepareDeleteBackendDeclarationCommand(*backend)
h.SyncApplyCommand(command, "ModuleConnectedCommand")
SyncApplyCommand(command, "DeleteBackendDeclarationCommand")
}
}
@@ -84,10 +109,9 @@ func (h *socketEventHandler) handleError(conn ws.Conn, err error) {
log.Warnf(codes.SocketIoError, "socket.io: %v", err)
}
func NewSocketEventHandler(socket *ws.WebsocketServer, cluster *cluster.Client, store *store.Store) *socketEventHandler {
func NewSocketEventHandler(socket *ws.WebsocketServer, store *store.Store) *socketEventHandler {
return &socketEventHandler{
socket: socket,
cluster: cluster,
store: store,
socket: socket,
store: store,
}
}
+3 -3
View File
@@ -25,10 +25,10 @@ func (s *WebsocketServer) Rooms() *RoomStore {
}
func (s *WebsocketServer) OnWithAck(event string, f func(conn Conn, data []byte) string) *WebsocketServer {
must(s.s.On(event, func(conn socketio.Socket, data []byte) string {
logger.Debugf("[%s]:%s:%s", conn.Request().RemoteAddr, event, string(data))
must(s.s.On(event, func(conn socketio.Socket, data string) string {
logger.Debugf("[%s]:%s:%s", conn.Request().RemoteAddr, event, data)
return f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), data)
return f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), []byte(data))
}))
return s
}