syncAppendEntries.c 33.6 KB
Newer Older
M
Minghao Li 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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/>.
 */

#include "syncAppendEntries.h"
M
Minghao Li 已提交
17
#include "syncInt.h"
M
Minghao Li 已提交
18
#include "syncRaftCfg.h"
M
Minghao Li 已提交
19 20
#include "syncRaftLog.h"
#include "syncRaftStore.h"
M
Minghao Li 已提交
21
#include "syncSnapshot.h"
M
Minghao Li 已提交
22 23
#include "syncUtil.h"
#include "syncVoteMgr.h"
M
Minghao Li 已提交
24
#include "wal.h"
M
Minghao Li 已提交
25

M
Minghao Li 已提交
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 88 89 90
// 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>>
//
91

M
Minghao Li 已提交
92 93 94 95 96
int32_t syncNodeOnAppendEntriesCb(SSyncNode* ths, SyncAppendEntries* pMsg) {
  int32_t ret = 0;

  // if already drop replica, do not process
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId)) && !ths->pRaftCfg->isStandBy) {
M
Minghao Li 已提交
97
    syncLogRecvAppendEntries(ths, pMsg, "maybe replica already dropped");
M
Minghao Li 已提交
98
    return -1;
M
Minghao Li 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  }

  // maybe update term
  if (pMsg->term > ths->pRaftStore->currentTerm) {
    syncNodeUpdateTerm(ths, pMsg->term);
  }
  ASSERT(pMsg->term <= ths->pRaftStore->currentTerm);

  // reset elect timer
  if (pMsg->term == ths->pRaftStore->currentTerm) {
    ths->leaderCache = pMsg->srcId;
    syncNodeResetElectTimer(ths);
  }
  ASSERT(pMsg->dataLen >= 0);

M
Minghao Li 已提交
114 115 116 117 118 119
  // return to follower state
  if (pMsg->term == ths->pRaftStore->currentTerm && ths->state == TAOS_SYNC_STATE_CANDIDATE) {
    syncLogRecvAppendEntries(ths, pMsg, "candidate to follower");
    syncNodeBecomeFollower(ths, "from candidate by append entries");
    return -1;  // ret or reply?
  }
