done #1
This commit is contained in:
1 parent
e32e55df15
commit
c3e95fa98c
18 files changed
+509
-152
No files matched your search
+1
-1
@@ -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 {
|
||||
|
||||
@@ -6,3 +6,8 @@ const (
|
||||
TokenParam = "token"
|
||||
ClusterParam = "cluster"
|
||||
)
|
||||
const (
|
||||
_ = iota
|
||||
BackendDeclarationCommand
|
||||
ConfigSchemaCommand
|
||||
)
|
||||
@@ -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
|
||||
})
|
||||
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -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)}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package state
|
||||
|
||||
type state struct {
|
||||
mesh *Mesh
|
||||
}
|
||||
|
||||
func newState() state {
|
||||
return state{
|
||||
mesh: NewMesh(),
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
+102
@@ -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
|
||||
}
|
||||
+57
-1
@@ -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) {
|
||||
|
||||
+10
-5
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
+8
-6
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -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...)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user