syncAppendEntries.c 11.2 KB
Newer Older
M
Minghao Li 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@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/>.
 */

16
#define _DEFAULT_SOURCE
M
Minghao Li 已提交
17
#include "syncAppendEntries.h"
18
#include "syncMessage.h"
M
Minghao Li 已提交
19 20
#include "syncRaftLog.h"
#include "syncRaftStore.h"
21
#include "syncUtil.h"
M
Minghao Li 已提交
22

M
Minghao Li 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
// TLA+ Spec
// HandleAppendEntriesRequest(i, j, m) ==
//    LET logOk == \/ m.mprevLogIndex = 0
//                 \/ /\ m.mprevLogIndex > 0
//                    /\ m.mprevLogIndex <= Len(log[i])
//                    /\ m.mprevLogTerm = log[i][m.mprevLogIndex].term
//    IN /\ m.mterm <= currentTerm[i]
//       /\ \/ /\ \* reject request
//                \/ m.mterm < currentTerm[i]
//                \/ /\ m.mterm = currentTerm[i]
//                   /\ state[i] = Follower
//                   /\ \lnot logOk
//             /\ Reply([mtype           |-> AppendEntriesResponse,
//                       mterm           |-> currentTerm[i],
//                       msuccess        |-> FALSE,
//                       mmatchIndex     |-> 0,
//                       msource         |-> i,
//                       mdest           |-> j],
//                       m)
//             /\ UNCHANGED <<serverVars, logVars>>
//          \/ \* return to follower state
//             /\ m.mterm = currentTerm[i]
//             /\ state[i] = Candidate
//             /\ state' = [state EXCEPT ![i] = Follower]
//             /\ UNCHANGED <<currentTerm, votedFor, logVars, messages>>
//          \/ \* accept request
//             /\ m.mterm = currentTerm[i]
//             /\ state[i] = Follower
//             /\ logOk
//             /\ LET index == m.mprevLogIndex + 1
//                IN \/ \* already done with request
//                       /\ \/ m.mentries = << >>
//                          \/ /\ m.mentries /= << >>
//                             /\ Len(log[i]) >= index
//                             /\ log[i][index].term = m.mentries[1].term
//                          \* This could make our commitIndex decrease (for
//                          \* example if we process an old, duplicated request),
//                          \* but that doesn't really affect anything.
//                       /\ commitIndex' = [commitIndex EXCEPT ![i] =
//                                              m.mcommitIndex]
//                       /\ Reply([mtype           |-> AppendEntriesResponse,
//                                 mterm           |-> currentTerm[i],
//                                 msuccess        |-> TRUE,
//                                 mmatchIndex     |-> m.mprevLogIndex +
//                                                     Len(m.mentries),
//                                 msource         |-> i,
//                                 mdest           |-> j],
//                                 m)
//                       /\ UNCHANGED <<serverVars, log>>
//                   \/ \* conflict: remove 1 entry
//                       /\ m.mentries /= << >>
//                       /\ Len(log[i]) >= index
//                       /\ log[i][index].term /= m.mentries[1].term
//                       /\ LET new == [index2 \in 1..(Len(log[i]) - 1) |->
//                                          log[i][index2]]
//                          IN log' = [log EXCEPT ![i] = new]
//                       /\ UNCHANGED <<serverVars, commitIndex, messages>>
//                   \/ \* no conflict: append entry
//                       /\ m.mentries /= << >>
//                       /\ Len(log[i]) = m.mprevLogIndex
//                       /\ log' = [log EXCEPT ![i] =
//                                      Append(log[i], m.mentries[1])]
//                       /\ UNCHANGED <<serverVars, commitIndex, messages>>
//       /\ UNCHANGED <<candidateVars, leaderVars>>
//
88

89
int32_t syncNodeFollowerCommit(SSyncNode* ths, SyncIndex newCommitIndex) {
90
  if (ths->state != TAOS_SYNC_STATE_FOLLOWER) {
S
Shengliang Guan 已提交
91
    sNTrace(ths, "can not do follower commit");
92 93 94
    return -1;
  }

95 96 97 98 99 100 101 102 103 104 105
  // maybe update commit index, leader notice me
  if (newCommitIndex > ths->commitIndex) {
    // has commit entry in local
    if (newCommitIndex <= ths->pLogStore->syncLogLastIndex(ths->pLogStore)) {
      // advance commit index to sanpshot first
      SSnapshot snapshot;
      ths->pFsm->FpGetSnapshotInfo(ths->pFsm, &snapshot);
      if (snapshot.lastApplyIndex >= 0 && snapshot.lastApplyIndex > ths->commitIndex) {
        SyncIndex commitBegin = ths->commitIndex;
        SyncIndex commitEnd = snapshot.lastApplyIndex;
        ths->commitIndex = snapshot.lastApplyIndex;
S
Shengliang Guan 已提交
106
        sNTrace(ths, "commit by snapshot from index:%" PRId64 " to index:%" PRId64, commitBegin, commitEnd);
107 108 109 110 111 112 113 114 115
      }

      SyncIndex beginIndex = ths->commitIndex + 1;
      SyncIndex endIndex = newCommitIndex;

      // update commit index
      ths->commitIndex = newCommitIndex;

      // call back Wal
M
Minghao Li 已提交
116
      int32_t code = ths->pLogStore->syncLogUpdateCommitIndex(ths->pLogStore, ths->commitIndex);
117 118
      ASSERT(code == 0);

M
Minghao Li 已提交
119
      code = syncNodeDoCommit(ths, beginIndex, endIndex, ths->state);
120 121 122 123 124 125 126
      ASSERT(code == 0);
    }
  }

  return 0;
}

