raft

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 24 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

go-raft

CI License

Production-grade shared Raft library for Go: HashiCorp Raft + BoltDB + Kubernetes StatefulSet DNS discovery + dynamic mTLS + Vault-style in-band phased TLS keyring rotation + autopilot + HTTP probes/leader forwarding.

The library extracts and hardens the Raft, storage, discovery, and TLS subsystems used by dagger-kubernetes and gohookbridge, and adds the pre-cluster bootstrap and phased key rotation patterns from HashiCorp Vault.

Features

  • Turnkey raft.Node facade with lifecycle, readiness, membership, recovery, and keyring helpers.
  • Two storage modes: raft-boltdb/v2 with an in-memory log cache, or a single shared bbolt file containing logs, stable data, FSM data, and system state.
  • Kubernetes-native discovery: StatefulSet FQDN peers, ordinal-0 single-voter bootstrap, peerResolvable guard, and generation fencing for stale PVCs.
  • Dynamic mTLS: hot-reloads both leaf certificates and CA pools via GetConfigForClient (server) and per-dial DialTLSConfig (client).
  • Vault-style phased TLS keyring: two-phase stage/activate rotation with dual trust, follower applied-index tracking, and crash/leader-change recovery.
  • Bootstrap PKI before Raft exists: Kubernetes Secret, manual PEM files, or local CA, with dual-trust migration into the in-band keyring.
  • Built-in FSMs: in-memory and Bolt-backed transactional KV with atomic set-multi, plus an envelope FSM for system state.
  • Autopilot: follower health, MinFollowerAppliedIndex, dead-server cleanup with quorum and stabilization guards.
  • HTTP helpers: /readyz, /startup, /livez, and mTLS leader forwarding with loop prevention.
  • At-rest encryption: AES-256-GCM Sealer with key rotation and lazy plaintext migration.

Architecture

flowchart LR
    subgraph Node
        D[discovery] --> N[raft.Node]
        P[pki bootstrap] --> N
        N --> S[storage backend]
        N --> F[EnvelopeFSM]
        F --> K[keyring.Manager]
        K --> T[transport.DynamicTLSProvider]
        N --> A[autopilot]
        N --> R[PhasedRotator]
    end
    R -->|SysKindSetKeyring| F
    A -->|MinFollowerAppliedIndex| R
    T -->|mTLS| Peers[(Raft peers)]
Phased TLS rotation
sequenceDiagram
    participant L as Leader
    participant FSM as EnvelopeFSM
    participant F as Followers
    participant TLS as DynamicTLSProvider
    L->>FSM: Term 2, Keys=[K0,K1], Active=K0
    FSM->>TLS: trust {K0,K1}, dial with K0
    L->>FSM: commit AppliedIndex
    F->>L: echo AppliedIndex
    L->>L: MinFollowerAppliedIndex >= AppliedIndex
    L->>FSM: Term 3, Keys=[K1], Active=K1
    FSM->>TLS: trust {K1}, dial with K1
    TLS->>TLS: close idle pooled connections

Quickstart

package main

import (
    "context"
    "log"
    "time"

    raft "github.com/disaster37/go-raft"
    "github.com/disaster37/go-raft/config"
    "github.com/disaster37/go-raft/fsm"
)

func main() {
    cfg := config.DefaultConfig()
    cfg.Dir = "/var/lib/raft"
    cfg.NodeID = "node-0"
    cfg.BindAddr = "127.0.0.1:8081"
    cfg.AdvertiseAddr = "127.0.0.1:8081"
    cfg.Autopilot.Enabled = false

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    n, err := raft.NewNode(ctx, &cfg, raft.NodeOptions{})
    if err != nil {
        log.Fatal(err)
    }
    if err := n.Start(ctx); err != nil {
        log.Fatal(err)
    }
    defer n.Close()
    if err := n.WaitForLeader(ctx); err != nil {
        log.Fatal(err)
    }
    if _, err := n.ApplyCommand(ctx, fsm.KindSet, fsm.KVEntry{
        Bucket: "demo", Key: "hello", Value: []byte("world"),
    }); err != nil {
        log.Fatal(err)
    }
}

