syncAppendEntries.c 48.8 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    do {
      char     host[64];
      uint16_t port;
      syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
      char logBuf[256];
      snprintf(logBuf, sizeof(logBuf),
               "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
               ", commit:" PRId64 ", pterm:" PRIu64
               ", "
               "datalen:%d}, maybe replica already dropped",
               host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
               pMsg->dataLen);
      syncNodeErrorLog(ths, logBuf);
    } while (0);

    return -1;
M
Minghao Li 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  }

  // 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);

  do {
    // return to follower state
    if (pMsg->term == ths->pRaftStore->currentTerm && ths->state == TAOS_SYNC_STATE_CANDIDATE) {
M
Minghao Li 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144
      do {
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "datalen:%d}, candidate to follower",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataLen);
        syncNodeEventLog(ths, logBuf);
      } while (0);
M
Minghao Li 已提交
145 146 147 148

      syncNodeBecomeFollower(ths, "from candidate by append entries");

      // ret or reply?
M
Minghao Li 已提交
149
      return -1;
M
Minghao Li 已提交
150 151 152 153 154 155 156 157
    }
  } while (0);

  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 已提交
158
      snprintf(logBuf, sizeof(logBuf), "getEntry error, index:%" PRId64 ", since %s", pMsg->prevLogIndex, terrstr());
M
Minghao Li 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
      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)) {
    do {
M
Minghao Li 已提交
176 177 178 179
      char     host[64];
      uint16_t port;
      syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
      char logBuf[256];
S
Shengliang Guan 已提交
180
      snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
181 182 183 184 185 186
               "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
               ", commit:" PRId64 ", pterm:" PRIu64
               ", "
               "datalen:%d}, reject",
               host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
               pMsg->dataLen);
M
Minghao Li 已提交
187 188 189 190 191 192 193 194 195 196
      syncNodeEventLog(ths, logBuf);
    } while (0);

    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 已提交
197 198
    // msg event log
    do {
M
Minghao Li 已提交
199
      char     host[64];
M
Minghao Li 已提交
200 201
      uint16_t port;
      syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
202 203 204 205 206 207
      char logBuf[256];
      snprintf(logBuf, sizeof(logBuf),
               "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
               ", success:%d, match-index:%" PRId64 "}",
               host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
      syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
208 209
    } while (0);

M
Minghao Li 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    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;

    do {
M
Minghao Li 已提交
230 231 232 233
      char     host[64];
      uint16_t port;
      syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
      char logBuf[256];
S
Shengliang Guan 已提交
234
      snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
235 236 237 238 239 240
               "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
               ", commit:" PRId64 ", pterm:" PRIu64
               ", "
               "datalen:%d}, accept",
               host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
               pMsg->dataLen);
M
Minghao Li 已提交
241 242 243 244 245 246 247 248 249 250 251
      syncNodeEventLog(ths, logBuf);
    } while (0);

    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 已提交
252
        snprintf(logBuf, sizeof(logBuf), "getEntry error2, index:%" PRId64 ", since %s", extraIndex, terrstr());
M
Minghao Li 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        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 已提交
274 275
        sTrace("syncNodeOnAppendEntriesCb --> conflict:%d, delBegin:%" PRId64 ", delEnd:%" PRId64, conflict, delBegin,
               delEnd);
M
Minghao Li 已提交
276 277 278 279 280 281 282

        // 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 已提交
283
              snprintf(logBuf, sizeof(logBuf), "getEntry error3, index:%" PRId64 ", since %s", index, terrstr());
