influxdb/command.go

75 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 (
"bytes"
"encoding/json"
2013-05-10 03:50:57 +00:00
"fmt"
"io"
2013-05-10 03:50:57 +00:00
"reflect"
)
var commandTypes map[string]Command
func init() {
commandTypes = map[string]Command{}
}
2013-12-23 14:16:37 +00:00
// Command represents an action to be taken on the replicated state machine.
2013-04-14 21:37:33 +00:00
type Command interface {
2013-04-28 04:51:17 +00:00
CommandName() string
2013-12-23 14:16:37 +00:00
}
// CommandApply represents the interface to apply a command to the server.
type CommandApply interface {
Apply(Context) (interface{}, error)
}
// deprecatedCommandApply represents the old interface to apply a command to the server.
type deprecatedCommandApply interface {
Apply(Server) (interface{}, error)
2013-04-14 21:37:33 +00:00
}
2013-05-05 19:36:23 +00:00
type CommandEncoder interface {
Encode(w io.Writer) error
Decode(r io.Reader) error
}
2013-05-10 03:50:57 +00:00
// Creates a new instance of a command by name.
func newCommand(name string, data []byte) (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 {
2013-06-08 02:41:36 +00:00
panic(fmt.Sprintf("raft: Unable to copy command: %s (%v)", command.CommandName(), reflect.ValueOf(v).Kind().String()))
2013-05-10 03:50:57 +00:00
}
// If data for the command was passed in the decode it.
if data != nil {
if encoder, ok := copy.(CommandEncoder); ok {
if err := encoder.Decode(bytes.NewReader(data)); err != nil {
return nil, err
}
} else {
json.NewDecoder(bytes.NewReader(data)).Decode(copy)
}
}
2013-05-10 03:50:57 +00:00
return copy, nil
}
// Registers a command by storing a reference to an instance of it.
func RegisterCommand(command Command) {
if command == nil {
2013-06-08 02:41:36 +00:00
panic(fmt.Sprintf("raft: Cannot register nil"))
2013-05-10 03:50:57 +00:00
} else if commandTypes[command.CommandName()] != nil {
2013-07-11 05:19:57 +00:00
panic(fmt.Sprintf("raft: Duplicate registration: %s", command.CommandName()))
2013-05-10 03:50:57 +00:00
}
commandTypes[command.CommandName()] = command
2013-05-10 14:47:24 +00:00
}