forked from goraft/raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnapshot.go
64 lines (51 loc) · 1.2 KB
/
snapshot.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
package raft
import (
//"bytes"
"encoding/json"
"fmt"
"hash/crc32"
"os"
)
//------------------------------------------------------------------------------
//
// Typedefs
//
//------------------------------------------------------------------------------
// the in memory SnapShot struct
// TODO add cluster configuration
type Snapshot struct {
LastIndex uint64 `json:"lastIndex"`
LastTerm uint64 `json:"lastTerm"`
// cluster configuration.
Peers []*Peer `json:"peers"`
State []byte `json:"state"`
Path string `json:"path"`
}
// Save the snapshot to a file
func (ss *Snapshot) save() error {
// Write machine state to temporary buffer.
// open file
file, err := os.OpenFile(ss.Path, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer file.Close()
b, err := json.Marshal(ss)
// Generate checksum.
checksum := crc32.ChecksumIEEE(b)
// Write snapshot with checksum.
if _, err = fmt.Fprintf(file, "%08x\n", checksum); err != nil {
return err
}
if _, err = file.Write(b); err != nil {
return err
}
// force the change writting to disk
file.Sync()
return err
}
// remove the file of the snapshot
func (ss *Snapshot) remove() error {
err := os.Remove(ss.Path)
return err
}