open-consul/consul/fsm.go

106 lines
2.4 KiB
Go
Raw Normal View History

2013-12-06 23:43:07 +00:00
package consul
import (
"fmt"
"github.com/hashicorp/consul/rpc"
2013-12-06 23:43:07 +00:00
"github.com/hashicorp/raft"
"io"
)
// consulFSM implements a finite state machine that is used
2013-12-11 01:00:48 +00:00
// along with Raft to provide strong consistency. We implement
// this outside the Server to avoid exposing this outside the package.
2013-12-06 23:43:07 +00:00
type consulFSM struct {
2013-12-11 01:00:48 +00:00
state *StateStore
2013-12-06 23:43:07 +00:00
}
// consulSnapshot is used to provide a snapshot of the current
// state in a way that can be accessed concurrently with operations
// that may modify the live state.
type consulSnapshot struct {
fsm *consulFSM
}
2013-12-11 01:00:48 +00:00
// NewFSM is used to construct a new FSM with a blank state
func NewFSM() (*consulFSM, error) {
state, err := NewStateStore()
if err != nil {
return nil, err
}
fsm := &consulFSM{
state: state,
}
return fsm, nil
}
func (c *consulFSM) Apply(buf []byte) interface{} {
switch rpc.MessageType(buf[0]) {
case rpc.RegisterRequestType:
return c.applyRegister(buf[1:])
2013-12-11 23:34:10 +00:00
case rpc.DeregisterRequestType:
return c.applyDeregister(buf[1:])
default:
panic(fmt.Errorf("failed to apply request: %#v", buf))
}
}
2013-12-11 02:19:15 +00:00
func (c *consulFSM) applyRegister(buf []byte) interface{} {
var req rpc.RegisterRequest
if err := rpc.Decode(buf, &req); err != nil {
panic(fmt.Errorf("failed to decode request: %v", err))
}
2013-12-11 22:38:18 +00:00
// Ensure the node
c.state.EnsureNode(req.Node, req.Address)
// Ensure the service if provided
if req.ServiceName != "" {
c.state.EnsureService(req.Node, req.ServiceName, req.ServiceTag, req.ServicePort)
}
return nil
2013-12-06 23:43:07 +00:00
}
2013-12-11 23:34:10 +00:00
func (c *consulFSM) applyDeregister(buf []byte) interface{} {
var req rpc.DeregisterRequest
if err := rpc.Decode(buf, &req); err != nil {
panic(fmt.Errorf("failed to decode request: %v", err))
}
// Either remove the service entry or the whole node
if req.ServiceName != "" {
c.state.DeleteNodeService(req.Node, req.ServiceName)
} else {
c.state.DeleteNode(req.Node)
}
return nil
}
2013-12-06 23:43:07 +00:00
func (c *consulFSM) Snapshot() (raft.FSMSnapshot, error) {
snap := &consulSnapshot{fsm: c}
return snap, nil
}
2013-12-11 02:19:15 +00:00
func (c *consulFSM) Restore(old io.ReadCloser) error {
defer old.Close()
// Create a new state store
state, err := NewStateStore()
if err != nil {
return err
}
// TODO: Populate the new state
// Do an atomic flip, safe since Apply is not called concurrently
c.state = state
2013-12-06 23:43:07 +00:00
return nil
}
func (s *consulSnapshot) Persist(sink raft.SnapshotSink) error {
return nil
}
func (s *consulSnapshot) Release() {
}