-
Notifications
You must be signed in to change notification settings - Fork 2
/
fsm.go
267 lines (212 loc) · 5.64 KB
/
fsm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package agree
import (
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/raft"
"io"
"reflect"
"time"
)
var (
//ErrNotLeader is returned when a Command is mistakenly sent to a follower. You should never receive this as Go-Agree takes care of following commands to the leader.
ErrNotLeader = errors.New("Commands should be sent to leader and cannot be sent to followers")
//ErrIncorrectType is returned when a Raft snapshot cannot be unmarshalled to the expected type.
ErrIncorrectType = errors.New("Snapshot contained data of an incorrect type")
//ErrTooManyalues is returned when a Read() method returns more than one value (plus optional error return)
ErrTooManyalues = errors.New("Method returned too many values")
)
const raftTimeout = time.Second * 10
//ForwardingClient is a client that forwards commands to the Raft leader. Should not be used,
//the only reason it is exported is because the rpc package requires it.
type ForwardingClient struct {
fsm *fsm
}
type fsm struct {
fsmRPC *ForwardingClient
config *Config
raft *raft.Raft
wrapper *Wrapper
}
//Command represents a mutating Command (log entry) in the Raft commit log.
type Command struct {
ConsistencyLevel int
Method string
Args []interface{}
}
type fsmSnapshot struct {
store interface{}
}
//Apply forwards the given mutating Command to the Raft leader.
func (r *ForwardingClient) Apply(cmd []byte, reply *int) error {
if r.fsm.raft.State() != raft.Leader {
return ErrNotLeader
}
if r.fsm.raft.VerifyLeader().Error() != nil {
return ErrNotLeader
}
if errF := r.fsm.raft.Apply(cmd, raftTimeout); errF.Error() != nil {
return errF.Error()
}
return nil
}
//Read forwards the given read to the Raft leader.
func (r *ForwardingClient) Read(cmd []byte, reply interface{}) error {
var (
c Command
err error
)
if err := json.Unmarshal(cmd, &c); err != nil {
return err
}
if c.ConsistencyLevel == int(Leader) && r.fsm.raft.State() != raft.Leader {
return ErrNotLeader
}
if c.ConsistencyLevel == int(Consistent) && r.fsm.raft.VerifyLeader().Error() != nil {
return ErrNotLeader
}
reply, err = r.fsm.Read(c.Method, c.Args...)
reply = r
return err
}
//AddPeer accepts a forwarded request to add a peer, sent to the Raft leader.
func (r *ForwardingClient) AddPeer(addr string, reply *int) error {
if r.fsm.raft.State() != raft.Leader {
return ErrNotLeader
}
return r.fsm.wrapper.AddNode(addr)
}
//RemovePeer accepts a forwarded request to remove a peer, sent to the Raft leader.
func (r ForwardingClient) RemovePeer(addr string, reply *int) error {
if r.fsm.raft.State() != raft.Leader {
return ErrNotLeader
}
return r.fsm.wrapper.RemoveNode(addr)
}
func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
err := func() error {
// Encode data.
b, err := json.Marshal(f.store)
if err != nil {
return err
}
// Write data to sink.
if _, err := sink.Write(b); err != nil {
return err
}
// Close the sink.
if err := sink.Close(); err != nil {
return err
}
return nil
}()
if err != nil {
sink.Cancel()
return err
}
return nil
}
func (f *fsmSnapshot) Release() {}
func (f *fsm) Snapshot() (raft.FSMSnapshot, error) {
data, err := f.wrapper.Marshal()
if err != nil {
return nil, err
}
return &fsmSnapshot{store: data}, nil
}
func (f *fsm) Restore(rc io.ReadCloser) error {
var err error
e := f.wrapper.reflectType.Elem()
o := reflect.New(e).Interface()
if err := json.NewDecoder(rc).Decode(&o); err != nil {
return err
}
if !reflect.TypeOf(o).AssignableTo(f.wrapper.reflectType) {
return ErrIncorrectType
}
// Set the state from the snapshot, no lock required according to
// Hashicorp docs.
f.wrapper.Lock()
f.wrapper.value = o
f.wrapper.Unlock()
return err
}
func (f *fsm) Read(method string, args...interface{}) (interface{}, error){
t := f.wrapper
var (
m reflect.Value
found bool
)
if m, found = t.methods[method]; !found {
return nil, ErrMethodNotFound
}
//fmt.Println(cmd)
var callArgs []reflect.Value
for i := range args {
callArgs = append(callArgs, reflect.ValueOf(args[i]))
}
f.wrapper.Lock()
defer f.wrapper.Unlock()
ret := m.Call(callArgs)
switch len(ret){
case 0:
return nil, nil
case 1:
return ret[0].Interface(), nil
case 2:
if err, ok := ret[1].Interface().(error); ok {
return ret[0].Interface(), err
} else if !ok {
return nil, errors.New("If returning two values the second value should be of error type")
}
default:
return nil, ErrTooManyalues
}
//unreachable
return nil, nil
}
func (f *fsm) Apply(l *raft.Log) interface{} {
var (
cmd Command
m reflect.Value
found bool
)
if err := json.Unmarshal(l.Data, &cmd); err != nil {
panic(fmt.Sprintf("Could not unmarshal Command: %s", err.Error()))
}
t := f.wrapper
if m, found = t.methods[cmd.Method]; !found {
return ErrMethodNotFound
}
//fmt.Println(cmd)
var callArgs []reflect.Value
for i := range cmd.Args {
callArgs = append(callArgs, reflect.ValueOf(cmd.Args[i]))
}
f.wrapper.Lock()
defer f.wrapper.Unlock()
ret := m.Call(callArgs)
for _, callback := range f.wrapper.callbacks[cmd.Method] {
callback(Mutation{
NewValue: f.wrapper.value,
Method: cmd.Method,
MethodArgs: cmd.Args,
})
}
for _, c := range f.wrapper.callbackChans[cmd.Method] {
c <- &Mutation{
NewValue: f.wrapper.value,
Method: cmd.Method,
MethodArgs: cmd.Args,
}
}
switch {
case len(ret) == 0:
return nil
case len(ret) > 1:
panic("Applied methods should have at most one return parameter, and it should satisfy error interface")
default:
//one return param, which should satisfy error interface
return ret[0].Interface().(error)
}
}