More examples live in examples/.

Package map

Package Purpose
raft (root) Node facade, membership, recovery, keyring applier
config Config structs, defaults, Viper loading, validation, adapters
discovery DNS/static/single-node peer resolvers and SAN derivation
transport Plain/TLS/retrying stream layers and dynamic TLS provider
pki goca CA/leaf issuance, reuse checks, bootstrap providers
keyring Replicated TLS keyring, manager, phased rotator
storage raft-boltdb/v2, shared bbolt, snapshots, AES-GCM sealer
fsm Envelope FSM, in-memory KV, Bolt KV, command codec
autopilot Follower tracking, dead-server cleanup, min applied index
k8s Secret bootstrap, generation fencing, StatefulSet replicas
observ logrus/hclog adapters and Prometheus metrics
httpext Probes and leader-forwarding middleware
testutil FreeListener, fake clock, test cluster helpers

Compatibility

The library is a drop-in replacement for the Raft/TLS/storage layers of dagger-kubernetes and gohookbridge. See:

Security highlights

  • mTLS with SAN verification and dual-trust CA rotation (CWE-295).
  • AES-256-GCM at-rest encryption with key rotation (CWE-311/319).
  • No private keys or secrets in logs (CWE-532).
  • Single-voter bootstrap and peerResolvable guard (CWE-693).
  • 0700 directories and 0600 keys/DB/node-id/snapshots (CWE-732/922).

See SECURITY.md for the full threat model.

Documentation

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package raft is a production-grade layer on top of HashiCorp Raft that bundles storage, Kubernetes StatefulSet DNS discovery, dynamic mTLS, an in-band phased TLS keyring, autopilot, and HTTP helpers.

The root package exposes a turnkey Node facade. Consumers that need finer control can compose the subpackages directly:

  • config: configuration structs, defaults, loading, and validation
  • discovery: peer resolvers for DNS, static, and single-node clusters
  • transport: plaintext/TLS stream layers and hot-reloading TLS providers
  • pki: goca-backed CA and leaf certificate issuance
  • keyring: replicated TLS keyring and Vault-style phased rotation
  • storage: raft-boltdb/v2 and shared single-file bbolt backends
  • fsm: envelope FSM plus in-memory and Bolt-backed KV state machines
  • autopilot: follower health tracking and dead-server cleanup
  • k8s: Kubernetes Secret bootstrap, generation fencing, and replica reads
  • observ: logging and Prometheus metrics adapters
  • httpext: readiness/startup probes and leader-forwarding middleware
  • testutil: listener reservation and test cluster helpers

A minimal single-node node:

cfg := config.DefaultConfig()
cfg.Dir = "/var/lib/example"
cfg.NodeID = "node-0"
cfg.BindAddr = "127.0.0.1:8081"
cfg.AdvertiseAddr = "127.0.0.1:8081"

n, err := raft.NewNode(ctx, &cfg, raft.NodeOptions{})
if err != nil {
	return err
}
if err := n.Start(ctx); err != nil {
	return err
}
defer n.Close()
if err := n.WaitForLeader(ctx); err != nil {
	return err
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotLeader is returned when a write is attempted on a follower.
	ErrNotLeader = errors.New("raft: node is not the leader")
	// ErrRaftTimeout is returned when an apply or membership operation times out.
	ErrRaftTimeout = errors.New("raft: apply timed out")
	// ErrNodeRemoved is returned when the local node has been removed from the
	// cluster configuration.
	ErrNodeRemoved = errors.New("raft: node has been removed from cluster")
	// ErrAlreadyClosed is returned when an operation is attempted on a closed node.
	ErrAlreadyClosed = errors.New("raft: node is already closed")
	// ErrInvalidConfig is returned when the supplied configuration is invalid.
	ErrInvalidConfig = errors.New("raft: invalid configuration")
	// ErrBootstrapTimeout is returned when pre-Raft bootstrap material does not
	// appear within the configured timeout.
	ErrBootstrapTimeout = errors.New("raft: bootstrap material poll timed out")
	// ErrConflict is returned when a create-only KV mutation targets an
	// existing key.
	ErrConflict = fsm.ErrConflict
	// ErrNotFound is returned when a requested key does not exist.
	ErrNotFound = fsm.ErrNotFound
)

