github.com/moleculer-go/moleculer@v0.3.3/registry/nodeCatalog.go (about) 1 package registry 2 3 import ( 4 "sync" 5 "time" 6 7 "github.com/moleculer-go/moleculer" 8 log "github.com/sirupsen/logrus" 9 ) 10 11 // NodeCatalog catalog of nodes 12 type NodeCatalog struct { 13 nodes sync.Map 14 logger *log.Entry 15 } 16 17 // CreateNodesCatalog create a node catalog 18 func CreateNodesCatalog(logger *log.Entry) *NodeCatalog { 19 return &NodeCatalog{sync.Map{}, logger} 20 } 21 22 // HeartBeat delegate the heart beat to the node in question payload.sender 23 func (catalog *NodeCatalog) HeartBeat(heartbeat map[string]interface{}) bool { 24 sender := heartbeat["sender"].(string) 25 node, nodeExists := catalog.nodes.Load(sender) 26 27 if nodeExists && (node.(moleculer.Node)).IsAvailable() { 28 (node.(moleculer.Node)).HeartBeat(heartbeat) 29 return true 30 } 31 return false 32 } 33 34 func (catalog *NodeCatalog) list() []moleculer.Node { 35 var result []moleculer.Node 36 catalog.nodes.Range(func(key, value interface{}) bool { 37 node := value.(moleculer.Node) 38 result = append(result, node) 39 return true 40 }) 41 return result 42 } 43 44 // expiredNodes check nodes with heartbeat expired based on the timeout parameter 45 func (catalog *NodeCatalog) expiredNodes(timeout time.Duration) []moleculer.Node { 46 var result []moleculer.Node 47 catalog.nodes.Range(func(key, value interface{}) bool { 48 node := value.(moleculer.Node) 49 if node.IsExpired(timeout) { 50 result = append(result, node) 51 } 52 return true 53 }) 54 return result 55 } 56 57 // findNode : return a Node instance from the catalog 58 func (catalog *NodeCatalog) findNode(nodeID string) (moleculer.Node, bool) { 59 node, exists := catalog.nodes.Load(nodeID) 60 if exists { 61 return node.(moleculer.Node), true 62 } else { 63 return nil, false 64 } 65 } 66 67 // removeNode : remove a node from the catalog 68 func (catalog *NodeCatalog) removeNode(nodeID string) { 69 catalog.nodes.Delete(nodeID) 70 } 71 72 // Info : process info received about a NODE. It can be new, update to existing 73 func (catalog *NodeCatalog) Add(node moleculer.Node) { 74 catalog.nodes.Store(node.GetID(), node) 75 } 76 77 // Info : process info received about a NODE. It can be new, update to existing 78 func (catalog *NodeCatalog) Info(info map[string]interface{}) (bool, bool, []map[string]interface{}) { 79 sender := info["sender"].(string) 80 node, exists := catalog.findNode(sender) 81 var reconnected bool 82 removedServices := []map[string]interface{}{} 83 if exists { 84 reconnected, removedServices = node.Update(sender, info) 85 } else { 86 node := CreateNode(sender, false, catalog.logger.WithField("remote-node", sender)) 87 node.Update(sender, info) 88 catalog.Add(node) 89 } 90 return exists, reconnected, removedServices 91 }