From 73e3394d2d2d20fc0a7ca9354d367536be2333da Mon Sep 17 00:00:00 2001 From: Xiang Li Date: Wed, 21 May 2014 16:02:15 -0700 Subject: [PATCH] raft: reverse sort to figure out the ci --- raft/raft.go | 10 +++++----- raft/raft_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/raft/raft.go b/raft/raft.go index 98fbf95d4..8bdf2d54a 100644 --- a/raft/raft.go +++ b/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 } diff --git a/raft/raft_test.go b/raft/raft_test.go index a00eb9d9b..f6e2dd46d 100644 --- a/raft/raft_test.go +++ b/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