Functions

func RecoverPeersJSON

func RecoverPeersJSON(dir string, servers []hraft.Server) error

RecoverPeersJSON writes a peers.json recovery file into dir. It is a last-resort manual recovery mechanism; prefer SingleNodeRecovery or RecoveryMode.

Types

type GenerationFencer

type GenerationFencer interface {
	ReadClusterGeneration(ctx context.Context) (uint64, bool)
	BumpClusterGeneration(ctx context.Context) (uint64, error)
}

GenerationFencer coordinates cluster generation fencing across recoveries.

type Node

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

Node manages the full lifecycle of a HashiCorp Raft instance, storage backend, dynamic mTLS transport, in-band TLS keyring rotation, membership join loop, and autopilot.

func NewInmemNode

func NewInmemNode(nodeID string, userFSM hraft.FSM, applyTimeout time.Duration, logger observ.Logger) (*Node, error)

NewInmemNode creates and starts a single-node in-memory Raft node.

func NewNode

func NewNode(ctx context.Context, cfg *config.Config, opts NodeOptions) (*Node, error)

NewNode constructs a Node. Start must be called to open storage and start Raft.

Example
package main

import (
	hraft "github.com/hashicorp/raft"

	"github.com/disaster37/go-raft/config"
)

func main() {
	cfg := config.DefaultConfig()
	cfg.PerformanceMultiplier = 0.2
	cfg.Dir = "/tmp/raft-example"
	cfg.NodeID = "example-node"
	cfg.BindAddr = "127.0.0.1:0"
	cfg.AdvertiseAddr = "127.0.0.1:0"
	cfg.Storage.Backend = config.StorageBackendInmem
	cfg.Autopilot.Enabled = false
	_ = cfg
	_ = hraft.ServerID("example-node")
}

func (*Node) AddNonvoter

func (n *Node) AddNonvoter(id, address string, timeout time.Duration) error

AddNonvoter adds a non-voting member. Leader-only.

func (*Node) AddVoter

func (n *Node) AddVoter(id, address string, timeout time.Duration) error

AddVoter adds a voting member. Leader-only.

func (*Node) AppliedIndex

func (n *Node) AppliedIndex() uint64

AppliedIndex returns the FSM applied index.

func (*Node) Apply

func (n *Node) Apply(ctx context.Context, data []byte) (interface{}, error)

Apply applies raw bytes to the FSM.

func (*Node) ApplyCommand

func (n *Node) ApplyCommand(ctx context.Context, kind uint8, payload any) (interface{}, error)

ApplyCommand encodes and applies a typed command.

func (*Node) ApplyKeyring

func (n *Node) ApplyKeyring(ctx context.Context, kr *keyring.TLSKeyring) (uint64, error)

ApplyKeyring implements keyring.KeyringApplier.

func (*Node) ApplyMulti

func (n *Node) ApplyMulti(ctx context.Context, entries []fsm.KVEntry) error

ApplyMulti applies an atomic multi-key write.

func (*Node) Autopilot

func (n *Node) Autopilot() *autopilot.Autopilot

Autopilot returns the autopilot.

func (*Node) Close

func (n *Node) Close() error

Close shuts down the node. It is idempotent.

func (*Node) CommittedIndex

func (n *Node) CommittedIndex() uint64

CommittedIndex returns the last committed index.

func (*Node) FSM

