syncAppendEntries.c 13.2 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 18 19 20 21
#include "syncInt.h"
#include "syncRaftLog.h"
#include "syncRaftStore.h"
#include "syncUtil.h"
#include "syncVoteMgr.h"
M
Minghao Li 已提交
22

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

  char logBuf[128];
  snprintf(logBuf, sizeof(logBuf), "==syncNodeOnAppendEntriesCb== term:%lu", ths->pRaftStore->currentTerm);
  syncAppendEntriesLog2(logBuf, pMsg);
M
Minghao Li 已提交
94

M
Minghao Li 已提交
95 96 97 98 99
  if (pMsg->term > ths->pRaftStore->currentTerm) {
    syncNodeUpdateTerm(ths, pMsg->term);
  }
  assert(pMsg->term <= ths->pRaftStore->currentTerm);

M
Minghao Li 已提交
100
  // reset elect timer
M
Minghao Li 已提交
101 102 103 104 105 106 107
  if (pMsg->term == ths->pRaftStore->currentTerm) {
    ths->leaderCache = pMsg->srcId;
    syncNodeResetElectTimer(ths);
  }
  assert(pMsg->dataLen >= 0);

  SyncTerm localPreLogTerm = 0;
M
Minghao Li 已提交
108
  if (pMsg->prevLogIndex >= SYNC_INDEX_BEGIN && pMsg->prevLogIndex <= ths->pLogStore->getLastIndex(ths->pLogStore)) {
M
Minghao Li 已提交
109
    SSyncRaftEntry* pEntry = logStoreGetEntry(ths->pLogStore, pMsg->prevLogIndex);
M
Minghao Li 已提交
110 111 112 113 114 115 116 117
    assert(pEntry != NULL);
    localPreLogTerm = pEntry->term;
    syncEntryDestory(pEntry);
  }

  bool logOK =
      (pMsg->prevLogIndex == SYNC_INDEX_INVALID) ||
      ((pMsg->prevLogIndex >= SYNC_INDEX_BEGIN) &&
M
Minghao Li 已提交
118
       (pMsg->prevLogIndex <= ths->pLogStore->getLastIndex(ths->pLogStore)) && (pMsg->prevLogTerm == localPreLogTerm));
M
Minghao Li 已提交
119

M
Minghao Li 已提交
120
  // reject request