M
Minghao Li 已提交
284 285 286 287 288 289 290 291 292 293 294 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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 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
              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
        SRpcMsg rpcMsg;
        syncEntry2OriginalRpc(pAppendEntry, &rpcMsg);
        if (ths->pFsm != NULL) {
          // if (ths->pFsm->FpPreCommitCb != NULL && pAppendEntry->originalRpcType != TDMT_SYNC_NOOP) {
          if (ths->pFsm->FpPreCommitCb != NULL && syncUtilUserPreCommit(pAppendEntry->originalRpcType)) {
            SFsmCbMeta cbMeta = {0};
            cbMeta.index = pAppendEntry->index;
            cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
            cbMeta.isWeak = pAppendEntry->isWeak;
            cbMeta.code = 2;
            cbMeta.state = ths->state;
            cbMeta.seqNum = pAppendEntry->seqNum;
            ths->pFsm->FpPreCommitCb(ths->pFsm, &rpcMsg, cbMeta);
          }
        }
        rpcFreeCont(rpcMsg.pCont);
      }

      // 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
      SRpcMsg rpcMsg;
      syncEntry2OriginalRpc(pAppendEntry, &rpcMsg);
      if (ths->pFsm != NULL) {
        // if (ths->pFsm->FpPreCommitCb != NULL && pAppendEntry->originalRpcType != TDMT_SYNC_NOOP) {
        if (ths->pFsm->FpPreCommitCb != NULL && syncUtilUserPreCommit(pAppendEntry->originalRpcType)) {
          SFsmCbMeta cbMeta = {0};
          cbMeta.index = pAppendEntry->index;
          cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
          cbMeta.isWeak = pAppendEntry->isWeak;
          cbMeta.code = 3;
          cbMeta.state = ths->state;
          cbMeta.seqNum = pAppendEntry->seqNum;
          ths->pFsm->FpPreCommitCb(ths->pFsm, &rpcMsg, cbMeta);
        }
      }
      rpcFreeCont(rpcMsg.pCont);

      // 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 已提交
391 392
    // msg event log
    do {
M
Minghao Li 已提交
393
      char     host[64];
M
Minghao Li 已提交
394 395
      uint16_t port;
      syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
396 397 398 399 400 401
      char logBuf[256];
      snprintf(logBuf, sizeof(logBuf),
               "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
               ", success:%d, match-index:%" PRId64 "}",
               host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
      syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
402
    } while (0);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

    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 已提交
431
static int32_t syncNodeMakeLogSame(SSyncNode* ths, SyncAppendEntries* pMsg) {
432 433
  int32_t code;

M
Minghao Li 已提交
434 435
  SyncIndex delBegin = pMsg->prevLogIndex + 1;
  SyncIndex delEnd = ths->pLogStore->syncLogLastIndex(ths->pLogStore);
436

M
Minghao Li 已提交
437 438 439 440 441 442 443
  // 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);
444

M
Minghao Li 已提交
445 446 447 448
      if (syncUtilUserRollback(pRollBackEntry->msgType)) {
        SRpcMsg rpcMsg;
        syncEntry2OriginalRpc(pRollBackEntry, &rpcMsg);

449
        SFsmCbMeta cbMeta = {0};
M
Minghao Li 已提交
450
        cbMeta.index = pRollBackEntry->index;
451
        cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
M
Minghao Li 已提交
452 453 454 455 456 457
        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);
458 459
      }

M
Minghao Li 已提交
460 461
      syncEntryDestory(pRollBackEntry);
    }
462 463
  }

M
Minghao Li 已提交
464 465 466
  // delete confict entries
  code = ths->pLogStore->syncLogTruncate(ths->pLogStore, delBegin);
  ASSERT(code == 0);
M
Minghao Li 已提交
467 468

  char eventLog[128];
S
Shengliang Guan 已提交
469
  snprintf(eventLog, sizeof(eventLog), "log truncate, from %" PRId64 " to %" PRId64, delBegin, delEnd);
M
Minghao Li 已提交
470
  syncNodeEventLog(ths, eventLog);
M
Minghao Li 已提交
471
  logStoreSimpleLog2("after syncNodeMakeLogSame", ths->pLogStore);
M
Minghao Li 已提交
472 473

  return code;
474 475
}

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
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 已提交
514
  snprintf(eventLog, sizeof(eventLog), "log truncate, from %" PRId64 " to %" PRId64, delBegin, delEnd);
515 516 517 518 519 520
  syncNodeEventLog(ths, eventLog);
  logStoreSimpleLog2("after syncNodeMakeLogSame", ths->pLogStore);

  return code;
}

521 522 523
static int32_t syncNodePreCommit(SSyncNode* ths, SSyncRaftEntry* pEntry) {
  SRpcMsg rpcMsg;
  syncEntry2OriginalRpc(pEntry, &rpcMsg);
524 525 526 527 528 529 530

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

531 532
  if (ths->pFsm != NULL) {
    if (ths->pFsm->FpPreCommitCb != NULL && syncUtilUserPreCommit(pEntry->originalRpcType)) {
533
      SFsmCbMeta cbMeta = {0};
534
      cbMeta.index = pEntry->index;
535
      cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
536 537 538 539 540 541 542 543 544 545 546
      cbMeta.isWeak = pEntry->isWeak;
      cbMeta.code = 2;
      cbMeta.state = ths->state;
      cbMeta.seqNum = pEntry->seqNum;
      ths->pFsm->FpPreCommitCb(ths->pFsm, &rpcMsg, cbMeta);
    }
  }
  rpcFreeCont(rpcMsg.pCont);
  return 0;
}

