micro/registry/gossip/util.go

133 lines
2.2 KiB
Go
Raw Normal View History

2018-12-04 19:41:40 +03:00
package gossip
import (
"github.com/micro/go-micro/registry"
)
func cp(current []*registry.Service) []*registry.Service {
var services []*registry.Service
for _, service := range current {
// copy service
s := new(registry.Service)
*s = *service
// copy nodes
var nodes []*registry.Node
for _, node := range service.Nodes {
n := new(registry.Node)
*n = *node
nodes = append(nodes, n)
}
s.Nodes = nodes
// copy endpoints
var eps []*registry.Endpoint
for _, ep := range service.Endpoints {
e := new(registry.Endpoint)
*e = *ep
eps = append(eps, e)
}
s.Endpoints = eps
// append service
services = append(services, s)
}
return services
}
func addNodes(old, neu []*registry.Node) []*registry.Node {
var nodes []*registry.Node
// add all new nodes
2018-12-04 19:41:40 +03:00
for _, n := range neu {
node := *n
nodes = append(nodes, &node)
}
// look at old nodes
for _, o := range old {
var exists bool
// check against new nodes
for _, n := range nodes {
// ids match then skip
2018-12-04 19:41:40 +03:00
if o.Id == n.Id {
exists = true
2018-12-04 19:41:40 +03:00
break
}
}
// keep old node
if !exists {
node := *o
nodes = append(nodes, &node)
2018-12-04 19:41:40 +03:00
}
}
return nodes
2018-12-04 19:41:40 +03:00
}
func addServices(old, neu []*registry.Service) []*registry.Service {
for _, s := range neu {
var seen bool
for i, o := range old {
if o.Version == s.Version {
s.Nodes = addNodes(o.Nodes, s.Nodes)
seen = true
old[i] = s
break
}
}
if !seen {
old = append(old, s)
}
}
return old
}
func delNodes(old, del []*registry.Node) []*registry.Node {
var nodes []*registry.Node
for _, o := range old {
var rem bool
for _, n := range del {
if o.Id == n.Id {
rem = true
break
}
}
if !rem {
nodes = append(nodes, o)
}
}
return nodes
}
func delServices(old, del []*registry.Service) []*registry.Service {
var services []*registry.Service
for _, o := range old {
srv := new(registry.Service)
*srv = *o
2018-12-04 19:41:40 +03:00
var rem bool
2018-12-04 19:41:40 +03:00
for _, s := range del {
if srv.Version == s.Version {
srv.Nodes = delNodes(srv.Nodes, s.Nodes)
if len(srv.Nodes) == 0 {
2018-12-04 19:41:40 +03:00
rem = true
}
}
}
2018-12-04 19:41:40 +03:00
if !rem {
services = append(services, srv)
2018-12-04 19:41:40 +03:00
}
}
2018-12-04 19:41:40 +03:00
return services
}