M
Minghao Li 已提交
120 121 122 123 124 125

  SyncTerm localPreLogTerm = 0;
  if (pMsg->prevLogIndex >= SYNC_INDEX_BEGIN && pMsg->prevLogIndex <= ths->pLogStore->getLastIndex(ths->pLogStore)) {
    SSyncRaftEntry* pEntry = ths->pLogStore->getEntry(ths->pLogStore, pMsg->prevLogIndex);
    if (pEntry == NULL) {
      char logBuf[128];
S
Shengliang Guan 已提交
126
      snprintf(logBuf, sizeof(logBuf), "getEntry error, index:%" PRId64 ", since %s", pMsg->prevLogIndex, terrstr());
M
Minghao Li 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
      syncNodeErrorLog(ths, logBuf);
      return -1;
    }

    localPreLogTerm = pEntry->term;
    syncEntryDestory(pEntry);
  }

  bool logOK =
      (pMsg->prevLogIndex == SYNC_INDEX_INVALID) ||
      ((pMsg->prevLogIndex >= SYNC_INDEX_BEGIN) &&
       (pMsg->prevLogIndex <= ths->pLogStore->getLastIndex(ths->pLogStore)) && (pMsg->prevLogTerm == localPreLogTerm));

  // reject request
  if ((pMsg->term < ths->pRaftStore->currentTerm) ||
      ((pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) && !logOK)) {
M
Minghao Li 已提交
143
    syncLogRecvAppendEntries(ths, pMsg, "reject");
M
Minghao Li 已提交
144 145 146 147 148 149 150 151

    SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
    pReply->srcId = ths->myRaftId;
    pReply->destId = pMsg->srcId;
    pReply->term = ths->pRaftStore->currentTerm;
    pReply->success = false;
    pReply->matchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
152
    // msg event log
M
Minghao Li 已提交
153
    syncLogSendAppendEntriesReply(ths, pReply, "");
M
Minghao Li 已提交
154

M
Minghao Li 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    SRpcMsg rpcMsg;
    syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
    syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
    syncAppendEntriesReplyDestroy(pReply);

    return ret;
  }

  // accept request
  if (pMsg->term == ths->pRaftStore->currentTerm && ths->state == TAOS_SYNC_STATE_FOLLOWER && logOK) {
    // preIndex = -1, or has preIndex entry in local log
    ASSERT(pMsg->prevLogIndex <= ths->pLogStore->getLastIndex(ths->pLogStore));

    // has extra entries (> preIndex) in local log
    bool hasExtraEntries = pMsg->prevLogIndex < ths->pLogStore->getLastIndex(ths->pLogStore);

    // has entries in SyncAppendEntries msg
    bool hasAppendEntries = pMsg->dataLen > 0;

M
Minghao Li 已提交
174
    syncLogRecvAppendEntries(ths, pMsg, "accept");
M
Minghao Li 已提交
175 176 177 178 179 180 181 182 183

    if (hasExtraEntries && hasAppendEntries) {
      // not conflict by default
      bool conflict = false;

      SyncIndex       extraIndex = pMsg->prevLogIndex + 1;
      SSyncRaftEntry* pExtraEntry = ths->pLogStore->getEntry(ths->pLogStore, extraIndex);
      if (pExtraEntry == NULL) {
        char logBuf[128];
S
Shengliang Guan 已提交
184
        snprintf(logBuf, sizeof(logBuf), "getEntry error2, index:%" PRId64 ", since %s", extraIndex, terrstr());
M
Minghao Li 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        syncNodeErrorLog(ths, logBuf);
        return -1;
      }

      SSyncRaftEntry* pAppendEntry = syncEntryDeserialize(pMsg->data, pMsg->dataLen);
      if (pAppendEntry == NULL) {
        syncNodeErrorLog(ths, "syncEntryDeserialize pAppendEntry error");
        return -1;
      }

      // log not match, conflict
      ASSERT(extraIndex == pAppendEntry->index);
      if (pExtraEntry->term != pAppendEntry->term) {
        conflict = true;
      }

      if (conflict) {
        // roll back
        SyncIndex delBegin = ths->pLogStore->getLastIndex(ths->pLogStore);
        SyncIndex delEnd = extraIndex;

S
Shengliang Guan 已提交
206 207
        sTrace("syncNodeOnAppendEntriesCb --> conflict:%d, delBegin:%" PRId64 ", delEnd:%" PRId64, conflict, delBegin,
               delEnd);
M
Minghao Li 已提交
208 209 210 211 212 213 214

        // notice! reverse roll back!
        for (SyncIndex index = delEnd; index >= delBegin; --index) {
          if (ths->pFsm->FpRollBackCb != NULL) {
            SSyncRaftEntry* pRollBackEntry = ths->pLogStore->getEntry(ths->pLogStore, index);
            if (pRollBackEntry == NULL) {
              char logBuf[128];
S
Shengliang Guan 已提交
215
              snprintf(logBuf, sizeof(logBuf), "getEntry error3, index:%" PRId64 ", since %s", index, terrstr());
M
Minghao Li 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
              syncNodeErrorLog(ths, logBuf);
              return -1;
            }

            // if (pRollBackEntry->msgType != TDMT_SYNC_NOOP) {
            if (syncUtilUserRollback(pRollBackEntry->msgType)) {
              SRpcMsg rpcMsg;
              syncEntry2OriginalRpc(pRollBackEntry, &rpcMsg);

              SFsmCbMeta cbMeta = {0};
              cbMeta.index = pRollBackEntry->index;
              cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
              cbMeta.isWeak = pRollBackEntry->isWeak;
              cbMeta.code = 0;
              cbMeta.state = ths->state;
              cbMeta.seqNum = pRollBackEntry->seqNum;
              ths->pFsm->FpRollBackCb(ths->pFsm, &rpcMsg, cbMeta);
              rpcFreeCont(rpcMsg.pCont);
            }

            syncEntryDestory(pRollBackEntry);
          }
        }

        // delete confict entries
        ths->pLogStore->truncate(ths->pLogStore, extraIndex);

        // append new entries
        ths->pLogStore->appendEntry(ths->pLogStore, pAppendEntry);

        // pre commit
247
        syncNodePreCommit(ths, pAppendEntry, 0);
M
Minghao Li 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
      }

      // free memory
      syncEntryDestory(pExtraEntry);
      syncEntryDestory(pAppendEntry);

    } else if (hasExtraEntries && !hasAppendEntries) {
      // do nothing

    } else if (!hasExtraEntries && hasAppendEntries) {
      SSyncRaftEntry* pAppendEntry = syncEntryDeserialize(pMsg->data, pMsg->dataLen);
      if (pAppendEntry == NULL) {
        syncNodeErrorLog(ths, "syncEntryDeserialize pAppendEntry2 error");
        return -1;
      }

      // append new entries
      ths->pLogStore->appendEntry(ths->pLogStore, pAppendEntry);

      // pre commit
268
      syncNodePreCommit(ths, pAppendEntry, 0);
M
Minghao Li 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

      // free memory
      syncEntryDestory(pAppendEntry);

    } else if (!hasExtraEntries && !hasAppendEntries) {
      // do nothing

    } else {
      syncNodeLog3("", ths);
      ASSERT(0);
    }

    SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
    pReply->srcId = ths->myRaftId;
    pReply->destId = pMsg->srcId;
    pReply->term = ths->pRaftStore->currentTerm;
    pReply->success = true;

    if (hasAppendEntries) {
      pReply->matchIndex = pMsg->prevLogIndex + 1;
    } else {
      pReply->matchIndex = pMsg->prevLogIndex;
    }

M
Minghao Li 已提交
293
    // msg event log
M
Minghao Li 已提交
294
    syncLogSendAppendEntriesReply(ths, pReply, "");
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

    SRpcMsg rpcMsg;
    syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
    syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
    syncAppendEntriesReplyDestroy(pReply);

    // maybe update commit index from leader
    if (pMsg->commitIndex > ths->commitIndex) {
      // has commit entry in local
      if (pMsg->commitIndex <= ths->pLogStore->getLastIndex(ths->pLogStore)) {
        SyncIndex beginIndex = ths->commitIndex + 1;
        SyncIndex endIndex = pMsg->commitIndex;

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

        // call back Wal
        ths->pLogStore->updateCommitIndex(ths->pLogStore, ths->commitIndex);

        int32_t code = syncNodeCommit(ths, beginIndex, endIndex, ths->state);
        ASSERT(code == 0);
      }
    }
  }

  return ret;
}

