raft_handle_vote_message.c 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (c) 2019 TAOS Data, Inc. <cli@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "syncInt.h"
#include "raft.h"
L
lichuang 已提交
18
#include "sync_raft_impl.h"
19 20 21 22 23 24 25
#include "raft_log.h"
#include "raft_message.h"

static bool canGrantVoteMessage(SSyncRaft* pRaft, const SSyncMessage* pMsg);

int syncRaftHandleVoteMessage(SSyncRaft* pRaft, const SSyncMessage* pMsg) {
  SSyncMessage* pRespMsg;
L
lichuang 已提交
26 27
  SNodeInfo* pNode = syncRaftGetNodeById(pRaft, pMsg->from);
  if (pNode == NULL) {
28 29
    return 0;
  }
L
lichuang 已提交
30

31 32 33 34 35
  bool grant;
  SyncIndex lastIndex = syncRaftLogLastIndex(pRaft->log);
  SyncTerm lastTerm = syncRaftLogLastTerm(pRaft->log);

  grant = canGrantVoteMessage(pRaft, pMsg);
36
  pRespMsg = syncNewVoteRespMsg(pRaft->selfGroupId, pRaft->selfId, pMsg->vote.cType, !grant);
37 38 39
  if (pRespMsg == NULL) {
    return 0;
  }
S
Shengliang Guan 已提交
40
  syncInfo("[%d:%d] [logterm: %" PRId64 ", index: %" PRId64 ", vote: %d] %s for %d"    
41
    "[logterm: %" PRId64 ", index: %" PRId64 "] at term %" PRId64 "",
42 43 44 45
    pRaft->selfGroupId, pRaft->selfId, lastTerm, lastIndex, pRaft->voteFor,
    grant ? "grant" : "reject",
    pMsg->from, pMsg->vote.lastTerm, pMsg->vote.lastIndex, pRaft->term);

L
lichuang 已提交
46
  pRaft->io.send(pRespMsg, pNode);
47 48 49 50
  return 0;
}

static bool canGrantVoteMessage(SSyncRaft* pRaft, const SSyncMessage* pMsg) {
51 52 53 54 55 56 57 58 59 60
  bool canVote = 
                  // We can vote if this is a repeat of a vote we've already cast...
                 pRaft->voteFor == pMsg->from ||
                  // ...we haven't voted and we don't think there's a leader yet in this term...
                 (pRaft->voteFor == SYNC_NON_NODE_ID && pRaft->leaderId == SYNC_NON_NODE_ID) ||
                  // ...or this is a PreVote for a future term...
                 (pMsg->vote.cType == SYNC_RAFT_CAMPAIGN_PRE_ELECTION && pMsg->term > pRaft->term);

  // ...and we believe the candidate is up to date.
  return canVote && syncRaftLogIsUptodate(pRaft->log, pMsg->vote.lastIndex, pMsg->vote.lastTerm);
61
}