gonsensus

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2025 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gonsensus

Go Reference test Go Report Card

Gonsensus is a distributed consensus implementation, written in Go, using S3 conditional operations for leader election. It provides a simple, reliable way to coordinate distributed systems using any S3 compatible object storage as the backing store. Conditional writes are required. See RFC 7232 for more details about conditional requests in general.

See example_test.go for a fully fledged example use case for simple leader election.

See integration_test.go for an example use case for leader election with quorum.

Features

  • S3-based leader election with atomic operations
  • Automatic failover and clean shutdown
  • Configurable TTL, polling, and quorum settings
  • Leader election and demotion callbacks
  • Observer pattern with heartbeat monitoring
  • Thread-safe operations with mutex protection
  • Version control for consistency
  • Minimal dependencies (AWS SDK only)

How it works

Gonsensus implements distributed consensus through S3:

Leader Election
  • Nodes compete to create a lock file in S3 using atomic operations
  • Winner becomes leader and maintains lock through periodic renewals
  • Failed renewals trigger automatic failover
Optional Quorum Management
  • When enabled, leader tracks observer nodes through heartbeats
  • Configurable quorum size ensures consensus
  • Can operate in simple leader-election mode without quorum
Fault Tolerance
  • Automatic failover on leader failure
  • Version control prevents split-brain scenarios
  • Grace periods handle clean transitions

Installation

go get github.com/thevilledev/gonsensus

Getting started

package main

import (
    "context"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/s3"
    "github.com/thevilledev/gonsensus"
)

func main() {
    // Initialize AWS S3 client
    cfg, _ := config.LoadDefaultConfig(context.Background())
    s3Client := s3.NewFromConfig(cfg)

    // Create consensus manager
    manager, _ := gonsensus.NewManager(s3Client, "my-bucket", gonsensus.Config{
        NodeID:     "node-1",
        LockPrefix: "consensus/",
    })

    // Set leader callbacks
    manager.SetCallbacks(
        func(ctx context.Context) error { /* on elected */ return nil },
        func(ctx context.Context) { /* on demoted */ },
    )

    // Run manager
    manager.Run(context.Background())
}

Authentication

This project relies on the AWS S3 client default authentication mechanism. See AWS documentation for full reference on configuration and credentials presedence.

In short, if you want to use environment variables you may do it like this:

export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_ENDPOINT_URL_S3=
export AWS_ENDPOINT_URL_IAM=
export AWS_ENDPOINT_URL_STS=
export AWS_REGION=

# run acceptance tests
make test-acc

If your configuration is in a local AWS profile in ~/.aws/config you may do it like this instead:

export AWS_PROFILE=xyz

# run acceptance tests
make test-acc

Note that acceptance tests require a bucket with the name of "my-bucket-1".

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package gonsensus provides distributed consensus using S3 conditional operations

Example
// example_test.go
package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/thevilledev/gonsensus"
)

func main() {
	// Load AWS configuration
	cfg, err := config.LoadDefaultConfig(context.Background())
	if err != nil {
		log.Printf("Failed to load AWS config: %v", err)
		return
	}

	// Create S3 client
	s3Client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		// https://github.com/aws/aws-sdk-go-v2/discussions/2960
		o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired
	})

	// Create consensus manager config
	consensusConfig := gonsensus.Config{
		TTL:          30 * time.Second,
		PollInterval: 5 * time.Second,
		LockPrefix:   "consensus/",
		NodeID:       "example-node-1",
	}

	// Create consensus manager
	manager, err := gonsensus.NewManager(s3Client, "my-bucket-1", consensusConfig)
	if err != nil {
		log.Printf("Failed to create consensus manager: %v", err)
		return
	}

	// Create worker to handle leader duties
	worker := &Worker{nodeID: "example-node-1"}

	// Set callbacks
	manager.SetCallbacks(worker.OnElected, worker.OnDemoted)

	// Create cancellable context
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
	defer cancel()

	// Run consensus manager
	go func() {
		if err := manager.Run(ctx); err != nil && err != context.Canceled {
			fmt.Printf("Consensus manager error: %v\n", err)
		}
	}()

	// Simulate some work
	time.Sleep(5 * time.Second)

	// Get current leader info
	lockInfo, err := manager.GetLockInfo(ctx)
	if err != nil {
		fmt.Printf("%s: %v\n", gonsensus.ErrFailedToGetLockInfo, err)
		return
	}

	fmt.Printf("Current leader: %s\n", lockInfo.Node)

}

