syncReplication.c 9.0 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/>.
 */

M
Minghao Li 已提交
16
#include "syncReplication.h"
M
Minghao Li 已提交
17
#include "syncIndexMgr.h"
M
Minghao Li 已提交
18
#include "syncMessage.h"
M
Minghao Li 已提交
19
#include "syncRaftCfg.h"
M
Minghao Li 已提交
20
#include "syncRaftEntry.h"
M
Minghao Li 已提交
21
#include "syncRaftLog.h"
M
Minghao Li 已提交
22
#include "syncRaftStore.h"
23
#include "syncSnapshot.h"
M
Minghao Li 已提交
24
#include "syncUtil.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
// TLA+ Spec
// AppendEntries(i, j) ==
//    /\ i /= j
//    /\ state[i] = Leader
//    /\ LET prevLogIndex == nextIndex[i][j] - 1
//           prevLogTerm == IF prevLogIndex > 0 THEN
//                              log[i][prevLogIndex].term
//                          ELSE
//                              0
//           \* Send up to 1 entry, constrained by the end of the log.
//           lastEntry == Min({Len(log[i]), nextIndex[i][j]})
//           entries == SubSeq(log[i], nextIndex[i][j], lastEntry)
//       IN Send([mtype          |-> AppendEntriesRequest,
//                mterm          |-> currentTerm[i],
//                mprevLogIndex  |-> prevLogIndex,
//                mprevLogTerm   |-> prevLogTerm,
//                mentries       |-> entries,
//                \* mlog is used as a history variable for the proof.
//                \* It would not exist in a real implementation.
//                mlog           |-> log[i],
//                mcommitIndex   |-> Min({commitIndex[i], lastEntry}),
//                msource        |-> i,
//                mdest          |-> j])
//    /\ UNCHANGED <<serverVars, candidateVars, leaderVars, logVars>>
M
Minghao Li 已提交
50
//
M
Minghao Li 已提交
51
int32_t syncNodeAppendEntriesPeers(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
52 53
  assert(pSyncNode->state == TAOS_SYNC_STATE_LEADER);

M
Minghao Li 已提交
54 55 56 57
  syncIndexMgrLog2("==syncNodeAppendEntriesPeers== pNextIndex", pSyncNode->pNextIndex);
  syncIndexMgrLog2("==syncNodeAppendEntriesPeers== pMatchIndex", pSyncNode->pMatchIndex);
  logStoreSimpleLog2("==syncNodeAppendEntriesPeers==", pSyncNode->pLogStore);

M
Minghao Li 已提交
58
  int32_t ret = 0;
M
Minghao Li 已提交
59
  for (int i = 0; i < pSyncNode->peersNum; ++i) {
M
Minghao Li 已提交
60
    SRaftId* pDestId = &(pSyncNode->peersId[i]);
M
Minghao Li 已提交
61

M
Minghao Li 已提交
62 63
    // set prevLogIndex
    SyncIndex nextIndex = syncIndexMgrGetIndex(pSyncNode->pNextIndex, pDestId);
M
Minghao Li 已提交
64

M
Minghao Li 已提交
65
    SyncIndex preLogIndex = nextIndex - 1;
M
Minghao Li 已提交
66

M
Minghao Li 已提交
67
    // set preLogTerm
M
Minghao Li 已提交
68 69
    SyncTerm preLogTerm = 0;
    if (preLogIndex >= SYNC_INDEX_BEGIN) {
M
Minghao Li 已提交
70
      SSyncRaftEntry* pPreEntry = pSyncNode->pLogStore->getEntry(pSyncNode->pLogStore, preLogIndex);
M
Minghao Li 已提交
71 72
      assert(pPreEntry != NULL);

M
Minghao Li 已提交
73
      preLogTerm = pPreEntry->term;
M
Minghao Li 已提交
74
      syncEntryDestory(pPreEntry);
M
Minghao Li 已提交
75
    }
M
Minghao Li 已提交
76

M
Minghao Li 已提交
77 78 79 80
    // batch optimized
    // SyncIndex lastIndex = syncUtilMinIndex(pSyncNode->pLogStore->getLastIndex(pSyncNode->pLogStore), nextIndex);

    SyncAppendEntries* pMsg = NULL;
81
    SSyncRaftEntry*    pEntry = pSyncNode->pLogStore->getEntry(pSyncNode->pLogStore, nextIndex);
M
Minghao Li 已提交
82
    if (pEntry != NULL) {
M
Minghao Li 已提交
83
      pMsg = syncAppendEntriesBuild(pEntry->bytes, pSyncNode->vgId);
M
Minghao Li 已提交
84
      assert(pMsg != NULL);
M
Minghao Li 已提交
85

M
Minghao Li 已提交
86 87 88 89 90 91
      // add pEntry into msg
      uint32_t len;
      char*    serialized = syncEntrySerialize(pEntry, &len);
      assert(len == pEntry->bytes);
      memcpy(pMsg->data, serialized, len);

wafwerar's avatar
wafwerar 已提交
92
      taosMemoryFree(serialized);
M
Minghao Li 已提交
93 94 95 96
      syncEntryDestory(pEntry);

    } else {
      // maybe overflow, send empty record
M
Minghao Li 已提交
97
      pMsg = syncAppendEntriesBuild(0, pSyncNode->vgId);
M
Minghao Li 已提交
98
      assert(pMsg != NULL);
M
Minghao Li 已提交
99
    }
M
Minghao Li 已提交
100

M
Minghao Li 已提交
101
    assert(pMsg != NULL);
M
Minghao Li 已提交
102 103
    pMsg->srcId = pSyncNode->myRaftId;
    pMsg->destId = *pDestId;
M
Minghao Li 已提交
104
    pMsg->term = pSyncNode->pRaftStore->currentTerm;
M
Minghao Li 已提交
105 106 107 108
    pMsg->prevLogIndex = preLogIndex;
    pMsg->prevLogTerm = preLogTerm;
    pMsg->commitIndex = pSyncNode->commitIndex;

M
Minghao Li 已提交
109 110
    syncAppendEntriesLog2("==syncNodeAppendEntriesPeers==", pMsg);

M
Minghao Li 已提交
111
    // send AppendEntries
M
Minghao Li 已提交
112
    syncNodeAppendEntries(pSyncNode, pDestId, pMsg);
M
Minghao Li 已提交
113
    syncAppendEntriesDestroy(pMsg);
M
Minghao Li 已提交
114 115
  }

M
Minghao Li 已提交
116 117 118
  return ret;
}

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
int32_t syncNodeAppendEntriesPeersSnapshot(SSyncNode* pSyncNode) {
  assert(pSyncNode->state == TAOS_SYNC_STATE_LEADER);

  syncIndexMgrLog2("==syncNodeAppendEntriesPeersSnapshot== pNextIndex", pSyncNode->pNextIndex);
  syncIndexMgrLog2("==syncNodeAppendEntriesPeersSnapshot== pMatchIndex", pSyncNode->pMatchIndex);
  logStoreSimpleLog2("==syncNodeAppendEntriesPeersSnapshot==", pSyncNode->pLogStore);

  int32_t ret = 0;
  for (int i = 0; i < pSyncNode->peersNum; ++i) {
    SRaftId* pDestId = &(pSyncNode->peersId[i]);

    SyncIndex nextIndex = syncIndexMgrGetIndex(pSyncNode->pNextIndex, pDestId);
    SyncIndex preLogIndex;
    SyncTerm  preLogTerm;

    // batch optimized
    // SyncIndex lastIndex = syncUtilMinIndex(pSyncNode->pLogStore->getLastIndex(pSyncNode->pLogStore), nextIndex);

M
Minghao Li 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    // sending snapshot finish?
    bool                 snapshotSendingFinish = false;
    SSyncSnapshotSender* pSender = NULL;
    for (int i = 0; i < pSyncNode->replicaNum; ++i) {
      if (syncUtilSameId(pDestId, &((pSyncNode->replicasId)[i]))) {
        pSender = (pSyncNode->senders)[i];
      }
    }
    ASSERT(pSender != NULL);
    snapshotSendingFinish = (pSender->finish) && (pSender->term == pSyncNode->pRaftStore->currentTerm);
    if (snapshotSendingFinish) {
      sInfo("snapshotSendingFinish! term:%lu", pSender->term);
    }

    if ((syncNodeIsIndexInSnapshot(pSyncNode, nextIndex - 1) && !snapshotSendingFinish) ||
        syncNodeIsIndexInSnapshot(pSyncNode, nextIndex)) {
153
      // will send this msg until snapshot receive finish!
M
Minghao Li 已提交
154 155

      SSnapshot snapshot = pSender->snapshot;
156 157 158
      sInfo("nextIndex:%ld in snapshot: <lastApplyIndex:%ld, lastApplyTerm:%lu>, begin snapshot", nextIndex,
            snapshot.lastApplyIndex, snapshot.lastApplyTerm);

159
      // do not use next index
M
Minghao Li 已提交
160 161 162 163
      // always send from snapshot.lastApplyIndex + 1, and wait for snapshot transfer finish

      preLogIndex = snapshot.lastApplyIndex;
      preLogTerm = snapshot.lastApplyTerm;
164

M
Minghao Li 已提交
165 166 167
      // update next index!
      syncIndexMgrSetIndex(pSyncNode->pNextIndex, pDestId, snapshot.lastApplyIndex + 1);

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
      // to claim leader
      SyncAppendEntries* pMsg = syncAppendEntriesBuild(0, pSyncNode->vgId);
      assert(pMsg != NULL);
      pMsg->srcId = pSyncNode->myRaftId;
      pMsg->destId = *pDestId;
      pMsg->term = pSyncNode->pRaftStore->currentTerm;
      pMsg->prevLogIndex = preLogIndex;
      pMsg->prevLogTerm = preLogTerm;
      pMsg->commitIndex = pSyncNode->commitIndex;

      syncAppendEntriesLog2("==syncNodeAppendEntriesPeersSnapshot==", pMsg);

      // send AppendEntries
      syncNodeAppendEntries(pSyncNode, pDestId, pMsg);
      syncAppendEntriesDestroy(pMsg);

M
Minghao Li 已提交
184 185 186 187 188 189 190
      if (!snapshotSendingFinish) {
        SSyncSnapshotSender* pSender = NULL;
        for (int i = 0; i < pSyncNode->replicaNum; ++i) {
          if (syncUtilSameId(&((pSyncNode->replicasId)[i]), pDestId)) {
            pSender = (pSyncNode->senders)[i];
            break;
          }
191
        }
M
Minghao Li 已提交
192 193
        ASSERT(pSender != NULL);
        snapshotSenderStart(pSender);
194 195 196
      }

    } else {
M
Minghao Li 已提交
197 198 199
      ret = syncNodeGetPreIndexTerm(pSyncNode, nextIndex, &preLogIndex, &preLogTerm);
      ASSERT(ret == 0);

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
      SyncAppendEntries* pMsg = NULL;
      SSyncRaftEntry*    pEntry = pSyncNode->pLogStore->getEntry(pSyncNode->pLogStore, nextIndex);
      if (pEntry != NULL) {
        pMsg = syncAppendEntriesBuild(pEntry->bytes, pSyncNode->vgId);
        assert(pMsg != NULL);

        // add pEntry into msg
        uint32_t len;
        char*    serialized = syncEntrySerialize(pEntry, &len);
        assert(len == pEntry->bytes);
        memcpy(pMsg->data, serialized, len);

        taosMemoryFree(serialized);
        syncEntryDestory(pEntry);

      } else {
        // maybe overflow, send empty record
        pMsg = syncAppendEntriesBuild(0, pSyncNode->vgId);
        assert(pMsg != NULL);
      }

      assert(pMsg != NULL);
      pMsg->srcId = pSyncNode->myRaftId;
      pMsg->destId = *pDestId;
      pMsg->term = pSyncNode->pRaftStore->currentTerm;
      pMsg->prevLogIndex = preLogIndex;
      pMsg->prevLogTerm = preLogTerm;
      pMsg->commitIndex = pSyncNode->commitIndex;

      syncAppendEntriesLog2("==syncNodeAppendEntriesPeersSnapshot==", pMsg);

      // send AppendEntries
      syncNodeAppendEntries(pSyncNode, pDestId, pMsg);
      syncAppendEntriesDestroy(pMsg);
    }
  }

  return ret;
}
M
Minghao Li 已提交
239

M
Minghao Li 已提交
240 241
int32_t syncNodeReplicate(SSyncNode* pSyncNode) {
  // start replicate
M
Minghao Li 已提交
242 243 244 245 246 247 248
  int32_t ret = 0;

  if (pSyncNode->pRaftCfg->snapshotEnable) {
    ret = syncNodeAppendEntriesPeersSnapshot(pSyncNode);
  } else {
    ret = syncNodeAppendEntriesPeers(pSyncNode);
  }
M
Minghao Li 已提交
249 250
  return ret;
}
M
Minghao Li 已提交
251 252 253 254 255 256 257 258 259 260

int32_t syncNodeAppendEntries(SSyncNode* pSyncNode, const SRaftId* destRaftId, const SyncAppendEntries* pMsg) {
  sTrace("syncNodeAppendEntries pSyncNode:%p ", pSyncNode);
  int32_t ret = 0;

  SRpcMsg rpcMsg;
  syncAppendEntries2RpcMsg(pMsg, &rpcMsg);
  syncNodeSendMsgById(destRaftId, pSyncNode, &rpcMsg);
  return ret;
}