547 548 549 550 551 552 553
static bool syncNodeOnAppendEntriesBatchLogOK(SSyncNode* pSyncNode, SyncAppendEntriesBatch* pMsg) {
  if (pMsg->prevLogIndex == SYNC_INDEX_INVALID) {
    return true;
  }

  SyncIndex myLastIndex = syncNodeGetLastIndex(pSyncNode);
  if (pMsg->prevLogIndex > myLastIndex) {
S
Shengliang Guan 已提交
554
    sDebug("vgId:%d sync log not ok, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
555 556 557 558 559
    return false;
  }

  SyncTerm myPreLogTerm = syncNodeGetPreTerm(pSyncNode, pMsg->prevLogIndex + 1);
  if (myPreLogTerm == SYNC_TERM_INVALID) {
S
Shengliang Guan 已提交
560
    sDebug("vgId:%d sync log not ok2, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
561 562 563 564 565 566 567
    return false;
  }

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

S
Shengliang Guan 已提交
568
  sDebug("vgId:%d sync log not ok3, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
569 570
  return false;
}
571

M
Minghao Li 已提交
572 573 574 575 576 577 578 579 580
// 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) {
S
Shengliang Guan 已提交
581
    sDebug("vgId:%d sync log not ok, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
M
Minghao Li 已提交
582 583 584 585
    return false;
  }

  SyncTerm myPreLogTerm = syncNodeGetPreTerm(pSyncNode, pMsg->prevLogIndex + 1);
586
  if (myPreLogTerm == SYNC_TERM_INVALID) {
S
Shengliang Guan 已提交
587
    sDebug("vgId:%d sync log not ok2, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
588 589 590
    return false;
  }

M
Minghao Li 已提交
591
  if (pMsg->prevLogIndex <= myLastIndex && pMsg->prevLogTerm == myPreLogTerm) {
M
Minghao Li 已提交
592 593 594
    return true;
  }

S
Shengliang Guan 已提交
595
  sDebug("vgId:%d sync log not ok3, preindex:%" PRId64, pSyncNode->vgId, pMsg->prevLogIndex);
M
Minghao Li 已提交
596 597 598
  return false;
}

599 600 601 602 603 604
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 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    do {
      char     host[64];
      uint16_t port;
      syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
      char logBuf[256];
      snprintf(logBuf, sizeof(logBuf),
               "recv sync-append-entries-batch from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
               ", commit:" PRId64 ", pterm:" PRIu64
               ", "
               "count:%d}, maybe replica already dropped",
               host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
               pMsg->dataCount);
      syncNodeErrorLog(ths, logBuf);
    } while (0);

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    return ret;
  }

  // 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 已提交
643 644 645 646 647 648 649 650 651 652 653 654 655 656
      do {
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "recv sync-append-entries-batch from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "count:%d}, candidate to follower",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataCount);
        syncNodeEventLog(ths, logBuf);
      } while (0);
657 658 659 660 661 662 663 664 665 666 667 668 669 670

      syncNodeBecomeFollower(ths, "from candidate by append entries");
      // do not reply?
      return ret;
    }
  } while (0);

  // fake match2
  //
  // condition1:
  // preIndex <= my commit index
  //
  // operation:
  // if hasAppendEntries && pMsg->prevLogIndex == ths->commitIndex, append entry
M
Minghao Li 已提交
671
  // match my-commit-index or my-commit-index + batchSize