M
Minghao Li 已提交
323
static int32_t syncNodeMakeLogSame(SSyncNode* ths, SyncAppendEntries* pMsg) {
324 325
  int32_t code;

M
Minghao Li 已提交
326 327
  SyncIndex delBegin = pMsg->prevLogIndex + 1;
  SyncIndex delEnd = ths->pLogStore->syncLogLastIndex(ths->pLogStore);
328

M
Minghao Li 已提交
329 330 331 332 333 334 335
  // invert roll back!
  for (SyncIndex index = delEnd; index >= delBegin; --index) {
    if (ths->pFsm->FpRollBackCb != NULL) {
      SSyncRaftEntry* pRollBackEntry;
      code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, index, &pRollBackEntry);
      ASSERT(code == 0);
      ASSERT(pRollBackEntry != NULL);
336

M
Minghao Li 已提交
337 338 339 340
      if (syncUtilUserRollback(pRollBackEntry->msgType)) {
        SRpcMsg rpcMsg;
        syncEntry2OriginalRpc(pRollBackEntry, &rpcMsg);

341
        SFsmCbMeta cbMeta = {0};
M
Minghao Li 已提交
342
        cbMeta.index = pRollBackEntry->index;
343
        cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
M
Minghao Li 已提交
344 345 346 347 348 349
        cbMeta.isWeak = pRollBackEntry->isWeak;
        cbMeta.code = 0;
        cbMeta.state = ths->state;
        cbMeta.seqNum = pRollBackEntry->seqNum;
        ths->pFsm->FpRollBackCb(ths->pFsm, &rpcMsg, cbMeta);
        rpcFreeCont(rpcMsg.pCont);
350 351
      }

M
Minghao Li 已提交
352 353
      syncEntryDestory(pRollBackEntry);
    }
354 355
  }

M
Minghao Li 已提交
356 357 358
  // delete confict entries
  code = ths->pLogStore->syncLogTruncate(ths->pLogStore, delBegin);
  ASSERT(code == 0);
M
Minghao Li 已提交
359 360

  char eventLog[128];
S
Shengliang Guan 已提交
361
  snprintf(eventLog, sizeof(eventLog), "log truncate, from %" PRId64 " to %" PRId64, delBegin, delEnd);
M
Minghao Li 已提交
362
  syncNodeEventLog(ths, eventLog);
M
Minghao Li 已提交
363
  logStoreSimpleLog2("after syncNodeMakeLogSame", ths->pLogStore);
M
Minghao Li 已提交
364 365

  return code;
366 367
}

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
static int32_t syncNodeDoMakeLogSame(SSyncNode* ths, SyncIndex FromIndex) {
  int32_t code;

  SyncIndex delBegin = FromIndex;
  SyncIndex delEnd = ths->pLogStore->syncLogLastIndex(ths->pLogStore);

  // invert roll back!
  for (SyncIndex index = delEnd; index >= delBegin; --index) {
    if (ths->pFsm->FpRollBackCb != NULL) {
      SSyncRaftEntry* pRollBackEntry;
      code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, index, &pRollBackEntry);
      ASSERT(code == 0);
      ASSERT(pRollBackEntry != NULL);

      if (syncUtilUserRollback(pRollBackEntry->msgType)) {
        SRpcMsg rpcMsg;
        syncEntry2OriginalRpc(pRollBackEntry, &rpcMsg);

        SFsmCbMeta cbMeta = {0};
        cbMeta.index = pRollBackEntry->index;
        cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
        cbMeta.isWeak = pRollBackEntry->isWeak;
        cbMeta.code = 0;
        cbMeta.state = ths->state;
        cbMeta.seqNum = pRollBackEntry->seqNum;
        ths->pFsm->FpRollBackCb(ths->pFsm, &rpcMsg, cbMeta);
        rpcFreeCont(rpcMsg.pCont);
      }

      syncEntryDestory(pRollBackEntry);
    }
  }

  // delete confict entries
  code = ths->pLogStore->syncLogTruncate(ths->pLogStore, delBegin);
  ASSERT(code == 0);

  char eventLog[128];