127 128 129 130 131 132 133 134 135 136 137 138 139 140
void syncLogRecvAppendEntries(SSyncNode* pSyncNode, const SyncAppendEntries* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);

  sNTrace(pSyncNode,
          "recv sync-append-entries from %s:%d {term:%" PRId64 ", pre-index:%" PRId64 ", pre-term:%" PRId64
          ", cmt:%" PRId64 ", pterm:%" PRId64 ", datalen:%d}, %s",
          host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
          pMsg->dataLen, s);
}

int32_t syncNodeOnAppendEntries(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncAppendEntries* pMsg = pRpcMsg->pCont;
141
  SRpcMsg            rpcRsp = {0};
142

M
Minghao Li 已提交
143
  // if already drop replica, do not process
M
Minghao Li 已提交
144 145
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId))) {
    syncLogRecvAppendEntries(ths, pMsg, "not in my config");
M
Minghao Li 已提交
146 147 148
    goto _IGNORE;
  }

M
Minghao Li 已提交
149
  // prepare response msg
150 151 152 153 154 155 156
  int32_t code = syncBuildRequestVoteReply(&rpcRsp, ths->vgId);
  if (code != 0) {
    syncLogRecvAppendEntries(ths, pMsg, "build rsp error");
    goto _IGNORE;
  }

  SyncAppendEntriesReply* pReply = rpcRsp.pCont;
M
Minghao Li 已提交
157 158 159 160
  pReply->srcId = ths->myRaftId;
  pReply->destId = pMsg->srcId;
  pReply->term = ths->pRaftStore->currentTerm;
  pReply->success = false;
M
Minghao Li 已提交
161 162
  // pReply->matchIndex = ths->pLogStore->syncLogLastIndex(ths->pLogStore);
  pReply->matchIndex = SYNC_INDEX_INVALID;
M
Minghao Li 已提交
163 164 165 166
  pReply->lastSendIndex = pMsg->prevLogIndex + 1;
  pReply->startTime = ths->startTime;

  if (pMsg->term < ths->pRaftStore->currentTerm) {
M
Minghao Li 已提交
167
    syncLogRecvAppendEntries(ths, pMsg, "reject, small term");
M
Minghao Li 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181
    goto _SEND_RESPONSE;
  }

  if (pMsg->term > ths->pRaftStore->currentTerm) {
    pReply->term = pMsg->term;
  }

  syncNodeStepDown(ths, pMsg->term);
  syncNodeResetElectTimer(ths);

  SyncIndex startIndex = ths->pLogStore->syncLogBeginIndex(ths->pLogStore);
  SyncIndex lastIndex = ths->pLogStore->syncLogLastIndex(ths->pLogStore);

  if (pMsg->prevLogIndex > lastIndex) {
M
Minghao Li 已提交
182
    syncLogRecvAppendEntries(ths, pMsg, "reject, index not match");
M
Minghao Li 已提交
183 184 185 186 187 188 189 190
    goto _SEND_RESPONSE;
  }

  if (pMsg->prevLogIndex >= startIndex) {
    SyncTerm myPreLogTerm = syncNodeGetPreTerm(ths, pMsg->prevLogIndex + 1);
    ASSERT(myPreLogTerm != SYNC_TERM_INVALID);

    if (myPreLogTerm != pMsg->prevLogTerm) {
M
Minghao Li 已提交
191
      syncLogRecvAppendEntries(ths, pMsg, "reject, pre-term not match");
M
Minghao Li 已提交
192 193 194 195 196 197 198 199
      goto _SEND_RESPONSE;
    }
  }

  // accept
  pReply->success = true;
  bool hasAppendEntries = pMsg->dataLen > 0;
  if (hasAppendEntries) {
200
    SSyncRaftEntry* pAppendEntry = syncEntryBuildFromAppendEntries(pMsg);
M
Minghao Li 已提交
201 202 203 204 205
    ASSERT(pAppendEntry != NULL);

    SyncIndex       appendIndex = pMsg->prevLogIndex + 1;
    SSyncRaftEntry* pLocalEntry = NULL;
    int32_t         code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, appendIndex, &pLocalEntry);