672 673 674 675 676
  do {
    bool condition = (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) &&
                     (pMsg->prevLogIndex <= ths->commitIndex);
    if (condition) {
      do {
M
Minghao Li 已提交
677 678 679 680
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
681
        snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
682 683 684 685 686 687
                 "recv sync-append-entries-batch from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "count:%d}, fake match2",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataCount);
688 689 690
        syncNodeEventLog(ths, logBuf);
      } while (0);

691 692 693
      SyncIndex          matchIndex = ths->commitIndex;
      bool               hasAppendEntries = pMsg->dataLen > 0;
      SOffsetAndContLen* metaTableArr = syncAppendEntriesBatchMetaTableArray(pMsg);
694

695
      if (hasAppendEntries && pMsg->prevLogIndex == ths->commitIndex) {
696 697 698 699 700 701 702
        // make log same
        do {
          SyncIndex logLastIndex = ths->pLogStore->syncLogLastIndex(ths->pLogStore);
          bool      hasExtraEntries = logLastIndex > pMsg->prevLogIndex;

          if (hasExtraEntries) {
            // make log same, rollback deleted entries
703
            code = syncNodeDoMakeLogSame(ths, pMsg->prevLogIndex + 1);
704 705 706 707 708 709
            ASSERT(code == 0);
          }

        } while (0);

        // append entry batch
710 711
        for (int32_t i = 0; i < pMsg->dataCount; ++i) {
          SSyncRaftEntry* pAppendEntry = (SSyncRaftEntry*)(pMsg->data + metaTableArr[i].offset);
712 713 714 715 716 717 718 719
          code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
          if (code != 0) {
            return -1;
          }

          code = syncNodePreCommit(ths, pAppendEntry);
          ASSERT(code == 0);

720
          // syncEntryDestory(pAppendEntry);
721 722 723 724 725 726 727 728
        }

        // fsync once
        SSyncLogStoreData* pData = ths->pLogStore->data;
        SWal*              pWal = pData->pWal;
        walFsync(pWal, true);

        // update match index
729
        matchIndex = pMsg->prevLogIndex + pMsg->dataCount;
730 731 732 733 734 735 736 737 738 739 740
      }

      // 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 已提交
741 742
      // msg event log
      do {
M
Minghao Li 已提交
743
        char     host[64];
M
Minghao Li 已提交
744 745
        uint16_t port;
        syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
746 747 748 749 750 751
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
                 ", success:%d, match-index:%" PRId64 "}",
                 host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
        syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
752 753
      } while (0);

754 755 756 757 758 759
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);

760
      return 0;
761 762 763 764
    }
  } while (0);

  // calculate logOK here, before will coredump, due to fake match
765
  bool logOK = syncNodeOnAppendEntriesBatchLogOK(ths, pMsg);
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784

  // 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 已提交
785
      do {
M
Minghao Li 已提交
786 787 788 789
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
M
Minghao Li 已提交
790
        snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
791 792 793 794 795 796
                 "recv sync-append-entries-batch from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "count:%d}, not match",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataCount);
M
Minghao Li 已提交
797 798
        syncNodeEventLog(ths, logBuf);
      } while (0);
799

M
Minghao Li 已提交
800 801 802
      // maybe update commit index by snapshot
      syncNodeMaybeUpdateCommitBySnapshot(ths);

803 804 805 806 807 808 809
      // 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 已提交
810
      pReply->matchIndex = ths->commitIndex;
811

M
Minghao Li 已提交
812 813
      // msg event log
      do {
M
Minghao Li 已提交
814
        char     host[64];
M
Minghao Li 已提交
815 816
        uint16_t port;
        syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
817 818 819 820 821 822
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
                 ", success:%d, match-index:%" PRId64 "}",
                 host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
        syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
823 824
      } while (0);

825 826 827 828 829 830
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);

831
      return 0;
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    }
  } 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
851 852
      bool               hasAppendEntries = pMsg->dataLen > 0;
      SOffsetAndContLen* metaTableArr = syncAppendEntriesBatchMetaTableArray(pMsg);
853

854
      do {
M
Minghao Li 已提交
855 856 857 858
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
859
        snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
860 861 862 863 864 865
                 "recv sync-append-entries-batch from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "count:%d}, match",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataCount);
866 867
        syncNodeEventLog(ths, logBuf);
      } while (0);
868 869 870

      if (hasExtraEntries) {
        // make log same, rollback deleted entries
871
        code = syncNodeDoMakeLogSame(ths, pMsg->prevLogIndex + 1);
872 873 874 875 876
        ASSERT(code == 0);
      }

      if (hasAppendEntries) {
        // append entry batch
877 878
        for (int32_t i = 0; i < pMsg->dataCount; ++i) {
          SSyncRaftEntry* pAppendEntry = (SSyncRaftEntry*)(pMsg->data + metaTableArr[i].offset);
879 880 881 882 883 884 885 886
          code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
          if (code != 0) {
            return -1;
          }

          code = syncNodePreCommit(ths, pAppendEntry);
          ASSERT(code == 0);

887
          // syncEntryDestory(pAppendEntry);
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
        }

        // fsync once
        SSyncLogStoreData* pData = ths->pLogStore->data;
        SWal*              pWal = pData->pWal;
        walFsync(pWal, true);
      }

      // 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;
