Skip to content

octu0/bully-election

Repository files navigation

bully-election

MIT License GoDoc Go Report Card Releases

Hashicorp's memberlist based Bully Leader Election.

Features:

  • Simple API
  • Voter / Nonvoter node state management(monitoring)
  • TransferLeadership

Installation

go get github.com/octu0/bully-election

Example

package main

import (
	"context"
	"log"
	"time"

	"github.com/hashicorp/memberlist"
	"github.com/octu0/bully-election"
)

func main() {
	ctx := context.Background()
	conf := memberlist.DefaultLANConfig()
	conf.Name = "node1"
	conf.BindPort = 7947
	conf.AdvertiseAddr = "10.0.0.123"
	conf.AdvertisePort = conf.BindPort

	b, err := bullyelection.CreateVoter(ctx, conf,
		WithElectionTimeout(1*time.Second),
		WithObserveFunc(func(b *bullyelection.Bully, evt bullyelection.NodeEvent, id, addr string) {
			log.Printf("[%s] event: %s node=%s(%s)", b.ID(), evt.String(), id, addr)
			if evt == bullyelection.ElectionEvent {
			for _, n := range b.Members() {
				log.Printf("%s is_leader=%v", n.ID(), n.IsLeader())
			}
		}
		}),
		WithOnErrorFunc(func(err error) {
			log.Printf("error=%+v", err)
		}),
	)
	err := b.Join("10.0.0.1")
	b.IsLeader()
	b.UpdateMetadata([]byte("hello world"))

	nn, _ := bullyelection.CreateNonVoter(ctx, conf2)
	err := nn.Join("10.0.0.1")
	for _, m := range nn.Members() {
		_ = m.UserMetadata()
	}

	b.Leave()
}

License

MIT, see LICENSE file for details.