update the gossiper
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
// Package gossip provides a zero dependency registry using the gossip protocol SWIM
|
||||
// Package Gossip provides a gossip registry based on hashicorp/memberlist
|
||||
package gossip
|
||||
|
||||
import (
|
||||
@@ -15,22 +15,13 @@ import (
|
||||
"github.com/micro/go-log"
|
||||
"github.com/micro/go-micro/registry"
|
||||
pb "github.com/micro/go-micro/registry/gossip/proto"
|
||||
"github.com/mitchellh/hashstructure"
|
||||
)
|
||||
|
||||
type gossipRegistry struct {
|
||||
opts registry.Options
|
||||
queue *memberlist.TransmitLimitedQueue
|
||||
memberlist *memberlist.Memberlist
|
||||
delegate *delegate
|
||||
|
||||
sync.RWMutex
|
||||
services map[string][]*registry.Service
|
||||
watchers map[string]*watcher
|
||||
}
|
||||
|
||||
var (
|
||||
// defaults to random port
|
||||
defaultPort = 0
|
||||
const (
|
||||
addAction = "update"
|
||||
delAction = "delete"
|
||||
syncAction = "sync"
|
||||
)
|
||||
|
||||
type broadcast struct {
|
||||
@@ -39,8 +30,134 @@ type broadcast struct {
|
||||
}
|
||||
|
||||
type delegate struct {
|
||||
queue *memberlist.TransmitLimitedQueue
|
||||
updates chan *update
|
||||
}
|
||||
|
||||
type gossipRegistry struct {
|
||||
queue *memberlist.TransmitLimitedQueue
|
||||
registry *gossipRegistry
|
||||
updates chan *update
|
||||
options registry.Options
|
||||
member *memberlist.Memberlist
|
||||
interval time.Duration
|
||||
|
||||
sync.RWMutex
|
||||
services map[string][]*registry.Service
|
||||
|
||||
s sync.RWMutex
|
||||
watchers map[string]chan *registry.Result
|
||||
}
|
||||
|
||||
type update struct {
|
||||
Update *pb.Update
|
||||
Service *registry.Service
|
||||
sync chan *registry.Service
|
||||
}
|
||||
|
||||
var (
|
||||
// You should change this if using secure
|
||||
DefaultSecret = []byte("gossip")
|
||||
ExpiryTick = time.Second * 5
|
||||
)
|
||||
|
||||
func configure(g *gossipRegistry, opts ...registry.Option) error {
|
||||
// loop through address list and get valid entries
|
||||
addrs := func(curAddrs []string) []string {
|
||||
var newAddrs []string
|
||||
for _, addr := range curAddrs {
|
||||
if trimAddr := strings.TrimSpace(addr); len(trimAddr) > 0 {
|
||||
newAddrs = append(newAddrs, trimAddr)
|
||||
}
|
||||
}
|
||||
return newAddrs
|
||||
}
|
||||
|
||||
// current address list
|
||||
curAddrs := addrs(g.options.Addrs)
|
||||
|
||||
// parse options
|
||||
for _, o := range opts {
|
||||
o(&g.options)
|
||||
}
|
||||
|
||||
// new address list
|
||||
newAddrs := addrs(g.options.Addrs)
|
||||
|
||||
// no new nodes and existing member. no configure
|
||||
if (len(newAddrs) == len(curAddrs)) && g.member != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// shutdown old member
|
||||
if g.member != nil {
|
||||
g.member.Shutdown()
|
||||
}
|
||||
|
||||
// replace addresses
|
||||
curAddrs = newAddrs
|
||||
|
||||
// create a queue
|
||||
queue := &memberlist.TransmitLimitedQueue{
|
||||
NumNodes: func() int {
|
||||
return len(curAddrs)
|
||||
},
|
||||
RetransmitMult: 3,
|
||||
}
|
||||
|
||||
// machine hostname
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
// create a new default config
|
||||
c := memberlist.DefaultLocalConfig()
|
||||
|
||||
// set bind to random port
|
||||
c.BindPort = 0
|
||||
|
||||
// set the name
|
||||
c.Name = strings.Join([]string{"micro", hostname, uuid.New().String()}, "-")
|
||||
|
||||
// set the delegate
|
||||
c.Delegate = &delegate{
|
||||
updates: g.updates,
|
||||
queue: queue,
|
||||
}
|
||||
|
||||
// log to dev null
|
||||
c.LogOutput = ioutil.Discard
|
||||
|
||||
// set a secret key if secure
|
||||
if g.options.Secure {
|
||||
k, ok := g.options.Context.Value(contextSecretKey{}).([]byte)
|
||||
if !ok {
|
||||
// use the default secret
|
||||
k = DefaultSecret
|
||||
}
|
||||
c.SecretKey = k
|
||||
}
|
||||
|
||||
// TODO: set advertise addr to advertise behind nat
|
||||
|
||||
// create the memberlist
|
||||
m, err := memberlist.Create(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// join the memberlist
|
||||
if len(curAddrs) > 0 {
|
||||
_, err := m.Join(curAddrs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// set internals
|
||||
g.queue = queue
|
||||
g.member = m
|
||||
g.interval = c.GossipInterval
|
||||
|
||||
log.Logf("Registry Listening on %s", m.LocalNode().Address())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *broadcast) Invalidates(other memberlist.Broadcast) bool {
|
||||
@@ -91,56 +208,35 @@ func (d *delegate) NotifyMsg(b []byte) {
|
||||
return
|
||||
}
|
||||
|
||||
up := new(pb.Update)
|
||||
if err := proto.Unmarshal(b, up); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// only process service action
|
||||
if up.Type != "service" {
|
||||
return
|
||||
}
|
||||
|
||||
var service *registry.Service
|
||||
|
||||
switch up.Metadata["Content-Type"] {
|
||||
case "application/json":
|
||||
if err := json.Unmarshal(up.Data, &service); err != nil {
|
||||
go func() {
|
||||
up := new(pb.Update)
|
||||
if err := proto.Unmarshal(b, up); err != nil {
|
||||
return
|
||||
}
|
||||
// no other content type
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
d.registry.Lock()
|
||||
defer d.registry.Unlock()
|
||||
|
||||
// get existing service
|
||||
s := d.registry.services[service.Name]
|
||||
|
||||
// save update
|
||||
switch up.Action {
|
||||
case "update":
|
||||
d.registry.services[service.Name] = addServices(s, []*registry.Service{service})
|
||||
case "delete":
|
||||
services := delServices(s, []*registry.Service{service})
|
||||
if len(services) == 0 {
|
||||
delete(d.registry.services, service.Name)
|
||||
// only process service action
|
||||
if up.Type != "service" {
|
||||
return
|
||||
}
|
||||
d.registry.services[service.Name] = services
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
// notify watchers
|
||||
for _, w := range d.registry.watchers {
|
||||
select {
|
||||
case w.ch <- ®istry.Result{Action: up.Action, Service: service}:
|
||||
var service *registry.Service
|
||||
|
||||
switch up.Metadata["Content-Type"] {
|
||||
case "application/json":
|
||||
if err := json.Unmarshal(up.Data, &service); err != nil {
|
||||
return
|
||||
}
|
||||
// no other content type
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// send update
|
||||
d.updates <- &update{
|
||||
Update: up,
|
||||
Service: service,
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (d *delegate) GetBroadcasts(overhead, limit int) [][]byte {
|
||||
@@ -148,9 +244,25 @@ func (d *delegate) GetBroadcasts(overhead, limit int) [][]byte {
|
||||
}
|
||||
|
||||
func (d *delegate) LocalState(join bool) []byte {
|
||||
d.registry.RLock()
|
||||
b, _ := json.Marshal(d.registry.services)
|
||||
d.registry.RUnlock()
|
||||
if !join {
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
syncCh := make(chan *registry.Service, 1)
|
||||
services := map[string][]*registry.Service{}
|
||||
|
||||
d.updates <- &update{
|
||||
Update: &pb.Update{
|
||||
Action: syncAction,
|
||||
},
|
||||
sync: syncCh,
|
||||
}
|
||||
|
||||
for srv := range syncCh {
|
||||
services[srv.Name] = append(services[srv.Name], srv)
|
||||
}
|
||||
|
||||
b, _ := json.Marshal(services)
|
||||
return b
|
||||
}
|
||||
|
||||
@@ -161,37 +273,164 @@ func (d *delegate) MergeRemoteState(buf []byte, join bool) {
|
||||
if !join {
|
||||
return
|
||||
}
|
||||
|
||||
var services map[string][]*registry.Service
|
||||
if err := json.Unmarshal(buf, &services); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
d.registry.Lock()
|
||||
for k, v := range services {
|
||||
d.registry.services[k] = addServices(d.registry.services[k], v)
|
||||
for _, service := range services {
|
||||
for _, srv := range service {
|
||||
d.updates <- &update{
|
||||
Update: &pb.Update{Action: addAction},
|
||||
Service: srv,
|
||||
sync: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) publish(action string, services []*registry.Service) {
|
||||
g.s.RLock()
|
||||
for _, sub := range g.watchers {
|
||||
go func(sub chan *registry.Result) {
|
||||
for _, service := range services {
|
||||
sub <- ®istry.Result{Action: action, Service: service}
|
||||
}
|
||||
}(sub)
|
||||
}
|
||||
g.s.RUnlock()
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) subscribe() (chan *registry.Result, chan bool) {
|
||||
next := make(chan *registry.Result, 10)
|
||||
exit := make(chan bool)
|
||||
|
||||
id := uuid.New().String()
|
||||
|
||||
g.s.Lock()
|
||||
g.watchers[id] = next
|
||||
g.s.Unlock()
|
||||
|
||||
go func() {
|
||||
<-exit
|
||||
g.s.Lock()
|
||||
delete(g.watchers, id)
|
||||
close(next)
|
||||
g.s.Unlock()
|
||||
}()
|
||||
|
||||
return next, exit
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) run() {
|
||||
var mtx sync.Mutex
|
||||
updates := map[uint64]*update{}
|
||||
|
||||
// expiry loop
|
||||
go func() {
|
||||
t := time.NewTicker(ExpiryTick)
|
||||
defer t.Stop()
|
||||
|
||||
for _ = range t.C {
|
||||
now := uint64(time.Now().UnixNano())
|
||||
|
||||
mtx.Lock()
|
||||
|
||||
// process all the updates
|
||||
for k, v := range updates {
|
||||
// check if expiry time has passed
|
||||
if d := (v.Update.Timestamp + v.Update.Expires); d < now {
|
||||
// delete from records
|
||||
delete(updates, k)
|
||||
// set to delete
|
||||
v.Update.Action = delAction
|
||||
// fire a new update
|
||||
g.updates <- v
|
||||
}
|
||||
}
|
||||
|
||||
mtx.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// process the updates
|
||||
for u := range g.updates {
|
||||
switch u.Update.Action {
|
||||
case addAction:
|
||||
g.Lock()
|
||||
if service, ok := g.services[u.Service.Name]; !ok {
|
||||
g.services[u.Service.Name] = []*registry.Service{u.Service}
|
||||
|
||||
} else {
|
||||
g.services[u.Service.Name] = addServices(service, []*registry.Service{u.Service})
|
||||
}
|
||||
g.Unlock()
|
||||
|
||||
// publish update to watchers
|
||||
go g.publish(addAction, []*registry.Service{u.Service})
|
||||
|
||||
// we need to expire the node at some point in the future
|
||||
if u.Update.Expires > 0 {
|
||||
// create a hash of this service
|
||||
if hash, err := hashstructure.Hash(u.Service, nil); err == nil {
|
||||
mtx.Lock()
|
||||
updates[hash] = u
|
||||
mtx.Unlock()
|
||||
}
|
||||
}
|
||||
case delAction:
|
||||
g.Lock()
|
||||
if service, ok := g.services[u.Service.Name]; ok {
|
||||
if services := delServices(service, []*registry.Service{u.Service}); len(services) == 0 {
|
||||
delete(g.services, u.Service.Name)
|
||||
} else {
|
||||
g.services[u.Service.Name] = services
|
||||
}
|
||||
}
|
||||
g.Unlock()
|
||||
|
||||
// publish update to watchers
|
||||
go g.publish(delAction, []*registry.Service{u.Service})
|
||||
|
||||
// delete from expiry checks
|
||||
if hash, err := hashstructure.Hash(u.Service, nil); err == nil {
|
||||
mtx.Lock()
|
||||
delete(updates, hash)
|
||||
mtx.Unlock()
|
||||
}
|
||||
case syncAction:
|
||||
// no sync channel provided
|
||||
if u.sync == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
g.RLock()
|
||||
|
||||
// push all services through the sync chan
|
||||
for _, service := range g.services {
|
||||
for _, srv := range service {
|
||||
u.sync <- srv
|
||||
}
|
||||
|
||||
// publish to watchers
|
||||
go g.publish(addAction, service)
|
||||
}
|
||||
|
||||
g.RUnlock()
|
||||
|
||||
// close the sync chan
|
||||
close(u.sync)
|
||||
}
|
||||
}
|
||||
d.registry.Unlock()
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) Init(opts ...registry.Option) error {
|
||||
addrs := g.opts.Addrs
|
||||
for _, o := range opts {
|
||||
o(&g.opts)
|
||||
}
|
||||
|
||||
// if we have memberlist join it
|
||||
if len(addrs) != len(g.opts.Addrs) {
|
||||
_, err := g.memberlist.Join(g.opts.Addrs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return configure(g, opts...)
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) Options() registry.Options {
|
||||
return g.opts
|
||||
return g.options
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) Register(s *registry.Service, opts ...registry.RegisterOption) error {
|
||||
@@ -201,12 +440,22 @@ func (g *gossipRegistry) Register(s *registry.Service, opts ...registry.Register
|
||||
}
|
||||
|
||||
g.Lock()
|
||||
g.services[s.Name] = addServices(g.services[s.Name], []*registry.Service{s})
|
||||
if service, ok := g.services[s.Name]; !ok {
|
||||
g.services[s.Name] = []*registry.Service{s}
|
||||
} else {
|
||||
g.services[s.Name] = addServices(service, []*registry.Service{s})
|
||||
}
|
||||
g.Unlock()
|
||||
|
||||
var options registry.RegisterOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
up := &pb.Update{
|
||||
Id: uuid.New().String(),
|
||||
Timestamp: uint64(time.Now().UnixNano()),
|
||||
Expires: uint64(options.TTL.Nanoseconds()),
|
||||
Action: "update",
|
||||
Type: "service",
|
||||
Metadata: map[string]string{
|
||||
@@ -220,6 +469,9 @@ func (g *gossipRegistry) Register(s *registry.Service, opts ...registry.Register
|
||||
notify: nil,
|
||||
})
|
||||
|
||||
// wait
|
||||
<-time.After(g.interval * 2)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -230,7 +482,13 @@ func (g *gossipRegistry) Deregister(s *registry.Service) error {
|
||||
}
|
||||
|
||||
g.Lock()
|
||||
g.services[s.Name] = delServices(g.services[s.Name], []*registry.Service{s})
|
||||
if service, ok := g.services[s.Name]; ok {
|
||||
if services := delServices(service, []*registry.Service{s}); len(services) == 0 {
|
||||
delete(g.services, s.Name)
|
||||
} else {
|
||||
g.services[s.Name] = services
|
||||
}
|
||||
}
|
||||
g.Unlock()
|
||||
|
||||
up := &pb.Update{
|
||||
@@ -249,135 +507,59 @@ func (g *gossipRegistry) Deregister(s *registry.Service) error {
|
||||
notify: nil,
|
||||
})
|
||||
|
||||
// wait
|
||||
<-time.After(g.interval * 2)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) GetService(name string) ([]*registry.Service, error) {
|
||||
g.RLock()
|
||||
if s, ok := g.services[name]; ok {
|
||||
service := cp(s)
|
||||
g.RUnlock()
|
||||
return service, nil
|
||||
}
|
||||
service, ok := g.services[name]
|
||||
g.RUnlock()
|
||||
return nil, registry.ErrNotFound
|
||||
if !ok {
|
||||
return nil, registry.ErrNotFound
|
||||
}
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) ListServices() ([]*registry.Service, error) {
|
||||
var services []*registry.Service
|
||||
g.RLock()
|
||||
for name, _ := range g.services {
|
||||
services = append(services, ®istry.Service{Name: name})
|
||||
for _, service := range g.services {
|
||||
services = append(services, service...)
|
||||
}
|
||||
g.RUnlock()
|
||||
return services, nil
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) {
|
||||
var options registry.WatchOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
// watcher id
|
||||
id := uuid.New().String()
|
||||
|
||||
// create watcher
|
||||
w := &watcher{
|
||||
ch: make(chan *registry.Result, 1),
|
||||
exit: make(chan bool),
|
||||
id: id,
|
||||
// filter service
|
||||
srv: options.Service,
|
||||
// delete self
|
||||
fn: func() {
|
||||
g.Lock()
|
||||
delete(g.watchers, id)
|
||||
g.Unlock()
|
||||
},
|
||||
}
|
||||
|
||||
// save watcher
|
||||
g.Lock()
|
||||
g.watchers[w.id] = w
|
||||
g.Unlock()
|
||||
|
||||
return w, nil
|
||||
n, e := g.subscribe()
|
||||
return newGossipWatcher(n, e, opts...)
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) String() string {
|
||||
return "gossip"
|
||||
}
|
||||
|
||||
func (g *gossipRegistry) run() error {
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
// delegates
|
||||
d := new(delegate)
|
||||
|
||||
// create a new default config
|
||||
c := memberlist.DefaultLocalConfig()
|
||||
|
||||
// assign the delegate
|
||||
c.Delegate = d
|
||||
|
||||
// Set the bind port
|
||||
c.BindPort = defaultPort
|
||||
|
||||
// set the name
|
||||
c.Name = strings.Join([]string{"micro", hostname, uuid.New().String()}, "-")
|
||||
|
||||
// log to dev null
|
||||
c.LogOutput = ioutil.Discard
|
||||
|
||||
// TODO: set advertise addr to advertise behind nat
|
||||
|
||||
// create the memberlist
|
||||
m, err := memberlist.Create(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// if we have memberlist join it
|
||||
if len(g.opts.Addrs) > 0 {
|
||||
_, err := m.Join(g.opts.Addrs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Set the broadcast limit and number of nodes
|
||||
d.queue = &memberlist.TransmitLimitedQueue{
|
||||
NumNodes: func() int {
|
||||
return m.NumMembers()
|
||||
},
|
||||
RetransmitMult: 3,
|
||||
}
|
||||
|
||||
g.queue = d.queue
|
||||
g.memberlist = m
|
||||
g.delegate = d
|
||||
d.registry = g
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewRegistry returns a new gossip registry
|
||||
func NewRegistry(opts ...registry.Option) registry.Registry {
|
||||
var options registry.Options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
g := &gossipRegistry{
|
||||
opts: options,
|
||||
gossip := &gossipRegistry{
|
||||
options: registry.Options{},
|
||||
updates: make(chan *update, 100),
|
||||
services: make(map[string][]*registry.Service),
|
||||
}
|
||||
if err := g.run(); err != nil {
|
||||
log.Fatal(err)
|
||||
watchers: make(map[string]chan *registry.Result),
|
||||
}
|
||||
|
||||
log.Logf("Registry Listening on %s", g.memberlist.LocalNode().Address())
|
||||
// return gossip registry
|
||||
return g
|
||||
// configure the gossiper
|
||||
if err := configure(gossip, opts...); err != nil {
|
||||
log.Fatal("Error configuring registry: %v", err)
|
||||
}
|
||||
|
||||
// run the updater
|
||||
go gossip.run()
|
||||
|
||||
// wait for setup
|
||||
<-time.After(gossip.interval * 2)
|
||||
|
||||
return gossip
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user