This repository was archived by the owner on Mar 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.go
More file actions
47 lines (40 loc) · 1.31 KB
/
state.go
File metadata and controls
47 lines (40 loc) · 1.31 KB
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
package raftify
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/hashicorp/memberlist"
)
// saveState saves the current memberlist into a separate state.json file. This file is used
// to allow a timed out or crashed node which has lost its internal memberlist to rejoin the
// cluster it is already part of. The state.json file is generated on the first successful join.
func (n *Node) saveState() error {
stateJSON, _ := json.MarshalIndent(n.memberlist.Members(), "", " ")
_ = ioutil.WriteFile(n.workingDir+"/state.json", stateJSON, 0755)
n.logger.Println("[DEBUG] raftify: Created/Updated state.json ✓")
return nil
}
// deleteState deletes the state.json. Called only when the node explicitly leaves on its own
// accord.
func (n *Node) deleteState() error {
os.Remove(n.workingDir + "/state.json")
n.logger.Println("[DEBUG] raftify: Deleted state.json ✓")
return nil
}
// loadState loads the contents of the state.json file.
func (n *Node) loadState() ([]*memberlist.Node, error) {
stateJSON, err := os.Open(n.workingDir + "/state.json")
if err != nil {
return nil, err
}
defer stateJSON.Close()
stateBytes, err := ioutil.ReadAll(stateJSON)
if err != nil {
return nil, err
}
var list []*memberlist.Node
if err = json.Unmarshal(stateBytes, &list); err != nil {
return nil, err
}
return list, nil
}