snapshot.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package raft
  2. import (
  3. //"bytes"
  4. "encoding/json"
  5. "fmt"
  6. "hash/crc32"
  7. "os"
  8. )
  9. //------------------------------------------------------------------------------
  10. //
  11. // Typedefs
  12. //
  13. //------------------------------------------------------------------------------
  14. // the in memory SnapShot struct
  15. // TODO add cluster configuration
  16. type Snapshot struct {
  17. LastIndex uint64 `json:"lastIndex"`
  18. LastTerm uint64 `json:"lastTerm"`
  19. // cluster configuration.
  20. Peers []*Peer `json: "peers"`
  21. State []byte `json: "state"`
  22. Path string `json: "path"`
  23. }
  24. // Save the snapshot to a file
  25. func (ss *Snapshot) save() error {
  26. // Write machine state to temporary buffer.
  27. // open file
  28. file, err := os.OpenFile(ss.Path, os.O_CREATE|os.O_WRONLY, 0600)
  29. if err != nil {
  30. return err
  31. }
  32. defer file.Close()
  33. b, err := json.Marshal(ss)
  34. // Generate checksum.
  35. checksum := crc32.ChecksumIEEE(b)
  36. // Write snapshot with checksum.
  37. if _, err = fmt.Fprintf(file, "%08x\n", checksum); err != nil {
  38. return err
  39. }
  40. if _, err = file.Write(b); err != nil {
  41. return err
  42. }
  43. // force the change writting to disk
  44. file.Sync()
  45. return err
  46. }
  47. // remove the file of the snapshot
  48. func (ss *Snapshot) remove() error {
  49. err := os.Remove(ss.Path)
  50. return err
  51. }