S
Shengliang Guan 已提交
406
  snprintf(eventLog, sizeof(eventLog), "log truncate, from %" PRId64 " to %" PRId64, delBegin, delEnd);
407 408 409 410 411 412
  syncNodeEventLog(ths, eventLog);
  logStoreSimpleLog2("after syncNodeMakeLogSame", ths->pLogStore);

  return code;
}

413
int32_t syncNodePreCommit(SSyncNode* ths, SSyncRaftEntry* pEntry, int32_t code) {
414 415
  SRpcMsg rpcMsg;
  syncEntry2OriginalRpc(pEntry, &rpcMsg);
416 417 418 419 420 421 422

  // leader transfer
  if (pEntry->originalRpcType == TDMT_SYNC_LEADER_TRANSFER) {
    int32_t code = syncDoLeaderTransfer(ths, &rpcMsg, pEntry);
    ASSERT(code == 0);
  }

423 424
  if (ths->pFsm != NULL) {
    if (ths->pFsm->FpPreCommitCb != NULL && syncUtilUserPreCommit(pEntry->originalRpcType)) {
425
      SFsmCbMeta cbMeta = {0};
426
      cbMeta.index = pEntry->index;
427
      cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
428
      cbMeta.isWeak = pEntry->isWeak;
429
      cbMeta.code = code;
430 431 432 433 434 435 436 437 438
      cbMeta.state = ths->state;
      cbMeta.seqNum = pEntry->seqNum;
      ths->pFsm->FpPreCommitCb(ths->pFsm, &rpcMsg, cbMeta);
    }
  }
  rpcFreeCont(rpcMsg.pCont);
  return 0;
}