M
Minghao Li 已提交
121 122
  if ((pMsg->term < ths->pRaftStore->currentTerm) ||
      ((pMsg->term == ths->pRaftStore->currentTerm) && (ths->state == TAOS_SYNC_STATE_FOLLOWER) && !logOK)) {
M
Minghao Li 已提交
123 124 125 126 127
    sTrace(
        "syncNodeOnAppendEntriesCb --> reject, pMsg->term:%lu, ths->pRaftStore->currentTerm:%lu, ths->state:%d, "
        "logOK:%d",
        pMsg->term, ths->pRaftStore->currentTerm, ths->state, logOK);

M
Minghao Li 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild();
    pReply->srcId = ths->myRaftId;
    pReply->destId = pMsg->srcId;
    pReply->term = ths->pRaftStore->currentTerm;
    pReply->success = false;
    pReply->matchIndex = SYNC_INDEX_INVALID;

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

    return ret;
  }

  // return to follower state
  if (pMsg->term == ths->pRaftStore->currentTerm && ths->state == TAOS_SYNC_STATE_CANDIDATE) {
M
Minghao Li 已提交
145 146 147 148 149
    sTrace(
        "syncNodeOnAppendEntriesCb --> return to follower, pMsg->term:%lu, ths->pRaftStore->currentTerm:%lu, "
        "ths->state:%d, logOK:%d",
        pMsg->term, ths->pRaftStore->currentTerm, ths->state, logOK);

M
Minghao Li 已提交
150
    syncNodeBecomeFollower(ths);
M
Minghao Li 已提交
151

M
Minghao Li 已提交
152
    // ret or reply?
M
Minghao Li 已提交
153
    return ret;
M
Minghao Li 已提交
154 155 156 157
  }

  // accept request
  if (pMsg->term == ths->pRaftStore->currentTerm && ths->state == TAOS_SYNC_STATE_FOLLOWER && logOK) {
M
Minghao Li 已提交
158 159 160 161 162 163 164 165 166 167 168 169
    /*
        bool preMatch = false;
        if (pMsg->prevLogIndex == SYNC_INDEX_INVALID &&
            ths->pLogStore->getLastIndex(ths->pLogStore) == SYNC_INDEX_INVALID) {
          preMatch = true;
        }
        if (pMsg->prevLogIndex >= SYNC_INDEX_BEGIN && pMsg->prevLogIndex <=
       ths->pLogStore->getLastIndex(ths->pLogStore)) { SSyncRaftEntry* pPreEntry = logStoreGetEntry(ths->pLogStore,
       pMsg->prevLogIndex); assert(pPreEntry != NULL); if (pMsg->prevLogTerm == pPreEntry->term) { preMatch = true;
          }
          syncEntryDestory(pPreEntry);
        }
M
Minghao Li 已提交
170

M
Minghao Li 已提交
171 172 173 174 175 176 177
        sTrace(
            "syncNodeOnAppendEntriesCb --> accept, pMsg->term:%lu, ths->pRaftStore->currentTerm:%lu, "
            "ths->state:%d, logOK:%d, preMatch:%d",
            pMsg->term, ths->pRaftStore->currentTerm, ths->state, logOK, preMatch);

        if (preMatch) {
    */
M
Minghao Li 已提交
178

M
Minghao Li 已提交
179 180
    {
      // preIndex = -1, or has preIndex entry in local log
M
Minghao Li 已提交
181 182
      assert(pMsg->prevLogIndex <= ths->pLogStore->getLastIndex(ths->pLogStore));

M
Minghao Li 已提交
183
      // has extra entries (> preIndex) in local log
M
Minghao Li 已提交
184
      bool hasExtraEntries = pMsg->prevLogIndex < ths->pLogStore->getLastIndex(ths->pLogStore);
M
Minghao Li 已提交
185 186

      // has entries in SyncAppendEntries msg
M
Minghao Li 已提交
187 188 189
      bool hasAppendEntries = pMsg->dataLen > 0;

      if (hasExtraEntries && hasAppendEntries) {
M
Minghao Li 已提交
190
        // not conflict by default
M
Minghao Li 已提交
191 192 193 194 195 196 197 198 199
        bool conflict = false;

        SyncIndex       extraIndex = pMsg->prevLogIndex + 1;
        SSyncRaftEntry* pExtraEntry = logStoreGetEntry(ths->pLogStore, extraIndex);
        assert(pExtraEntry != NULL);

        SSyncRaftEntry* pAppendEntry = syncEntryDeserialize(pMsg->data, pMsg->dataLen);
        assert(pAppendEntry != NULL);

M
Minghao Li 已提交
200
        // log not match, conflict
M
Minghao Li 已提交
201
        assert(extraIndex == pAppendEntry->index);
M
Minghao Li 已提交
202
        if (pExtraEntry->term != pAppendEntry->term) {
M
Minghao Li 已提交
203 204 205 206 207 208 209 210
          conflict = true;
        }

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

M
Minghao Li 已提交
211 212
          sTrace("syncNodeOnAppendEntriesCb --> conflict:%d, delBegin:%ld, delEnd:%ld", conflict, delBegin, delEnd);

M
Minghao Li 已提交
213 214 215 216 217 218 219 220
          // notice! reverse roll back!
          for (SyncIndex index = delEnd; index >= delBegin; --index) {
            if (ths->pFsm->FpRollBackCb != NULL) {
              SSyncRaftEntry* pRollBackEntry = logStoreGetEntry(ths->pLogStore, index);
              assert(pRollBackEntry != NULL);

              SRpcMsg rpcMsg;
              syncEntry2OriginalRpc(pRollBackEntry, &rpcMsg);
M
Minghao Li 已提交
221
              ths->pFsm->FpRollBackCb(ths->pFsm, &rpcMsg, pRollBackEntry->index, pRollBackEntry->isWeak, 0, ths->state);
M
Minghao Li 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
              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) {
M
Minghao Li 已提交
238
              ths->pFsm->FpPreCommitCb(ths->pFsm, &rpcMsg, pAppendEntry->index, pAppendEntry->isWeak, 2, ths->state);
M
Minghao Li 已提交
239 240 241 242 243 244 245 246
            }
          }
          rpcFreeCont(rpcMsg.pCont);
        }

        // free memory
        syncEntryDestory(pExtraEntry);
        syncEntryDestory(pAppendEntry);
M
Minghao Li 已提交
247

M
Minghao Li 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
      } else if (hasExtraEntries && !hasAppendEntries) {
        // do nothing

      } else if (!hasExtraEntries && hasAppendEntries) {
        SSyncRaftEntry* pAppendEntry = syncEntryDeserialize(pMsg->data, pMsg->dataLen);
        assert(pAppendEntry != NULL);

        // 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) {
M
Minghao Li 已提交
263
            ths->pFsm->FpPreCommitCb(ths->pFsm, &rpcMsg, pAppendEntry->index, pAppendEntry->isWeak, 3, ths->state);
M
Minghao Li 已提交
264 265 266 267 268 269 270 271 272 273 274 275
          }
        }
        rpcFreeCont(rpcMsg.pCont);

        // free memory
        syncEntryDestory(pAppendEntry);

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

      } else {
        assert(0);
M
Minghao Li 已提交
276 277 278 279 280 281 282
      }

      SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild();
      pReply->srcId = ths->myRaftId;
      pReply->destId = pMsg->srcId;
      pReply->term = ths->pRaftStore->currentTerm;
      pReply->success = true;
