snapshot_recovery_request.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 SnapshotRecoveryRequest struct {
  10. LeaderName string
  11. LastIndex uint64
  12. LastTerm uint64
  13. Peers []string
  14. State []byte
  15. }
  16. //------------------------------------------------------------------------------
  17. //
  18. // Constructors
  19. //
  20. //------------------------------------------------------------------------------
  21. // Creates a new Snapshot request.
  22. func newSnapshotRecoveryRequest(leaderName string, snapshot *Snapshot) *SnapshotRecoveryRequest {
  23. return &SnapshotRecoveryRequest{
  24. LeaderName: leaderName,
  25. LastIndex: snapshot.LastIndex,
  26. LastTerm: snapshot.LastTerm,
  27. Peers: snapshot.Peers,
  28. State: snapshot.State,
  29. }
  30. }
  31. // Encodes the SnapshotRecoveryRequest to a buffer. Returns the number of bytes
  32. // written and any error that may have occurred.
  33. func (req *SnapshotRecoveryRequest) encode(w io.Writer) (int, error) {
  34. pb := &protobuf.ProtoSnapshotRecoveryRequest{
  35. LeaderName: proto.String(req.LeaderName),
  36. LastIndex: proto.Uint64(req.LastIndex),
  37. LastTerm: proto.Uint64(req.LastTerm),
  38. Peers: req.Peers,
  39. State: req.State,
  40. }
  41. p, err := proto.Marshal(pb)
  42. if err != nil {
  43. return -1, err
  44. }
  45. return w.Write(p)
  46. }
  47. // Decodes the SnapshotRecoveryRequest from a buffer. Returns the number of bytes read and
  48. // any error that occurs.
  49. func (req *SnapshotRecoveryRequest) decode(r io.Reader) (int, error) {
  50. data, err := ioutil.ReadAll(r)
  51. if err != nil {
  52. return 0, err
  53. }
  54. totalBytes := len(data)
  55. pb := &protobuf.ProtoSnapshotRequest{}
  56. if err = proto.Unmarshal(data, pb); err != nil {
  57. return -1, err
  58. }
  59. req.LeaderName = pb.GetLeaderName()
  60. req.LastIndex = pb.GetLastIndex()
  61. req.LastTerm = pb.GetLastTerm()
  62. req.Peers = req.Peers
  63. req.State = req.State
  64. return totalBytes, nil
  65. }