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

16
#define _DEFAULT_SOURCE
M
Minghao Li 已提交
17
#include "syncAppendEntries.h"
18
#include "syncPipeline.h"
19
#include "syncMessage.h"
M
Minghao Li 已提交
20 21
#include "syncRaftLog.h"
#include "syncRaftStore.h"
B
Benguang Zhao 已提交
22
#include "syncReplication.h"
M
Minghao Li 已提交
23
#include "syncUtil.h"
24
#include "syncCommit.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

92
int32_t syncNodeFollowerCommit(SSyncNode* ths, SyncIndex newCommitIndex) {
93
  ASSERT(false && "deprecated");
94
  if (ths->state != TAOS_SYNC_STATE_FOLLOWER) {
S
Shengliang Guan 已提交
95
    sNTrace(ths, "can not do follower commit");
96
    return -1;
M
Minghao Li 已提交
97 98
  }

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

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

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

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

M
Minghao Li 已提交
123
      code = syncNodeDoCommit(ths, beginIndex, endIndex, ths->state);
124 125 126 127 128 129 130
      ASSERT(code == 0);
    }
  }

  return 0;
}

B
Benguang Zhao 已提交
131 132 133 134 135 136 137 138 139 140 141
SSyncRaftEntry* syncLogAppendEntriesToRaftEntry(const SyncAppendEntries* pMsg) {
  SSyncRaftEntry* pEntry = taosMemoryMalloc(pMsg->dataLen);
  if (pEntry == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
  (void)memcpy(pEntry, pMsg->data, pMsg->dataLen);
  ASSERT(pEntry->bytes == pMsg->dataLen);
  return pEntry;
}

142 143
int32_t syncNodeOnAppendEntries(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncAppendEntries* pMsg = pRpcMsg->pCont;
144
  SRpcMsg            rpcRsp = {0};
145
  bool               accepted = false;
B
Benguang Zhao 已提交
146 147 148 149 150 151
  // if already drop replica, do not process
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId))) {
    syncLogRecvAppendEntries(ths, pMsg, "not in my config");
    goto _IGNORE;
  }

152 153 154 155 156 157 158
  int32_t code = syncBuildAppendEntriesReply(&rpcRsp, ths->vgId);
  if (code != 0) {
    syncLogRecvAppendEntries(ths, pMsg, "build rsp error");
    goto _IGNORE;
  }

  SyncAppendEntriesReply* pReply = rpcRsp.pCont;
B
Benguang Zhao 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  // prepare response msg
  pReply->srcId = ths->myRaftId;
  pReply->destId = pMsg->srcId;
  pReply->term = ths->pRaftStore->currentTerm;
  pReply->success = false;
  pReply->matchIndex = SYNC_INDEX_INVALID;
  pReply->lastSendIndex = pMsg->prevLogIndex + 1;
  pReply->startTime = ths->startTime;

  if (pMsg->term < ths->pRaftStore->currentTerm) {
    goto _SEND_RESPONSE;
  }

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

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

  if (pMsg->dataLen < (int32_t)sizeof(SSyncRaftEntry)) {
    sError("vgId:%d, incomplete append entries received. prev index:%" PRId64 ", term:%" PRId64 ", datalen:%d",
           ths->vgId, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->dataLen);
    goto _IGNORE;
  }

  SSyncRaftEntry* pEntry = syncLogAppendEntriesToRaftEntry(pMsg);

  if (pEntry == NULL) {
    sError("vgId:%d, failed to get raft entry from append entries since %s", ths->vgId, terrstr());
    goto _IGNORE;
  }

192
  if (pMsg->prevLogIndex + 1 != pEntry->index || pEntry->term < 0) {
B
Benguang Zhao 已提交
193 194 195 196 197 198
    sError("vgId:%d, invalid previous log index in msg. index:%" PRId64 ",  term:%" PRId64 ", prevLogIndex:%" PRId64
           ", prevLogTerm:%" PRId64,
           ths->vgId, pEntry->index, pEntry->term, pMsg->prevLogIndex, pMsg->prevLogTerm);
    goto _IGNORE;
  }

199 200 201
  sTrace("vgId:%d, recv append entries msg. index:%" PRId64 ", term:%" PRId64 ", preLogIndex:%" PRId64
         ", prevLogTerm:%" PRId64 " commitIndex:%" PRId64 "",
         pMsg->vgId, pMsg->prevLogIndex + 1, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex);
B
Benguang Zhao 已提交
202 203 204 205 206

  // accept
  if (syncLogBufferAccept(ths->pLogBuf, ths, pEntry, pMsg->prevLogTerm) < 0) {
    goto _SEND_RESPONSE;
  }
207
  accepted = true;
B
Benguang Zhao 已提交
208 209

_SEND_RESPONSE:
210
  pEntry = NULL;
211
  pReply->matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, &pReply->lastMatchTerm);
B
Benguang Zhao 已提交
212
  bool matched = (pReply->matchIndex >= pReply->lastSendIndex);
213 214
  if (accepted && matched) {
    pReply->success = true;
B
Benguang Zhao 已提交
215
    // update commit index only after matching
216
    (void)syncNodeUpdateCommitIndex(ths, TMIN(pMsg->commitIndex, pReply->lastSendIndex));
B
Benguang Zhao 已提交
217
  }
B
Benguang Zhao 已提交
218 219

  // ack, i.e. send response
220
  (void)syncNodeSendMsgById(&pReply->destId, ths, &rpcRsp);
B
Benguang Zhao 已提交
221 222

  // commit index, i.e. leader notice me
B
Benguang Zhao 已提交
223
  if (syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex) < 0) {
B
Benguang Zhao 已提交
224 225 226 227 228
    sError("vgId:%d, failed to commit raft fsm log since %s.", ths->vgId, terrstr());
    goto _out;
  }

_out:
229 230
  return 0;

B
Benguang Zhao 已提交
231
_IGNORE:
232
  rpcFreeCont(rpcRsp.pCont);
B
Benguang Zhao 已提交
233 234 235
  return 0;
}

236 237 238
int32_t syncNodeOnAppendEntriesOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncAppendEntries* pMsg = pRpcMsg->pCont;
  SRpcMsg            rpcRsp = {0};
239

M
Minghao Li 已提交
240
  // if already drop replica, do not process
M
Minghao Li 已提交
241 242
  if (!syncNodeInRaftGroup(ths, &(pMsg->srcId))) {
    syncLogRecvAppendEntries(ths, pMsg, "not in my config");
M
Minghao Li 已提交
243 244 245
    goto _IGNORE;
  }

M
Minghao Li 已提交
246
  // prepare response msg
247
  int32_t code = syncBuildAppendEntriesReply(&rpcRsp, ths->vgId);
248 249 250 251 252 253
  if (code != 0) {
    syncLogRecvAppendEntries(ths, pMsg, "build rsp error");
    goto _IGNORE;
  }

  SyncAppendEntriesReply* pReply = rpcRsp.pCont;
M
Minghao Li 已提交
254 255 256 257
  pReply->srcId = ths->myRaftId;
  pReply->destId = pMsg->srcId;
  pReply->term = ths->pRaftStore->currentTerm;
  pReply->success = false;
M
Minghao Li 已提交
258 259
  // pReply->matchIndex = ths->pLogStore->syncLogLastIndex(ths->pLogStore);
  pReply->matchIndex = SYNC_INDEX_INVALID;
M
Minghao Li 已提交
260 261 262 263
  pReply->lastSendIndex = pMsg->prevLogIndex + 1;
  pReply->startTime = ths->startTime;

  if (pMsg->term < ths->pRaftStore->currentTerm) {
M
Minghao Li 已提交
264
    syncLogRecvAppendEntries(ths, pMsg, "reject, small term");
M
Minghao Li 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278
    goto _SEND_RESPONSE;
  }

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

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

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

  if (pMsg->prevLogIndex > lastIndex) {
M
Minghao Li 已提交
279
    syncLogRecvAppendEntries(ths, pMsg, "reject, index not match");
M
Minghao Li 已提交
280 281 282 283 284
    goto _SEND_RESPONSE;
  }

  if (pMsg->prevLogIndex >= startIndex) {
    SyncTerm myPreLogTerm = syncNodeGetPreTerm(ths, pMsg->prevLogIndex + 1);
M
Minghao Li 已提交
285 286 287 288 289
    // ASSERT(myPreLogTerm != SYNC_TERM_INVALID);
    if (myPreLogTerm == SYNC_TERM_INVALID) {
      syncLogRecvAppendEntries(ths, pMsg, "reject, pre-term invalid");
      goto _SEND_RESPONSE;
    }
M
Minghao Li 已提交
290 291

    if (myPreLogTerm != pMsg->prevLogTerm) {
M
Minghao Li 已提交
292
      syncLogRecvAppendEntries(ths, pMsg, "reject, pre-term not match");
M
Minghao Li 已提交
293 294 295 296 297 298 299 300
      goto _SEND_RESPONSE;
    }
  }

  // accept
  pReply->success = true;
  bool hasAppendEntries = pMsg->dataLen > 0;
  if (hasAppendEntries) {
301
    SSyncRaftEntry* pAppendEntry = syncEntryBuildFromAppendEntries(pMsg);
M
Minghao Li 已提交
302 303
    ASSERT(pAppendEntry != NULL);

304 305 306 307 308 309
    SyncIndex appendIndex = pMsg->prevLogIndex + 1;

    LRUHandle* hLocal = NULL;
    LRUHandle* hAppend = NULL;

    int32_t         code = 0;
M
Minghao Li 已提交
310
    SSyncRaftEntry* pLocalEntry = NULL;
311 312 313 314 315 316
    SLRUCache*      pCache = ths->pLogStore->pCache;
    hLocal = taosLRUCacheLookup(pCache, &appendIndex, sizeof(appendIndex));
    if (hLocal) {
      pLocalEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, hLocal);
      code = 0;

317
      ths->pLogStore->cacheHit++;
318 319 320
      sNTrace(ths, "hit cache index:%" PRId64 ", bytes:%u, %p", appendIndex, pLocalEntry->bytes, pLocalEntry);

    } else {
321
      ths->pLogStore->cacheMiss++;
322 323 324 325 326
      sNTrace(ths, "miss cache index:%" PRId64, appendIndex);

      code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, appendIndex, &pLocalEntry);
    }

M
Minghao Li 已提交
327
    if (code == 0) {
328 329
      // get local entry success

M
Minghao Li 已提交
330 331
      if (pLocalEntry->term == pAppendEntry->term) {
        // do nothing
S
Shengliang Guan 已提交
332
        sNTrace(ths, "log match, do nothing, index:%" PRId64, appendIndex);
M
Minghao Li 已提交
333 334 335 336 337 338

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

342 343 344
          if (hLocal) {
            taosLRUCacheRelease(ths->pLogStore->pCache, hLocal, false);
          } else {
345
            syncEntryDestroy(pLocalEntry);
346 347 348 349 350
          }

          if (hAppend) {
            taosLRUCacheRelease(ths->pLogStore->pCache, hAppend, false);
          } else {
351
            syncEntryDestroy(pAppendEntry);
352 353
          }

M
Minghao Li 已提交
354 355 356
          goto _IGNORE;
        }

B
Benguang Zhao 已提交
357 358
        ASSERT(pAppendEntry->index == appendIndex);

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

366 367 368
          if (hLocal) {
            taosLRUCacheRelease(ths->pLogStore->pCache, hLocal, false);
          } else {
369
            syncEntryDestroy(pLocalEntry);
370 371 372 373 374
          }

          if (hAppend) {
            taosLRUCacheRelease(ths->pLogStore->pCache, hAppend, false);
          } else {
375
            syncEntryDestroy(pAppendEntry);
376 377
          }

M
Minghao Li 已提交
378 379
          goto _IGNORE;
        }
380 381

        syncCacheEntry(ths->pLogStore, pAppendEntry, &hAppend);
M
Minghao Li 已提交
382 383 384 385 386 387 388 389 390 391
      }

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

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

395 396
          syncEntryDestroy(pLocalEntry);
          syncEntryDestroy(pAppendEntry);
M
Minghao Li 已提交
397 398 399 400 401 402 403
          goto _IGNORE;
        }

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

407 408 409
          if (hLocal) {
            taosLRUCacheRelease(ths->pLogStore->pCache, hLocal, false);
          } else {
410
            syncEntryDestroy(pLocalEntry);
411 412 413 414 415
          }

          if (hAppend) {
            taosLRUCacheRelease(ths->pLogStore->pCache, hAppend, false);
          } else {
416
            syncEntryDestroy(pAppendEntry);
417 418
          }

M
Minghao Li 已提交
419 420 421
          goto _IGNORE;
        }

422 423
        syncCacheEntry(ths->pLogStore, pAppendEntry, &hAppend);

M
Minghao Li 已提交
424
      } else {
425
        // get local entry success
M
Minghao Li 已提交
426
        char logBuf[128];
427 428
        snprintf(logBuf, sizeof(logBuf), "ignore, get local entry error, append-index:%" PRId64 " err:%d", appendIndex,
                 terrno);
M
Minghao Li 已提交
429 430
        syncLogRecvAppendEntries(ths, pMsg, logBuf);

431 432 433
        if (hLocal) {
          taosLRUCacheRelease(ths->pLogStore->pCache, hLocal, false);
        } else {
434
          syncEntryDestroy(pLocalEntry);
435 436 437 438 439
        }

        if (hAppend) {
          taosLRUCacheRelease(ths->pLogStore->pCache, hAppend, false);
        } else {
440
          syncEntryDestroy(pAppendEntry);
441 442
        }

M
Minghao Li 已提交
443 444 445 446 447 448
        goto _IGNORE;
      }
    }

    // update match index
    pReply->matchIndex = pAppendEntry->index;
M
Minghao Li 已提交
449

450 451 452
    if (hLocal) {
      taosLRUCacheRelease(ths->pLogStore->pCache, hLocal, false);
    } else {
453
      syncEntryDestroy(pLocalEntry);
454 455 456 457 458
    }

    if (hAppend) {
      taosLRUCacheRelease(ths->pLogStore->pCache, hAppend, false);
    } else {
459
      syncEntryDestroy(pAppendEntry);
460
    }
M
Minghao Li 已提交
461

M
Minghao Li 已提交
462 463 464 465 466 467 468
  } else {
    // no append entries, do nothing
    // maybe has extra entries, no harm

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

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

M
Minghao Li 已提交
473
  syncLogRecvAppendEntries(ths, pMsg, "accept");
M
Minghao Li 已提交
474 475 476
  goto _SEND_RESPONSE;

_IGNORE:
477
  rpcFreeCont(rpcRsp.pCont);
M
Minghao Li 已提交
478 479 480 481 482 483 484
  return 0;

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

  // send response
485
  syncNodeSendMsgById(&pReply->destId, ths, &rpcRsp);
M
Minghao Li 已提交
486
  return 0;
B
Benguang Zhao 已提交
487
}