M
Minghao Li 已提交
206 207 208
    if (code == 0) {
      if (pLocalEntry->term == pAppendEntry->term) {
        // do nothing
S
Shengliang Guan 已提交
209
        sNTrace(ths, "log match, do nothing, index:%" PRId64, appendIndex);
M
Minghao Li 已提交
210 211 212 213 214
      } else {
        // truncate
        code = ths->pLogStore->syncLogTruncate(ths->pLogStore, appendIndex);
        if (code != 0) {
          char logBuf[128];
S
Shengliang Guan 已提交
215
          snprintf(logBuf, sizeof(logBuf), "ignore, truncate error, append-index:%" PRId64, appendIndex);
M
Minghao Li 已提交
216 217
          syncLogRecvAppendEntries(ths, pMsg, logBuf);

M
Minghao Li 已提交
218 219
          syncEntryDestory(pLocalEntry);
          syncEntryDestory(pAppendEntry);
M
Minghao Li 已提交
220 221 222 223 224 225 226
          goto _IGNORE;
        }

        // append
        code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
        if (code != 0) {
          char logBuf[128];
S
Shengliang Guan 已提交
227
          snprintf(logBuf, sizeof(logBuf), "ignore, append error, append-index:%" PRId64, appendIndex);
M
Minghao Li 已提交
228 229
          syncLogRecvAppendEntries(ths, pMsg, logBuf);

M
Minghao Li 已提交
230 231
          syncEntryDestory(pLocalEntry);
          syncEntryDestory(pAppendEntry);
M
Minghao Li 已提交
232 233 234 235 236 237 238 239 240 241 242 243
          goto _IGNORE;
        }
      }

    } else {
      if (terrno == TSDB_CODE_WAL_LOG_NOT_EXIST) {
        // log not exist

        // truncate
        code = ths->pLogStore->syncLogTruncate(ths->pLogStore, appendIndex);
        if (code != 0) {
          char logBuf[128];
S
Shengliang Guan 已提交
244
          snprintf(logBuf, sizeof(logBuf), "ignore, log not exist, truncate error, append-index:%" PRId64, appendIndex);
M
Minghao Li 已提交
245 246
          syncLogRecvAppendEntries(ths, pMsg, logBuf);

M
Minghao Li 已提交
247 248
          syncEntryDestory(pLocalEntry);
          syncEntryDestory(pAppendEntry);
M
Minghao Li 已提交
249 250 251 252 253 254 255
          goto _IGNORE;
        }

        // append
        code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
        if (code != 0) {
          char logBuf[128];
S
Shengliang Guan 已提交
256
          snprintf(logBuf, sizeof(logBuf), "ignore, log not exist, append error, append-index:%" PRId64, appendIndex);
M
Minghao Li 已提交
257 258
          syncLogRecvAppendEntries(ths, pMsg, logBuf);

M
Minghao Li 已提交
259 260
          syncEntryDestory(pLocalEntry);
          syncEntryDestory(pAppendEntry);
M
Minghao Li 已提交
261 262 263 264 265 266
          goto _IGNORE;
        }

      } else {
        // error
        char logBuf[128];
267 268
        snprintf(logBuf, sizeof(logBuf), "ignore, get local entry error, append-index:%" PRId64 " err:%d", appendIndex,
                 terrno);
M
Minghao Li 已提交
269 270
        syncLogRecvAppendEntries(ths, pMsg, logBuf);

M
Minghao Li 已提交
271 272
        syncEntryDestory(pLocalEntry);
        syncEntryDestory(pAppendEntry);
M
Minghao Li 已提交
273 274 275 276 277 278
        goto _IGNORE;
      }
    }

    // update match index
    pReply->matchIndex = pAppendEntry->index;
M
Minghao Li 已提交
279 280 281 282

    syncEntryDestory(pLocalEntry);
    syncEntryDestory(pAppendEntry);

M
Minghao Li 已提交
283 284 285 286 287 288 289
  } else {
    // no append entries, do nothing
    // maybe has extra entries, no harm

    // update match index
    pReply->matchIndex = pMsg->prevLogIndex;
  }
M
Minghao Li 已提交
290 291

  // maybe update commit index, leader notice me
292
  syncNodeFollowerCommit(ths, pMsg->commitIndex);
M
Minghao Li 已提交
293

M
Minghao Li 已提交
294
  syncLogRecvAppendEntries(ths, pMsg, "accept");
M
Minghao Li 已提交
295 296 297
  goto _SEND_RESPONSE;

_IGNORE:
298
  rpcFreeCont(rpcRsp.pCont);
M
Minghao Li 已提交
299 300 301 302 303 304 305
  return 0;

_SEND_RESPONSE:
  // msg event log
  syncLogSendAppendEntriesReply(ths, pReply, "");

  // send response
306
  syncNodeSendMsgById(&pReply->destId, ths, &rpcRsp);
M
Minghao Li 已提交
307 308
  return 0;
}