903
      pReply->matchIndex = hasAppendEntries ? pMsg->prevLogIndex + pMsg->dataCount : pMsg->prevLogIndex;
904

M
Minghao Li 已提交
905 906
      // msg event log
      do {
M
Minghao Li 已提交
907
        char     host[64];
M
Minghao Li 已提交
908 909
        uint16_t port;
        syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
910 911 912 913 914 915
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
                 ", success:%d, match-index:%" PRId64 "}",
                 host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
        syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
916 917
      } while (0);

918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
      // 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) {
        // has commit entry in local
        if (pMsg->commitIndex <= 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;

            char eventLog[128];
S
Shengliang Guan 已提交
937 938
            snprintf(eventLog, sizeof(eventLog), "commit by snapshot from index:%" PRId64 " to index:%" PRId64,
                     commitBegin, commitEnd);
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
            syncNodeEventLog(ths, eventLog);
          }

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

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

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

          code = syncNodeCommit(ths, beginIndex, endIndex, ths->state);
          ASSERT(code == 0);
        }
      }
956
      return 0;
957 958 959
    }
  } while (0);

960
  return 0;
961
}
962

963 964
int32_t syncNodeOnAppendEntriesSnapshotCb(SSyncNode* ths, SyncAppendEntries* pMsg) {
  int32_t ret = 0;
965
  int32_t code = 0;
966

M
Minghao Li 已提交
967 968
  // if already drop replica, do not process
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId)) && !ths->pRaftCfg->isStandBy) {
M
Minghao Li 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    do {
      char     host[64];
      uint16_t port;
      syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
      char logBuf[256];
      snprintf(logBuf, sizeof(logBuf),
               "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
               ", commit:" PRId64 ", pterm:" PRIu64
               ", "
               "datalen:%d}, maybe replica dropped",
               host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
               pMsg->dataLen);
      syncNodeErrorLog(ths, logBuf);
    } while (0);

M
Minghao Li 已提交
984 985
    return ret;
  }
M
Minghao Li 已提交
986

987
  // maybe update term
988 989 990
  if (pMsg->term > ths->pRaftStore->currentTerm) {
    syncNodeUpdateTerm(ths, pMsg->term);
  }
991
  ASSERT(pMsg->term <= ths->pRaftStore->currentTerm);
992 993 994 995 996 997

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

M
Minghao Li 已提交
1000 1001 1002 1003 1004 1005 1006
  // 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 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
      do {
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "datalen:%d}, candidate to follower",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataLen);
        syncNodeEventLog(ths, logBuf);
      } while (0);
M
Minghao Li 已提交
1021

1022
      syncNodeBecomeFollower(ths, "from candidate by append entries");
M
Minghao Li 已提交
1023 1024 1025 1026 1027
      // do not reply?
      return ret;
    }
  } while (0);

1028
#if 0
M
Minghao Li 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037
  // fake match
  //
  // condition1:
  // I have snapshot, no log, preIndex > myLastIndex
  //
  // condition2:
  // I have snapshot, have log, log <= snapshot, preIndex > myLastIndex
  //
  // condition3:
M
Minghao Li 已提交
1038 1039 1040 1041
  // I have snapshot, preIndex < snapshot.lastApplyIndex
  //
  // condition4:
  // I have snapshot, preIndex == snapshot.lastApplyIndex, no data
