tielect

package module
v0.0.0-...-ef08f28 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 26, 2022 License: Apache-2.0 Imports: 6 Imported by: 0

README

tielect

A leader-election library at scale using TiDB as backend

Usage

type MyCandidate struct {
	id string
}

// Make sure the ID is unique
func (c *MyCandidate) ID() string {
	return c.id
}

func (c *MyCandidate) Val() string {
	return "any value"
}

func UUID() string {
	u, _ := uuid.NewV4()
	return u.String()
}

func main() {
	// Use TiDB connection here
	db, err := sql.Open("mysql", "root:@tcp(localhost:4000)/test")
	if err != nil {
		log.Fatal(err)
	}

	e := tielect.NewElection(db, "default", &MyCandidate{
		id: UUID(),
	})
	e.Init()

	// Start election, it will block until election is finished
	if ok, err := e.Campaign(); err != nil {
		panic(err)
	} else if !ok {
		log.I("I am not the leader")
	} else {
		log.I("I'm the leader!")
	}
}

Documentation

Index

Constants

View Source
const (
	// DefaultLease is the default lease time for a leader.
	DefaultLeaseInSec = 5
)

Variables

View Source
var (
	ErrNotLeader = errors.New("not leader")
)

Functions

This section is empty.

Types

type Candidate

type Candidate interface {
	ID() string
	Val() string
}

type Election

type Election struct {
	// contains filtered or unexported fields
}

func NewElection

func NewElection(db *sql.DB, name string, candidate Candidate) *Election

func (*Election) Campaign

func (e *Election) Campaign() (bool, error)

Campaign will block until the election is won.

func (*Election) Init

func (e *Election) Init() error

func (*Election) Leader

func (e *Election) Leader() (Candidate, error)

Leader returns the current leader.

func (*Election) Proclaim

func (e *Election) Proclaim() error

Proclaim will update the lease time for the leader. if current candidate is not leader will return ErrNotLeader.

func (*Election) Resign

func (e *Election) Resign(name string) error

Resign will resign the current leader.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL