-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsm.go
46 lines (38 loc) · 928 Bytes
/
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
package main
import (
"encoding/json"
"gframework/log"
"io"
"github.com/hashicorp/raft"
)
type FSM struct {
cm *CacheManager
}
type logEntryData struct {
Key string
Value string
}
func NewFSM() *FSM {
fsm := &FSM{
cm: NewCacheManager(),
}
return fsm
}
// Apply applies a Raft log entry to the key-value store.
func (f *FSM) Apply(logEntry *raft.Log) interface{} {
e := logEntryData{}
if err := json.Unmarshal(logEntry.Data, &e); err != nil {
panic("Failed unmarshalling Raft log entry. This is a bug.")
}
ret := f.cm.Set(e.Key, e.Value)
log.Infof("fms.Apply(), logEntry:%s, ret:%v\n", logEntry.Data, ret)
return ret
}
// Snapshot returns the latest snapshot
func (f *FSM) Snapshot() (raft.FSMSnapshot, error) {
return &snapshot{cm: f.cm}, nil
}
// Restore stores the key-value store to a previous state.
func (f *FSM) Restore(serialized io.ReadCloser) error {
return f.cm.UnMarshal(serialized)
}