func (n *Node) FSM() hraft.FSM

FSM returns the envelope FSM.

func (*Node) GetConfiguration

func (n *Node) GetConfiguration() (hraft.Configuration, error)

GetConfiguration returns the current cluster configuration.

func (*Node) IsCleanState

func (n *Node) IsCleanState() bool

IsCleanState reports whether the Raft layer is settled.

func (*Node) IsLeader

func (n *Node) IsLeader() bool

IsLeader reports whether this node is the Raft leader.

func (*Node) IsNonVoter

func (n *Node) IsNonVoter() bool

IsNonVoter reports whether this node is a non-voting member.

func (*Node) IsRemoved

func (n *Node) IsRemoved() bool

IsRemoved reports whether this node is absent from the configuration.

func (*Node) IsStarted

func (n *Node) IsStarted() bool

IsStarted reports whether the node has joined the cluster.

func (*Node) IsVoter

func (n *Node) IsVoter() bool

IsVoter reports whether this node is a voting member.

func (*Node) KV

func (n *Node) KV() fsm.KVStore

KV returns the built-in KV store, or nil for a custom FSM.

func (*Node) KeyringManager

func (n *Node) KeyringManager() *keyring.Manager

KeyringManager returns the keyring manager.

func (*Node) LeaderAddress

func (n *Node) LeaderAddress() string

LeaderAddress returns the current leader's transport address.

func (*Node) LeaderWithID

func (n *Node) LeaderWithID() (address string, id string)

LeaderWithID returns the leader address and ID.

func (*Node) LeaveCluster

func (n *Node) LeaveCluster(ctx context.Context, timeout time.Duration) error

LeaveCluster removes this node from the voter configuration. The node must be the leader: removing the leader causes Raft to elect a new leader from the remaining voters. Transferring leadership first would leave this node unable to remove itself (RemoveServer is leader-only).

func (*Node) MinFollowerAppliedIndex

func (n *Node) MinFollowerAppliedIndex() uint64

MinFollowerAppliedIndex implements keyring.KeyringApplier.

func (*Node) NodeID

func (n *Node) NodeID() string

NodeID returns the stable node ID.

func (*Node) RawRaft

func (n *Node) RawRaft() *hraft.Raft

RawRaft returns the underlying HashiCorp Raft instance.

func (*Node) ReadKeyring

func (n *Node) ReadKeyring() (*keyring.TLSKeyring, error)

ReadKeyring implements keyring.KeyringApplier.

func (*Node) ReconcileMembership

func (n *Node) ReconcileMembership(desired []discovery.Peer, timeout time.Duration) (added, updated, removed []string, err error)

ReconcileMembership makes the cluster configuration match desired.

func (*Node) RemoveServer

func (n *Node) RemoveServer(id string, timeout time.Duration) error

RemoveServer removes a member. Leader-only.

func (*Node) Shutdown

func (n *Node) Shutdown() error

Shutdown is an alias for Close.

func (*Node) Start

func (n *Node) Start(ctx context.Context) (err error)

Start opens storage, bootstraps or recovers the cluster, and starts Raft.

func (*Node) StartJoinLoop

func (n *Node) StartJoinLoop(ctx context.Context)

StartJoinLoop starts the membership reconciliation loop.

func (*Node) Stats

func (n *Node) Stats() map[string]string

Stats returns the raw Raft stats.

func (*Node) StepDown

func (n *Node) StepDown(ctx context.Context) error

StepDown transfers leadership when possible.

func (*Node) Storage

func (n *Node) Storage() storage.Backend

Storage returns the storage backend.

func (*Node) TLSProvider

func (n *Node) TLSProvider() *transport.DynamicTLSProvider

TLSProvider returns the dynamic TLS provider.

func (*Node) TransferLeadership

func (n *Node) TransferLeadership(ctx context.Context, timeout time.Duration) error

TransferLeadership transfers leadership to another voter.

func (*Node) WaitForCleanState

