Browse Source

raft: address issues with election timeout

Xiang Li 11 years ago
parent
commit
1cd3345e00
2 changed files with 6 additions and 7 deletions
  1. 3 4
      raft/raft.go
  2. 3 3
      raft/raft_test.go

+ 3 - 4
raft/raft.go

@@ -5,7 +5,6 @@ import (
 	"fmt"
 	"math/rand"
 	"sort"
-	"time"
 
 	pb "github.com/coreos/etcd/raft/raftpb"
 )
@@ -134,7 +133,7 @@ func newRaft(id int64, peers []int64, election, heartbeat int) *raft {
 	if id == None {
 		panic("cannot use none id")
 	}
-	rand.Seed(time.Now().UnixNano())
+	rand.Seed(id)
 	r := &raft{
 		id:               id,
 		lead:             None,
@@ -589,12 +588,12 @@ func (r *raft) loadState(state pb.HardState) {
 }
 
 // isElectionTimeout returns true if r.elapsed is greater than the
-// randomized election timeout in [electiontimeout, 2 * electiontimeout - 1).
+// randomized election timeout in (electiontimeout, 2 * electiontimeout - 1).
 // Otherwise, it returns false.
 func (r *raft) isElectionTimeout() bool {
 	d := r.elapsed - r.electionTimeout
 	if d < 0 {
 		return false
 	}
-	return d > int(rand.Int31())%r.electionTimeout
+	return d > rand.Int()%r.electionTimeout
 }

+ 3 - 3
raft/raft_test.go

@@ -496,7 +496,7 @@ func TestCommit(t *testing.T) {
 func TestIsElectionTimeout(t *testing.T) {
 	tests := []struct {
 		elapse       int
-		wpossibility float64
+		wprobability float64
 		round        bool
 	}{
 		{5, 0, false},
@@ -519,8 +519,8 @@ func TestIsElectionTimeout(t *testing.T) {
 		if tt.round {
 			got = math.Floor(got*10+0.5) / 10.0
 		}
-		if got != tt.wpossibility {
-			t.Errorf("#%d: possibility = %v, want %v", i, got, tt.wpossibility)
+		if got != tt.wprobability {
+			t.Errorf("#%d: possibility = %v, want %v", i, got, tt.wprobability)
 		}
 	}
 }