439 440 441 442 443 444 445
static bool syncNodeOnAppendEntriesBatchLogOK(SSyncNode* pSyncNode, SyncAppendEntriesBatch* pMsg) {
  if (pMsg->prevLogIndex == SYNC_INDEX_INVALID) {
    return true;
  }

  SyncIndex myLastIndex = syncNodeGetLastIndex(pSyncNode);
  if (pMsg->prevLogIndex > myLastIndex) {
M
Minghao Li 已提交
446
    sDebug("vgId:%d, sync log not ok, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
447 448 449 450 451
    return false;
  }

  SyncTerm myPreLogTerm = syncNodeGetPreTerm(pSyncNode, pMsg->prevLogIndex + 1);
  if (myPreLogTerm == SYNC_TERM_INVALID) {
M
Minghao Li 已提交
452
    sDebug("vgId:%d, sync log not ok2, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
453 454 455 456 457 458 459
    return false;
  }

  if (pMsg->prevLogIndex <= myLastIndex && pMsg->prevLogTerm == myPreLogTerm) {
    return true;
  }

M
Minghao Li 已提交
460
  sDebug("vgId:%d, sync log not ok3, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
461 462
  return false;
}
463

M
Minghao Li 已提交
464 465 466 467 468 469 470 471 472
// really pre log match
// prevLogIndex == -1
static bool syncNodeOnAppendEntriesLogOK(SSyncNode* pSyncNode, SyncAppendEntries* pMsg) {
  if (pMsg->prevLogIndex == SYNC_INDEX_INVALID) {
    return true;
  }

  SyncIndex myLastIndex = syncNodeGetLastIndex(pSyncNode);
  if (pMsg->prevLogIndex > myLastIndex) {
M
Minghao Li 已提交
473
    sDebug("vgId:%d, sync log not ok, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
M
Minghao Li 已提交
474 475 476 477
    return false;
  }

  SyncTerm myPreLogTerm = syncNodeGetPreTerm(pSyncNode, pMsg->prevLogIndex + 1);
478
  if (myPreLogTerm == SYNC_TERM_INVALID) {
M
Minghao Li 已提交
479
    sDebug("vgId:%d, sync log not ok2, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
480 481 482
    return false;
  }

M
Minghao Li 已提交
483
  if (pMsg->prevLogIndex <= myLastIndex && pMsg->prevLogTerm == myPreLogTerm) {
M
Minghao Li 已提交
484 485 486
    return true;
  }

M
Minghao Li 已提交
487
  sDebug("vgId:%d, sync log not ok3, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
M
Minghao Li 已提交
488 489 490
  return false;
}

491 492 493 494 495 496
int32_t syncNodeOnAppendEntriesSnapshot2Cb(SSyncNode* ths, SyncAppendEntriesBatch* pMsg) {
  int32_t ret = 0;
  int32_t code = 0;

  // if already drop replica, do not process
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId)) && !ths->pRaftCfg->isStandBy) {
M
Minghao Li 已提交
497 498
    syncLogRecvAppendEntriesBatch(ths, pMsg, "maybe replica already dropped");
    return -1;
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
  }

  // maybe update term
  if (pMsg->term > ths->pRaftStore->currentTerm) {
    syncNodeUpdateTerm(ths, pMsg->term);
  }
  ASSERT(pMsg->term <= ths->pRaftStore->currentTerm);

  // reset elect timer
  if (pMsg->term == ths->pRaftStore->currentTerm) {
    ths->leaderCache = pMsg->srcId;
    syncNodeResetElectTimer(ths);
  }
  ASSERT(pMsg->dataLen >= 0);

  // candidate to follower
  //
  // operation:
  // to follower
  do {
    bool condition = pMsg->term == ths->pRaftStore->currentTerm && ths->state == TAOS_SYNC_STATE_CANDIDATE;
    if (condition) {
M
Minghao Li 已提交
521
      syncLogRecvAppendEntriesBatch(ths, pMsg, "candidate to follower");
522
      syncNodeBecomeFollower(ths, "from candidate by append entries");
M
Minghao Li 已提交
523
      return 0;  // do not reply?
524 525 526
    }
  } while (0);

M
Minghao Li 已提交
527
  // fake match
528 529 530 531 532 533
  //
  // condition1:
  // preIndex <= my commit index
  //
  // operation:
  // if hasAppendEntries && pMsg->prevLogIndex == ths->commitIndex, append entry
M
Minghao Li 已提交
534
  // match my-commit-index or my-commit-index + batchSize
535 536 537 538
  do {
    bool condition = (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) &&
                     (pMsg->prevLogIndex <= ths->commitIndex);
    if (condition) {
M
Minghao Li 已提交
539
      syncLogRecvAppendEntriesBatch(ths, pMsg, "fake match");
540

541 542 543
      SyncIndex          matchIndex = ths->commitIndex;
      bool               hasAppendEntries = pMsg->dataLen > 0;
      SOffsetAndContLen* metaTableArr = syncAppendEntriesBatchMetaTableArray(pMsg);
544

545
      if (hasAppendEntries && pMsg->prevLogIndex == ths->commitIndex) {
546 547 548 549 550 551 552
        // make log same
        do {
          SyncIndex logLastIndex = ths->pLogStore->syncLogLastIndex(ths->pLogStore);
          bool      hasExtraEntries = logLastIndex > pMsg->prevLogIndex;

          if (hasExtraEntries) {
            // make log same, rollback deleted entries
553
            code = syncNodeDoMakeLogSame(ths, pMsg->prevLogIndex + 1);
554 555 556 557 558 559
            ASSERT(code == 0);
          }

        } while (0);

        // append entry batch
560 561
        for (int32_t i = 0; i < pMsg->dataCount; ++i) {
          SSyncRaftEntry* pAppendEntry = (SSyncRaftEntry*)(pMsg->data + metaTableArr[i].offset);
562 563 564 565 566
          code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
          if (code != 0) {
            return -1;
          }

567
          code = syncNodePreCommit(ths, pAppendEntry, 0);
568 569
          ASSERT(code == 0);

570
          // syncEntryDestory(pAppendEntry);
571 572 573 574 575
        }

        // fsync once
        SSyncLogStoreData* pData = ths->pLogStore->data;
        SWal*              pWal = pData->pWal;
576
        walFsync(pWal, false);
577 578

        // update match index
579
        matchIndex = pMsg->prevLogIndex + pMsg->dataCount;
580 581 582 583 584 585 586 587 588 589 590
      }

      // prepare response msg
      SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
      pReply->srcId = ths->myRaftId;
      pReply->destId = pMsg->srcId;
      pReply->term = ths->pRaftStore->currentTerm;
      pReply->privateTerm = ths->pNewNodeReceiver->privateTerm;
      pReply->success = true;
      pReply->matchIndex = matchIndex;

M
Minghao Li 已提交
591
      // msg event log
M
Minghao Li 已提交
592
      syncLogSendAppendEntriesReply(ths, pReply, "");
M
Minghao Li 已提交
593

594 595 596 597 598 599
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);

600
      return 0;
601 602 603 604
    }
  } while (0);

  // calculate logOK here, before will coredump, due to fake match
605
  bool logOK = syncNodeOnAppendEntriesBatchLogOK(ths, pMsg);
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624

  // not match
  //
  // condition1:
  // term < myTerm
  //
  // condition2:
  // !logOK
  //
  // operation:
  // not match
  // no operation on log
  do {
    bool condition1 = pMsg->term < ths->pRaftStore->currentTerm;
    bool condition2 =
        (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) && !logOK;
    bool condition = condition1 || condition2;

    if (condition) {
M
Minghao Li 已提交
625
      syncLogRecvAppendEntriesBatch(ths, pMsg, "not match");
626

M
Minghao Li 已提交
627 628 629
      // maybe update commit index by snapshot
      syncNodeMaybeUpdateCommitBySnapshot(ths);

630 631 632 633 634 635 636
      // prepare response msg
      SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
      pReply->srcId = ths->myRaftId;
      pReply->destId = pMsg->srcId;
      pReply->term = ths->pRaftStore->currentTerm;
      pReply->privateTerm = ths->pNewNodeReceiver->privateTerm;
      pReply->success = false;
M
Minghao Li 已提交
637
      pReply->matchIndex = ths->commitIndex;
638

M
Minghao Li 已提交
639
      // msg event log
M
Minghao Li 已提交
640
      syncLogSendAppendEntriesReply(ths, pReply, "");
M
Minghao Li 已提交
641

642 643 644 645 646 647
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);

648
      return 0;
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    }
  } while (0);

  // really match
  //
  // condition:
  // logOK
  //
  // operation:
  // match
  // make log same
  do {
    bool condition = (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) && logOK;
    if (condition) {
      // has extra entries (> preIndex) in local log
      SyncIndex myLastIndex = syncNodeGetLastIndex(ths);
      bool      hasExtraEntries = myLastIndex > pMsg->prevLogIndex;

      // has entries in SyncAppendEntries msg
668 669
      bool               hasAppendEntries = pMsg->dataLen > 0;
      SOffsetAndContLen* metaTableArr = syncAppendEntriesBatchMetaTableArray(pMsg);
670

M
Minghao Li 已提交
671
      syncLogRecvAppendEntriesBatch(ths, pMsg, "really match");
672 673 674

      if (hasExtraEntries) {
        // make log same, rollback deleted entries
675
        code = syncNodeDoMakeLogSame(ths, pMsg->prevLogIndex + 1);
676 677 678 679 680
        ASSERT(code == 0);
      }

      if (hasAppendEntries) {
        // append entry batch
681 682
        for (int32_t i = 0; i < pMsg->dataCount; ++i) {
          SSyncRaftEntry* pAppendEntry = (SSyncRaftEntry*)(pMsg->data + metaTableArr[i].offset);
683 684 685 686 687
          code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
          if (code != 0) {
            return -1;
          }

688
          code = syncNodePreCommit(ths, pAppendEntry, 0);
689 690
          ASSERT(code == 0);

691
          // syncEntryDestory(pAppendEntry);
692 693 694 695 696
        }

        // fsync once
        SSyncLogStoreData* pData = ths->pLogStore->data;
        SWal*              pWal = pData->pWal;
697
        walFsync(pWal, false);
698 699 700 701 702 703 704 705 706
      }

      // prepare response msg
      SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
      pReply->srcId = ths->myRaftId;
      pReply->destId = pMsg->srcId;
      pReply->term = ths->pRaftStore->currentTerm;
      pReply->privateTerm = ths->pNewNodeReceiver->privateTerm;
      pReply->success = true;
707
      pReply->matchIndex = hasAppendEntries ? pMsg->prevLogIndex + pMsg->dataCount : pMsg->prevLogIndex;
708

M
Minghao Li 已提交
709
      // msg event log
M
Minghao Li 已提交
710
      syncLogSendAppendEntriesReply(ths, pReply, "");
M
Minghao Li 已提交
711

712 713 714 715 716 717 718 719
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);

      // maybe update commit index, leader notice me
      if (pMsg->commitIndex > ths->commitIndex) {
720 721 722 723
        SyncIndex lastIndex = ths->pLogStore->syncLogLastIndex(ths->pLogStore);

        SyncIndex beginIndex = 0;
        SyncIndex endIndex = -1;
724

725 726 727 728
        // has commit entry in local
        if (pMsg->commitIndex <= lastIndex) {
          beginIndex = ths->commitIndex + 1;
          endIndex = pMsg->commitIndex;
729 730 731 732 733 734 735 736

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

          // call back Wal
          code = ths->pLogStore->updateCommitIndex(ths->pLogStore, ths->commitIndex);
          ASSERT(code == 0);

737 738 739 740 741 742 743 744 745
        } else if (pMsg->commitIndex > lastIndex && ths->commitIndex < lastIndex) {
          beginIndex = ths->commitIndex + 1;
          endIndex = lastIndex;

          // update commit index, speed up
          ths->commitIndex = lastIndex;

          // call back Wal
          code = ths->pLogStore->updateCommitIndex(ths->pLogStore, ths->commitIndex);
746 747
          ASSERT(code == 0);
        }
748 749 750

        code = syncNodeCommit(ths, beginIndex, endIndex, ths->state);
        ASSERT(code == 0);
751
      }
752

753
      return 0;
754 755 756
    }
  } while (0);

757
  return 0;
758
}
759