M
Minghao Li 已提交
1042 1043 1044 1045 1046 1047
  //
  // operation:
  // match snapshot.lastApplyIndex - 1;
  // no operation on log
  do {
    SyncIndex myLastIndex = syncNodeGetLastIndex(ths);
M
Minghao Li 已提交
1048
    SSnapshot snapshot;
1049
    ths->pFsm->FpGetSnapshotInfo(ths->pFsm, &snapshot);
M
Minghao Li 已提交
1050

M
Minghao Li 已提交
1051 1052 1053
    bool condition0 = (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) &&
                      syncNodeHasSnapshot(ths);
    bool condition1 =
1054
        condition0 && (ths->pLogStore->syncLogEntryCount(ths->pLogStore) == 0) && (pMsg->prevLogIndex > myLastIndex);   // donot use syncLogEntryCount!!! use isEmpty
M
Minghao Li 已提交
1055 1056
    bool condition2 = condition0 && (ths->pLogStore->syncLogLastIndex(ths->pLogStore) <= snapshot.lastApplyIndex) &&
                      (pMsg->prevLogIndex > myLastIndex);
M
Minghao Li 已提交
1057 1058 1059
    bool condition3 = condition0 && (pMsg->prevLogIndex < snapshot.lastApplyIndex);
    bool condition4 = condition0 && (pMsg->prevLogIndex == snapshot.lastApplyIndex) && (pMsg->dataLen == 0);
    bool condition = condition1 || condition2 || condition3 || condition4;
M
Minghao Li 已提交
1060 1061

    if (condition) {
1062
      char logBuf[128];
S
Shengliang Guan 已提交
1063
      snprintf(logBuf, sizeof(logBuf), "recv sync-append-entries, fake match, pre-index:%" PRId64 ", pre-term:%" PRIu64,
1064 1065
               pMsg->prevLogIndex, pMsg->prevLogTerm);
      syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
1066

M
Minghao Li 已提交
1067 1068 1069 1070 1071 1072
      // 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;
M
Minghao Li 已提交
1073
      pReply->success = true;
M
Minghao Li 已提交
1074
      pReply->matchIndex = snapshot.lastApplyIndex;
M
Minghao Li 已提交
1075 1076 1077 1078 1079 1080 1081 1082 1083

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

      return ret;
    }
M
Minghao Li 已提交
1084
  } while (0);
1085
#endif
M
Minghao Li 已提交
1086

1087
  // fake match2
1088 1089 1090 1091 1092
  //
  // condition1:
  // preIndex <= my commit index
  //
  // operation:
1093 1094
  // if hasAppendEntries && pMsg->prevLogIndex == ths->commitIndex, append entry
  // match my-commit-index or my-commit-index + 1
1095 1096 1097 1098 1099
  // no operation on log
  do {
    bool condition = (pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) &&
                     (pMsg->prevLogIndex <= ths->commitIndex);
    if (condition) {
1100
      do {
M
Minghao Li 已提交
1101 1102 1103 1104
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
1105
        snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
1106 1107 1108 1109 1110 1111
                 "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "datalen:%d}, fake match2",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataLen);
1112 1113
        syncNodeEventLog(ths, logBuf);
      } while (0);
1114

1115 1116 1117 1118 1119 1120 1121
      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);

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        {
          // 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);
          }
        }

1134
        code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
1135 1136 1137
        if (code != 0) {
          return -1;
        }
1138 1139 1140 1141 1142

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

1143
        // update match index
1144 1145 1146 1147 1148
        matchIndex = pMsg->prevLogIndex + 1;

        syncEntryDestory(pAppendEntry);
      }

1149 1150 1151 1152 1153 1154 1155
      // 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;
1156
      pReply->matchIndex = matchIndex;
1157

M
Minghao Li 已提交
1158 1159
      // msg event log
      do {
M
Minghao Li 已提交
1160
        char     host[64];
M
Minghao Li 已提交
1161 1162
        uint16_t port;
        syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
1163 1164 1165 1166 1167 1168
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
                 ", success:%d, match-index:%" PRId64 "}",
                 host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
        syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
1169 1170
      } while (0);

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);

      return ret;
    }
  } while (0);

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

M
Minghao Li 已提交
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
  // 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 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
      do {
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "datalen:%d}, not match",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataLen);
        syncNodeEventLog(ths, logBuf);
      } while (0);
M
Minghao Li 已提交
1216

M
Minghao Li 已提交
1217 1218 1219 1220 1221 1222 1223 1224
      // 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;
1225

M
Minghao Li 已提交
1226 1227
      // msg event log
      do {
M
Minghao Li 已提交
1228
        char     host[64];
M
Minghao Li 已提交
1229 1230
        uint16_t port;
        syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
1231 1232 1233 1234 1235 1236
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
                 ", success:%d, match-index:%" PRId64 "}",
                 host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
        syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
1237 1238
      } while (0);

M
Minghao Li 已提交
1239 1240 1241 1242 1243
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);
1244

