raft: reverse sort to figure out the ci

release-2.0
Xiang Li 2014-05-21 16:02:15 -07:00 committed by Yicheng Qin
parent 8ddcd9799d
commit 73e3394d2d
2 changed files with 40 additions and 5 deletions

View File

@ -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
}

View File

@ -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