snapshot.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package raft
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "hash/crc32"
  6. "os"
  7. )
  8. // Snapshot represents an in-memory representation of the current state of the system.
  9. type Snapshot struct {
  10. LastIndex uint64 `json:"lastIndex"`
  11. LastTerm uint64 `json:"lastTerm"`
  12. // Cluster configuration.
  13. Peers []*Peer `json:"peers"`
  14. State []byte `json:"state"`
  15. Path string `json:"path"`
  16. }
  17. // save writes the snapshot to file.
  18. func (ss *Snapshot) save() error {
  19. // Open the file for writing.
  20. file, err := os.OpenFile(ss.Path, os.O_CREATE|os.O_WRONLY, 0600)
  21. if err != nil {
  22. return err
  23. }
  24. defer file.Close()
  25. // Serialize to JSON.
  26. b, err := json.Marshal(ss)
  27. if err != nil {
  28. return err
  29. }
  30. // Generate checksum and write it to disk.
  31. checksum := crc32.ChecksumIEEE(b)
  32. if _, err = fmt.Fprintf(file, "%08x\n", checksum); err != nil {
  33. return err
  34. }
  35. // Write the snapshot to disk.
  36. if _, err = file.Write(b); err != nil {
  37. return err
  38. }
  39. // Ensure that the snapshot has been flushed to disk before continuing.
  40. if err := file.Sync(); err != nil {
  41. return err
  42. }
  43. return nil
  44. }
  45. // remove deletes the snapshot file.
  46. func (ss *Snapshot) remove() error {
  47. if err := os.Remove(ss.Path); err != nil {
  48. return err
  49. }
  50. return nil
  51. }