influxdb/command.go

72 lines
1.9 KiB
Go
Raw Normal View History

2013-04-14 21:37:33 +00:00
package raft
2013-05-10 03:50:57 +00:00
import (
"fmt"
"reflect"
)
//------------------------------------------------------------------------------
//
// Globals
//
//------------------------------------------------------------------------------
var commandTypes map[string]Command
func init() {
commandTypes = map[string]Command{}
}
2013-04-14 21:37:33 +00:00
//------------------------------------------------------------------------------
//
// Typedefs
//
//------------------------------------------------------------------------------
// A command represents an action to be taken on the replicated state machine.
type Command interface {
2013-04-28 04:51:17 +00:00
CommandName() string
Apply(server *Server) error
2013-04-14 21:37:33 +00:00
}
2013-05-05 19:36:23 +00:00
2013-05-10 03:50:57 +00:00
//------------------------------------------------------------------------------
//
// Functions
//
//------------------------------------------------------------------------------
//--------------------------------------
// Instantiation
//--------------------------------------
// Creates a new instance of a command by name.
2013-06-03 02:43:40 +00:00
func NewCommand(name string) (Command, error) {
2013-05-10 03:50:57 +00:00
// Find the registered command.
command := commandTypes[name]
if command == nil {
return nil, fmt.Errorf("raft.Command: Unregistered command type: %s", name)
}
// Make a copy of the command.
v := reflect.New(reflect.Indirect(reflect.ValueOf(command)).Type()).Interface()
copy, ok := v.(Command)
if !ok {
panic(fmt.Sprintf("raft.Command: Unable to copy command: %s (%v)", command.CommandName(), reflect.ValueOf(v).Kind().String()))
}
return copy, nil
}
//--------------------------------------
// Registration
//--------------------------------------
// Registers a command by storing a reference to an instance of it.
func RegisterCommand(command Command) {
if command == nil {
panic(fmt.Sprintf("raft.Command: Cannot register nil"))
} else if commandTypes[command.CommandName()] != nil {
panic(fmt.Sprintf("raft.Command: Duplicate registration: %s", command.CommandName()))
}
commandTypes[command.CommandName()] = command
2013-05-10 14:47:24 +00:00
}