760 761
int32_t syncNodeOnAppendEntriesSnapshotCb(SSyncNode* ths, SyncAppendEntries* pMsg) {
  int32_t ret = 0;
762
  int32_t code = 0;
763

M
Minghao Li 已提交
764 765
  // if already drop replica, do not process
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId)) && !ths->pRaftCfg->isStandBy) {
M
Minghao Li 已提交
766 767
    syncLogRecvAppendEntries(ths, pMsg, "maybe replica already dropped");
    return -1;
M
Minghao Li 已提交
768
  }
M
Minghao Li 已提交
769

770
  // maybe update term
771 772 773
  if (pMsg->term > ths->pRaftStore->currentTerm) {
    syncNodeUpdateTerm(ths, pMsg->term);
  }
774
  ASSERT(pMsg->term <= ths->pRaftStore->currentTerm);
775 776 777 778 779 780

  // reset elect timer
  if (pMsg->term == ths->pRaftStore->currentTerm) {
    ths->leaderCache = pMsg->srcId;
    syncNodeResetElectTimer(ths);
  }
781
  ASSERT(pMsg->dataLen >= 0);
M
Minghao Li 已提交
782

M
Minghao Li 已提交
783 784 785 786 787 788 789
  // candidate to follower
  //
  // operation:
  // to follower
  do {
    bool condition = pMsg->term == ths->pRaftStore->currentTerm && ths->state == TAOS_SYNC_STATE_CANDIDATE;
    if (condition) {
M
Minghao Li 已提交
790
      syncLogRecvAppendEntries(ths, pMsg, "candidate to follower");
791
      syncNodeBecomeFollower(ths, "from candidate by append entries");
M
Minghao Li 已提交
792
      return 0;  // do not reply?
M
Minghao Li 已提交
793 794 795
    }
  } while (0);

