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 }