snapshot.go 1.2 KB

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