snapshot_request.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package raft
  2. import (
  3. "code.google.com/p/goprotobuf/proto"
  4. "github.com/benbjohnson/go-raft/protobuf"
  5. "io"
  6. "io/ioutil"
  7. )
  8. // The request sent to a server to start from the snapshot.
  9. type SnapshotRequest struct {
  10. LeaderName string
  11. LastIndex uint64
  12. LastTerm uint64
  13. }
  14. //------------------------------------------------------------------------------
  15. //
  16. // Constructors
  17. //
  18. //------------------------------------------------------------------------------
  19. // Creates a new Snapshot request.
  20. func newSnapshotRequest(leaderName string, snapshot *Snapshot) *SnapshotRequest {
  21. return &SnapshotRequest{
  22. LeaderName: leaderName,
  23. LastIndex: snapshot.LastIndex,
  24. LastTerm: snapshot.LastTerm,
  25. }
  26. }
  27. // Encodes the SnapshotRequest to a buffer. Returns the number of bytes
  28. // written and any error that may have occurred.
  29. func (req *SnapshotRequest) encode(w io.Writer) (int, error) {
  30. pb := &protobuf.ProtoSnapshotRequest{
  31. LeaderName: proto.String(req.LeaderName),
  32. LastIndex: proto.Uint64(req.LastIndex),
  33. LastTerm: proto.Uint64(req.LastTerm),
  34. }
  35. p, err := proto.Marshal(pb)
  36. if err != nil {
  37. return -1, err
  38. }
  39. return w.Write(p)
  40. }
  41. // Decodes the SnapshotRequest from a buffer. Returns the number of bytes read and
  42. // any error that occurs.
  43. func (req *SnapshotRequest) decode(r io.Reader) (int, error) {
  44. data, err := ioutil.ReadAll(r)
  45. if err != nil {
  46. return 0, err
  47. }
  48. totalBytes := len(data)
  49. pb := &protobuf.ProtoSnapshotRequest{}
  50. if err := proto.Unmarshal(data, pb); err != nil {
  51. return -1, err
  52. }
  53. req.LeaderName = pb.GetLeaderName()
  54. req.LastIndex = pb.GetLastIndex()
  55. req.LastTerm = pb.GetLastTerm()
  56. return totalBytes, nil
  57. }