Browse Source

raft: reverse sort to figure out the ci

Xiang Li 11 years ago
parent
commit
73e3394d2d
2 changed files with 40 additions and 5 deletions
  1. 5 5
      raft/raft.go
  2. 35 0
      raft/raft_test.go

+ 5 - 5
raft/raft.go

@@ -182,12 +182,12 @@ func (sm *stateMachine) theN() int {
 	for i := range mis {
 		mis[i] = sm.ins[i].match
 	}
-	sort.Ints(mis)
-	for _, mi := range mis[sm.k/2+1:] {
-		if sm.log[mi].Term == sm.term {
-			return mi
-		}
+	sort.Sort(sort.Reverse(sort.IntSlice(mis)))
+	mci := mis[sm.q()-1]
+	if sm.log[mci].Term == sm.term {
+		return mci
 	}
+
 	return -1
 }
 

+ 35 - 0
raft/raft_test.go

@@ -242,6 +242,41 @@ func TestProposalByProxy(t *testing.T) {
 	}
 }
 
+func TestTheN(t *testing.T) {
+	tests := []struct {
+		matches []int
+		logs    []Entry
+		smTerm  int
+		w       int
+	}{
+		// odd
+		{[]int{2, 1, 1}, []Entry{{}, {Term: 1}, {Term: 2}}, 1, 1},
+		{[]int{2, 1, 1}, []Entry{{}, {Term: 1}, {Term: 1}}, 2, -1},
+		{[]int{2, 1, 2}, []Entry{{}, {Term: 1}, {Term: 2}}, 2, 2},
+		{[]int{2, 1, 2}, []Entry{{}, {Term: 1}, {Term: 1}}, 2, -1},
+
+		// even
+		{[]int{2, 1, 1, 1}, []Entry{{}, {Term: 1}, {Term: 2}}, 1, 1},
+		{[]int{2, 1, 1, 1}, []Entry{{}, {Term: 1}, {Term: 1}}, 2, -1},
+		{[]int{2, 1, 1, 2}, []Entry{{}, {Term: 1}, {Term: 2}}, 1, 1},
+		{[]int{2, 1, 1, 2}, []Entry{{}, {Term: 1}, {Term: 1}}, 2, -1},
+		{[]int{2, 1, 2, 2}, []Entry{{}, {Term: 1}, {Term: 2}}, 2, 2},
+		{[]int{2, 1, 2, 2}, []Entry{{}, {Term: 1}, {Term: 1}}, 2, -1},
+	}
+
+	for i, tt := range tests {
+		ins := make([]*index, len(tt.matches))
+		for j := 0; j < len(ins); j++ {
+			ins[j] = &index{tt.matches[j], tt.matches[j] + 1}
+		}
+		sm := &stateMachine{log: tt.logs, ins: ins, k: len(ins), term: tt.smTerm}
+		g := sm.theN()
+		if g != tt.w {
+			t.Errorf("#%d: theN = %d, want %d", i, g, tt.w)
+		}
+	}
+}
+
 func TestVote(t *testing.T) {
 	tests := []struct {
 		i, term int