init
This commit is contained in:
commit
fe88eed4a8
71 files changed
+4927
No files matched your search
@@ -0,0 +1,99 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"github.com/googollee/go-socket.io"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTimeout = 1 * time.Second
|
||||
)
|
||||
|
||||
type Record struct {
|
||||
data interface{}
|
||||
future *time.Timer
|
||||
}
|
||||
|
||||
type broadcaster struct {
|
||||
Server *socketio.Server
|
||||
AwaitNewRecordTimeout time.Duration
|
||||
|
||||
configMap map[string]*Record
|
||||
routesMap map[string]*Record
|
||||
converterMap map[string]*Record
|
||||
routerMap map[string]*Record
|
||||
|
||||
configLock sync.Mutex
|
||||
routesLock sync.Mutex
|
||||
converterLock sync.Mutex
|
||||
routerLock sync.Mutex
|
||||
}
|
||||
|
||||
func (b *broadcaster) BroadcastConfig(moduleKey string, data interface{}, callback func(data interface{})) {
|
||||
b.doBroadcast(moduleKey, data, utils.ConfigSendConfigChanged, &b.configLock, b.configMap, callback)
|
||||
}
|
||||
|
||||
func (b *broadcaster) BroadcastRoutes(instanceId string, data interface{}, callback func(data interface{})) {
|
||||
b.doBroadcast(instanceId, data, utils.ConfigSendRoutesChanged, &b.routesLock, b.routesMap, callback)
|
||||
}
|
||||
|
||||
/*func (b *broadcaster) BroadcastConverterAddressList(instanceId string, data interface{}, callback func(data interface{})) {
|
||||
b.doBroadcast(instanceId, data, utils.SendNewConverterConnected, &b.converterLock, b.converterMap, callback)
|
||||
}
|
||||
|
||||
func (b *broadcaster) BroadcastRouterAddressList(instanceId string, data interface{}, callback func(data interface{})) {
|
||||
b.doBroadcast(instanceId, data, utils.SendNewRouterConnected, &b.routerLock, b.routerMap, callback)
|
||||
}*/
|
||||
|
||||
func (b *broadcaster) doBroadcast(
|
||||
key string,
|
||||
data interface{},
|
||||
event string,
|
||||
lock *sync.Mutex,
|
||||
store map[string]*Record,
|
||||
callback func(data interface{}),
|
||||
) {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if r, present := store[key]; present {
|
||||
r.data = data
|
||||
if r.future.Stop() {
|
||||
r.future.Reset(b.AwaitNewRecordTimeout)
|
||||
}
|
||||
} else {
|
||||
r := &Record{
|
||||
data: data,
|
||||
}
|
||||
r.future = time.AfterFunc(b.AwaitNewRecordTimeout, func() {
|
||||
lock.Lock()
|
||||
if r.data != nil {
|
||||
b.Server.BroadcastTo(key, event, r.data)
|
||||
if callback != nil {
|
||||
callback(r.data)
|
||||
}
|
||||
}
|
||||
delete(store, key)
|
||||
lock.Unlock()
|
||||
})
|
||||
|
||||
store[key] = r
|
||||
}
|
||||
}
|
||||
|
||||
func NewBroadcaster(server *socketio.Server, awaitNewRecordTimeout time.Duration) *broadcaster {
|
||||
timeout := awaitNewRecordTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultTimeout
|
||||
}
|
||||
return &broadcaster{
|
||||
Server: server,
|
||||
AwaitNewRecordTimeout: timeout,
|
||||
configMap: map[string]*Record{},
|
||||
routesMap: map[string]*Record{},
|
||||
converterMap: map[string]*Record{},
|
||||
routerMap: map[string]*Record{},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/cenkalti/backoff"
|
||||
"github.com/googollee/go-socket.io"
|
||||
"github.com/integration-system/isp-lib/logger"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
discoverersMap = make(map[string]*Discoverer)
|
||||
discoverersLock sync.RWMutex
|
||||
)
|
||||
|
||||
type channelIdList []string
|
||||
|
||||
type Discoverer struct {
|
||||
subs map[string]channelIdList
|
||||
instanceId string
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func (d *Discoverer) OnDisconnection(channelId string) {
|
||||
d.lock.Lock()
|
||||
defer d.lock.Unlock()
|
||||
|
||||
newSubs := make(map[string]channelIdList, len(d.subs))
|
||||
|
||||
for event, list := range d.subs {
|
||||
newList := make(channelIdList, 0)
|
||||
for _, id := range list {
|
||||
if id != channelId {
|
||||
newList = append(newList, id)
|
||||
}
|
||||
}
|
||||
if len(newList) > 0 {
|
||||
newSubs[event] = newList
|
||||
}
|
||||
}
|
||||
|
||||
d.subs = newSubs
|
||||
}
|
||||
|
||||
func (d *Discoverer) Subscribe(events []string, socket socketio.Socket) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
}
|
||||
channelId := socket.Id()
|
||||
|
||||
d.lock.Lock()
|
||||
defer d.lock.Unlock()
|
||||
|
||||
connectedModulesEvents := getConnectedModulesEventMap(d.instanceId)
|
||||
|
||||
for _, event := range events {
|
||||
if list, ok := d.subs[event]; ok {
|
||||
d.subs[event] = append(list, channelId)
|
||||
} else {
|
||||
d.subs[event] = []string{channelId}
|
||||
}
|
||||
|
||||
if addrList, ok := connectedModulesEvents[event]; ok {
|
||||
d.sendAddrList(socket, event, addrList)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Discoverer) BroadcastModuleAddresses(moduleName string) {
|
||||
d.lock.RLock()
|
||||
defer d.lock.RUnlock()
|
||||
|
||||
event := utils.ModuleConnected(moduleName)
|
||||
connectedModulesEvents := getConnectedModulesEventMap(d.instanceId)
|
||||
addrList := connectedModulesEvents[event]
|
||||
channelList, channelListPresent := d.subs[event]
|
||||
if channelListPresent {
|
||||
for _, id := range channelList {
|
||||
if s, ok := GetConnectionById(d.instanceId, id); ok {
|
||||
d.sendAddrList(s, event, addrList)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Discoverer) sendAddrList(socket socketio.Socket, event string, addressList []structure.AddressConfiguration) {
|
||||
if addressList == nil {
|
||||
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 socket.Emit(event, string(bytes))
|
||||
}, bf)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetModuleAddressList(instanceId string, moduleName string) []structure.AddressConfiguration {
|
||||
event := utils.ModuleConnected(moduleName)
|
||||
connectedModulesEvents := getConnectedModulesEventMap(instanceId)
|
||||
addrList := connectedModulesEvents[event]
|
||||
if addrList == nil {
|
||||
return make([]structure.AddressConfiguration, 0)
|
||||
}
|
||||
return addrList
|
||||
}
|
||||
|
||||
func getConnectedModulesEventMap(instanceId string) map[string][]structure.AddressConfiguration {
|
||||
connectedModulesEventMap := make(map[string][]structure.AddressConfiguration)
|
||||
connMap := GetModuleConnectionIdMapByInstanceId(instanceId)
|
||||
|
||||
for moduleName, channelIdList := range connMap {
|
||||
event := utils.ModuleConnected(moduleName)
|
||||
addrList := make([]structure.AddressConfiguration, 0)
|
||||
|
||||
backendConfigs := GetRoutes().Routes
|
||||
for _, id := range channelIdList {
|
||||
if cfg, ok := backendConfigs[id]; ok {
|
||||
addrList = append(addrList, cfg.Address)
|
||||
}
|
||||
}
|
||||
connectedModulesEventMap[event] = addrList
|
||||
}
|
||||
return connectedModulesEventMap
|
||||
}
|
||||
|
||||
func getOrRegisterDiscoverer(instanceId string) *Discoverer {
|
||||
discoverersLock.RLock()
|
||||
d, ok := discoverersMap[instanceId]
|
||||
discoverersLock.RUnlock()
|
||||
if ok {
|
||||
return d
|
||||
}
|
||||
|
||||
discoverersLock.Lock()
|
||||
defer discoverersLock.Unlock()
|
||||
if d, ok := discoverersMap[instanceId]; ok {
|
||||
return d
|
||||
}
|
||||
d = &Discoverer{
|
||||
subs: make(map[string]channelIdList),
|
||||
instanceId: instanceId,
|
||||
}
|
||||
discoverersMap[instanceId] = d
|
||||
return d
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/asaskevich/govalidator"
|
||||
"github.com/integration-system/isp-lib/bootstrap"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
|
||||
"isp-config-service/service"
|
||||
|
||||
"github.com/googollee/go-socket.io"
|
||||
"github.com/integration-system/isp-lib/config/schema"
|
||||
"github.com/integration-system/isp-lib/logger"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/model"
|
||||
)
|
||||
|
||||
const (
|
||||
routesSubscribers = ":routes_subs"
|
||||
)
|
||||
|
||||
func RoutesSubscribersRoom(instanceUuid string) string {
|
||||
return instanceUuid + routesSubscribers
|
||||
}
|
||||
|
||||
func onError(so socketio.Socket, err error) {
|
||||
logger.Warnf("error: %s", err)
|
||||
}
|
||||
|
||||
func onDisconnect(so socketio.Socket) {
|
||||
logger.Debugf("onDisconnect: %s", so.Id())
|
||||
instanceUuid, moduleName, err := service.ParseParameters(so.Request().URL.RawQuery)
|
||||
if err != nil {
|
||||
logger.Warn(err)
|
||||
return
|
||||
}
|
||||
|
||||
must(so.Leave(instanceUuid + moduleName))
|
||||
must(so.Leave(instanceUuid))
|
||||
must(so.Leave(RoutesSubscribersRoom(instanceUuid)))
|
||||
must(service.Disonnect(instanceUuid, moduleName))
|
||||
|
||||
discoverer := getOrRegisterDiscoverer(instanceUuid)
|
||||
discoverer.OnDisconnection(so.Id())
|
||||
discoverer.BroadcastModuleAddresses(moduleName)
|
||||
if backendRoutes.DeleteRoute(so.Id()) {
|
||||
BroadcastRoutesSnapshot(instanceUuid)
|
||||
}
|
||||
}
|
||||
|
||||
func onConnect(so socketio.Socket) {
|
||||
logger.Debugf("onConnect: %s", so.Id())
|
||||
|
||||
instanceUuid, moduleName, err := service.ParseParameters(so.Request().URL.RawQuery)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ConfigError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
config, err := service.NewConnection(instanceUuid, moduleName)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ConfigError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
must(so.Join(instanceUuid + moduleName))
|
||||
must(so.Join(instanceUuid))
|
||||
_ = so.Emit(
|
||||
utils.ConfigSendConfigWhenConnected, config.Data.ToJSON(), func(so socketio.Socket, data string) {
|
||||
logger.Debug("Client ACK with data: ", data)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func onReceivedModuleRequirements(so socketio.Socket, msg string) {
|
||||
logger.Debugf("onReceivedModuleRequirements: %s %s", so.Id(), msg)
|
||||
|
||||
instanceUuid, _, err := service.ParseParameters(so.Request().URL.RawQuery)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
declaration := bootstrap.ModuleRequirements{}
|
||||
err = json.Unmarshal([]byte(msg), &declaration)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
|
||||
logger.Debugf("onReceivedModuleRequirements: %s, error parse json data: %s", so.Id(), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if declaration.RequireRoutes {
|
||||
must(so.Join(RoutesSubscribersRoom(instanceUuid)))
|
||||
SendRoutesSnapshot(so)
|
||||
}
|
||||
discoverer := getOrRegisterDiscoverer(instanceUuid)
|
||||
discoverer.Subscribe(declaration.RequiredModules, so)
|
||||
}
|
||||
|
||||
func onReceiveModuleReady(so socketio.Socket, msg string) {
|
||||
logger.Debugf("onReceiveModuleReady: %s", so.Id())
|
||||
|
||||
handleModuleDeclaration(so, msg)
|
||||
}
|
||||
|
||||
func onReceiveRoutesUpdate(so socketio.Socket, msg string) {
|
||||
logger.Debugf("onReceiveRoutesUpdate: %s", so.Id())
|
||||
|
||||
handleModuleDeclaration(so, msg)
|
||||
}
|
||||
|
||||
func onReceiveRemoteConfigSchema(so socketio.Socket, msg string) {
|
||||
logger.Debugf("onReceiveRemoteConfigSchema: %s %s", so.Id(), msg)
|
||||
|
||||
instanceUuid, moduleName, err := service.ParseParameters(so.Request().URL.RawQuery)
|
||||
if err != nil {
|
||||
logger.Warn(err)
|
||||
return
|
||||
}
|
||||
|
||||
module, err := model.ModulesRep.GetModulesByInstanceUuidAndName(instanceUuid, moduleName)
|
||||
if err != nil {
|
||||
logger.Warn(err)
|
||||
return
|
||||
}
|
||||
if module == nil {
|
||||
logger.Warnf("Module '%s' in instance '%s' not found", moduleName, instanceUuid)
|
||||
return
|
||||
}
|
||||
|
||||
s := new(schema.ConfigSchema)
|
||||
if err := json.Unmarshal([]byte(msg), s); err != nil {
|
||||
logger.Warn(err)
|
||||
return
|
||||
}
|
||||
res, err := model.SchemaRep.GetSchemasByModulesId([]int32{module.Id})
|
||||
if err != nil {
|
||||
logger.Warn(err)
|
||||
return
|
||||
}
|
||||
if len(res) > 0 {
|
||||
schema := &res[0]
|
||||
if s.Version > schema.Version {
|
||||
schema.Version = s.Version
|
||||
schema.Schema = s.Schema
|
||||
if _, err := model.SchemaRep.UpdateConfigSchema(schema); err != nil {
|
||||
logger.Warn(err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cs := &entity.ConfigSchema{
|
||||
Version: s.Version,
|
||||
Schema: s.Schema,
|
||||
ModuleId: module.Id,
|
||||
}
|
||||
if _, err := model.SchemaRep.InsertConfigSchema(cs); err != nil {
|
||||
logger.Warn(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleModuleDeclaration(so socketio.Socket, msg string) {
|
||||
instanceUuid, moduleName, err := service.ParseParameters(so.Request().URL.RawQuery)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
declaration := structure.BackendDeclaration{}
|
||||
err = json.Unmarshal([]byte(msg), &declaration)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
|
||||
logger.Warnf("handleModuleDeclaration: %s, error parse json data: %s", so.Id(), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
_, err = govalidator.ValidateStruct(declaration)
|
||||
if err != nil {
|
||||
errors := govalidator.ErrorsByField(err)
|
||||
_ = so.Emit(utils.ErrorConnection, map[string]map[string]string{"error": errors})
|
||||
logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", so.Id(), errors)
|
||||
} else if backendRoutes.AddAddressOrUpdate(so.Id(), declaration) {
|
||||
BroadcastRoutesSnapshot(instanceUuid)
|
||||
|
||||
discoverer := getOrRegisterDiscoverer(instanceUuid)
|
||||
discoverer.BroadcastModuleAddresses(moduleName)
|
||||
}
|
||||
}
|
||||
|
||||
func onRequestConfig(so socketio.Socket) {
|
||||
logger.Debugf("onRequestConfig: %s", so.Id())
|
||||
|
||||
instanceUuid, moduleName, err := service.ParseParameters(so.Request().URL.RawQuery)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
config, err := service.GetConfig(instanceUuid, moduleName)
|
||||
if err != nil {
|
||||
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
_ = so.Emit(
|
||||
utils.ConfigSendConfigOnRequest,
|
||||
config.Data.ToJSON(),
|
||||
func(so socketio.Socket, data string) {
|
||||
logger.Debug("Client ACK with data: ", data)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package socket
|
||||
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/googollee/go-socket.io"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"github.com/integration-system/isp-lib/logger"
|
||||
sck "github.com/integration-system/isp-lib/socket"
|
||||
str "github.com/integration-system/isp-lib/structure"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"isp-config-service/conf"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/model"
|
||||
"isp-config-service/service"
|
||||
)
|
||||
|
||||
var (
|
||||
server *socketio.Server
|
||||
br *broadcaster
|
||||
socketRoomStats = sck.NewRoomStats()
|
||||
backendRoutes = &service.RouterTables{}
|
||||
ConfigServiceBackendDeclaration = &str.BackendDeclaration{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
newServer, err := socketio.NewServer(nil)
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
}
|
||||
sessionStore := sck.NewSessionStore(sck.WithOnRemoveCallback(func(id string) {
|
||||
socketRoomStats.RemoveSocketConn(id)
|
||||
}))
|
||||
newServer.SetSessionManager(sessionStore)
|
||||
newServer.SetAdaptor(socketRoomStats)
|
||||
|
||||
must(newServer.On("connection", onConnect))
|
||||
must(newServer.On("disconnection", onDisconnect))
|
||||
must(newServer.On("error", onError))
|
||||
must(newServer.On(utils.ModuleSendRequirements, onReceivedModuleRequirements))
|
||||
must(newServer.On(utils.ModuleReady, onReceiveModuleReady))
|
||||
must(newServer.On(utils.ModuleSendConfigSchema, onReceiveRemoteConfigSchema))
|
||||
must(newServer.On(utils.ModuleUpdateRoutes, onReceiveRoutesUpdate))
|
||||
|
||||
server = newServer
|
||||
br = NewBroadcaster(server, 0)
|
||||
}
|
||||
|
||||
func Get() *socketio.Server {
|
||||
return server
|
||||
}
|
||||
|
||||
func GetRoutes() *service.RouterTables {
|
||||
return backendRoutes
|
||||
}
|
||||
|
||||
func SetBackendMethods(backendConfig *str.BackendDeclaration) {
|
||||
ConfigServiceBackendDeclaration = backendConfig
|
||||
|
||||
moduleName := config.Get().(*conf.Configuration).ModuleName
|
||||
backendRoutes.AddAddressOrUpdate(moduleName, *ConfigServiceBackendDeclaration)
|
||||
instances, err := model.InstanceRep.GetInstances(nil)
|
||||
if err != nil {
|
||||
logger.Warn("Error receiving instance from db", err)
|
||||
} else {
|
||||
for _, v := range instances {
|
||||
BroadcastRoutesSnapshot(v.Uuid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetRoomsCount() map[string]map[string]int {
|
||||
return socketRoomStats.RoomsCount()
|
||||
}
|
||||
|
||||
func GetModuleConnectionIdMapByInstanceId(instanceId string) map[string][]string {
|
||||
return socketRoomStats.GetModuleConnectionMap()[instanceId]
|
||||
}
|
||||
|
||||
func GetConnectionById(instanceId, sockId string) (*sck.SocketConn, bool) {
|
||||
return socketRoomStats.GetConnection(instanceId, sockId)
|
||||
}
|
||||
|
||||
func SendNewConfig(instanceUuid string, moduleName string, config *entity.Config) {
|
||||
moduleKey := instanceUuid + moduleName
|
||||
br.BroadcastConfig(moduleKey, config.Data.ToJSON(), nil)
|
||||
}
|
||||
|
||||
func SendRoutesSnapshot(so socketio.Socket) {
|
||||
bytes, err := json.Marshal(backendRoutes.GetRoutes())
|
||||
if err != nil {
|
||||
logger.Warn("Error when serializing Backend Routes", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := so.Emit(utils.ConfigSendRoutesWhenConnected, string(bytes)); err != nil {
|
||||
logger.Warn(err)
|
||||
}
|
||||
}
|
||||
|
||||
func BroadcastRoutesSnapshot(instanceUuid string) {
|
||||
bytes, err := json.Marshal(backendRoutes.GetRoutes())
|
||||
if err != nil {
|
||||
logger.Warn("Error when serializing Backend Routes", err)
|
||||
return
|
||||
}
|
||||
|
||||
br.BroadcastRoutes(RoutesSubscribersRoom(instanceUuid), string(bytes), func(data interface{}) {
|
||||
logger.Infof("Send %d routes", len(*backendRoutes.GetRoutes()))
|
||||
logger.Debugf("Send Routes: %v", *backendRoutes.GetRoutes())
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user