From c3e95fa98c915828260d46b14384c2a7977fadd2 Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Wed, 4 Sep 2019 13:55:07 +0300 Subject: [PATCH 1/8] done #1 --- cluster/client.go | 2 +- cluster/const.go | 5 ++ cluster/leader_client.go | 12 ++-- main.go | 19 +++--- service/applylog.go | 35 +++++++++++ service/discovery.go | 122 +++++++++++++++++++++++++++++++++++++++ state/mesh.go | 32 ---------- state/state.go | 11 ---- state/store.go | 81 -------------------------- store/apply.go | 22 +++++++ store/state/mesh.go | 91 +++++++++++++++++++++++++++++ store/state/state.go | 30 ++++++++++ store/store.go | 102 ++++++++++++++++++++++++++++++++ subs/client.go | 58 ++++++++++++++++++- subs/root.go | 15 +++-- ws/conn.go | 6 ++ ws/room.go | 14 +++-- ws/server.go | 4 +- 18 files changed, 509 insertions(+), 152 deletions(-) create mode 100644 service/applylog.go create mode 100644 service/discovery.go delete mode 100644 state/mesh.go delete mode 100644 state/state.go delete mode 100644 state/store.go create mode 100644 store/apply.go create mode 100644 store/state/mesh.go create mode 100644 store/state/state.go create mode 100644 store/store.go diff --git a/cluster/client.go b/cluster/client.go index 32f3c61..9311870 100644 --- a/cluster/client.go +++ b/cluster/client.go @@ -70,7 +70,7 @@ func (client *ClusterClient) SyncApplyOnLeader(command []byte) (interface{}, err func (client *ClusterClient) listenLeader() { for n := range client.r.LeaderCh() { - logger.Debug(n) + logger.Debug("ChangeLeaderNotification:", n) client.leaderMu.Lock() if client.leaderState.leaderAddr != n.CurrentLeaderAddress { diff --git a/cluster/const.go b/cluster/const.go index 2247d02..a922757 100644 --- a/cluster/const.go +++ b/cluster/const.go @@ -6,3 +6,8 @@ const ( TokenParam = "token" ClusterParam = "cluster" ) +const ( + _ = iota + BackendDeclarationCommand + ConfigSchemaCommand +) diff --git a/cluster/leader_client.go b/cluster/leader_client.go index dcfd9e7..33bd145 100644 --- a/cluster/leader_client.go +++ b/cluster/leader_client.go @@ -3,8 +3,11 @@ package cluster import ( "github.com/cenkalti/backoff" gosocketio "github.com/integration-system/golang-socketio" + "github.com/integration-system/isp-lib/config" "github.com/integration-system/isp-lib/logger" + "isp-config-service/conf" "net" + "strconv" "time" ) @@ -46,14 +49,13 @@ func getSocketIoUrl(address string) string { panic(err) //must never occured } - /*cfg := config.Get().(*conf.Configuration) + cfg := config.Get().(*conf.Configuration) port, err := strconv.Atoi(cfg.WS.Rest.Port) if err != nil { panic(err) - }*/ - - return gosocketio.GetUrl(addr.IP.String(), 9001, false, map[string]string{ + } + return gosocketio.GetUrl(addr.IP.String(), port, false, map[string]string{ ClusterParam: "true", - }) //TODO for test + }) } diff --git a/main.go b/main.go index 1f2bde0..e058b6f 100644 --- a/main.go +++ b/main.go @@ -12,7 +12,7 @@ import ( "isp-config-service/helper" "isp-config-service/holder" "isp-config-service/raft" - "isp-config-service/state" + "isp-config-service/store" "isp-config-service/subs" "isp-config-service/ws" "net/http" @@ -49,12 +49,12 @@ func main() { <-shutdownChan } -func initWebsocket(bindAddress string, clusterClint *cluster.ClusterClient, store *state.Store) { +func initWebsocket(bindAddress string, clusterClient *cluster.ClusterClient, store *store.Store) { socket, err := ws.NewWebsocketServer() if err != nil { logger.Fatal(err) } - subs.NewSocketEventHandler(socket, clusterClint, store).SubscribeAll() + subs.NewSocketEventHandler(socket, clusterClient, store).SubscribeAll() mux := http.NewServeMux() mux.HandleFunc("/socket.io/", socket.ServeHttp) @@ -70,8 +70,8 @@ func initWebsocket(bindAddress string, clusterClint *cluster.ClusterClient, stor logger.Infof("socket.IO server start on %s", bindAddress) } -func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration) (*cluster.ClusterClient, *state.Store) { - store := state.NewStateStore() +func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration) (*cluster.ClusterClient, *store.Store) { + store := store.NewStateStore() r, err := raft.NewRaft(bindAddress, clusterCfg, store) if err != nil { logger.Fatal(err) @@ -79,7 +79,10 @@ func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration) (*cluste clusterClient := cluster.NewRaftClusterClient(r) holder.ClusterClient = clusterClient - _ = r.BootstrapCluster() // err can be ignored + err = r.BootstrapCluster() // err can be ignored + if err != nil { + logger.Error("BootstrapCluster err:", err) + } logger.Infof("raft server start on %s", bindAddress) @@ -103,13 +106,13 @@ func onShutdown(ctx context.Context, sig os.Signal) { } if err := holder.Socket.Close(); err != nil { - logger.Info("socket.io shutdown err: %v", err) + logger.Warnf("socket.io shutdown err: %v", err) } else { logger.Info("socket.io shutdown success") } if err := holder.HttpServer.Shutdown(ctx); err != nil { - logger.Info("http server shutdown err: %v", err) + logger.Warnf("http server shutdown err: %v", err) } else { logger.Info("http server shutdown success") } diff --git a/service/applylog.go b/service/applylog.go new file mode 100644 index 0000000..b500959 --- /dev/null +++ b/service/applylog.go @@ -0,0 +1,35 @@ +package service + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" + "isp-config-service/cluster" + "isp-config-service/store/state" +) + +var ApplyLogService applyLogService + +type applyLogService struct{} + +func (l applyLogService) HandleBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { + state.UpsertBackend(declaration) + logger.Debug("HandleBackendDeclarationCommand: upserted backend", declaration.ModuleName) + DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) + DiscoveryService.BroadcastRoutes(state) + return state, nil +} + +func (l applyLogService) PrepareBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { + var buf bytes.Buffer + buf2 := make([]byte, 8) + binary.BigEndian.PutUint64(buf2, cluster.BackendDeclarationCommand) + buf.Write(buf2) + err := json.NewEncoder(&buf).Encode(backend) + if err != nil { + logger.Fatal("PrepareBackendDeclarationCommand json encoding", err) + } + return buf.Bytes() +} diff --git a/service/discovery.go b/service/discovery.go new file mode 100644 index 0000000..9f1f958 --- /dev/null +++ b/service/discovery.go @@ -0,0 +1,122 @@ +package service + +import ( + "encoding/json" + "github.com/cenkalti/backoff" + "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" + "github.com/integration-system/isp-lib/utils" + "isp-config-service/holder" + "isp-config-service/store/state" + "isp-config-service/ws" + "sync" + "time" +) + +var DiscoveryService = NewDiscoveryService() + +var RoutesSubscribersRoom = "__routesSubscribers" + +type discoveryService struct { + subs map[string][]string + lock sync.RWMutex +} + +func (ds *discoveryService) HandleDisconnect(connId string) { + ds.lock.Lock() + defer ds.lock.Unlock() + if events, ok := ds.subs[connId]; ok { + holder.Socket.Rooms().LeaveByConnId(connId, events...) + delete(ds.subs, connId) + } + holder.Socket.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom) +} + +func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state.State) { + if len(events) == 0 { + return + } + ds.lock.Lock() + defer ds.lock.Unlock() + ds.subs[conn.Id()] = events + holder.Socket.Rooms().Join(conn, events...) + for _, event := range events { + addressList := state.GetModuleAddresses(event) + ds.sendAddrList(conn, event, addressList) + } +} + +func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, state state.State) { + ds.lock.RLock() + defer ds.lock.RUnlock() + event := utils.ModuleConnected(moduleName) + addressList := state.GetModuleAddresses(moduleName) + ds.broadcastAddrList(moduleName, event, addressList) +} + +func (ds *discoveryService) broadcastAddrList(moduleName string, event string, addressList []structure.AddressConfiguration) { + if bytes, err := json.Marshal(addressList); err != nil { + logger.Warn(err) + } else { + err = holder.Socket.Broadcast(moduleName, event, string(bytes)) + if err != nil { + logger.Error(err) + } + } +} + +func (ds *discoveryService) sendAddrList(conn ws.Conn, event string, addressList []structure.AddressConfiguration) { + if bytes, err := json.Marshal(addressList); err != nil { + logger.Warn(err) + } else { + bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3) + err := backoff.Retry(func() error { + return conn.Emit(event, string(bytes)) + }, bf) + if err != nil { + logger.Error(err) + } + } +} + +func (ds *discoveryService) SubscribeRoutes(conn ws.Conn, state state.State) { + holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom) + routes := state.GetRoutes() + ds.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes) +} + +func (ds *discoveryService) BroadcastRoutes(state state.State) { + routes := state.GetRoutes() + ds.broadcastRoutes(utils.ConfigSendRoutesChanged, routes) +} + +func (ds *discoveryService) broadcastRoutes(event string, routes structure.RoutingConfig) { + if bytes, err := json.Marshal(routes); err != nil { + logger.Warn(err) + } else { + err = holder.Socket.Broadcast(RoutesSubscribersRoom, event, string(bytes)) + if err != nil { + logger.Error(err) + } + } +} + +func (ds *discoveryService) sendRoutes(conn ws.Conn, event string, routes structure.RoutingConfig) { + if bytes, err := json.Marshal(routes); err != nil { + logger.Warn(err) + } else { + bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3) + err := backoff.Retry(func() error { + return conn.Emit(event, string(bytes)) + }, bf) + if err != nil { + logger.Error(err) + } + } +} + +func NewDiscoveryService() *discoveryService { + return &discoveryService{ + subs: make(map[string][]string), + } +} diff --git a/state/mesh.go b/state/mesh.go deleted file mode 100644 index 22b7364..0000000 --- a/state/mesh.go +++ /dev/null @@ -1,32 +0,0 @@ -package state - -import "github.com/integration-system/isp-lib/structure" - -type Mesh struct { - modulesMap map[string]NodesMap -} - -func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) { - address := backend.Address.GetAddress() - if nodes, ok := m.modulesMap[backend.ModuleName]; ok { - nodes[address] = backend - } else { - m.modulesMap[backend.ModuleName] = NodesMap{address: backend} - } -} - -func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) { - address := backend.Address.GetAddress() - if nodes, ok := m.modulesMap[backend.ModuleName]; ok { - delete(nodes, address) - if len(nodes) == 0 { - delete(m.modulesMap, backend.ModuleName) - } - } -} - -type NodesMap map[string]structure.BackendDeclaration - -func NewMesh() *Mesh { - return &Mesh{modulesMap: make(map[string]NodesMap)} -} diff --git a/state/state.go b/state/state.go deleted file mode 100644 index 3ada0ca..0000000 --- a/state/state.go +++ /dev/null @@ -1,11 +0,0 @@ -package state - -type state struct { - mesh *Mesh -} - -func newState() state { - return state{ - mesh: NewMesh(), - } -} diff --git a/state/store.go b/state/store.go deleted file mode 100644 index ae3505b..0000000 --- a/state/store.go +++ /dev/null @@ -1,81 +0,0 @@ -package state - -import ( - "github.com/hashicorp/raft" - jsoniter "github.com/json-iterator/go" - "github.com/mohae/deepcopy" - "github.com/pkg/errors" - "io" - "sync" -) - -var ( - json = jsoniter.ConfigFastest -) - -type Store struct { - state state - lock sync.Mutex -} - -func (f *Store) Apply(l *raft.Log) interface{} { - f.lock.Lock() - defer f.lock.Unlock() - return nil -} - -// Snapshot returns a snapshot of the key-value store. -func (f *Store) Snapshot() (raft.FSMSnapshot, error) { - f.lock.Lock() - defer f.lock.Unlock() - - copied := deepcopy.Copy(f.state).(state) - - return &fsmSnapshot{copied}, nil -} - -// Restore stores the key-value store to a previous state. -func (f *Store) Restore(rc io.ReadCloser) error { - s := state{} - - if err := json.NewDecoder(rc).Decode(&s); err != nil { - return errors.WithMessage(err, "unmarshal state") - } - - f.state = s - - return nil -} - -type fsmSnapshot struct { - state state -} - -func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error { - err := func() error { - b, err := json.Marshal(f.state) - if err != nil { - return err - } - - if _, err := sink.Write(b); err != nil { - return err - } - - return sink.Close() - }() - - if err != nil { - _ = sink.Cancel() - } - - return err -} - -func (f *fsmSnapshot) Release() {} - -func NewStateStore() *Store { - return &Store{ - state: newState(), - } -} diff --git a/store/apply.go b/store/apply.go new file mode 100644 index 0000000..e5fc538 --- /dev/null +++ b/store/apply.go @@ -0,0 +1,22 @@ +package store + +import ( + "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" + "isp-config-service/service" +) + +func (s *Store) applyBackendDeclarationCommand(data []byte) error { + declaration := structure.BackendDeclaration{} + err := json.Unmarshal(data, &declaration) + if err != nil { + logger.Warnf("Store.applyBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) + return err + } + state, err := service.ApplyLogService.HandleBackendDeclarationCommand(declaration, s.state) + if err != nil { + return err + } + s.state = state + return nil +} diff --git a/store/state/mesh.go b/store/state/mesh.go new file mode 100644 index 0000000..a1d00f1 --- /dev/null +++ b/store/state/mesh.go @@ -0,0 +1,91 @@ +package state + +import "github.com/integration-system/isp-lib/structure" + +type Mesh struct { + // { "ModuleName": { "address": BackendDeclaration, ...}, ... } + modulesMap map[string]NodesMap +} + +func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool) { + address := backend.Address.GetAddress() + if nodes, ok := m.modulesMap[backend.ModuleName]; ok { + if oldBackend, ok := nodes[address]; ok { + if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion { + nodes[address] = backend + changed = true + } + } else { + nodes[address] = backend + changed = true + } + } else { + m.modulesMap[backend.ModuleName] = NodesMap{address: backend} + changed = true + } + return +} + +func (m *Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) { + address := backend.Address.GetAddress() + if nodes, ok := m.modulesMap[backend.ModuleName]; ok { + if oldBackend, ok := nodes[address]; ok { + if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion { + changed = true + } + } else { + changed = true + } + } else { + changed = true + } + return +} + +func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (changed bool) { + address := backend.Address.GetAddress() + if nodes, ok := m.modulesMap[backend.ModuleName]; ok { + changed = true + delete(nodes, address) + if len(nodes) == 0 { + delete(m.modulesMap, backend.ModuleName) + } + } + return +} + +func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { + if nodes, ok := m.modulesMap[backend.ModuleName]; ok { + exist = true + if len(nodes) == 0 { + delete(m.modulesMap, backend.ModuleName) + } + } + return +} + +func (m *Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration { + addressList := []structure.AddressConfiguration{} + if nodes, ok := m.modulesMap[moduleName]; ok { + for _, backend := range nodes { + addressList = append(addressList, backend.Address) + } + } + return addressList +} + +func (m *Mesh) GetRoutes() structure.RoutingConfig { + routes := structure.RoutingConfig{} + for _, node := range m.modulesMap { + for _, backend := range node { + routes = append(routes, backend) + } + } + return routes +} + +type NodesMap map[string]structure.BackendDeclaration + +func NewMesh() *Mesh { + return &Mesh{modulesMap: make(map[string]NodesMap)} +} diff --git a/store/state/state.go b/store/state/state.go new file mode 100644 index 0000000..98951c3 --- /dev/null +++ b/store/state/state.go @@ -0,0 +1,30 @@ +package state + +import ( + "github.com/integration-system/isp-lib/structure" +) + +type State struct { + mesh *Mesh +} + +func NewState() State { + return State{ + mesh: NewMesh(), + } +} +func (s *State) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) { + return s.mesh.CheckBackendChanged(backend) +} + +func (s *State) UpsertBackend(backend structure.BackendDeclaration) (changed bool) { + return s.mesh.UpsertBackend(backend) +} + +func (s *State) GetModuleAddresses(moduleName string) []structure.AddressConfiguration { + return s.mesh.GetModuleAddresses(moduleName) +} + +func (s *State) GetRoutes() structure.RoutingConfig { + return s.mesh.GetRoutes() +} diff --git a/store/store.go b/store/store.go new file mode 100644 index 0000000..73024fc --- /dev/null +++ b/store/store.go @@ -0,0 +1,102 @@ +package store + +import ( + "encoding/binary" + "github.com/hashicorp/raft" + "github.com/integration-system/isp-lib/logger" + jsoniter "github.com/json-iterator/go" + "github.com/mohae/deepcopy" + "github.com/pkg/errors" + "io" + "isp-config-service/cluster" + "isp-config-service/store/state" + "sync" +) + +var ( + json = jsoniter.ConfigFastest +) + +type Store struct { + state state.State + lock sync.Mutex + handlers map[uint64]func([]byte) error +} + +func (s *Store) Apply(l *raft.Log) interface{} { + s.lock.Lock() + defer s.lock.Unlock() + if len(l.Data) < 8 { + logger.Fatal("Invalid log data command", l.Data) + } + command := binary.BigEndian.Uint64(l.Data[:8]) + if handler, ok := s.handlers[command]; ok { + err := handler(l.Data[8:]) + if err != nil { + logger.Fatal("error while applying log command", command, err) + } + } else { + logger.Fatal("Log command not found", command) + } + return nil +} + +func (s *Store) Snapshot() (raft.FSMSnapshot, error) { + s.lock.Lock() + defer s.lock.Unlock() + logger.Debug("Create snapshot") + + copied := deepcopy.Copy(s.state).(state.State) + return &fsmSnapshot{copied}, nil +} + +func (s *Store) Restore(rc io.ReadCloser) error { + state := state.State{} + logger.Debug("Try to restore snapshot") + if err := json.NewDecoder(rc).Decode(&state); err != nil { + return errors.WithMessage(err, "unmarshal store") + } + s.state = state + return nil +} + +func (s *Store) GetState() *state.State { + return &s.state +} + +type fsmSnapshot struct { + state state.State +} + +func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error { + err := func() error { + b, err := json.Marshal(f.state) + if err != nil { + return err + } + + if _, err := sink.Write(b); err != nil { + return err + } + + return sink.Close() + }() + + if err != nil { + _ = sink.Cancel() + } + + return err +} + +func (f *fsmSnapshot) Release() {} + +func NewStateStore() *Store { + store := &Store{ + state: state.NewState(), + } + store.handlers = map[uint64]func([]byte) error{ + cluster.BackendDeclarationCommand: store.applyBackendDeclarationCommand, + } + return store +} diff --git a/subs/client.go b/subs/client.go index 84a62cc..6942251 100644 --- a/subs/client.go +++ b/subs/client.go @@ -1,8 +1,42 @@ package subs -import "isp-config-service/ws" +import ( + "encoding/json" + "github.com/asaskevich/govalidator" + "github.com/integration-system/isp-lib/bootstrap" + "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" + "github.com/integration-system/isp-lib/utils" + "isp-config-service/service" + "isp-config-service/ws" +) func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) { + instanceUuid, moduleName, err := conn.Parameters() + logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE + if err != nil { + _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) + return + } + + declaration := structure.BackendDeclaration{} + err = json.Unmarshal(data, &declaration) + if err != nil { + _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) + logger.Warnf("handleModuleDeclaration: %s, error parse json data: %s", conn.Id(), err.Error()) + return + } + + _, err = govalidator.ValidateStruct(declaration) + if err != nil { + errors := govalidator.ErrorsByField(err) + _ = conn.Emit(utils.ErrorConnection, map[string]map[string]string{"error": errors}) + logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", conn.Id(), errors) + } else if h.store.GetState().CheckBackendChanged(declaration) { + // TODO h.store.GetState() locks + i, err := h.cluster.SyncApply(service.ApplyLogService.PrepareBackendDeclarationCommand(declaration)) + logger.Debug("cluster.SyncApply:", i, err) + } } @@ -11,7 +45,29 @@ func (h *socketEventHandler) handleRoutesUpdate(conn ws.Conn, data []byte) { } func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) { + logger.Debugf("onReceivedModuleRequirements: %s %s", conn.Id(), string(data)) + instanceUuid, moduleName, err := conn.Parameters() + logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE + if err != nil { + _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) + return + } + + declaration := bootstrap.ModuleRequirements{} + err = json.Unmarshal(data, &declaration) + if err != nil { + _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) + logger.Debugf("onReceivedModuleRequirements: %s, error parse json data: %s", conn.Id(), err.Error()) + return + } + + if declaration.RequireRoutes { + // TODO h.store.GetState() locks + service.DiscoveryService.SubscribeRoutes(conn, *h.store.GetState()) + } + // TODO h.store.GetState() locks + service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, *h.store.GetState()) } func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) { diff --git a/subs/root.go b/subs/root.go index 3616cb5..a85fd1d 100644 --- a/subs/root.go +++ b/subs/root.go @@ -2,9 +2,11 @@ package subs import ( "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/utils" "isp-config-service/cluster" "isp-config-service/holder" - "isp-config-service/state" + "isp-config-service/service" + "isp-config-service/store" "isp-config-service/ws" ) @@ -17,7 +19,7 @@ const ( type socketEventHandler struct { socket *ws.WebsocketServer cluster *cluster.ClusterClient - state *state.Store + store *store.Store } func (h *socketEventHandler) SubscribeAll() { @@ -25,7 +27,9 @@ func (h *socketEventHandler) SubscribeAll() { OnConnect(h.handleConnect). OnDisconnect(h.handleDisconnect). OnError(h.handleError). - OnWithAck(cluster.ApplyCommandEvent, h.applyCommandOnLeader) + OnWithAck(cluster.ApplyCommandEvent, h.applyCommandOnLeader). + On(utils.ModuleReady, h.handleModuleReady). + On(utils.ModuleSendRequirements, h.handleModuleRequirements) } func (h *socketEventHandler) handleConnect(conn ws.Conn) { @@ -40,16 +44,17 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { if conn.IsConfigClusterNode() { holder.Socket.Rooms().Leave(conn, followersRoom) } + service.DiscoveryService.HandleDisconnect(conn.Id()) } func (h *socketEventHandler) handleError(conn ws.Conn, err error) { logger.Warnf("socket.io: %v", err) } -func NewSocketEventHandler(socket *ws.WebsocketServer, cluster *cluster.ClusterClient, state *state.Store) *socketEventHandler { +func NewSocketEventHandler(socket *ws.WebsocketServer, cluster *cluster.ClusterClient, store *store.Store) *socketEventHandler { return &socketEventHandler{ socket: socket, cluster: cluster, - state: state, + store: store, } } diff --git a/ws/conn.go b/ws/conn.go index 9083bd6..f3b06b6 100644 --- a/ws/conn.go +++ b/ws/conn.go @@ -3,11 +3,13 @@ package ws import ( socketio "github.com/googollee/go-socket.io" "github.com/integration-system/isp-lib/structure" + "github.com/integration-system/isp-lib/utils" "isp-config-service/cluster" ) type Conn interface { Id() string + Parameters() (instanceUUID string, moduleName string, error error) Emit(event string, args ...interface{}) error IsConfigClusterNode() bool SetBackendDeclaration(backend structure.BackendDeclaration) @@ -19,6 +21,10 @@ type wsConn struct { backend *structure.BackendDeclaration } +func (c *wsConn) Parameters() (instanceUUID string, moduleName string, error error) { + return utils.ParseParameters(c.conn.Request().URL.RawQuery) +} + func (c *wsConn) Id() string { return c.conn.Id() } diff --git a/ws/room.go b/ws/room.go index 0613ced..18cebbe 100644 --- a/ws/room.go +++ b/ws/room.go @@ -60,12 +60,16 @@ func (s *RoomStore) Join(conn Conn, rooms ...string) { } func (s *RoomStore) Leave(conn Conn, rooms ...string) { + s.LeaveByConnId(conn.Id(), rooms...) +} + +func (s *RoomStore) LeaveByConnId(id string, rooms ...string) { s.mu.Lock() defer s.mu.Unlock() for _, room := range rooms { if conns, ok := s.rooms[room]; ok { - delete(conns, conn.Id()) + delete(conns, id) if len(conns) == 0 { delete(s.rooms, room) } @@ -73,17 +77,15 @@ func (s *RoomStore) Leave(conn Conn, rooms ...string) { } } -func (s *RoomStore) ToBroadcast(except Conn, rooms ...string) []Conn { +func (s *RoomStore) ToBroadcast(rooms ...string) []Conn { s.mu.RLock() defer s.mu.RUnlock() result := make([]Conn, 0) for _, room := range rooms { if conns, ok := s.rooms[room]; ok { - for id, conn := range conns { - if id != except.Id() { - result = append(result, conn) - } + for _, conn := range conns { + result = append(result, conn) } } } diff --git a/ws/server.go b/ws/server.go index 1fd0c3d..4494df5 100644 --- a/ws/server.go +++ b/ws/server.go @@ -71,8 +71,8 @@ func (s *WebsocketServer) OnError(f func(Conn, error)) *WebsocketServer { return s } -func (s *WebsocketServer) Broadcast(except Conn, room string, msg string, v ...interface{}) error { - conns := s.roomStore.ToBroadcast(except, room) +func (s *WebsocketServer) Broadcast(room string, msg string, v ...interface{}) error { + conns := s.roomStore.ToBroadcast(room) for _, conn := range conns { _ = conn.Emit(msg, v...) } From d678f28909a62df905056ceb6ba21832060d58c7 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Wed, 4 Sep 2019 14:45:21 +0300 Subject: [PATCH 2/8] add commnets --- service/applylog.go | 11 +++++++---- service/discovery.go | 11 ++++++++--- store/apply.go | 2 +- store/state/mesh.go | 4 ++-- store/store.go | 4 ++-- subs/client.go | 4 ++-- subs/root.go | 3 ++- 7 files changed, 24 insertions(+), 15 deletions(-) diff --git a/service/applylog.go b/service/applylog.go index b500959..b498f2f 100644 --- a/service/applylog.go +++ b/service/applylog.go @@ -10,11 +10,13 @@ import ( "isp-config-service/store/state" ) -var ApplyLogService applyLogService +var ( + ClusterStoreService clusterStoreService +) -type applyLogService struct{} +type clusterStoreService struct{} -func (l applyLogService) HandleBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { +func (l clusterStoreService) HandleBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { state.UpsertBackend(declaration) logger.Debug("HandleBackendDeclarationCommand: upserted backend", declaration.ModuleName) DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) @@ -22,7 +24,8 @@ func (l applyLogService) HandleBackendDeclarationCommand(declaration structure.B return state, nil } -func (l applyLogService) PrepareBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { +//TODO вынести как отдельную функция с парметрами вызова (int command, payload interface{}) ([]byte, error) для возможности переиспользования +func (l clusterStoreService) PrepareBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { var buf bytes.Buffer buf2 := make([]byte, 8) binary.BigEndian.PutUint64(buf2, cluster.BackendDeclarationCommand) diff --git a/service/discovery.go b/service/discovery.go index 9f1f958..fe8e7f7 100644 --- a/service/discovery.go +++ b/service/discovery.go @@ -13,16 +13,20 @@ import ( "time" ) -var DiscoveryService = NewDiscoveryService() +const ( + RoutesSubscribersRoom = "__routesSubscribers" +) -var RoutesSubscribersRoom = "__routesSubscribers" +var ( + DiscoveryService = NewDiscoveryService() +) type discoveryService struct { subs map[string][]string lock sync.RWMutex } -func (ds *discoveryService) HandleDisconnect(connId string) { +func (ds *discoveryService) HandleDisconnect(connId string) { //TODO где то передается целиком объект ws.Conn, привести к одному виду(думаю ws.Conn) ds.lock.Lock() defer ds.lock.Unlock() if events, ok := ds.subs[connId]; ok { @@ -79,6 +83,7 @@ func (ds *discoveryService) sendAddrList(conn ws.Conn, event string, addressList } } +//TODO вынесли логику работы с роутами в отдельный сервис func (ds *discoveryService) SubscribeRoutes(conn ws.Conn, state state.State) { holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom) routes := state.GetRoutes() diff --git a/store/apply.go b/store/apply.go index e5fc538..ca39bd5 100644 --- a/store/apply.go +++ b/store/apply.go @@ -13,7 +13,7 @@ func (s *Store) applyBackendDeclarationCommand(data []byte) error { logger.Warnf("Store.applyBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) return err } - state, err := service.ApplyLogService.HandleBackendDeclarationCommand(declaration, s.state) + state, err := service.ClusterStoreService.HandleBackendDeclarationCommand(declaration, s.state) if err != nil { return err } diff --git a/store/state/mesh.go b/store/state/mesh.go index a1d00f1..2f5c8f9 100644 --- a/store/state/mesh.go +++ b/store/state/mesh.go @@ -54,7 +54,7 @@ func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (changed bool return } -func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { +func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { //TODO используется ? if nodes, ok := m.modulesMap[backend.ModuleName]; ok { exist = true if len(nodes) == 0 { @@ -65,7 +65,7 @@ func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { } func (m *Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration { - addressList := []structure.AddressConfiguration{} + addressList := make([]structure.AddressConfiguration, 0) if nodes, ok := m.modulesMap[moduleName]; ok { for _, backend := range nodes { addressList = append(addressList, backend.Address) diff --git a/store/store.go b/store/store.go index 73024fc..28b2063 100644 --- a/store/store.go +++ b/store/store.go @@ -19,7 +19,7 @@ var ( type Store struct { state state.State - lock sync.Mutex + lock sync.Mutex //TODO RWMutex handlers map[uint64]func([]byte) error } @@ -60,7 +60,7 @@ func (s *Store) Restore(rc io.ReadCloser) error { return nil } -func (s *Store) GetState() *state.State { +func (s *Store) GetState() *state.State { //TODO почему указатель ? =), добавим функцию VisitState(f(state state)), попробуем с ней return &s.state } diff --git a/subs/client.go b/subs/client.go index 6942251..fedc817 100644 --- a/subs/client.go +++ b/subs/client.go @@ -15,7 +15,7 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) { instanceUuid, moduleName, err := conn.Parameters() logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE if err != nil { - _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) + _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) //эти штуки тогда убертся вовсе return } @@ -34,7 +34,7 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) { logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", conn.Id(), errors) } else if h.store.GetState().CheckBackendChanged(declaration) { // TODO h.store.GetState() locks - i, err := h.cluster.SyncApply(service.ApplyLogService.PrepareBackendDeclarationCommand(declaration)) + i, err := h.cluster.SyncApply(service.ClusterStoreService.PrepareBackendDeclarationCommand(declaration)) logger.Debug("cluster.SyncApply:", i, err) } diff --git a/subs/root.go b/subs/root.go index a85fd1d..9650dde 100644 --- a/subs/root.go +++ b/subs/root.go @@ -28,7 +28,7 @@ func (h *socketEventHandler) SubscribeAll() { OnDisconnect(h.handleDisconnect). OnError(h.handleError). OnWithAck(cluster.ApplyCommandEvent, h.applyCommandOnLeader). - On(utils.ModuleReady, h.handleModuleReady). + On(utils.ModuleReady, h.handleModuleReady). //TODO сделать функцию с Ack, возвращать текстовку ошибки в случае возниконовения ошибки, константу ok, если все ок On(utils.ModuleSendRequirements, h.handleModuleRequirements) } @@ -45,6 +45,7 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { holder.Socket.Rooms().Leave(conn, followersRoom) } service.DiscoveryService.HandleDisconnect(conn.Id()) + //TODO при отключении топология кластера меняется, соответсвенно нужно обновлять состояние и уведомлять всех об изменении } func (h *socketEventHandler) handleError(conn ws.Conn, err error) { From 79f83e245cd24d62b1c886626858a63c6bf608fa Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Wed, 4 Sep 2019 18:20:11 +0300 Subject: [PATCH 3/8] refactoring, added DeleteBackendDeclarationCommand --- Gopkg.lock | 94 ++++++++++++++++++++++++++++++++++++++++- cluster/const.go | 4 +- service/applylog.go | 38 ----------------- service/clusterstate.go | 53 +++++++++++++++++++++++ service/discovery.go | 42 ++---------------- service/routes.go | 57 +++++++++++++++++++++++++ store/apply.go | 21 +++++++-- store/state/mesh.go | 11 +++-- store/state/state.go | 22 ++++++++-- store/store.go | 18 +++++--- subs/client.go | 49 +++++++++++---------- subs/root.go | 12 ++++-- 12 files changed, 294 insertions(+), 127 deletions(-) delete mode 100644 service/applylog.go create mode 100644 service/clusterstate.go create mode 100644 service/routes.go diff --git a/Gopkg.lock b/Gopkg.lock index 9e45be8..bb5c868 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -1,6 +1,14 @@ # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. +[[projects]] + digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214" + name = "github.com/StackExchange/wmi" + packages = ["."] + pruneopts = "UT" + revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" + version = "1.0.0" + [[projects]] branch = "master" digest = "1:7a9140c806333a78122763d08ec6c0d7358c7fff1df8cfbb01881c5dc46e24e5" @@ -25,6 +33,14 @@ revision = "2f1ce7a837dcb8da3ec595b1dac9d0632f0f99e8" version = "v1.3.1" +[[projects]] + digest = "1:652880afc6b57ce0a67173f552cb35ccda816493a1da6ca20e5074a66bcd083f" + name = "github.com/buaazp/fasthttprouter" + packages = ["."] + pruneopts = "UT" + revision = "ade4e2031af3aed7fffd241084aad80a58faf421" + version = "v0.1.1" + [[projects]] digest = "1:c1100fc71e23b6a32b2c68a5202a848fd13811d5a10b12edb8019c3667d1cd9a" name = "github.com/cenkalti/backoff" @@ -41,6 +57,17 @@ revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" +[[projects]] + digest = "1:440028f55cb322d8cb5b9d5ebec298a00b7d74690a658fe6b1c0c0b44341bfae" + name = "github.com/go-ole/go-ole" + packages = [ + ".", + "oleutil", + ] + pruneopts = "UT" + revision = "97b6244175ae18ea6eef668034fd6565847501c9" + version = "v1.2.4" + [[projects]] digest = "1:07f4fafe81587b642166199f41c3edcca12929fcfcc0261b00be5dea2f968f44" name = "github.com/golang/protobuf" @@ -186,14 +213,17 @@ revision = "5959fcea049facd9441fff9de976191accd3cf9f" [[projects]] - digest = "1:fd6ba35c1332fa3ad5be6f4fa1206adba26c184e79f32310a0c50b6811e0e530" + digest = "1:86431b6d676940fee5c9fa74cc730041a33454271ca5069caa72049c77445dd0" name = "github.com/integration-system/isp-lib" packages = [ "backend", + "bootstrap", "config", "config/schema", "logger", + "metric", "proto/stubs", + "socket", "streaming", "structure", "utils", @@ -221,6 +251,26 @@ revision = "27518f6661eba504be5a7a9a9f6d9460d892ade3" version = "v1.1.7" +[[projects]] + digest = "1:caa1da085cc12cd39d3ddb267434902f621050e1b46f7e9477b2b933df680193" + name = "github.com/klauspost/compress" + packages = [ + "flate", + "gzip", + "zlib", + ] + pruneopts = "UT" + revision = "2c38f6d2dc5a6a21b6851f2414f4e10adf8e3eee" + version = "v1.8.1" + +[[projects]] + digest = "1:923c4d7194b42e054b2eb8a6c62824ac55e23ececc1c7e48d4da69c971c55954" + name = "github.com/klauspost/cpuid" + packages = ["."] + pruneopts = "UT" + revision = "05a8198c0f5a27739aec358908d7e12c64ce6eb7" + version = "v1.2.1" + [[projects]] digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de" name = "github.com/konsorten/go-windows-terminal-sequences" @@ -309,6 +359,25 @@ revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4" version = "v0.8.1" +[[projects]] + branch = "master" + digest = "1:5bbebe8ac19ecb6c87790a89faa20566e38ed0d6494a1d14c4f5b05d9ce2436c" + name = "github.com/rcrowley/go-metrics" + packages = ["."] + pruneopts = "UT" + revision = "cac0b30c2563378d434b5af411844adff8e32960" + +[[projects]] + digest = "1:f5139e9f4441369ffb5d44fa9fae62b921457d4dc09cd873ed0fd44511cc87ee" + name = "github.com/shirou/gopsutil" + packages = [ + "cpu", + "internal/common", + ] + pruneopts = "UT" + revision = "d80c43f9c984a48783daf22f4bd9278006ae483a" + version = "v2.19.7" + [[projects]] digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976" name = "github.com/sirupsen/logrus" @@ -368,6 +437,26 @@ pruneopts = "UT" revision = "a83968bda2d37294a3541b7d2207fb6f5a3559a3" +[[projects]] + digest = "1:c468422f334a6b46a19448ad59aaffdfc0a36b08fdcc1c749a0b29b6453d7e59" + name = "github.com/valyala/bytebufferpool" + packages = ["."] + pruneopts = "UT" + revision = "e746df99fe4a3986f4d4f79e13c1e0117ce9c2f7" + version = "v1.0.0" + +[[projects]] + branch = "master" + digest = "1:30fe8021645a9d9966fcede2a59c2e2f498d433687fc5cddd7de85a6a0a44c28" + name = "github.com/valyala/fasthttp" + packages = [ + ".", + "fasthttputil", + "stackless", + ] + pruneopts = "UT" + revision = "8ce231e840720d91e22f855ddba797b3b916fc75" + [[projects]] digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" name = "github.com/x-cray/logrus-prefixed-formatter" @@ -501,16 +590,19 @@ analyzer-name = "dep" analyzer-version = 1 input-imports = [ + "github.com/asaskevich/govalidator", "github.com/cenkalti/backoff", "github.com/googollee/go-socket.io", "github.com/hashicorp/raft", "github.com/hashicorp/raft-boltdb", "github.com/integration-system/golang-socketio", "github.com/integration-system/isp-lib/backend", + "github.com/integration-system/isp-lib/bootstrap", "github.com/integration-system/isp-lib/config", "github.com/integration-system/isp-lib/config/schema", "github.com/integration-system/isp-lib/logger", "github.com/integration-system/isp-lib/structure", + "github.com/integration-system/isp-lib/utils", "github.com/json-iterator/go", "github.com/mohae/deepcopy", "github.com/pkg/errors", diff --git a/cluster/const.go b/cluster/const.go index a922757..1c1a847 100644 --- a/cluster/const.go +++ b/cluster/const.go @@ -8,6 +8,6 @@ const ( ) const ( _ = iota - BackendDeclarationCommand - ConfigSchemaCommand + UpdateBackendDeclarationCommand + DeleteBackendDeclarationCommand ) diff --git a/service/applylog.go b/service/applylog.go deleted file mode 100644 index b498f2f..0000000 --- a/service/applylog.go +++ /dev/null @@ -1,38 +0,0 @@ -package service - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "github.com/integration-system/isp-lib/logger" - "github.com/integration-system/isp-lib/structure" - "isp-config-service/cluster" - "isp-config-service/store/state" -) - -var ( - ClusterStoreService clusterStoreService -) - -type clusterStoreService struct{} - -func (l clusterStoreService) HandleBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { - state.UpsertBackend(declaration) - logger.Debug("HandleBackendDeclarationCommand: upserted backend", declaration.ModuleName) - DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) - DiscoveryService.BroadcastRoutes(state) - return state, nil -} - -//TODO вынести как отдельную функция с парметрами вызова (int command, payload interface{}) ([]byte, error) для возможности переиспользования -func (l clusterStoreService) PrepareBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { - var buf bytes.Buffer - buf2 := make([]byte, 8) - binary.BigEndian.PutUint64(buf2, cluster.BackendDeclarationCommand) - buf.Write(buf2) - err := json.NewEncoder(&buf).Encode(backend) - if err != nil { - logger.Fatal("PrepareBackendDeclarationCommand json encoding", err) - } - return buf.Bytes() -} diff --git a/service/clusterstate.go b/service/clusterstate.go new file mode 100644 index 0000000..8785e38 --- /dev/null +++ b/service/clusterstate.go @@ -0,0 +1,53 @@ +package service + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" + "isp-config-service/cluster" + "isp-config-service/store/state" +) + +var ( + ClusterStateService clusterStateService +) + +type clusterStateService struct{} + +func (l clusterStateService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { + state.UpsertBackend(declaration) + logger.Debug("HandleUpdateBackendDeclarationCommand: upserted backend", declaration.ModuleName) + DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) + RoutesService.BroadcastRoutes(state) + return state, nil +} + +func (l clusterStateService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { + state.DeleteBackend(declaration) + logger.Debug("HandleDeleteBackendDeclarationCommand: deleted backend", declaration.ModuleName) + DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) + RoutesService.BroadcastRoutes(state) + return state, nil +} + +func (l clusterStateService) PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { + return l.prepareCommand(cluster.UpdateBackendDeclarationCommand, backend) +} + +func (l clusterStateService) PrepareDeleteBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { + return l.prepareCommand(cluster.DeleteBackendDeclarationCommand, backend) +} + +func (l clusterStateService) prepareCommand(command uint64, payload interface{}) []byte { + var buf bytes.Buffer + buf2 := make([]byte, 8) + binary.BigEndian.PutUint64(buf2, command) + buf.Write(buf2) + err := json.NewEncoder(&buf).Encode(payload) + if err != nil { + logger.Fatal("prepareCommand json encoding", err) + } + return buf.Bytes() +} diff --git a/service/discovery.go b/service/discovery.go index fe8e7f7..9daeee5 100644 --- a/service/discovery.go +++ b/service/discovery.go @@ -26,7 +26,7 @@ type discoveryService struct { lock sync.RWMutex } -func (ds *discoveryService) HandleDisconnect(connId string) { //TODO где то передается целиком объект ws.Conn, привести к одному виду(думаю ws.Conn) +func (ds *discoveryService) HandleDisconnect(connId string) { ds.lock.Lock() defer ds.lock.Unlock() if events, ok := ds.subs[connId]; ok { @@ -36,7 +36,7 @@ func (ds *discoveryService) HandleDisconnect(connId string) { //TODO где то holder.Socket.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom) } -func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state.State) { +func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state.ReadState) { if len(events) == 0 { return } @@ -46,6 +46,7 @@ func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state holder.Socket.Rooms().Join(conn, events...) for _, event := range events { addressList := state.GetModuleAddresses(event) + event = utils.ModuleConnected(event) ds.sendAddrList(conn, event, addressList) } } @@ -83,43 +84,6 @@ func (ds *discoveryService) sendAddrList(conn ws.Conn, event string, addressList } } -//TODO вынесли логику работы с роутами в отдельный сервис -func (ds *discoveryService) SubscribeRoutes(conn ws.Conn, state state.State) { - holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom) - routes := state.GetRoutes() - ds.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes) -} - -func (ds *discoveryService) BroadcastRoutes(state state.State) { - routes := state.GetRoutes() - ds.broadcastRoutes(utils.ConfigSendRoutesChanged, routes) -} - -func (ds *discoveryService) broadcastRoutes(event string, routes structure.RoutingConfig) { - if bytes, err := json.Marshal(routes); err != nil { - logger.Warn(err) - } else { - err = holder.Socket.Broadcast(RoutesSubscribersRoom, event, string(bytes)) - if err != nil { - logger.Error(err) - } - } -} - -func (ds *discoveryService) sendRoutes(conn ws.Conn, event string, routes structure.RoutingConfig) { - if bytes, err := json.Marshal(routes); err != nil { - logger.Warn(err) - } else { - bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3) - err := backoff.Retry(func() error { - return conn.Emit(event, string(bytes)) - }, bf) - if err != nil { - logger.Error(err) - } - } -} - func NewDiscoveryService() *discoveryService { return &discoveryService{ subs: make(map[string][]string), diff --git a/service/routes.go b/service/routes.go new file mode 100644 index 0000000..094d4a9 --- /dev/null +++ b/service/routes.go @@ -0,0 +1,57 @@ +package service + +import ( + "encoding/json" + "github.com/cenkalti/backoff" + "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" + "github.com/integration-system/isp-lib/utils" + "isp-config-service/holder" + "isp-config-service/store/state" + "isp-config-service/ws" + "time" +) + +var RoutesService routesService + +type routesService struct{} + +func (rs *routesService) HandleDisconnect(connId string) { + holder.Socket.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom) +} + +func (rs *routesService) SubscribeRoutes(conn ws.Conn, state state.ReadState) { + holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom) + routes := state.GetRoutes() + rs.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes) +} + +func (rs *routesService) BroadcastRoutes(state state.ReadState) { + routes := state.GetRoutes() + rs.broadcastRoutes(utils.ConfigSendRoutesChanged, routes) +} + +func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingConfig) { + if bytes, err := json.Marshal(routes); err != nil { + logger.Warn(err) + } else { + err = holder.Socket.Broadcast(RoutesSubscribersRoom, event, string(bytes)) + if err != nil { + logger.Error(err) + } + } +} + +func (rs *routesService) sendRoutes(conn ws.Conn, event string, routes structure.RoutingConfig) { + if bytes, err := json.Marshal(routes); err != nil { + logger.Warn(err) + } else { + bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3) + err := backoff.Retry(func() error { + return conn.Emit(event, string(bytes)) + }, bf) + if err != nil { + logger.Error(err) + } + } +} diff --git a/store/apply.go b/store/apply.go index ca39bd5..00b88f7 100644 --- a/store/apply.go +++ b/store/apply.go @@ -6,14 +6,29 @@ import ( "isp-config-service/service" ) -func (s *Store) applyBackendDeclarationCommand(data []byte) error { +func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) error { declaration := structure.BackendDeclaration{} err := json.Unmarshal(data, &declaration) if err != nil { - logger.Warnf("Store.applyBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) + logger.Warnf("Store.applyUpdateBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) return err } - state, err := service.ClusterStoreService.HandleBackendDeclarationCommand(declaration, s.state) + state, err := service.ClusterStateService.HandleUpdateBackendDeclarationCommand(declaration, s.state) + if err != nil { + return err + } + s.state = state + return nil +} + +func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) error { + declaration := structure.BackendDeclaration{} + err := json.Unmarshal(data, &declaration) + if err != nil { + logger.Warnf("Store.applyDeleteBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) + return err + } + state, err := service.ClusterStateService.HandleDeleteBackendDeclarationCommand(declaration, s.state) if err != nil { return err } diff --git a/store/state/mesh.go b/store/state/mesh.go index 2f5c8f9..ad17149 100644 --- a/store/state/mesh.go +++ b/store/state/mesh.go @@ -42,10 +42,9 @@ func (m *Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (change return } -func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (changed bool) { +func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) { address := backend.Address.GetAddress() if nodes, ok := m.modulesMap[backend.ModuleName]; ok { - changed = true delete(nodes, address) if len(nodes) == 0 { delete(m.modulesMap, backend.ModuleName) @@ -54,11 +53,11 @@ func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (changed bool return } -func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { //TODO используется ? +func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { + address := backend.Address.GetAddress() if nodes, ok := m.modulesMap[backend.ModuleName]; ok { - exist = true - if len(nodes) == 0 { - delete(m.modulesMap, backend.ModuleName) + if _, ok := nodes[address]; ok { + exist = true } } return diff --git a/store/state/state.go b/store/state/state.go index 98951c3..3b22192 100644 --- a/store/state/state.go +++ b/store/state/state.go @@ -8,12 +8,20 @@ type State struct { mesh *Mesh } +type ReadState interface { + CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) + GetModuleAddresses(moduleName string) []structure.AddressConfiguration + GetRoutes() structure.RoutingConfig + BackendExist(backend structure.BackendDeclaration) (exist bool) +} + func NewState() State { return State{ mesh: NewMesh(), } } -func (s *State) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) { + +func (s State) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) { return s.mesh.CheckBackendChanged(backend) } @@ -21,10 +29,18 @@ func (s *State) UpsertBackend(backend structure.BackendDeclaration) (changed boo return s.mesh.UpsertBackend(backend) } -func (s *State) GetModuleAddresses(moduleName string) []structure.AddressConfiguration { +func (s State) GetModuleAddresses(moduleName string) []structure.AddressConfiguration { return s.mesh.GetModuleAddresses(moduleName) } -func (s *State) GetRoutes() structure.RoutingConfig { +func (s State) GetRoutes() structure.RoutingConfig { return s.mesh.GetRoutes() } + +func (s *State) DeleteBackend(backend structure.BackendDeclaration) { + s.mesh.DeleteBackend(backend) +} + +func (s State) BackendExist(backend structure.BackendDeclaration) (exist bool) { + return s.mesh.BackendExist(backend) +} diff --git a/store/store.go b/store/store.go index 28b2063..0272d52 100644 --- a/store/store.go +++ b/store/store.go @@ -19,7 +19,7 @@ var ( type Store struct { state state.State - lock sync.Mutex //TODO RWMutex + lock sync.RWMutex handlers map[uint64]func([]byte) error } @@ -60,8 +60,14 @@ func (s *Store) Restore(rc io.ReadCloser) error { return nil } -func (s *Store) GetState() *state.State { //TODO почему указатель ? =), добавим функцию VisitState(f(state state)), попробуем с ней - return &s.state +func (s *Store) GetReadState() state.ReadState { + return s.state +} + +func (s *Store) VisitReadState(f func(state.ReadState)) { + s.lock.RLock() + defer s.lock.RUnlock() + f(s.GetReadState()) } type fsmSnapshot struct { @@ -74,18 +80,15 @@ func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error { if err != nil { return err } - if _, err := sink.Write(b); err != nil { return err } - return sink.Close() }() if err != nil { _ = sink.Cancel() } - return err } @@ -96,7 +99,8 @@ func NewStateStore() *Store { state: state.NewState(), } store.handlers = map[uint64]func([]byte) error{ - cluster.BackendDeclarationCommand: store.applyBackendDeclarationCommand, + cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand, + cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand, } return store } diff --git a/subs/client.go b/subs/client.go index fedc817..b7aa162 100644 --- a/subs/client.go +++ b/subs/client.go @@ -6,68 +6,67 @@ import ( "github.com/integration-system/isp-lib/bootstrap" "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" - "github.com/integration-system/isp-lib/utils" "isp-config-service/service" + "isp-config-service/store/state" "isp-config-service/ws" ) -func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) { +func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string { instanceUuid, moduleName, err := conn.Parameters() logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE if err != nil { - _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) //эти штуки тогда убертся вовсе - return + return err.Error() } declaration := structure.BackendDeclaration{} err = json.Unmarshal(data, &declaration) if err != nil { - _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) logger.Warnf("handleModuleDeclaration: %s, error parse json data: %s", conn.Id(), err.Error()) - return + return err.Error() } _, err = govalidator.ValidateStruct(declaration) if err != nil { errors := govalidator.ErrorsByField(err) - _ = conn.Emit(utils.ErrorConnection, map[string]map[string]string{"error": errors}) logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", conn.Id(), errors) - } else if h.store.GetState().CheckBackendChanged(declaration) { - // TODO h.store.GetState() locks - i, err := h.cluster.SyncApply(service.ClusterStoreService.PrepareBackendDeclarationCommand(declaration)) - logger.Debug("cluster.SyncApply:", i, err) + return err.Error() } - + h.store.VisitReadState(func(state state.ReadState) { + if state.CheckBackendChanged(declaration) { + conn.SetBackendDeclaration(declaration) + command := service.ClusterStateService.PrepareUpdateBackendDeclarationCommand(declaration) + i, err := h.cluster.SyncApply(command) + logger.Debug("cluster.SyncApply:", i, err) + } + }) + return ok } -func (h *socketEventHandler) handleRoutesUpdate(conn ws.Conn, data []byte) { - -} - -func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) { +func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) string { logger.Debugf("onReceivedModuleRequirements: %s %s", conn.Id(), string(data)) instanceUuid, moduleName, err := conn.Parameters() logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE if err != nil { - _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) - return + return err.Error() } declaration := bootstrap.ModuleRequirements{} err = json.Unmarshal(data, &declaration) if err != nil { - _ = conn.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()}) logger.Debugf("onReceivedModuleRequirements: %s, error parse json data: %s", conn.Id(), err.Error()) - return + return err.Error() } if declaration.RequireRoutes { - // TODO h.store.GetState() locks - service.DiscoveryService.SubscribeRoutes(conn, *h.store.GetState()) + h.store.VisitReadState(func(state state.ReadState) { + service.RoutesService.SubscribeRoutes(conn, state) + }) } - // TODO h.store.GetState() locks - service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, *h.store.GetState()) + h.store.VisitReadState(func(state state.ReadState) { + service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, state) + }) + return ok } func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) { diff --git a/subs/root.go b/subs/root.go index 9650dde..076dd6d 100644 --- a/subs/root.go +++ b/subs/root.go @@ -28,8 +28,8 @@ func (h *socketEventHandler) SubscribeAll() { OnDisconnect(h.handleDisconnect). OnError(h.handleError). OnWithAck(cluster.ApplyCommandEvent, h.applyCommandOnLeader). - On(utils.ModuleReady, h.handleModuleReady). //TODO сделать функцию с Ack, возвращать текстовку ошибки в случае возниконовения ошибки, константу ok, если все ок - On(utils.ModuleSendRequirements, h.handleModuleRequirements) + OnWithAck(utils.ModuleReady, h.handleModuleReady). + OnWithAck(utils.ModuleSendRequirements, h.handleModuleRequirements) } func (h *socketEventHandler) handleConnect(conn ws.Conn) { @@ -45,7 +45,13 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { holder.Socket.Rooms().Leave(conn, followersRoom) } service.DiscoveryService.HandleDisconnect(conn.Id()) - //TODO при отключении топология кластера меняется, соответсвенно нужно обновлять состояние и уведомлять всех об изменении + service.RoutesService.HandleDisconnect(conn.Id()) + backend := conn.GetBackendDeclaration() + if backend != nil { + command := service.ClusterStateService.PrepareDeleteBackendDeclarationCommand(*backend) + i, err := h.cluster.SyncApply(command) + logger.Debug("cluster.SyncApply:", i, err) + } } func (h *socketEventHandler) handleError(conn ws.Conn, err error) { From 1ddbe43618d1c6d8be58edf57a41781b11ac16fb Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Wed, 4 Sep 2019 18:48:54 +0300 Subject: [PATCH 4/8] fix --- subs/client.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/subs/client.go b/subs/client.go index b7aa162..c6baba9 100644 --- a/subs/client.go +++ b/subs/client.go @@ -31,14 +31,17 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", conn.Id(), errors) return err.Error() } + var changed bool h.store.VisitReadState(func(state state.ReadState) { - if state.CheckBackendChanged(declaration) { - conn.SetBackendDeclaration(declaration) - command := service.ClusterStateService.PrepareUpdateBackendDeclarationCommand(declaration) - i, err := h.cluster.SyncApply(command) - logger.Debug("cluster.SyncApply:", i, err) - } + changed = state.CheckBackendChanged(declaration) }) + if changed { + conn.SetBackendDeclaration(declaration) + command := service.ClusterStateService.PrepareUpdateBackendDeclarationCommand(declaration) + i, err := h.cluster.SyncApply(command) + logger.Debug("cluster.SyncApply:", i, err) + } + return ok } From 7632e07f4e221106cbfcd14874e9b96970942118 Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Mon, 9 Sep 2019 12:16:17 +0300 Subject: [PATCH 5/8] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=BE=20=D0=B0=D0=BD=D0=BE=D0=BD=D1=81=D0=B8=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8?= =?UTF-8?q?=D0=B3=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cluster/client.go | 37 +++++++++++++++++++++++++------- cluster/const.go | 27 +++++++++++++++++++++++ cluster/leader_client.go | 35 +++++++++++++++++++++++++++++- main.go | 46 +++++++++++++++++++++++++++++++++++++--- service/clusterstate.go | 44 +++++++++++--------------------------- service/discovery.go | 7 +----- service/routes.go | 4 ++++ store/state/mesh.go | 7 ++++-- store/state/state.go | 4 ++-- store/store.go | 7 ++++++ subs/client.go | 20 ++++++----------- subs/cluster.go | 2 +- subs/root.go | 6 +++--- ws/server.go | 15 +++++++------ 14 files changed, 184 insertions(+), 77 deletions(-) diff --git a/cluster/client.go b/cluster/client.go index 9311870..c2fc520 100644 --- a/cluster/client.go +++ b/cluster/client.go @@ -3,6 +3,7 @@ package cluster import ( "errors" "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" "isp-config-service/raft" "sync" "time" @@ -22,9 +23,11 @@ const ( type ClusterClient struct { r *raft.Raft - leaderMu sync.RWMutex - leaderState leaderState - leaderClient *SocketLeaderClient + leaderMu sync.RWMutex + leaderState leaderState + leaderClient *SocketLeaderClient + declaration structure.BackendDeclaration + onClientDisconnect func(string) } func (client *ClusterClient) Shutdown() error { @@ -71,7 +74,6 @@ func (client *ClusterClient) SyncApplyOnLeader(command []byte) (interface{}, err func (client *ClusterClient) listenLeader() { for n := range client.r.LeaderCh() { logger.Debug("ChangeLeaderNotification:", n) - client.leaderMu.Lock() if client.leaderState.leaderAddr != n.CurrentLeaderAddress { if client.leaderClient != nil { @@ -80,12 +82,29 @@ func (client *ClusterClient) listenLeader() { } } if n.LeaderElected && !n.IsLeader { - leaderClient := NewSocketLeaderClient(n.CurrentLeaderAddress) + leaderClient := NewSocketLeaderClient(n.CurrentLeaderAddress, func() { + client.onClientDisconnect(client.leaderState.leaderAddr) + }) if err := leaderClient.Dial(leaderConnectionTimeout); err != nil { logger.Fatalf("could not connect to leader: %v", err) continue } + go func(declaration structure.BackendDeclaration) { + response, err := leaderClient.SendDeclaration(declaration, defaultApplyTimeout) + if err != nil { + logger.Warn("leaderClient.SendDeclaration", err) + } else if response != `"ok"` { + logger.Warn("leaderClient.SendDeclaration response", response) + } + }(client.declaration) + client.leaderClient = leaderClient + } else if n.LeaderElected && n.IsLeader { + go func(declaration structure.BackendDeclaration) { + command := PrepareUpdateBackendDeclarationCommand(declaration) + i, err := client.SyncApply(command) + logger.Debug("cluster.SyncApply announce myself:", i, err) + }(client.declaration) } client.leaderState = leaderState{ leaderElected: n.LeaderElected, @@ -103,10 +122,12 @@ type leaderState struct { leaderAddr string } -func NewRaftClusterClient(r *raft.Raft) *ClusterClient { +func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration, onClientDisconnect func(string)) *ClusterClient { client := &ClusterClient{ - r: r, - leaderState: leaderState{}, + r: r, + declaration: declaration, + leaderState: leaderState{}, + onClientDisconnect: onClientDisconnect, } go client.listenLeader() diff --git a/cluster/const.go b/cluster/const.go index 1c1a847..18ad1da 100644 --- a/cluster/const.go +++ b/cluster/const.go @@ -1,5 +1,13 @@ package cluster +import ( + "bytes" + "encoding/binary" + "encoding/json" + "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" +) + const ( ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND" @@ -11,3 +19,22 @@ const ( UpdateBackendDeclarationCommand DeleteBackendDeclarationCommand ) + +func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { + return prepareCommand(UpdateBackendDeclarationCommand, backend) +} + +func PrepareDeleteBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { + return prepareCommand(DeleteBackendDeclarationCommand, backend) +} + +func prepareCommand(command uint64, payload interface{}) []byte { + cmd := make([]byte, 8) + binary.BigEndian.PutUint64(cmd, command) + buf := bytes.NewBuffer(cmd) + err := json.NewEncoder(buf).Encode(payload) + if err != nil { + logger.Fatal("prepareCommand json encoding", err) + } + return buf.Bytes() +} diff --git a/cluster/leader_client.go b/cluster/leader_client.go index 33bd145..a1d9c54 100644 --- a/cluster/leader_client.go +++ b/cluster/leader_client.go @@ -1,10 +1,14 @@ package cluster import ( + "encoding/json" + "errors" "github.com/cenkalti/backoff" gosocketio "github.com/integration-system/golang-socketio" "github.com/integration-system/isp-lib/config" "github.com/integration-system/isp-lib/logger" + "github.com/integration-system/isp-lib/structure" + "github.com/integration-system/isp-lib/utils" "isp-config-service/conf" "net" "strconv" @@ -19,6 +23,17 @@ func (c *SocketLeaderClient) Send(data []byte, timeout time.Duration) (string, e return c.c.Ack(ApplyCommandEvent, data, timeout) } +func (c *SocketLeaderClient) SendDeclaration(backend structure.BackendDeclaration, timeout time.Duration) (string, error) { + data, err := json.Marshal(backend) + if err != nil { + return "", err + } + if c.c.IsAlive() { + return c.c.Ack(utils.ModuleReady, data, timeout) + } + return "", errors.New("SendDeclaration connection is not alive") +} + func (c *SocketLeaderClient) Dial(timeout time.Duration) error { backOff := backoff.NewExponentialBackOff() backOff.MaxElapsedTime = timeout @@ -29,7 +44,7 @@ func (c *SocketLeaderClient) Close() { c.c.Close() } -func NewSocketLeaderClient(address string) *SocketLeaderClient { +func NewSocketLeaderClient(address string, f func()) *SocketLeaderClient { socketIoAddress := getSocketIoUrl(address) client := gosocketio.NewClientBuilder(). EnableReconnection(). @@ -38,6 +53,13 @@ func NewSocketLeaderClient(address string) *SocketLeaderClient { logger.Warnf("socket.io leader(%s) client reconnection err: %v", socketIoAddress, err) }). BuildToConnect(socketIoAddress) + err := client.On(gosocketio.OnDisconnection, func(channel *gosocketio.Channel) { + logger.Debugf("[%s]:%s", channel.Ip(), "LeaderClient OnDisconnection") + f() + }) + if err != nil { + logger.Fatal(err) + } return &SocketLeaderClient{ c: client, } @@ -54,6 +76,17 @@ func getSocketIoUrl(address string) string { if err != nil { panic(err) } + // TODO логика для определения порта пира, т.к всё тестируется на одной машине + //peerNumber := addr.Port - 9000 + //switch peerNumber { + //case 2: + // port = 9011 + //case 3: + // port = 9021 + //case 4: + // port = 9031 + //} + // return gosocketio.GetUrl(addr.IP.String(), port, false, map[string]string{ ClusterParam: "true", }) diff --git a/main.go b/main.go index e058b6f..c402d54 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "context" "github.com/integration-system/isp-lib/backend" + "github.com/integration-system/isp-lib/bootstrap" "github.com/integration-system/isp-lib/config" "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" @@ -12,11 +13,15 @@ import ( "isp-config-service/helper" "isp-config-service/holder" "isp-config-service/raft" + "isp-config-service/service" "isp-config-service/store" + "isp-config-service/store/state" "isp-config-service/subs" "isp-config-service/ws" + "net" "net/http" "os" + "strconv" ) const ( @@ -36,8 +41,17 @@ func init() { func main() { cfg := config.Get().(*conf.Configuration) + handlers := helper.GetAllHandlers() + endpoints := backend.GetEndpoints(cfg.ModuleName, handlers...) + declaration := structure.BackendDeclaration{ + ModuleName: cfg.ModuleName, + Version: version, + LibVersion: bootstrap.LibraryVersion, + Endpoints: endpoints, + Address: cfg.WS.Grpc, + } - client, store := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster) + client, store := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster, declaration) initWebsocket(cfg.WS.Rest.GetAddress(), client, store) initGrpc(cfg.WS.Grpc) @@ -70,13 +84,39 @@ func initWebsocket(bindAddress string, clusterClient *cluster.ClusterClient, sto logger.Infof("socket.IO server start on %s", bindAddress) } -func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration) (*cluster.ClusterClient, *store.Store) { +func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.ClusterClient, *store.Store) { store := store.NewStateStore() r, err := raft.NewRaft(bindAddress, clusterCfg, store) if err != nil { logger.Fatal(err) } - clusterClient := cluster.NewRaftClusterClient(r) + clusterClient := cluster.NewRaftClusterClient(r, declaration, func(address string) { + store.VisitState(func(s state.State) { + cfg := config.Get().(*conf.Configuration) + addr, err := net.ResolveTCPAddr("tcp", address) + if err != nil { + panic(err) //must never occured + } + port := addr.Port + // TODO логика для определения порта пира, т.к всё тестируется на одной машине + //peerNumber := addr.Port - 9000 + //switch peerNumber { + //case 2: + // port = 9022 + //case 3: + // port = 9032 + //case 4: + // port = 9042 + //} + // + addressConfiguration := structure.AddressConfiguration{Port: strconv.Itoa(port), IP: addr.IP.String()} + back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration} + _, err = service.ClusterStateService.HandleDeleteBackendDeclarationCommand(back, s) + if err != nil { + logger.Debug("onClientDisconnect HandleDeleteBackendDeclarationCommand", address, err) + } + }) + }) holder.ClusterClient = clusterClient err = r.BootstrapCluster() // err can be ignored diff --git a/service/clusterstate.go b/service/clusterstate.go index 8785e38..4080821 100644 --- a/service/clusterstate.go +++ b/service/clusterstate.go @@ -1,12 +1,8 @@ package service import ( - "bytes" - "encoding/binary" - "encoding/json" "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" - "isp-config-service/cluster" "isp-config-service/store/state" ) @@ -17,37 +13,21 @@ var ( type clusterStateService struct{} func (l clusterStateService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { - state.UpsertBackend(declaration) - logger.Debug("HandleUpdateBackendDeclarationCommand: upserted backend", declaration.ModuleName) - DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) - RoutesService.BroadcastRoutes(state) + changed := state.UpsertBackend(declaration) + if changed { + logger.Debug("HandleUpdateBackendDeclarationCommand: upserted backend", declaration.ModuleName) + DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) + RoutesService.BroadcastRoutes(state) + } return state, nil } func (l clusterStateService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { - state.DeleteBackend(declaration) - logger.Debug("HandleDeleteBackendDeclarationCommand: deleted backend", declaration.ModuleName) - DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) - RoutesService.BroadcastRoutes(state) + deleted := state.DeleteBackend(declaration) + if deleted { + logger.Debug("HandleDeleteBackendDeclarationCommand: deleted backend", declaration.ModuleName) + DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) + RoutesService.BroadcastRoutes(state) + } return state, nil } - -func (l clusterStateService) PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { - return l.prepareCommand(cluster.UpdateBackendDeclarationCommand, backend) -} - -func (l clusterStateService) PrepareDeleteBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { - return l.prepareCommand(cluster.DeleteBackendDeclarationCommand, backend) -} - -func (l clusterStateService) prepareCommand(command uint64, payload interface{}) []byte { - var buf bytes.Buffer - buf2 := make([]byte, 8) - binary.BigEndian.PutUint64(buf2, command) - buf.Write(buf2) - err := json.NewEncoder(&buf).Encode(payload) - if err != nil { - logger.Fatal("prepareCommand json encoding", err) - } - return buf.Bytes() -} diff --git a/service/discovery.go b/service/discovery.go index 9daeee5..6eb355d 100644 --- a/service/discovery.go +++ b/service/discovery.go @@ -13,10 +13,6 @@ import ( "time" ) -const ( - RoutesSubscribersRoom = "__routesSubscribers" -) - var ( DiscoveryService = NewDiscoveryService() ) @@ -33,7 +29,6 @@ func (ds *discoveryService) HandleDisconnect(connId string) { holder.Socket.Rooms().LeaveByConnId(connId, events...) delete(ds.subs, connId) } - holder.Socket.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom) } func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state.ReadState) { @@ -51,7 +46,7 @@ func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state } } -func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, state state.State) { +func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, state state.ReadState) { ds.lock.RLock() defer ds.lock.RUnlock() event := utils.ModuleConnected(moduleName) diff --git a/service/routes.go b/service/routes.go index 094d4a9..6660849 100644 --- a/service/routes.go +++ b/service/routes.go @@ -12,6 +12,10 @@ import ( "time" ) +const ( + RoutesSubscribersRoom = "__routesSubscribers" +) + var RoutesService routesService type routesService struct{} diff --git a/store/state/mesh.go b/store/state/mesh.go index ad17149..2038b50 100644 --- a/store/state/mesh.go +++ b/store/state/mesh.go @@ -42,10 +42,13 @@ func (m *Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (change return } -func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) { +func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) { address := backend.Address.GetAddress() if nodes, ok := m.modulesMap[backend.ModuleName]; ok { - delete(nodes, address) + if _, ok := nodes[address]; ok { + delete(nodes, address) + deleted = true + } if len(nodes) == 0 { delete(m.modulesMap, backend.ModuleName) } diff --git a/store/state/state.go b/store/state/state.go index 3b22192..e6a577e 100644 --- a/store/state/state.go +++ b/store/state/state.go @@ -37,8 +37,8 @@ func (s State) GetRoutes() structure.RoutingConfig { return s.mesh.GetRoutes() } -func (s *State) DeleteBackend(backend structure.BackendDeclaration) { - s.mesh.DeleteBackend(backend) +func (s *State) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) { + return s.mesh.DeleteBackend(backend) } func (s State) BackendExist(backend structure.BackendDeclaration) (exist bool) { diff --git a/store/store.go b/store/store.go index 0272d52..fbb740c 100644 --- a/store/store.go +++ b/store/store.go @@ -24,6 +24,7 @@ type Store struct { } func (s *Store) Apply(l *raft.Log) interface{} { + logger.Info("Applying...") s.lock.Lock() defer s.lock.Unlock() if len(l.Data) < 8 { @@ -70,6 +71,12 @@ func (s *Store) VisitReadState(f func(state.ReadState)) { f(s.GetReadState()) } +func (s *Store) VisitState(f func(state.State)) { + s.lock.Lock() + defer s.lock.Unlock() + f(s.state) +} + type fsmSnapshot struct { state state.State } diff --git a/subs/client.go b/subs/client.go index c6baba9..6838a36 100644 --- a/subs/client.go +++ b/subs/client.go @@ -6,20 +6,15 @@ import ( "github.com/integration-system/isp-lib/bootstrap" "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" + "isp-config-service/cluster" "isp-config-service/service" "isp-config-service/store/state" "isp-config-service/ws" ) func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string { - instanceUuid, moduleName, err := conn.Parameters() - logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE - if err != nil { - return err.Error() - } - declaration := structure.BackendDeclaration{} - err = json.Unmarshal(data, &declaration) + err := json.Unmarshal(data, &declaration) if err != nil { logger.Warnf("handleModuleDeclaration: %s, error parse json data: %s", conn.Id(), err.Error()) return err.Error() @@ -31,18 +26,17 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", conn.Id(), errors) return err.Error() } + conn.SetBackendDeclaration(declaration) var changed bool h.store.VisitReadState(func(state state.ReadState) { changed = state.CheckBackendChanged(declaration) }) if changed { - conn.SetBackendDeclaration(declaration) - command := service.ClusterStateService.PrepareUpdateBackendDeclarationCommand(declaration) + command := cluster.PrepareUpdateBackendDeclarationCommand(declaration) i, err := h.cluster.SyncApply(command) - logger.Debug("cluster.SyncApply:", i, err) + logger.Debug("cluster.SyncApply UpdateBackendDeclarationCommand:", i, err) } - - return ok + return Ok } func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) string { @@ -69,7 +63,7 @@ func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) h.store.VisitReadState(func(state state.ReadState) { service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, state) }) - return ok + return Ok } func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) { diff --git a/subs/cluster.go b/subs/cluster.go index f26629f..4ed7b95 100644 --- a/subs/cluster.go +++ b/subs/cluster.go @@ -9,5 +9,5 @@ func (h *socketEventHandler) applyCommandOnLeader(conn ws.Conn, cmd []byte) stri if err != nil { return err.Error() } - return ok + return Ok } diff --git a/subs/root.go b/subs/root.go index 076dd6d..841b553 100644 --- a/subs/root.go +++ b/subs/root.go @@ -11,7 +11,7 @@ import ( ) const ( - ok = "ok" + Ok = "ok" followersRoom = "followers" ) @@ -48,9 +48,9 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { service.RoutesService.HandleDisconnect(conn.Id()) backend := conn.GetBackendDeclaration() if backend != nil { - command := service.ClusterStateService.PrepareDeleteBackendDeclarationCommand(*backend) + command := cluster.PrepareDeleteBackendDeclarationCommand(*backend) i, err := h.cluster.SyncApply(command) - logger.Debug("cluster.SyncApply:", i, err) + logger.Debug("cluster.SyncApply DeleteBackendDeclarationCommand:", i, err) } } diff --git a/ws/server.go b/ws/server.go index 4494df5..6c1162c 100644 --- a/ws/server.go +++ b/ws/server.go @@ -26,7 +26,7 @@ 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)) + logger.Debugf("[%s]:%s:%s", conn.Request().RemoteAddr, event, string(data)) return f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), data) })) @@ -35,7 +35,7 @@ func (s *WebsocketServer) OnWithAck(event string, f func(conn Conn, data []byte) func (s *WebsocketServer) On(event string, f func(conn Conn, data []byte)) *WebsocketServer { must(s.s.On(event, func(conn socketio.Socket, data []byte) { - logger.Debugf("[%s]:$s:%s", conn.Request().RemoteAddr, event, string(data)) + logger.Debugf("[%s]:%s:%s", conn.Request().RemoteAddr, event, string(data)) f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), data) })) @@ -44,7 +44,7 @@ func (s *WebsocketServer) On(event string, f func(conn Conn, data []byte)) *Webs func (s *WebsocketServer) OnConnect(f func(Conn)) *WebsocketServer { must(s.s.On(gosocketio.OnConnection, func(conn socketio.Socket) { - logger.Debugf("[%s]:$s", conn.Request().RemoteAddr, gosocketio.OnConnection) + logger.Debugf("[%s]:%s", conn.Request().RemoteAddr, gosocketio.OnConnection) f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn})) })) @@ -53,7 +53,7 @@ func (s *WebsocketServer) OnConnect(f func(Conn)) *WebsocketServer { func (s *WebsocketServer) OnDisconnect(f func(Conn)) *WebsocketServer { must(s.s.On(gosocketio.OnDisconnection, func(conn socketio.Socket) { - logger.Debugf("[%s]:$s", conn.Request().RemoteAddr, gosocketio.OnDisconnection) + logger.Debugf("[%s]:%s", conn.Request().RemoteAddr, gosocketio.OnDisconnection) c := s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}) f(c) @@ -64,7 +64,7 @@ func (s *WebsocketServer) OnDisconnect(f func(Conn)) *WebsocketServer { func (s *WebsocketServer) OnError(f func(Conn, error)) *WebsocketServer { must(s.s.On(gosocketio.OnError, func(conn socketio.Socket, err error) { - logger.Debugf("[%s]:$s:%v", conn.Request().RemoteAddr, gosocketio.OnError, err) + logger.Debugf("[%s]:%s:%v", conn.Request().RemoteAddr, gosocketio.OnError, err) f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), err) })) @@ -74,7 +74,10 @@ func (s *WebsocketServer) OnError(f func(Conn, error)) *WebsocketServer { func (s *WebsocketServer) Broadcast(room string, msg string, v ...interface{}) error { conns := s.roomStore.ToBroadcast(room) for _, conn := range conns { - _ = conn.Emit(msg, v...) + err := conn.Emit(msg, v...) + if err != nil { + logger.Warnf("Broadcast to %s, message %s. err: %v", room, msg, err) + } } return nil } From 05c5db53bde38bd4a4cfe637a9dab71d6911d349 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Mon, 9 Sep 2019 16:23:36 +0300 Subject: [PATCH 6/8] rename func --- cluster/client.go | 4 ++-- cluster/leader_client.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cluster/client.go b/cluster/client.go index c2fc520..5543e04 100644 --- a/cluster/client.go +++ b/cluster/client.go @@ -122,12 +122,12 @@ type leaderState struct { leaderAddr string } -func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration, onClientDisconnect func(string)) *ClusterClient { +func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration, onLeaderDisconnect func(string)) *ClusterClient { client := &ClusterClient{ r: r, declaration: declaration, leaderState: leaderState{}, - onClientDisconnect: onClientDisconnect, + onClientDisconnect: onLeaderDisconnect, } go client.listenLeader() diff --git a/cluster/leader_client.go b/cluster/leader_client.go index a1d9c54..c612d8e 100644 --- a/cluster/leader_client.go +++ b/cluster/leader_client.go @@ -44,7 +44,7 @@ func (c *SocketLeaderClient) Close() { c.c.Close() } -func NewSocketLeaderClient(address string, f func()) *SocketLeaderClient { +func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *SocketLeaderClient { socketIoAddress := getSocketIoUrl(address) client := gosocketio.NewClientBuilder(). EnableReconnection(). @@ -55,7 +55,7 @@ func NewSocketLeaderClient(address string, f func()) *SocketLeaderClient { BuildToConnect(socketIoAddress) err := client.On(gosocketio.OnDisconnection, func(channel *gosocketio.Channel) { logger.Debugf("[%s]:%s", channel.Ip(), "LeaderClient OnDisconnection") - f() + leaderDisconnectionCallback() }) if err != nil { logger.Fatal(err) From 0b351ea3a2cda9eb5ae569e8ef8362e4b6644f94 Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Tue, 10 Sep 2019 14:16:12 +0300 Subject: [PATCH 7/8] - updated golang-socketio lib --- Gopkg.lock | 4 ++-- cluster/client.go | 6 +++++- store/store.go | 2 +- subs/client.go | 8 +++----- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index bb5c868..572f8c6 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -202,7 +202,7 @@ [[projects]] branch = "master" - digest = "1:9e2fd899fdb17e28e9d036fe7a604a1e04918aa4865d5a2150008fc12c6134be" + digest = "1:5fe2b83ed2a106e83b286114a5607702f8b9267da157e2fdd188183082d6e25f" name = "github.com/integration-system/golang-socketio" packages = [ ".", @@ -210,7 +210,7 @@ "transport", ] pruneopts = "UT" - revision = "5959fcea049facd9441fff9de976191accd3cf9f" + revision = "eab7356528fe3ff8d8cd3ba1464e4b7326032315" [[projects]] digest = "1:86431b6d676940fee5c9fa74cc730041a33454271ca5069caa72049c77445dd0" diff --git a/cluster/client.go b/cluster/client.go index 5543e04..33c6402 100644 --- a/cluster/client.go +++ b/cluster/client.go @@ -5,6 +5,7 @@ import ( "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" "isp-config-service/raft" + "strconv" "sync" "time" ) @@ -91,9 +92,12 @@ func (client *ClusterClient) 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 { logger.Warn("leaderClient.SendDeclaration", err) - } else if response != `"ok"` { + } else if response != "ok" { logger.Warn("leaderClient.SendDeclaration response", response) } }(client.declaration) diff --git a/store/store.go b/store/store.go index fbb740c..20154da 100644 --- a/store/store.go +++ b/store/store.go @@ -24,7 +24,7 @@ type Store struct { } func (s *Store) Apply(l *raft.Log) interface{} { - logger.Info("Applying...") + logger.Debug("Applying...") s.lock.Lock() defer s.lock.Unlock() if len(l.Data) < 8 { diff --git a/subs/client.go b/subs/client.go index 6838a36..41c3168 100644 --- a/subs/client.go +++ b/subs/client.go @@ -55,12 +55,10 @@ func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) return err.Error() } - if declaration.RequireRoutes { - h.store.VisitReadState(func(state state.ReadState) { - service.RoutesService.SubscribeRoutes(conn, state) - }) - } h.store.VisitReadState(func(state state.ReadState) { + if declaration.RequireRoutes { + service.RoutesService.SubscribeRoutes(conn, state) + } service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, state) }) return Ok From ca6fe7b86e96f3bc21d39775eadf0eee0007402f Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Wed, 11 Sep 2019 10:25:53 +0300 Subject: [PATCH 8/8] update golang-socketio lib --- Gopkg.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 572f8c6..aa295a6 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -202,7 +202,7 @@ [[projects]] branch = "master" - digest = "1:5fe2b83ed2a106e83b286114a5607702f8b9267da157e2fdd188183082d6e25f" + digest = "1:280d620c33aea271545c0b4456e1a9347a45b03aca09d2bb8923cc524864a325" name = "github.com/integration-system/golang-socketio" packages = [ ".", @@ -210,7 +210,7 @@ "transport", ] pruneopts = "UT" - revision = "eab7356528fe3ff8d8cd3ba1464e4b7326032315" + revision = "24b88aed7c77403c0b9b45de1f42ddc3c4fc0fb2" [[projects]] digest = "1:86431b6d676940fee5c9fa74cc730041a33454271ca5069caa72049c77445dd0"