добавлено анонсирование конфиг сервисов

This commit is contained in:
Maxim Merzhanov committed 2019-09-09 12:16:17 +03:00
1 parent 1ddbe43618
commit 7632e07f4e
14 files changed
+184 -77

No files matched your search

+29 -8
View File
@@ -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()
+27
View File
@@ -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()
}
+34 -1
View File
@@ -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",
})
+43 -3
View File
@@ -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
+12 -32
View File
@@ -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()
}
+1 -6
View File
@@ -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)
+4
View File
@@ -12,6 +12,10 @@ import (
"time"
)
const (
RoutesSubscribersRoom = "__routesSubscribers"
)
var RoutesService routesService
type routesService struct{}
+5 -2
View File
@@ -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)
}
+2 -2
View File
@@ -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) {
+7
View File
@@ -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
}
+7 -13
View File
@@ -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) {
+1 -1
View File
@@ -9,5 +9,5 @@ func (h *socketEventHandler) applyCommandOnLeader(conn ws.Conn, cmd []byte) stri
if err != nil {
return err.Error()
}
return ok
return Ok
}
+3 -3
View File
@@ -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)
}
}
+9 -6
View File
@@ -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
}