// Worker handles leader-specific tasks
type Worker struct {
	nodeID   string
	isLeader bool
	mu       sync.RWMutex
}

func (w *Worker) OnElected(ctx context.Context) error {
	w.mu.Lock()
	w.isLeader = true
	w.mu.Unlock()

	fmt.Printf("Node %s elected as leader\n", w.nodeID)
	return nil
}

func (w *Worker) OnDemoted(ctx context.Context) {
	w.mu.Lock()
	w.isLeader = false
	w.mu.Unlock()

	fmt.Printf("Node %s demoted from leader\n", w.nodeID)
}
Output:
Node example-node-1 elected as leader
Current leader: example-node-1

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrLockExists               = errors.New("lock already exists")
	ErrLockNotFound             = errors.New("lock not found")
	ErrLockModified             = errors.New("lock was modified")
	ErrInvalidConfig            = errors.New("invalid configuration")
	ErrLostQuorum               = errors.New("lost quorum")
	ErrNoActiveLock             = errors.New("no active lock exists")
	ErrNoObserversRegistered    = errors.New("no observers registered")
	ErrFailedToUpdateHeartbeat  = errors.New("failed to update heartbeat")
	ErrFailedToRegisterObserver = errors.New("failed to register observer")
	ErrFailedToMarshalLockInfo  = errors.New("failed to marshal lock info")
	ErrFailedToGetLockInfo      = errors.New("failed to get lock info")
	ErrRetryRegistration        = errors.New("retry registration attempt")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	TTL          time.Duration
	PollInterval time.Duration
	LockPrefix   string
	NodeID       string
	QuorumSize   int
	GracePeriod  time.Duration
}

type Lease added in v0.2.0

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

Lease represents the current leadership lease.

func NewLease added in v0.2.0

func NewLease() *Lease

NewLease creates a new lease instance.

func (*Lease) GetCurrentVersion added in v0.2.0

func (l *Lease) GetCurrentVersion() string

GetCurrentVersion returns the current lease version.

func (*Lease) GetLeaseInfo added in v0.2.0

func (l *Lease) GetLeaseInfo() *LockInfo

GetLeaseInfo returns the current lease information.

func (*Lease) UpdateLease added in v0.2.0

func (l *Lease) UpdateLease(info *LockInfo)

UpdateLease updates the lease information atomically.

type LockInfo

type LockInfo struct {
	Node            string                  `json:"node"`
	Timestamp       time.Time               `json:"timestamp"`
	Expiry          time.Time               `json:"expiry"`
	Term            int64                   `json:"term"`
	Version         string                  `json:"version"`
	FenceToken      int64                   `json:"fenceToken"`
	LastKnownLeader string                  `json:"lastKnownLeader"`
	Observers       map[string]observerInfo `json:"observers"`
}

func (*LockInfo) IsExpired

func (l *LockInfo) IsExpired() bool

IsExpired checks if a lock is expired.

func (*LockInfo) IsValid

func (l *LockInfo) IsValid() bool

IsValid checks if a lock is valid (exists and not expired).

type Manager

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

func NewManager

func NewManager(client S3Client, bucket string, cfg Config) (*Manager, error)

func (*Manager) GetActiveObservers added in v0.2.0

func (m *Manager) GetActiveObservers(ctx context.Context) (int, error)

GetActiveObservers returns the count of currently active observers from S3.

func (*Manager) GetLockInfo

func (m *Manager) GetLockInfo(ctx context.Context) (*LockInfo, error)

GetLockInfo retrieves current lock information.

func (*Manager) RegisterObserver added in v0.2.0

func (m *Manager) RegisterObserver(ctx context.Context, nodeID string, metadata map[string]string) error

RegisterObserver adds a node to the observers list through S3.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context) error

func (*Manager) SetCallbacks

func (m *Manager) SetCallbacks(onElected func(context.Context) error, onDemoted func(context.Context))

func (*Manager) UpdateHeartbeat added in v0.2.0

func (m *Manager) UpdateHeartbeat(ctx context.Context, nodeID string) error

UpdateHeartbeat updates the last heartbeat time for a node in S3.

type S3Client

type S3Client interface {
	PutObject(ctx context.Context, params *s3.PutObjectInput,
		optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)
	GetObject(ctx context.Context, params *s3.GetObjectInput,
		optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
	DeleteObject(ctx context.Context, params *s3.DeleteObjectInput,
		optFns ...func(*s3.Options)) (*s3.DeleteObjectOutput, error)
}

S3Client defines the interface for S3 operations.

Jump to

Keyboard shortcuts

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