M
Minghao Li 已提交
796
  // fake match
797 798 799 800 801
  //
  // condition1:
  // preIndex <= my commit index
  //
  // operation:
802 803
  // if hasAppendEntries && pMsg->prevLogIndex == ths->commitIndex, append entry
  // match my-commit-index or my-commit-index + 1
804 805 806 807 808
  // no operation on log
  do {
    bool condition = (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) &&
                     (pMsg->prevLogIndex <= ths->commitIndex);
    if (condition) {
M
Minghao Li 已提交
809
      syncLogRecvAppendEntries(ths, pMsg, "fake match");
810

811 812 813 814 815 816 817
      SyncIndex matchIndex = ths->commitIndex;
      bool      hasAppendEntries = pMsg->dataLen > 0;
      if (hasAppendEntries && pMsg->prevLogIndex == ths->commitIndex) {
        // append entry
        SSyncRaftEntry* pAppendEntry = syncEntryDeserialize(pMsg->data, pMsg->dataLen);
        ASSERT(pAppendEntry != NULL);

818 819 820 821 822 823 824 825 826 827 828 829
        {
          // has extra entries (> preIndex) in local log
          SyncIndex logLastIndex = ths->pLogStore->syncLogLastIndex(ths->pLogStore);
          bool      hasExtraEntries = logLastIndex > pMsg->prevLogIndex;

          if (hasExtraEntries) {
            // make log same, rollback deleted entries
            code = syncNodeMakeLogSame(ths, pMsg);
            ASSERT(code == 0);
          }
        }

830
        code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
831 832 833
        if (code != 0) {
          return -1;
        }
834 835

        // pre commit
836
        code = syncNodePreCommit(ths, pAppendEntry, 0);
837 838
        ASSERT(code == 0);

839
        // update match index
840 841 842 843 844
        matchIndex = pMsg->prevLogIndex + 1;

        syncEntryDestory(pAppendEntry);
      }

845 846 847 848 849 850 851
      // prepare response msg
      SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
      pReply->srcId = ths->myRaftId;
      pReply->destId = pMsg->srcId;
      pReply->term = ths->pRaftStore->currentTerm;
      pReply->privateTerm = ths->pNewNodeReceiver->privateTerm;
      pReply->success = true;
852
      pReply->matchIndex = matchIndex;
853

M
Minghao Li 已提交
854
      // msg event log
M
Minghao Li 已提交
855
      syncLogSendAppendEntriesReply(ths, pReply, "");
M
Minghao Li 已提交
856

857 858 859 860 861 862 863 864 865 866
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);

      return ret;
    }
  } while (0);

M
Minghao Li 已提交
867 868 869
  // calculate logOK here, before will coredump, due to fake match
  bool logOK = syncNodeOnAppendEntriesLogOK(ths, pMsg);

