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 ¶
- Variables
- func RecoverPeersJSON(dir string, servers []hraft.Server) error
- type GenerationFencer
- type Node
- func (n *Node) AddNonvoter(id, address string, timeout time.Duration) error
- func (n *Node) AddVoter(id, address string, timeout time.Duration) error
- func (n *Node) AppliedIndex() uint64
- func (n *Node) Apply(ctx context.Context, data []byte) (interface{}, error)
- func (n *Node) ApplyCommand(ctx context.Context, kind uint8, payload any) (interface{}, error)
- func (n *Node) ApplyKeyring(ctx context.Context, kr *keyring.TLSKeyring) (uint64, error)
- func (n *Node) ApplyMulti(ctx context.Context, entries []fsm.KVEntry) error
- func (n *Node) Autopilot() *autopilot.Autopilot
- func (n *Node) Close() error
- func (n *Node) CommittedIndex() uint64
- func (n *Node) FSM() hraft.FSM
- func (n *Node) GetConfiguration() (hraft.Configuration, error)
- func (n *Node) IsCleanState() bool
- func (n *Node) IsLeader() bool
- func (n *Node) IsNonVoter() bool
- func (n *Node) IsRemoved() bool
- func (n *Node) IsStarted() bool
- func (n *Node) IsVoter() bool
- func (n *Node) KV() fsm.KVStore
- func (n *Node) KeyringManager() *keyring.Manager
- func (n *Node) LeaderAddress() string
- func (n *Node) LeaderWithID() (address string, id string)
- func (n *Node) LeaveCluster(ctx context.Context, timeout time.Duration) error
- func (n *Node) MinFollowerAppliedIndex() uint64
- func (n *Node) NodeID() string
- func (n *Node) RawRaft() *hraft.Raft
- func (n *Node) ReadKeyring() (*keyring.TLSKeyring, error)
- func (n *Node) ReconcileMembership(desired []discovery.Peer, timeout time.Duration) (added, updated, removed []string, err error)
- func (n *Node) RemoveServer(id string, timeout time.Duration) error
- func (n *Node) Shutdown() error
- func (n *Node) Start(ctx context.Context) (err error)
- func (n *Node) StartJoinLoop(ctx context.Context)
- func (n *Node) Stats() map[string]string
- func (n *Node) StepDown(ctx context.Context) error
- func (n *Node) Storage() storage.Backend
- func (n *Node) TLSProvider() *transport.DynamicTLSProvider
- func (n *Node) TransferLeadership(ctx context.Context, timeout time.Duration) error
- func (n *Node) WaitForCleanState(ctx context.Context) error
- func (n *Node) WaitForLeader(ctx context.Context) error
- func (n *Node) WaitForSelfLeadership(ctx context.Context) error
- type NodeOptions
- type ReplicaCountAuthorizer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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")
}
Output:
func (*Node) AddNonvoter ¶
AddNonvoter adds a non-voting member. Leader-only.
func (*Node) AppliedIndex ¶
AppliedIndex returns the FSM applied index.
func (*Node) ApplyCommand ¶
ApplyCommand encodes and applies a typed command.
func (*Node) ApplyKeyring ¶
ApplyKeyring implements keyring.KeyringApplier.
func (*Node) ApplyMulti ¶
ApplyMulti applies an atomic multi-key write.
func (*Node) CommittedIndex ¶
CommittedIndex returns the last committed index.
func (*Node) GetConfiguration ¶
func (n *Node) GetConfiguration() (hraft.Configuration, error)
GetConfiguration returns the current cluster configuration.
func (*Node) IsCleanState ¶
IsCleanState reports whether the Raft layer is settled.
func (*Node) IsNonVoter ¶
IsNonVoter reports whether this node is a non-voting member.
func (*Node) KeyringManager ¶
KeyringManager returns the keyring manager.
func (*Node) LeaderAddress ¶
LeaderAddress returns the current leader's transport address.
func (*Node) LeaderWithID ¶
LeaderWithID returns the leader address and ID.
func (*Node) LeaveCluster ¶
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 ¶
MinFollowerAppliedIndex implements keyring.KeyringApplier.
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 ¶
RemoveServer removes a member. Leader-only.
func (*Node) StartJoinLoop ¶
StartJoinLoop starts the membership reconciliation loop.
func (*Node) TLSProvider ¶
func (n *Node) TLSProvider() *transport.DynamicTLSProvider
TLSProvider returns the dynamic TLS provider.
func (*Node) TransferLeadership ¶
TransferLeadership transfers leadership to another voter.
func (*Node) WaitForCleanState ¶
WaitForCleanState blocks until IsCleanState reports true.
func (*Node) WaitForLeader ¶
WaitForLeader blocks until a leader exists.
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.
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
|
|
|
at-rest-encryption
command
|
|
|
custom-fsm
command
|
|
|
inband-keyring-rotation
command
|
|
|
k8s-mtls-secret-bootstrap
command
|
|
|
manual-certs-hot-reload
command
|
|
|
single-node-plaintext
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. |