diff --git a/Gopkg.lock b/Gopkg.lock index 27cb5d5..c48de41 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -405,6 +405,14 @@ pruneopts = "UT" revision = "cac0b30c2563378d434b5af411844adff8e32960" +[[projects]] + digest = "1:274f67cb6fed9588ea2521ecdac05a6d62a8c51c074c1fccc6a49a40ba80e925" + name = "github.com/satori/go.uuid" + packages = ["."] + pruneopts = "UT" + revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3" + version = "v1.2.0" + [[projects]] digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976" name = "github.com/sirupsen/logrus" @@ -636,6 +644,7 @@ "github.com/hashicorp/go-hclog", "github.com/hashicorp/raft", "github.com/hashicorp/raft-boltdb", + "github.com/integration-system/bellows", "github.com/integration-system/golang-socketio", "github.com/integration-system/isp-lib/backend", "github.com/integration-system/isp-lib/bootstrap", @@ -650,6 +659,7 @@ "github.com/json-iterator/go", "github.com/mohae/deepcopy", "github.com/pkg/errors", + "github.com/satori/go.uuid", "github.com/sirupsen/logrus", "github.com/spf13/cast", "github.com/thecodeteam/goodbye", diff --git a/cluster/client.go b/cluster/client.go index bf3b40c..de183a2 100644 --- a/cluster/client.go +++ b/cluster/client.go @@ -4,6 +4,7 @@ import ( "errors" "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" + jsoniter "github.com/json-iterator/go" "isp-config-service/codes" "isp-config-service/raft" "strconv" @@ -15,6 +16,7 @@ var ( ErrNoLeader = errors.New("no leader in cluster") ErrLeaderClientNotInitialized = errors.New("leader client not initialized") ErrNotLeader = errors.New("node is not a leader") + json = jsoniter.ConfigFastest ) const ( @@ -44,7 +46,14 @@ func (client *ClusterClient) Shutdown() error { return client.r.GracefulShutdown() } -func (client *ClusterClient) SyncApply(command []byte) (interface{}, error) { +func (client *ClusterClient) IsLeader() bool { + client.leaderMu.RLock() + defer client.leaderMu.RUnlock() + + return client.leaderState.isLeader +} + +func (client *ClusterClient) SyncApply(command []byte) (*ApplyLogResponse, error) { client.leaderMu.RLock() defer client.leaderMu.RUnlock() @@ -53,24 +62,42 @@ func (client *ClusterClient) SyncApply(command []byte) (interface{}, error) { } if client.leaderState.isLeader { - return client.r.SyncApply(command) + apply, err := client.r.SyncApply(command) + if err != nil { + return nil, err + } + logResponse := apply.(ApplyLogResponse) + return &logResponse, err } else { if client.leaderClient == nil { return nil, ErrLeaderClientNotInitialized } - return client.leaderClient.Send(command, defaultApplyTimeout) + response, err := client.leaderClient.Send(command, defaultApplyTimeout) + if err != nil { + return nil, err + } + var logResponse ApplyLogResponse + err = json.Unmarshal([]byte(response), &logResponse) + if err != nil { + return nil, err + } + return &logResponse, nil } } -func (client *ClusterClient) SyncApplyOnLeader(command []byte) (interface{}, error) { +func (client *ClusterClient) SyncApplyOnLeader(command []byte) (*ApplyLogResponse, error) { client.leaderMu.RLock() defer client.leaderMu.RUnlock() if !client.leaderState.isLeader { return nil, ErrNotLeader } - - return client.r.SyncApply(command) + apply, err := client.r.SyncApply(command) + if err != nil { + return nil, err + } + logResponse := apply.(ApplyLogResponse) + return &logResponse, err } func (client *ClusterClient) listenLeader() { @@ -97,7 +124,7 @@ func (client *ClusterClient) listenLeader() { } if err != nil { log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader err: %v", err) - } else if response != "ok" { + } else if response != Ok { log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader response: %s", response) } }(client.declaration) @@ -106,8 +133,17 @@ func (client *ClusterClient) listenLeader() { } else if n.LeaderElected && n.IsLeader { go func(declaration structure.BackendDeclaration) { command := PrepareUpdateBackendDeclarationCommand(declaration) - i, err := client.SyncApply(command) - log.Debugf(0, "cluster.SyncApply announce myself:%v, %v", i, err) + + applyLogResponse, err := client.SyncApply(command) + if err != nil { + log.Warnf(codes.SyncApplyError, "cluster.SyncApply announce myself: %v", err) + } + if applyLogResponse != nil && applyLogResponse.ApplyError != "" { + log.WithMetadata(map[string]interface{}{ + "comment": applyLogResponse.Comment, + "applyError": applyLogResponse.ApplyError, + }).Warn(codes.SyncApplyError, "cluster.SyncApply announce myself") + } }(client.declaration) } client.leaderState = leaderState{ diff --git a/cluster/const.go b/cluster/const.go index 28bfa28..bc8b045 100644 --- a/cluster/const.go +++ b/cluster/const.go @@ -3,7 +3,6 @@ package cluster import ( "bytes" "encoding/binary" - "encoding/json" "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" "isp-config-service/codes" @@ -14,11 +13,13 @@ const ( TokenParam = "token" ClusterParam = "cluster" + Ok = "ok" ) const ( _ = iota UpdateBackendDeclarationCommand DeleteBackendDeclarationCommand + ModuleConnectedCommand ) func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { @@ -29,6 +30,10 @@ func PrepareDeleteBackendDeclarationCommand(backend structure.BackendDeclaration return prepareCommand(DeleteBackendDeclarationCommand, backend) } +func PrepareModuleConnectedCommand(moduleName string) []byte { + return prepareCommand(ModuleConnectedCommand, ModuleConnected{ModuleName: moduleName}) +} + func prepareCommand(command uint64, payload interface{}) []byte { cmd := make([]byte, 8) binary.BigEndian.PutUint64(cmd, command) diff --git a/cluster/events.go b/cluster/events.go new file mode 100644 index 0000000..4959df7 --- /dev/null +++ b/cluster/events.go @@ -0,0 +1,14 @@ +package cluster + +type ModuleConnected struct { + ModuleName string +} + +type ApplyLogResponse struct { + ApplyError string + Comment string +} + +func (a ApplyLogResponse) Error() string { + return a.ApplyError +} diff --git a/cluster/leader_client.go b/cluster/leader_client.go index 569c2e2..fce1761 100644 --- a/cluster/leader_client.go +++ b/cluster/leader_client.go @@ -1,7 +1,6 @@ package cluster import ( - "encoding/json" "errors" "github.com/cenkalti/backoff" gosocketio "github.com/integration-system/golang-socketio" @@ -92,7 +91,10 @@ func getSocketIoUrl(address string) string { //} // return gosocketio.GetUrl(addr.IP.String(), port, false, map[string]string{ - ClusterParam: "true", + ClusterParam: "true", + "module_name": cfg.ModuleName, + // TODO вынести ключи в константы в isp-lib и выпилить instance_uuid + "instance_uuid": "9d89354b-c728-4b48-b002-a7d3b229f151", }) } diff --git a/codes/codes.go b/codes/codes.go index 69f2a04..4fc42fb 100644 --- a/codes/codes.go +++ b/codes/codes.go @@ -7,7 +7,10 @@ const ( ShutdownHttpServerError = 0 ShutdownHttpServerInfo = 0 - SocketIoError = 0 + SocketIoError = 0 + SocketIoEmitError = 0 + + DatabaseOperationError = 0 // Raft InitRaftError = 0 diff --git a/entity/module.go b/entity/module.go index a1463e3..aacb324 100644 --- a/entity/module.go +++ b/entity/module.go @@ -6,7 +6,6 @@ type Module struct { tableName string `sql:"?db_schema.modules" json:"-"` Id string `json:"id" valid:"required~Required"` Name string `json:"name" valid:"required~Required"` - Active bool `json:"active" sql:"-"` CreatedAt time.Time `json:"createdAt" sql:",null"` LastConnectedAt time.Time `json:"lastConnectedAt"` LastDisconnectedAt time.Time `json:"lastDisconnectedAt"` diff --git a/migrations/00007_2019-10-08_init_v2.sql b/migrations/00007_2019-10-08_init_v2.sql index c87d657..9a1d052 100644 --- a/migrations/00007_2019-10-08_init_v2.sql +++ b/migrations/00007_2019-10-08_init_v2.sql @@ -19,7 +19,9 @@ ALTER TABLE config_schemas ALTER COLUMN id TYPE varchar(255); ALTER TABLE modules - ALTER COLUMN id TYPE varchar(255); + ALTER COLUMN id TYPE varchar(255), + DROP COLUMN active, + DROP COLUMN instance_id; -- Constraints @@ -40,7 +42,6 @@ CREATE TABLE common_configs name VARCHAR(255) NOT NULL DEFAULT 'unnamed', description TEXT, version int4 NOT NULL, - active bool NOT NULL DEFAULT false, 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 '{}' diff --git a/service/clusterstate.go b/service/clusterstate.go index 3af94aa..47ad7c2 100644 --- a/service/clusterstate.go +++ b/service/clusterstate.go @@ -2,6 +2,11 @@ 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/holder" + "isp-config-service/model" "isp-config-service/store/state" ) @@ -11,7 +16,7 @@ var ( type clusterStateService struct{} -func (l clusterStateService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { +func (clusterStateService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { changed := state.UpsertBackend(declaration) if changed { DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) @@ -20,11 +25,29 @@ func (l clusterStateService) HandleUpdateBackendDeclarationCommand(declaration s return state, nil } -func (l clusterStateService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { +func (clusterStateService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { deleted := state.DeleteBackend(declaration) if deleted { DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) RoutesService.BroadcastRoutes(state) + module := state.UpdateModuleLastDisconnected(declaration.ModuleName) + if holder.ClusterClient.IsLeader() { + _, err := model.ModuleRep.Upsert(module) + if err != nil { + log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err) + } + } + } + return state, nil +} + +func (clusterStateService) HandleModuleConnectedCommand(moduleConnected cluster.ModuleConnected, state state.State) (state.State, error) { + module := state.UpdateModuleLastConnected(moduleConnected.ModuleName) + if holder.ClusterClient.IsLeader() { + _, err := model.ModuleRep.Upsert(module) + if err != nil { + log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err) + } } return state, nil } diff --git a/store/apply.go b/store/apply.go index c143fb3..d38bb1a 100644 --- a/store/apply.go +++ b/store/apply.go @@ -3,6 +3,7 @@ package store import ( "fmt" "github.com/integration-system/isp-lib/structure" + "isp-config-service/cluster" "isp-config-service/service" ) @@ -33,3 +34,17 @@ func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) error { s.state = state return nil } + +func (s *Store) applyModuleConnectedCommand(data []byte) error { + moduleConnected := cluster.ModuleConnected{} + err := json.Unmarshal(data, &moduleConnected) + if err != nil { + return fmt.Errorf("ModuleConnectedCommand: %w", err) + } + state, err := service.ClusterStateService.HandleModuleConnectedCommand(moduleConnected, s.state) + if err != nil { + return err + } + s.state = state + return nil +} diff --git a/store/state/common_config.go b/store/state/common_config.go index 9256d16..84f4f47 100644 --- a/store/state/common_config.go +++ b/store/state/common_config.go @@ -14,9 +14,18 @@ func (cs *CommonConfigStore) Delete(config entity.CommonConfig) { // TODO } -func (cs *CommonConfigStore) GetById(id int64) (*entity.CommonConfig, error) { - // TODO - return nil, nil +func (cs *CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig { + if len(ids) == 0 { + return nil + } + idsMap := StringsToMap(ids) + configs := make([]entity.CommonConfig, 0, len(ids)) + for _, config := range cs.configs { + if _, found := idsMap[config.Id]; found { + configs = append(configs, config) + } + } + return configs } func NewCommonConfigStore() *CommonConfigStore { diff --git a/store/state/configs.go b/store/state/configs.go index 42c0e9d..e8b486d 100644 --- a/store/state/configs.go +++ b/store/state/configs.go @@ -1,6 +1,9 @@ package state -import "isp-config-service/entity" +import ( + "fmt" + "isp-config-service/entity" +) type ConfigStore struct { configs []entity.Config @@ -18,9 +21,13 @@ func (cs *ConfigStore) Activate(config entity.Config) { // TODO } -func (cs *ConfigStore) GetByModuleName(moduleName string) (*entity.Config, error) { - // TODO - return nil, nil +func (cs *ConfigStore) GetActiveByModuleId(moduleId string) (*entity.Config, error) { + for _, conf := range cs.configs { + if conf.ModuleId == moduleId && conf.Active { + return &conf, nil + } + } + return nil, fmt.Errorf("no active configs for moduleId %s", moduleId) } func (cs *ConfigStore) GetById(id int64) (*entity.Config, error) { diff --git a/store/state/modules.go b/store/state/modules.go index c51e6a5..18dfd52 100644 --- a/store/state/modules.go +++ b/store/state/modules.go @@ -1,18 +1,30 @@ package state -import "isp-config-service/entity" +import ( + "fmt" + "isp-config-service/entity" + "time" +) type ModuleStore struct { modules []entity.Module } -func (ms *ModuleStore) Upsert(module entity.Module) { - // TODO +func (ms *ModuleStore) Update(module entity.Module) { + for i := range ms.modules { + if ms.modules[i].Id == module.Id { + ms.modules[i] = module + } + } } func (ms *ModuleStore) GetByName(name string) (*entity.Module, error) { - // TODO - return nil, nil + for _, module := range ms.modules { + if module.Name == name { + return &module, nil + } + } + return nil, fmt.Errorf("unknown module name %s", name) } func (ms *ModuleStore) GetById(id int32) (*entity.Module, error) { @@ -20,9 +32,16 @@ func (ms *ModuleStore) GetById(id int32) (*entity.Module, error) { return nil, nil } -func (ms *ModuleStore) GetActiveModules() ([]entity.Module, error) { - // TODO - return nil, nil +func (ms *ModuleStore) Create(name string) entity.Module { + module := entity.Module{ + Id: GenerateId(), + Name: name, + CreatedAt: time.Now(), + LastConnectedAt: time.Now(), + LastDisconnectedAt: time.Time{}, + } + ms.modules = append(ms.modules, module) + return module } func NewModuleStore() *ModuleStore { diff --git a/store/state/state.go b/store/state/state.go index 4f335ae..8d92ebe 100644 --- a/store/state/state.go +++ b/store/state/state.go @@ -3,6 +3,7 @@ package state import ( "github.com/integration-system/isp-lib/structure" "isp-config-service/entity" + "time" ) type State struct { @@ -18,6 +19,7 @@ type ReadState interface { GetModuleAddresses(moduleName string) []structure.AddressConfiguration GetRoutes() structure.RoutingConfig BackendExist(backend structure.BackendDeclaration) (exist bool) + GetCompiledConfig(moduleName string) (map[string]interface{}, error) } func NewState() State { @@ -63,3 +65,45 @@ func (s *State) DeleteBackend(backend structure.BackendDeclaration) (deleted boo func (s State) BackendExist(backend structure.BackendDeclaration) (exist bool) { return s.mesh.BackendExist(backend) } + +func (s State) GetCompiledConfig(moduleName string) (map[string]interface{}, error) { + module, err := s.modules.GetByName(moduleName) + if err != nil { + return nil, err + } + config, err := s.configs.GetActiveByModuleId(module.Id) + if err != nil { + return nil, err + } + commonConfigs := s.commonConfigs.GetByIds(config.CommonConfigs) + configsToMerge := make([]map[string]interface{}, 0, len(commonConfigs)) + for _, common := range commonConfigs { + configsToMerge = append(configsToMerge, common.Data) + } + configsToMerge = append(configsToMerge, config.Data) + + resultData := MergeNestedMaps(configsToMerge...) + return resultData, nil +} + +func (s State) UpdateModuleLastConnected(moduleName string) entity.Module { + existedModule, err := s.modules.GetByName(moduleName) + if err != nil { + module := s.modules.Create(moduleName) + return module + } + existedModule.LastConnectedAt = time.Now() + s.modules.Update(*existedModule) + return *existedModule +} + +func (s State) UpdateModuleLastDisconnected(moduleName string) entity.Module { + existedModule, err := s.modules.GetByName(moduleName) + if err != nil { + module := s.modules.Create(moduleName) + return module + } + existedModule.LastDisconnectedAt = time.Now() + s.modules.Update(*existedModule) + return *existedModule +} diff --git a/store/state/utils.go b/store/state/utils.go new file mode 100644 index 0000000..c6dbc06 --- /dev/null +++ b/store/state/utils.go @@ -0,0 +1,33 @@ +package state + +import ( + "github.com/integration-system/bellows" + uuid "github.com/satori/go.uuid" +) + +func StringsToMap(list []string) map[string]struct{} { + newMap := make(map[string]struct{}, len(list)) + for _, x := range list { + newMap[x] = struct{}{} + } + return newMap +} + +func MergeNestedMaps(maps ...map[string]interface{}) map[string]interface{} { + if len(maps) == 1 { + return maps[0] + } + result := bellows.Flatten(maps[0]) + for i := 1; i < len(maps); i++ { + newFlatten := bellows.Flatten(maps[i]) + for k, v := range newFlatten { + result[k] = v + } + } + return bellows.Expand(result).(map[string]interface{}) +} + +func GenerateId() string { + uuidV4 := uuid.NewV4() + return uuidV4.String() +} diff --git a/store/store.go b/store/store.go index e3b006e..039f0e2 100644 --- a/store/store.go +++ b/store/store.go @@ -25,6 +25,7 @@ type Store struct { } func (s *Store) Apply(l *raft.Log) interface{} { + var returnError error s.lock.Lock() defer s.lock.Unlock() if len(l.Data) < 8 { @@ -34,12 +35,17 @@ func (s *Store) Apply(l *raft.Log) interface{} { if handler, ok := s.handlers[command]; ok { err := handler(l.Data[8:]) if err != nil { - log.Fatalf(codes.ApplyLogCommandError, "apply log command: %v", err) + returnError = err } } else { log.Fatalf(codes.ApplyLogCommandError, "unknown log command %s", command) } - return nil + + var logResponse cluster.ApplyLogResponse + if returnError != nil { + logResponse.ApplyError = returnError.Error() + } + return logResponse } func (s *Store) Snapshot() (raft.FSMSnapshot, error) { @@ -105,6 +111,7 @@ func NewStateStore(st state.State) *Store { store.handlers = map[uint64]func([]byte) error{ cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand, cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand, + cluster.ModuleConnectedCommand: store.applyModuleConnectedCommand, } return store } diff --git a/subs/client.go b/subs/client.go index 2f547ca..60bcbe1 100644 --- a/subs/client.go +++ b/subs/client.go @@ -1,7 +1,6 @@ package subs import ( - "encoding/json" "github.com/asaskevich/govalidator" "github.com/integration-system/isp-lib/bootstrap" "github.com/integration-system/isp-lib/structure" @@ -31,18 +30,23 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string }) if changed { command := cluster.PrepareUpdateBackendDeclarationCommand(declaration) - i, err := h.cluster.SyncApply(command) + applyLogResponse, err := h.cluster.SyncApply(command) if err != nil { + return err.Error() + } + if applyLogResponse.ApplyError != "" { log.WithMetadata(map[string]interface{}{ - "answer": i, - }).Warnf(codes.SyncApplyError, "apply UpdateBackendDeclarationCommand %v", err) + "comment": applyLogResponse.Comment, + "applyError": applyLogResponse.ApplyError, + "commandName": "UpdateBackendDeclarationCommand", + }).Warn(codes.SyncApplyError, "apply command") + return applyLogResponse.ApplyError } } return Ok } func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) string { - moduleName, err := conn.Parameters() log.Debugf(0, "handleModuleRequirements moduleName: %s", moduleName) // REMOVE if err != nil { diff --git a/subs/cluster.go b/subs/cluster.go index 4ed7b95..15deaf7 100644 --- a/subs/cluster.go +++ b/subs/cluster.go @@ -1,13 +1,26 @@ package subs import ( + log "github.com/integration-system/isp-log" + "isp-config-service/cluster" + "isp-config-service/codes" "isp-config-service/ws" ) func (h *socketEventHandler) applyCommandOnLeader(conn ws.Conn, cmd []byte) string { - _, err := h.cluster.SyncApplyOnLeader(cmd) + obj, err := h.cluster.SyncApplyOnLeader(cmd) if err != nil { - return err.Error() + var logResponse cluster.ApplyLogResponse + logResponse.ApplyError = err.Error() + data, err := json.Marshal(obj) + if err != nil { + log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err) + } + return string(data) } - return Ok + data, err := json.Marshal(obj) + if err != nil { + log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err) + } + return string(data) } diff --git a/subs/helpers.go b/subs/helpers.go new file mode 100644 index 0000000..efe2e09 --- /dev/null +++ b/subs/helpers.go @@ -0,0 +1,30 @@ +package subs + +import ( + log "github.com/integration-system/isp-log" + "isp-config-service/codes" + "isp-config-service/ws" +) + +func EmitConn(conn ws.Conn, event string, args ...interface{}) { + err := conn.Emit(event, args...) + if err != nil { + log.WithMetadata(map[string]interface{}{ + "event": event, + }).Warnf(codes.SocketIoEmitError, "emit err %v", err) + } +} + +func (h *socketEventHandler) SyncApplyCommand(command []byte, commandName string) { + applyLogResponse, err := h.cluster.SyncApply(command) + if err != nil { + log.Warnf(codes.SyncApplyError, "apply %s: %v", commandName, err) + } + if applyLogResponse != nil && applyLogResponse.ApplyError != "" { + log.WithMetadata(map[string]interface{}{ + "comment": applyLogResponse.Comment, + "applyError": applyLogResponse.ApplyError, + "commandName": commandName, + }).Warnf(codes.SyncApplyError, "apply command") + } +} diff --git a/subs/root.go b/subs/root.go index dd7a5bd..65d0391 100644 --- a/subs/root.go +++ b/subs/root.go @@ -3,11 +3,13 @@ package subs import ( "github.com/integration-system/isp-lib/utils" log "github.com/integration-system/isp-log" + jsoniter "github.com/json-iterator/go" "isp-config-service/cluster" "isp-config-service/codes" "isp-config-service/holder" "isp-config-service/service" "isp-config-service/store" + "isp-config-service/store/state" "isp-config-service/ws" ) @@ -16,6 +18,10 @@ const ( followersRoom = "followers" ) +var ( + json = jsoniter.ConfigFastest +) + type socketEventHandler struct { socket *ws.WebsocketServer cluster *cluster.ClusterClient @@ -35,9 +41,29 @@ func (h *socketEventHandler) SubscribeAll() { func (h *socketEventHandler) handleConnect(conn ws.Conn) { if conn.IsConfigClusterNode() { holder.Socket.Rooms().Join(conn, followersRoom) - } else { - } + moduleName, err := conn.Parameters() + if err != nil { + EmitConn(conn, utils.ErrorConnection, err.Error()) + return + } + command := cluster.PrepareModuleConnectedCommand(moduleName) + h.SyncApplyCommand(command, "ModuleConnectedCommand") + + var config map[string]interface{} + h.store.VisitReadState(func(state state.ReadState) { + config, err = state.GetCompiledConfig(moduleName) + }) + if err != nil { + EmitConn(conn, utils.ConfigError, err.Error()) + return + } + data, err := json.Marshal(config) + if err != nil { + EmitConn(conn, utils.ConfigError, err.Error()) + return + } + EmitConn(conn, utils.ConfigSendConfigWhenConnected, string(data)) } func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { @@ -49,12 +75,7 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { backend := conn.GetBackendDeclaration() if backend != nil { command := cluster.PrepareDeleteBackendDeclarationCommand(*backend) - i, err := h.cluster.SyncApply(command) - if err != nil { - log.WithMetadata(map[string]interface{}{ - "answer": i, - }).Warnf(codes.SyncApplyError, "apply DeleteBackendDeclarationCommand %v", err) - } + h.SyncApplyCommand(command, "ModuleConnectedCommand") } }