M
Minghao Li 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
  // not match
  //
  // condition1:
  // term < myTerm
  //
  // condition2:
  // !logOK
  //
  // operation:
  // not match
  // no operation on log
  do {
    bool condition1 = pMsg->term < ths->pRaftStore->currentTerm;
    bool condition2 =
        (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) && !logOK;
    bool condition = condition1 || condition2;

    if (condition) {
M
Minghao Li 已提交
888
      syncLogRecvAppendEntries(ths, pMsg, "not match");
M
Minghao Li 已提交
889

M
Minghao Li 已提交
890 891 892 893 894 895 896 897
      // prepare response msg
      SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
      pReply->srcId = ths->myRaftId;
      pReply->destId = pMsg->srcId;
      pReply->term = ths->pRaftStore->currentTerm;
      pReply->privateTerm = ths->pNewNodeReceiver->privateTerm;
      pReply->success = false;
      pReply->matchIndex = SYNC_INDEX_INVALID;
898

M
Minghao Li 已提交
899
      // msg event log
M
Minghao Li 已提交
900
      syncLogSendAppendEntriesReply(ths, pReply, "");
M
Minghao Li 已提交
901

M
Minghao Li 已提交
902 903 904 905 906
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);
907

M
Minghao Li 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
      return ret;
    }
  } while (0);

  // really match
  //
  // condition:
  // logOK
  //
  // operation:
  // match
  // make log same
  do {
    bool condition = (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) && logOK;
    if (condition) {
      // has extra entries (> preIndex) in local log
      SyncIndex myLastIndex = syncNodeGetLastIndex(ths);
      bool      hasExtraEntries = myLastIndex > pMsg->prevLogIndex;

      // has entries in SyncAppendEntries msg
      bool hasAppendEntries = pMsg->dataLen > 0;

M
Minghao Li 已提交
930
      syncLogRecvAppendEntries(ths, pMsg, "really match");
M
Minghao Li 已提交
931

M
Minghao Li 已提交
932 933 934 935 936
      if (hasExtraEntries) {
        // make log same, rollback deleted entries
        code = syncNodeMakeLogSame(ths, pMsg);
        ASSERT(code == 0);
      }
937

M
Minghao Li 已提交
938 939 940 941
      if (hasAppendEntries) {
        // append entry
        SSyncRaftEntry* pAppendEntry = syncEntryDeserialize(pMsg->data, pMsg->dataLen);
        ASSERT(pAppendEntry != NULL);
942

M
Minghao Li 已提交
943
        code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
944 945 946
        if (code != 0) {
          return -1;
        }
947

M
Minghao Li 已提交
948
        // pre commit
949
        code = syncNodePreCommit(ths, pAppendEntry, 0);
M
Minghao Li 已提交
950
        ASSERT(code == 0);
951

M
Minghao Li 已提交
952 953
        syncEntryDestory(pAppendEntry);
      }
954

M
Minghao Li 已提交
955 956 957 958 959 960 961 962
      // prepare response msg
      SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild(ths->vgId);
      pReply->srcId = ths->myRaftId;
      pReply->destId = pMsg->srcId;
      pReply->term = ths->pRaftStore->currentTerm;
      pReply->privateTerm = ths->pNewNodeReceiver->privateTerm;
      pReply->success = true;
      pReply->matchIndex = hasAppendEntries ? pMsg->prevLogIndex + 1 : pMsg->prevLogIndex;
963

M
Minghao Li 已提交
964
      // msg event log
M
Minghao Li 已提交
965
      syncLogSendAppendEntriesReply(ths, pReply, "");
M
Minghao Li 已提交
966

M
Minghao Li 已提交
967 968 969 970 971
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);
972

M
Minghao Li 已提交
973 974 975 976
      // maybe update commit index, leader notice me
      if (pMsg->commitIndex > ths->commitIndex) {
        // has commit entry in local
        if (pMsg->commitIndex <= ths->pLogStore->syncLogLastIndex(ths->pLogStore)) {
977 978
          // advance commit index to sanpshot first
          SSnapshot snapshot;
979
          ths->pFsm->FpGetSnapshotInfo(ths->pFsm, &snapshot);
980 981 982
          if (snapshot.lastApplyIndex >= 0 && snapshot.lastApplyIndex > ths->commitIndex) {
            SyncIndex commitBegin = ths->commitIndex;
            SyncIndex commitEnd = snapshot.lastApplyIndex;
983
            ths->commitIndex = snapshot.lastApplyIndex;
984

M
Minghao Li 已提交
985
            char eventLog[128];
S
Shengliang Guan 已提交
986 987
            snprintf(eventLog, sizeof(eventLog), "commit by snapshot from index:%" PRId64 " to index:%" PRId64,
                     commitBegin, commitEnd);
M
Minghao Li 已提交
988
            syncNodeEventLog(ths, eventLog);
989 990
          }

M
Minghao Li 已提交
991 992
          SyncIndex beginIndex = ths->commitIndex + 1;
          SyncIndex endIndex = pMsg->commitIndex;
993

M
Minghao Li 已提交
994 995
          // update commit index
          ths->commitIndex = pMsg->commitIndex;
996

M
Minghao Li 已提交
997 998 999
          // call back Wal
          code = ths->pLogStore->updateCommitIndex(ths->pLogStore, ths->commitIndex);
          ASSERT(code == 0);
1000

M
Minghao Li 已提交
1001 1002 1003
          code = syncNodeCommit(ths, beginIndex, endIndex, ths->state);
          ASSERT(code == 0);
        }
1004
      }
M
Minghao Li 已提交
1005
      return ret;
1006
    }
M
Minghao Li 已提交
1007
  } while (0);
1008 1009

  return ret;
M
Minghao Li 已提交
1010
}