2013-07-17 13:45:53 +00:00
|
|
|
package raft
|
|
|
|
|
|
|
|
import (
|
2013-07-18 16:26:31 +00:00
|
|
|
"code.google.com/p/goprotobuf/proto"
|
2013-07-18 16:41:33 +00:00
|
|
|
"github.com/benbjohnson/go-raft/protobuf"
|
2013-07-17 13:45:53 +00:00
|
|
|
"io"
|
2013-07-18 16:26:31 +00:00
|
|
|
"io/ioutil"
|
2013-07-17 13:45:53 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// The response returned from a server after a vote for a candidate to become a leader.
|
|
|
|
type RequestVoteResponse struct {
|
|
|
|
peer *Peer
|
|
|
|
Term uint64
|
|
|
|
VoteGranted bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// Creates a new RequestVote response.
|
|
|
|
func newRequestVoteResponse(term uint64, voteGranted bool) *RequestVoteResponse {
|
|
|
|
return &RequestVoteResponse{
|
|
|
|
Term: term,
|
|
|
|
VoteGranted: voteGranted,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-07-18 16:26:31 +00:00
|
|
|
// Encodes the RequestVoteResponse to a buffer. Returns the number of bytes
|
|
|
|
// written and any error that may have occurred.
|
2013-07-17 13:45:53 +00:00
|
|
|
func (resp *RequestVoteResponse) encode(w io.Writer) (int, error) {
|
2013-07-18 16:26:31 +00:00
|
|
|
pb := &protobuf.ProtoRequestVoteResponse{
|
|
|
|
Term: proto.Uint64(resp.Term),
|
|
|
|
VoteGranted: proto.Bool(resp.VoteGranted),
|
|
|
|
}
|
2013-07-17 13:45:53 +00:00
|
|
|
|
2013-08-02 08:49:56 +00:00
|
|
|
p, err := proto.Marshal(pb)
|
2013-07-18 16:26:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return -1, err
|
|
|
|
}
|
|
|
|
|
2013-08-02 08:49:56 +00:00
|
|
|
return w.Write(p)
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
|
2013-07-18 16:26:31 +00:00
|
|
|
// Decodes the RequestVoteResponse from a buffer. Returns the number of bytes read and
|
|
|
|
// any error that occurs.
|
2013-07-17 13:45:53 +00:00
|
|
|
func (resp *RequestVoteResponse) decode(r io.Reader) (int, error) {
|
2013-07-18 16:26:31 +00:00
|
|
|
data, err := ioutil.ReadAll(r)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
|
2013-07-18 16:26:31 +00:00
|
|
|
totalBytes := len(data)
|
|
|
|
|
|
|
|
pb := &protobuf.ProtoRequestVoteResponse{}
|
2013-08-02 08:49:56 +00:00
|
|
|
if err = proto.Unmarshal(data, pb); err != nil {
|
2013-07-18 16:26:31 +00:00
|
|
|
return -1, err
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
|
2013-07-18 16:26:31 +00:00
|
|
|
resp.Term = pb.GetTerm()
|
|
|
|
resp.VoteGranted = pb.GetVoteGranted()
|
2013-07-17 13:45:53 +00:00
|
|
|
|
2013-07-18 16:26:31 +00:00
|
|
|
return totalBytes, nil
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|