M
Minghao Li 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
      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 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
      do {
        char     host[64];
        uint16_t port;
        syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "recv sync-append-entries from %s:%d {term:" PRIu64 ", pre-index:" PRId64 ", pre-term:" PRIu64
                 ", commit:" PRId64 ", pterm:" PRIu64
                 ", "
                 "datalen:%d}, match",
                 host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
                 pMsg->dataLen);
        syncNodeEventLog(ths, logBuf);
      } while (0);
M
Minghao Li 已提交
1281

M
Minghao Li 已提交
1282 1283 1284 1285 1286
      if (hasExtraEntries) {
        // make log same, rollback deleted entries
        code = syncNodeMakeLogSame(ths, pMsg);
        ASSERT(code == 0);
      }
1287

M
Minghao Li 已提交
1288 1289 1290 1291
      if (hasAppendEntries) {
        // append entry
        SSyncRaftEntry* pAppendEntry = syncEntryDeserialize(pMsg->data, pMsg->dataLen);
        ASSERT(pAppendEntry != NULL);
1292

M
Minghao Li 已提交
1293
        code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pAppendEntry);
1294 1295 1296
        if (code != 0) {
          return -1;
        }
1297

M
Minghao Li 已提交
1298 1299 1300
        // pre commit
        code = syncNodePreCommit(ths, pAppendEntry);
        ASSERT(code == 0);
1301

M
Minghao Li 已提交
1302 1303
        syncEntryDestory(pAppendEntry);
      }
1304

M
Minghao Li 已提交
1305 1306 1307 1308 1309 1310 1311 1312
      // 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;
1313

M
Minghao Li 已提交
1314 1315
      // msg event log
      do {
M
Minghao Li 已提交
1316
        char     host[64];
M
Minghao Li 已提交
1317 1318
        uint16_t port;
        syncUtilU642Addr(pReply->destId.addr, host, sizeof(host), &port);
M
Minghao Li 已提交
1319 1320 1321 1322 1323 1324
        char logBuf[256];
        snprintf(logBuf, sizeof(logBuf),
                 "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64
                 ", success:%d, match-index:%" PRId64 "}",
                 host, port, pReply->term, pReply->privateTerm, pReply->success, pReply->matchIndex);
        syncNodeEventLog(ths, logBuf);
M
Minghao Li 已提交
1325 1326
      } while (0);

M
Minghao Li 已提交
1327 1328 1329 1330 1331
      // send response
      SRpcMsg rpcMsg;
      syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
      syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
      syncAppendEntriesReplyDestroy(pReply);
1332

M
Minghao Li 已提交
1333 1334 1335 1336
      // 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)) {
1337 1338
          // advance commit index to sanpshot first
          SSnapshot snapshot;
1339
          ths->pFsm->FpGetSnapshotInfo(ths->pFsm, &snapshot);
1340 1341 1342
          if (snapshot.lastApplyIndex >= 0 && snapshot.lastApplyIndex > ths->commitIndex) {
            SyncIndex commitBegin = ths->commitIndex;
            SyncIndex commitEnd = snapshot.lastApplyIndex;
1343
            ths->commitIndex = snapshot.lastApplyIndex;
1344

M
Minghao Li 已提交
1345
            char eventLog[128];
S
Shengliang Guan 已提交
1346 1347
            snprintf(eventLog, sizeof(eventLog), "commit by snapshot from index:%" PRId64 " to index:%" PRId64,
                     commitBegin, commitEnd);
M
Minghao Li 已提交
1348
            syncNodeEventLog(ths, eventLog);
1349 1350
          }

M
Minghao Li 已提交
1351 1352
          SyncIndex beginIndex = ths->commitIndex + 1;
          SyncIndex endIndex = pMsg->commitIndex;
1353

M
Minghao Li 已提交
1354 1355
          // update commit index
          ths->commitIndex = pMsg->commitIndex;
1356

M
Minghao Li 已提交
1357 1358 1359
          // call back Wal
          code = ths->pLogStore->updateCommitIndex(ths->pLogStore, ths->commitIndex);
          ASSERT(code == 0);
1360

M
Minghao Li 已提交
1361 1362 1363
          code = syncNodeCommit(ths, beginIndex, endIndex, ths->state);
          ASSERT(code == 0);
        }
1364
      }
M
Minghao Li 已提交
1365
      return ret;
1366
    }
M
Minghao Li 已提交
1367
  } while (0);
1368 1369

  return ret;
M
Minghao Li 已提交
1370
}