func (n *Node) WaitForCleanState(ctx context.Context) error

WaitForCleanState blocks until IsCleanState reports true.

func (*Node) WaitForLeader

func (n *Node) WaitForLeader(ctx context.Context) error

WaitForLeader blocks until a leader exists.

func (*Node) WaitForSelfLeadership

func (n *Node) WaitForSelfLeadership(ctx context.Context) error

WaitForSelfLeadership blocks until this node is the leader.

type NodeOptions

type NodeOptions struct {
	FSM                    hraft.FSM
	Resolver               discovery.PeerResolver
	BootstrapProvider      pki.BootstrapProvider
	GenerationFencer       GenerationFencer
	ReplicaCountAuthorizer ReplicaCountAuthorizer
	Sealer                 storage.Sealer
	SessionSink            fsm.SessionStateSink
	Logger                 observ.Logger
	Metrics                observ.MetricsCollector
	RemovedCallback        func()
	RestoreCallback        func(ctx context.Context) error
	CustomListener         net.Listener
}

NodeOptions configures optional dependencies injected into NewNode.

type ReplicaCountAuthorizer

type ReplicaCountAuthorizer interface {
	Replicas(ctx context.Context) (int32, bool)
}

ReplicaCountAuthorizer reports the authoritative desired replica count.

Directories

Path Synopsis
Package autopilot tracks follower health and removes dead servers while respecting quorum and stabilization guards.
Package autopilot tracks follower health and removes dead servers while respecting quorum and stabilization guards.
Package config defines the configuration surface of the raft library, including defaults, Viper loading, validation, and adapters for the source projects.
Package config defines the configuration surface of the raft library, including defaults, Viper loading, validation, and adapters for the source projects.
Package discovery resolves the Raft peer set for DNS, static, and single-node deployments and derives certificate SANs.
Package discovery resolves the Raft peer set for DNS, static, and single-node deployments and derives certificate SANs.
examples
custom-fsm command
Package fsm provides an envelope FSM for system state plus in-memory and Bolt-backed transactional KV state machines.
Package fsm provides an envelope FSM for system state plus in-memory and Bolt-backed transactional KV state machines.
Package httpext provides HTTP probes and leader-forwarding middleware.
Package httpext provides HTTP probes and leader-forwarding middleware.
internal
fileutil
Package fileutil provides small filesystem helpers shared by the raft packages.
Package fileutil provides small filesystem helpers shared by the raft packages.
netutil
Package netutil contains small networking helpers shared by the raft packages.
Package netutil contains small networking helpers shared by the raft packages.
Package k8s provides Kubernetes-specific bootstrap, generation fencing, and StatefulSet helpers.
Package k8s provides Kubernetes-specific bootstrap, generation fencing, and StatefulSet helpers.
Package keyring implements the replicated TLS keyring and Vault-style two-phase key rotation.
Package keyring implements the replicated TLS keyring and Vault-style two-phase key rotation.
Package observ provides logging and metrics adapters used across the raft packages.
Package observ provides logging and metrics adapters used across the raft packages.
Package pki wraps github.com/disaster37/goca for CA creation, leaf issuance, certificate reuse, and pre-Raft bootstrap material.
Package pki wraps github.com/disaster37/goca for CA creation, leaf issuance, certificate reuse, and pre-Raft bootstrap material.
Package storage provides Raft log/stable/snapshot backends and at-rest encryption helpers.
Package storage provides Raft log/stable/snapshot backends and at-rest encryption helpers.
Package testutil provides helpers for tests that need real listeners and deterministic clocks.
Package testutil provides helpers for tests that need real listeners and deterministic clocks.
Package transport provides plaintext and mTLS Raft stream layers with per-dial DNS resolution and hot-reloading TLS material.
Package transport provides plaintext and mTLS Raft stream layers with per-dial DNS resolution and hot-reloading TLS material.

Jump to

Keyboard shortcuts

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