gosensus

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

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

Go to latest
Published: Sep 24, 2020 License: MIT Imports: 16 Imported by: 0

README

Gosensus

Tests

This package implements a simple consensus algorithm to elect a leader among a number of nodes.

Includes a test to ensure the election algorithm works correctly.

Installation

go get github.com/bn4t/gosensus

How to use

package main

import (
    "github.com/bn4t/gosensus"
    "go.etcd.io/etcd/v3/clientv3"
    "go.uber.org/zap"
    "log"
    "time"
)

func main() { 
        // init etcd client 
	etcdCli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"http://localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	
        // init zap logger
	Zap, err := zap.NewProduction()
	if err != nil {
		log.Fatal(err)
	}

        // init gosensus client
	GosClient := &gosensus.Client{
		EtcdClient: etcdCli,
		Logger:     Zap,
		DataDir:    "/var/lib/gosensus/", // the directory in which the node's key is stored
	}
	if err := GosClient.Start(); err != nil {
		log.Fatal("failed to start consensus", zap.Error(err))
	}
	
        log.Print(GosClient.IsLeader())
	
        GosClient.Stop()
}

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	EtcdClient *clientv3.Client
	Logger     *zap.Logger
	DataDir    string // the directory in which the node key is stored
	// contains filtered or unexported fields
}

func (*Client) GetAllNodeIds

func (c *Client) GetAllNodeIds() ([]string, error)

GetAllNodeIds grabs all nodes from etcd and returns all the ids in a slice Important: this slice also contains the node id of this node

func (*Client) IsLeader

func (c *Client) IsLeader() (leader bool)

IsLeader returns whether the node is currently the leader.

func (*Client) NodeId

func (c *Client) NodeId() string

NodeId returns the node id of this node The node id is based on the node key

func (*Client) Start

func (c *Client) Start() error

Start initializes the consensus algorithm

func (*Client) Stop

func (c *Client) Stop()

Stop stops gosensus from operating. After 5 seconds this node's entry in etcd will expire and this node will be completely removed from the consensus algorithm

Jump to

Keyboard shortcuts

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