M
Minghao Li 已提交
283

M
Minghao Li 已提交
284
      if (hasAppendEntries) {
M
Minghao Li 已提交
285 286 287 288
        pReply->matchIndex = pMsg->prevLogIndex + 1;
      } else {
        pReply->matchIndex = pMsg->prevLogIndex;
      }
M
Minghao Li 已提交
289 290 291 292 293 294

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

      syncAppendEntriesReplyDestroy(pReply);
M
Minghao Li 已提交
295
    }
M
Minghao Li 已提交
296

M
Minghao Li 已提交
297 298 299 300 301 302 303 304
    /*
        else {
          SyncAppendEntriesReply* pReply = syncAppendEntriesReplyBuild();
          pReply->srcId = ths->myRaftId;
          pReply->destId = pMsg->srcId;
          pReply->term = ths->pRaftStore->currentTerm;
          pReply->success = false;
          pReply->matchIndex = SYNC_INDEX_INVALID;
M
Minghao Li 已提交
305

M
Minghao Li 已提交
306 307 308 309 310 311
          SRpcMsg rpcMsg;
          syncAppendEntriesReply2RpcMsg(pReply, &rpcMsg);
          syncNodeSendMsgById(&pReply->destId, ths, &rpcMsg);
          syncAppendEntriesReplyDestroy(pReply);
        }
    */
M
Minghao Li 已提交
312

M
Minghao Li 已提交
313
    // maybe update commit index from leader
M
Minghao Li 已提交
314
    if (pMsg->commitIndex > ths->commitIndex) {
M
Minghao Li 已提交
315
      // has commit entry in local
M
Minghao Li 已提交
316
      if (pMsg->commitIndex <= ths->pLogStore->getLastIndex(ths->pLogStore)) {
M
Minghao Li 已提交
317 318 319 320
        SyncIndex beginIndex = ths->commitIndex + 1;
        SyncIndex endIndex = pMsg->commitIndex;

        // update commit index
M
Minghao Li 已提交
321
        ths->commitIndex = pMsg->commitIndex;
M
Minghao Li 已提交
322 323

        // call back Wal
M
Minghao Li 已提交
324
        ths->pLogStore->updateCommitIndex(ths->pLogStore, ths->commitIndex);
M
Minghao Li 已提交
325 326 327 328 329 330 331 332 333 334 335 336

        // execute fsm
        if (ths->pFsm != NULL) {
          for (SyncIndex i = beginIndex; i <= endIndex; ++i) {
            if (i != SYNC_INDEX_INVALID) {
              SSyncRaftEntry* pEntry = ths->pLogStore->getEntry(ths->pLogStore, i);
              assert(pEntry != NULL);

              SRpcMsg rpcMsg;
              syncEntry2OriginalRpc(pEntry, &rpcMsg);

              if (ths->pFsm->FpCommitCb != NULL) {
M
Minghao Li 已提交
337
                ths->pFsm->FpCommitCb(ths->pFsm, &rpcMsg, pEntry->index, pEntry->isWeak, 0, ths->state);
M
Minghao Li 已提交
338 339 340 341 342 343 344
              }

              rpcFreeCont(rpcMsg.pCont);
              syncEntryDestory(pEntry);
            }
          }
        }
M
Minghao Li 已提交
345 346 347 348
      }
    }
  }

M
Minghao Li 已提交
349 350
  return ret;
}