syncMain.c 99.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/>.
 */

S
Shengliang Guan 已提交
16
#define _DEFAULT_SOURCE
M
Minghao Li 已提交
17
#include "sync.h"
M
Minghao Li 已提交
18 19
#include "syncAppendEntries.h"
#include "syncAppendEntriesReply.h"
M
Minghao Li 已提交
20
#include "syncCommit.h"
M
Minghao Li 已提交
21
#include "syncElection.h"
M
Minghao Li 已提交
22
#include "syncEnv.h"
M
Minghao Li 已提交
23
#include "syncIndexMgr.h"
M
Minghao Li 已提交
24
#include "syncInt.h"
M
Minghao Li 已提交
25
#include "syncMessage.h"
26
#include "syncPipeline.h"
M
Minghao Li 已提交
27
#include "syncRaftCfg.h"
M
Minghao Li 已提交
28
#include "syncRaftLog.h"
M
Minghao Li 已提交
29
#include "syncRaftStore.h"
M
Minghao Li 已提交
30
#include "syncReplication.h"
M
Minghao Li 已提交
31 32
#include "syncRequestVote.h"
#include "syncRequestVoteReply.h"
M
Minghao Li 已提交
33
#include "syncRespMgr.h"
M
Minghao Li 已提交
34
#include "syncSnapshot.h"
M
Minghao Li 已提交
35
#include "syncTimeout.h"
M
Minghao Li 已提交
36
#include "syncUtil.h"
M
Minghao Li 已提交
37
#include "syncVoteMgr.h"
38
#include "tglobal.h"
M
Minghao Li 已提交
39
#include "tref.h"
M
Minghao Li 已提交
40

M
Minghao Li 已提交
41 42 43 44 45
static void    syncNodeEqPingTimer(void* param, void* tmrId);
static void    syncNodeEqElectTimer(void* param, void* tmrId);
static void    syncNodeEqHeartbeatTimer(void* param, void* tmrId);
static int32_t syncNodeEqNoop(SSyncNode* ths);
static int32_t syncNodeAppendNoop(SSyncNode* ths);
46
static void    syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId);
S
Shengliang Guan 已提交
47
static bool    syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg);
S
Shengliang Guan 已提交
48 49 50
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId);
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
S
Shengliang Guan 已提交
51 52 53 54 55 56 57 58 59 60 61
static int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg);
static bool    syncNodeInConfig(SSyncNode* pSyncNode, const SSyncCfg* config);
static void    syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* newConfig, SyncIndex lastConfigChangeIndex);
static bool    syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg);

static bool    syncNodeCanChange(SSyncNode* pSyncNode);
static int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode);
static int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader);
static int32_t syncDoLeaderTransfer(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry);

static ESyncStrategy syncNodeStrategy(SSyncNode* pSyncNode);
M
Minghao Li 已提交
62

63
int64_t syncOpen(SSyncInfo* pSyncInfo) {
M
Minghao Li 已提交
64
  SSyncNode* pSyncNode = syncNodeOpen(pSyncInfo);
65
  if (pSyncNode == NULL) {
S
Shengliang Guan 已提交
66
    sError("vgId:%d, failed to open sync node", pSyncInfo->vgId);
67 68
    return -1;
  }
M
Minghao Li 已提交
69

S
Shengliang Guan 已提交
70
  pSyncNode->rid = syncNodeAdd(pSyncNode);
M
Minghao Li 已提交
71
  if (pSyncNode->rid < 0) {
72
    syncNodeClose(pSyncNode);
M
Minghao Li 已提交
73 74 75
    return -1;
  }

S
Shengliang Guan 已提交
76 77 78 79 80 81
  pSyncNode->pingBaseLine = pSyncInfo->pingMs;
  pSyncNode->pingTimerMS = pSyncInfo->pingMs;
  pSyncNode->electBaseLine = pSyncInfo->electMs;
  pSyncNode->hbBaseLine = pSyncInfo->heartbeatMs;
  pSyncNode->heartbeatTimerMS = pSyncInfo->heartbeatMs;
  pSyncNode->msgcb = pSyncInfo->msgcb;
M
Minghao Li 已提交
82
  return pSyncNode->rid;
M
Minghao Li 已提交
83
}
M
Minghao Li 已提交
84

B
Benguang Zhao 已提交
85
int32_t syncStart(int64_t rid) {
S
Shengliang Guan 已提交
86
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
M
Minghao Li 已提交
87
  if (pSyncNode == NULL) {
B
Benguang Zhao 已提交
88 89 90 91 92
    sError("failed to acquire rid: %" PRId64 " of tsNodeReftId for pSyncNode", rid);
    return -1;
  }

  if (syncNodeRestore(pSyncNode) < 0) {
93
    sError("vgId:%d, failed to restore sync log buffer since %s", pSyncNode->vgId, terrstr());
94
    goto _err;
M
Minghao Li 已提交
95
  }
M
Minghao Li 已提交
96

B
Benguang Zhao 已提交
97 98 99 100
  if (syncNodeStart(pSyncNode) < 0) {
    sError("vgId:%d, failed to start sync node since %s", pSyncNode->vgId, terrstr());
    goto _err;
  }
M
Minghao Li 已提交
101

B
Benguang Zhao 已提交
102 103
  syncNodeRelease(pSyncNode);
  return 0;
M
Minghao Li 已提交
104

105 106 107
_err:
  syncNodeRelease(pSyncNode);
  return -1;
M
Minghao Li 已提交
108 109
}

M
Minghao Li 已提交
110
void syncStop(int64_t rid) {
S
Shengliang Guan 已提交
111
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
112
  if (pSyncNode != NULL) {
113
    pSyncNode->isStart = false;
S
Shengliang Guan 已提交
114
    syncNodeRelease(pSyncNode);
S
Shengliang Guan 已提交
115
    syncNodeRemove(rid);
M
Minghao Li 已提交
116 117 118
  }
}

M
Minghao Li 已提交
119 120
void syncPreStop(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
121 122 123
  if (pSyncNode != NULL) {
    syncNodePreClose(pSyncNode);
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
124 125 126
  }
}

127 128 129 130 131 132 133 134
void syncPostStop(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode != NULL) {
    syncNodePostClose(pSyncNode);
    syncNodeRelease(pSyncNode);
  }
}

S
Shengliang Guan 已提交
135 136 137
static bool syncNodeCheckNewConfig(SSyncNode* pSyncNode, const SSyncCfg* pCfg) {
  if (!syncNodeInConfig(pSyncNode, pCfg)) return false;
  return abs(pCfg->replicaNum - pSyncNode->replicaNum) <= 1;
M
Minghao Li 已提交
138 139
}

S
Shengliang Guan 已提交
140
int32_t syncReconfig(int64_t rid, SSyncCfg* pNewCfg) {
S
Shengliang Guan 已提交
141
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
142
  if (pSyncNode == NULL) return -1;
M
Minghao Li 已提交
143

M
Minghao Li 已提交
144
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
S
Shengliang Guan 已提交
145
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
146
    terrno = TSDB_CODE_SYN_NEW_CONFIG_ERROR;
S
Shengliang Guan 已提交
147
    sError("vgId:%d, failed to reconfig since invalid new config", pSyncNode->vgId);
M
Minghao Li 已提交
148
    return -1;
M
Minghao Li 已提交
149
  }
150

S
Shengliang Guan 已提交
151 152
  syncNodeUpdateNewConfigIndex(pSyncNode, pNewCfg);
  syncNodeDoConfigChange(pSyncNode, pNewCfg, SYNC_INDEX_INVALID);
S
Shengliang Guan 已提交
153

M
Minghao Li 已提交
154 155 156 157
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    syncNodeStopHeartbeatTimer(pSyncNode);

    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
S
Shengliang Guan 已提交
158
      syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]);
M
Minghao Li 已提交
159 160 161
    }

    syncNodeStartHeartbeatTimer(pSyncNode);
S
Shengliang Guan 已提交
162
    // syncNodeReplicate(pSyncNode);
M
Minghao Li 已提交
163
  }
S
Shengliang Guan 已提交
164

S
Shengliang Guan 已提交
165
  syncNodeRelease(pSyncNode);
S
Shengliang Guan 已提交
166
  return 0;
M
Minghao Li 已提交
167
}
M
Minghao Li 已提交
168

S
Shengliang Guan 已提交
169 170 171 172
int32_t syncProcessMsg(int64_t rid, SRpcMsg* pMsg) {
  int32_t code = -1;
  if (!syncIsInit()) return code;

S
Shengliang Guan 已提交
173
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
174 175
  if (pSyncNode == NULL) return code;

S
Shengliang Guan 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  switch (pMsg->msgType) {
    case TDMT_SYNC_HEARTBEAT:
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_HEARTBEAT_REPLY:
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_TIMEOUT:
      code = syncNodeOnTimeout(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_CLIENT_REQUEST:
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
      break;
    case TDMT_SYNC_REQUEST_VOTE:
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_APPEND_ENTRIES:
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_SNAPSHOT_SEND:
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_SNAPSHOT_RSP:
S
Shengliang Guan 已提交
205
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
S
Shengliang Guan 已提交
206 207 208 209 210
      break;
    case TDMT_SYNC_LOCAL_CMD:
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
      break;
    default:
211
      terrno = TSDB_CODE_MSG_NOT_PROCESSED;
S
Shengliang Guan 已提交
212
      code = -1;
M
Minghao Li 已提交
213 214
  }

S
Shengliang Guan 已提交
215
  syncNodeRelease(pSyncNode);
216 217 218 219
  if (code != 0) {
    sDebug("vgId:%d, failed to process sync msg:%p type:%s since 0x%x", pSyncNode->vgId, pMsg, TMSG_INFO(pMsg->msgType),
           terrno);
  }
S
Shengliang Guan 已提交
220
  return code;
221 222
}

S
Shengliang Guan 已提交
223
int32_t syncLeaderTransfer(int64_t rid) {
S
Shengliang Guan 已提交
224
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
225
  if (pSyncNode == NULL) return -1;
226

S
Shengliang Guan 已提交
227
  int32_t ret = syncNodeLeaderTransfer(pSyncNode);
S
Shengliang Guan 已提交
228
  syncNodeRelease(pSyncNode);
229 230 231
  return ret;
}

232
int32_t syncSendTimeoutRsp(int64_t rid, int64_t seq) {
S
Shengliang Guan 已提交
233
  SSyncNode* pNode = syncNodeAcquire(rid);
234
  if (pNode == NULL) return -1;
S
Shengliang Guan 已提交
235 236

  SRpcMsg rpcMsg = {0};
237
  int32_t ret = syncRespMgrGetAndDel(pNode->pSyncRespMgr, seq, &rpcMsg.info);
S
Shengliang Guan 已提交
238 239 240
  rpcMsg.code = TSDB_CODE_SYN_TIMEOUT;

  syncNodeRelease(pNode);
241
  if (ret == 1) {
242
    sInfo("send timeout response, seq:%" PRId64 " handle:%p ahandle:%p", seq, rpcMsg.info.handle, rpcMsg.info.ahandle);
243
    rpcSendResponse(&rpcMsg);
244 245
    return 0;
  } else {
246
    sError("no message handle to send timeout response, seq:%" PRId64, seq);
247
    return -1;
248
  }
S
Shengliang Guan 已提交
249 250
}

M
Minghao Li 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
SyncIndex syncMinMatchIndex(SSyncNode* pSyncNode) {
  SyncIndex minMatchIndex = SYNC_INDEX_INVALID;

  if (pSyncNode->peersNum > 0) {
    minMatchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[0]));
  }

  for (int32_t i = 1; i < pSyncNode->peersNum; ++i) {
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
    if (matchIndex < minMatchIndex) {
      minMatchIndex = matchIndex;
    }
  }
  return minMatchIndex;
}

267
int32_t syncBeginSnapshot(int64_t rid, int64_t lastApplyIndex) {
S
Shengliang Guan 已提交
268
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
269
  if (pSyncNode == NULL) {
270
    sError("sync begin snapshot error");
271 272
    return -1;
  }
273

274 275
  int32_t code = 0;

M
Minghao Li 已提交
276
  if (syncNodeIsMnode(pSyncNode)) {
M
Minghao Li 已提交
277 278 279
    // mnode
    int64_t logRetention = SYNC_MNODE_LOG_RETENTION;

M
Minghao Li 已提交
280 281 282
    SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
    SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore);
    int64_t   logNum = endIndex - beginIndex;
M
Minghao Li 已提交
283 284 285
    bool      isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore);

    if (isEmpty || (!isEmpty && logNum < logRetention)) {
S
Shengliang Guan 已提交
286 287
      sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", log-num:%" PRId64 ", empty:%d, do not delete wal",
              lastApplyIndex, logNum, isEmpty);
S
Shengliang Guan 已提交
288
      syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
289 290 291
      return 0;
    }

M
Minghao Li 已提交
292 293 294
    goto _DEL_WAL;

  } else {
295 296 297 298 299 300 301 302 303 304 305 306
    lastApplyIndex -= SYNC_VNODE_LOG_RETENTION;

    SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
    SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore);
    bool      isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore);

    if (isEmpty || !(lastApplyIndex >= beginIndex && lastApplyIndex <= endIndex)) {
      sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", empty:%d, do not delete wal", lastApplyIndex, isEmpty);
      syncNodeRelease(pSyncNode);
      return 0;
    }

M
Minghao Li 已提交
307 308 309 310 311 312 313 314 315 316
    // vnode
    if (pSyncNode->replicaNum > 1) {
      // multi replicas

      if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);

        for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
          int64_t matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
          if (lastApplyIndex > matchIndex) {
317 318 319 320
            sNTrace(pSyncNode,
                    "new-snapshot-index:%" PRId64 " is greater than match-index:%" PRId64
                    " of dnode:%d, do not delete wal",
                    lastApplyIndex, matchIndex, DID(&pSyncNode->peersId[i]));
M
Minghao Li 已提交
321

S
Shengliang Guan 已提交
322
            syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
323 324 325 326 327 328
            return 0;
          }
        }

      } else if (pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER) {
        if (lastApplyIndex > pSyncNode->minMatchIndex) {
S
Shengliang Guan 已提交
329 330 331
          sNTrace(pSyncNode,
                  "new-snapshot-index:%" PRId64 " is greater than min-match-index:%" PRId64 ", do not delete wal",
                  lastApplyIndex, pSyncNode->minMatchIndex);
S
Shengliang Guan 已提交
332
          syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
333 334 335 336
          return 0;
        }

      } else if (pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE) {
S
Shengliang Guan 已提交
337
        sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " candidate, do not delete wal", lastApplyIndex);
S
Shengliang Guan 已提交
338
        syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
339 340 341
        return 0;

      } else {
S
Shengliang Guan 已提交
342
        sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " unknown state, do not delete wal", lastApplyIndex);
S
Shengliang Guan 已提交
343
        syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
344 345 346 347 348 349 350 351 352
        return 0;
      }

      goto _DEL_WAL;

    } else {
      // one replica

      goto _DEL_WAL;
353 354 355
    }
  }

M
Minghao Li 已提交
356
_DEL_WAL:
357

M
Minghao Li 已提交
358
  do {
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
    SyncIndex          snapshotVer = walGetSnapshotVer(pData->pWal);
    SyncIndex          walCommitVer = walGetCommittedVer(pData->pWal);
    SyncIndex          wallastVer = walGetLastVer(pData->pWal);
    if (lastApplyIndex <= walCommitVer) {
      SyncIndex snapshottingIndex = atomic_load_64(&pSyncNode->snapshottingIndex);

      if (snapshottingIndex == SYNC_INDEX_INVALID) {
        atomic_store_64(&pSyncNode->snapshottingIndex, lastApplyIndex);
        pSyncNode->snapshottingTime = taosGetTimestampMs();

        code = walBeginSnapshot(pData->pWal, lastApplyIndex);
        if (code == 0) {
          sNTrace(pSyncNode, "wal snapshot begin, index:%" PRId64 ", last apply index:%" PRId64,
                  pSyncNode->snapshottingIndex, lastApplyIndex);
        } else {
          sNError(pSyncNode, "wal snapshot begin error since:%s, index:%" PRId64 ", last apply index:%" PRId64,
                  terrstr(terrno), pSyncNode->snapshottingIndex, lastApplyIndex);
          atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
        }
379

M
Minghao Li 已提交
380
      } else {
381 382
        sNTrace(pSyncNode, "snapshotting for %" PRId64 ", do not delete wal for new-snapshot-index:%" PRId64,
                snapshottingIndex, lastApplyIndex);
M
Minghao Li 已提交
383
      }
384
    }
M
Minghao Li 已提交
385
  } while (0);
386

S
Shengliang Guan 已提交
387
  syncNodeRelease(pSyncNode);
388 389 390 391
  return code;
}

int32_t syncEndSnapshot(int64_t rid) {
S
Shengliang Guan 已提交
392
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
393
  if (pSyncNode == NULL) {
394
    sError("sync end snapshot error");
395 396 397
    return -1;
  }

398 399 400 401
  int32_t code = 0;
  if (atomic_load_64(&pSyncNode->snapshottingIndex) != SYNC_INDEX_INVALID) {
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
    code = walEndSnapshot(pData->pWal);
M
Minghao Li 已提交
402
    if (code != 0) {
403
      sNError(pSyncNode, "wal snapshot end error since:%s", terrstr());
S
Shengliang Guan 已提交
404
      syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
405 406
      return -1;
    } else {
S
Shengliang Guan 已提交
407
      sNTrace(pSyncNode, "wal snapshot end, index:%" PRId64, atomic_load_64(&pSyncNode->snapshottingIndex));
M
Minghao Li 已提交
408 409
      atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
    }
410
  }
411

S
Shengliang Guan 已提交
412
  syncNodeRelease(pSyncNode);
413 414 415
  return code;
}

M
Minghao Li 已提交
416
int32_t syncStepDown(int64_t rid, SyncTerm newTerm) {
S
Shengliang Guan 已提交
417
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
M
Minghao Li 已提交
418
  if (pSyncNode == NULL) {
419
    sError("sync step down error");
M
Minghao Li 已提交
420 421 422
    return -1;
  }

M
Minghao Li 已提交
423
  syncNodeStepDown(pSyncNode, newTerm);
S
Shengliang Guan 已提交
424
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
425
  return 0;
M
Minghao Li 已提交
426 427
}

428
bool syncNodeIsReadyForRead(SSyncNode* pSyncNode) {
429
  if (pSyncNode == NULL) {
430
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
431
    sError("sync ready for read error");
432 433
    return false;
  }
M
Minghao Li 已提交
434

435 436 437 438 439 440
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
    terrno = TSDB_CODE_SYN_NOT_LEADER;
    return false;
  }

  if (pSyncNode->restoreFinish) {
441
    return true;
M
Minghao Li 已提交
442 443
  }

444
  bool ready = false;
445 446 447
  if (!pSyncNode->pFsm->FpApplyQueueEmptyCb(pSyncNode->pFsm)) {
    // apply queue not empty
    ready = false;
M
Minghao Li 已提交
448

449 450 451 452 453 454 455 456 457 458 459 460 461
  } else {
    if (!pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore)) {
      SyncIndex       lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
      SSyncRaftEntry* pEntry = NULL;
      SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
      LRUHandle*      h = taosLRUCacheLookup(pCache, &lastIndex, sizeof(lastIndex));
      int32_t         code = 0;
      if (h) {
        pEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
        code = 0;

        pSyncNode->pLogStore->cacheHit++;
        sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", lastIndex, pEntry->bytes, pEntry);
M
Minghao Li 已提交
462

463 464 465
      } else {
        pSyncNode->pLogStore->cacheMiss++;
        sNTrace(pSyncNode, "miss cache index:%" PRId64, lastIndex);
M
Minghao Li 已提交
466

467 468
        code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, lastIndex, &pEntry);
      }
469

470 471 472
      if (code == 0 && pEntry != NULL) {
        if (pEntry->originalRpcType == TDMT_SYNC_NOOP && pEntry->term == pSyncNode->pRaftStore->currentTerm) {
          ready = true;
473
        }
474

475 476 477 478
        if (h) {
          taosLRUCacheRelease(pCache, h, false);
        } else {
          syncEntryDestroy(pEntry);
479
        }
480 481 482 483
      }
    }
  }

484
  if (!ready) {
485
    terrno = TSDB_CODE_SYN_RESTORING;
486
  }
487

488 489 490 491 492 493 494 495 496 497 498 499
  return ready;
}

bool syncIsReadyForRead(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode == NULL) {
    sError("sync ready for read error");
    return false;
  }

  bool ready = syncNodeIsReadyForRead(pSyncNode);

500 501
  syncNodeRelease(pSyncNode);
  return ready;
M
Minghao Li 已提交
502
}
M
Minghao Li 已提交
503

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
bool syncSnapshotSending(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode == NULL) {
    return false;
  }

  bool b = syncNodeSnapshotSending(pSyncNode);
  syncNodeRelease(pSyncNode);
  return b;
}

bool syncSnapshotRecving(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode == NULL) {
    return false;
  }

  bool b = syncNodeSnapshotRecving(pSyncNode);
  syncNodeRelease(pSyncNode);
  return b;
}

M
Minghao Li 已提交
526 527
int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode) {
  if (pSyncNode->peersNum == 0) {
S
Shengliang Guan 已提交
528
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
M
Minghao Li 已提交
529 530
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
M
Minghao Li 已提交
531
  }
M
Minghao Li 已提交
532

533
  int32_t ret = 0;
534
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && pSyncNode->replicaNum > 1) {
535
    SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
536 537 538 539 540 541 542
    if (pSyncNode->peersNum == 2) {
      SyncIndex matchIndex0 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[0]));
      SyncIndex matchIndex1 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[1]));
      if (matchIndex1 > matchIndex0) {
        newLeader = (pSyncNode->peersNodeInfo)[1];
      }
    }
543 544 545
    ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
  }

M
Minghao Li 已提交
546
  return ret;
M
Minghao Li 已提交
547 548
}

M
Minghao Li 已提交
549 550
int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader) {
  if (pSyncNode->replicaNum == 1) {
S
Shengliang Guan 已提交
551
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
M
Minghao Li 已提交
552 553
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
M
Minghao Li 已提交
554
  }
555

S
Shengliang Guan 已提交
556
  sNTrace(pSyncNode, "begin leader transfer to %s:%u", newLeader.nodeFqdn, newLeader.nodePort);
M
Minghao Li 已提交
557

558 559 560 561
  SRpcMsg rpcMsg = {0};
  (void)syncBuildLeaderTransfer(&rpcMsg, pSyncNode->vgId);

  SyncLeaderTransfer* pMsg = rpcMsg.pCont;
562
  pMsg->newLeaderId.addr = SYNC_ADDR(&newLeader);
M
Minghao Li 已提交
563 564 565
  pMsg->newLeaderId.vgId = pSyncNode->vgId;
  pMsg->newNodeInfo = newLeader;

S
Shengliang Guan 已提交
566
  int32_t ret = syncNodePropose(pSyncNode, &rpcMsg, false, NULL);
S
Shengliang Guan 已提交
567 568
  rpcFreeCont(rpcMsg.pCont);
  return ret;
M
Minghao Li 已提交
569 570
}

571 572
SSyncState syncGetState(int64_t rid) {
  SSyncState state = {.state = TAOS_SYNC_STATE_ERROR};
M
Minghao Li 已提交
573

S
Shengliang Guan 已提交
574
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
575 576 577
  if (pSyncNode != NULL) {
    state.state = pSyncNode->state;
    state.restored = pSyncNode->restoreFinish;
578 579 580 581 582
    if (pSyncNode->vgId != 1) {
      state.canRead = syncNodeIsReadyForRead(pSyncNode);
    } else {
      state.canRead = state.restored;
    }
583
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
584 585
  }

586
  return state;
M
Minghao Li 已提交
587 588
}

589
#if 0
590 591 592 593 594
int32_t syncGetSnapshotByIndex(int64_t rid, SyncIndex index, SSnapshot* pSnapshot) {
  if (index < SYNC_INDEX_BEGIN) {
    return -1;
  }

S
Shengliang Guan 已提交
595
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
596 597 598
  if (pSyncNode == NULL) {
    return -1;
  }
599
  ASSERT(rid == pSyncNode->rid);
600 601 602 603 604

  SSyncRaftEntry* pEntry = NULL;
  int32_t         code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, index, &pEntry);
  if (code != 0) {
    if (pEntry != NULL) {
B
Benguang Zhao 已提交
605
      syncEntryDestroy(pEntry);
606
    }
S
Shengliang Guan 已提交
607
    syncNodeRelease(pSyncNode);
608 609
    return -1;
  }
610
  ASSERT(pEntry != NULL);
611 612 613 614 615 616

  pSnapshot->data = NULL;
  pSnapshot->lastApplyIndex = index;
  pSnapshot->lastApplyTerm = pEntry->term;
  pSnapshot->lastConfigIndex = syncNodeGetSnapshotConfigIndex(pSyncNode, index);

617
  syncEntryDestroy(pEntry);
S
Shengliang Guan 已提交
618
  syncNodeRelease(pSyncNode);
619 620 621
  return 0;
}

622
int32_t syncGetSnapshotMeta(int64_t rid, struct SSnapshotMeta* sMeta) {
S
Shengliang Guan 已提交
623
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
624 625 626
  if (pSyncNode == NULL) {
    return -1;
  }
627
  ASSERT(rid == pSyncNode->rid);
628
  sMeta->lastConfigIndex = pSyncNode->raftCfg.lastConfigIndex;
629

630
  sTrace("vgId:%d, get snapshot meta, lastConfigIndex:%" PRId64, pSyncNode->vgId, pSyncNode->raftCfg.lastConfigIndex);
631

S
Shengliang Guan 已提交
632
  syncNodeRelease(pSyncNode);
633 634 635
  return 0;
}

636
int32_t syncGetSnapshotMetaByIndex(int64_t rid, SyncIndex snapshotIndex, struct SSnapshotMeta* sMeta) {
S
Shengliang Guan 已提交
637
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
638 639 640
  if (pSyncNode == NULL) {
    return -1;
  }
641
  ASSERT(rid == pSyncNode->rid);
642

643 644
  ASSERT(pSyncNode->raftCfg.configIndexCount >= 1);
  SyncIndex lastIndex = (pSyncNode->raftCfg.configIndexArr)[0];
645

646 647 648 649
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotIndex) {
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
650 651 652
    }
  }
  sMeta->lastConfigIndex = lastIndex;
653
  sTrace("vgId:%d, get snapshot meta by index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId, snapshotIndex,
S
Shengliang Guan 已提交
654
         sMeta->lastConfigIndex);
655

S
Shengliang Guan 已提交
656
  syncNodeRelease(pSyncNode);
657 658
  return 0;
}
659
#endif
660

661
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
662 663
  ASSERT(pSyncNode->raftCfg.configIndexCount >= 1);
  SyncIndex lastIndex = (pSyncNode->raftCfg.configIndexArr)[0];
664

665 666 667 668
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
669 670
    }
  }
S
Shengliang Guan 已提交
671
  sTrace("vgId:%d, sync get last config index, index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId,
S
Shengliang Guan 已提交
672
         snapshotLastApplyIndex, lastIndex);
673 674 675 676

  return lastIndex;
}

677 678
void syncGetRetryEpSet(int64_t rid, SEpSet* pEpSet) {
  pEpSet->numOfEps = 0;
M
Minghao Li 已提交
679

S
Shengliang Guan 已提交
680
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
681
  if (pSyncNode == NULL) return;
M
Minghao Li 已提交
682

683
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.replicaNum; ++i) {
S
Shengliang Guan 已提交
684
    SEp* pEp = &pEpSet->eps[i];
685 686
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
S
Shengliang Guan 已提交
687
    pEpSet->numOfEps++;
688
    sDebug("vgId:%d, sync get retry epset, index:%d %s:%d", pSyncNode->vgId, i, pEp->fqdn, pEp->port);
M
Minghao Li 已提交
689
  }
M
Minghao Li 已提交
690
  if (pEpSet->numOfEps > 0) {
691
    pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
M
Minghao Li 已提交
692 693
  }

S
Shengliang Guan 已提交
694
  sInfo("vgId:%d, sync get retry epset numOfEps:%d inUse:%d", pSyncNode->vgId, pEpSet->numOfEps, pEpSet->inUse);
S
Shengliang Guan 已提交
695
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
696 697
}

S
Shengliang Guan 已提交
698
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
S
Shengliang Guan 已提交
699
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
700
  if (pSyncNode == NULL) {
701
    sError("sync propose error");
M
Minghao Li 已提交
702
    return -1;
703
  }
704

S
Shengliang Guan 已提交
705
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak, seq);
S
Shengliang Guan 已提交
706
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
707 708
  return ret;
}
M
Minghao Li 已提交
709

S
Shengliang Guan 已提交
710
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
S
Shengliang Guan 已提交
711 712
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
    terrno = TSDB_CODE_SYN_NOT_LEADER;
S
Shengliang Guan 已提交
713
    sNError(pSyncNode, "sync propose not leader, type:%s", TMSG_INFO(pMsg->msgType));
S
Shengliang Guan 已提交
714 715
    return -1;
  }
716

S
Shengliang Guan 已提交
717 718 719 720 721 722 723
  // not restored, vnode enable
  if (!pSyncNode->restoreFinish && pSyncNode->vgId != 1) {
    terrno = TSDB_CODE_SYN_PROPOSE_NOT_READY;
    sNError(pSyncNode, "failed to sync propose since not ready, type:%s, last:%" PRId64 ", cmt:%" PRId64,
            TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
    return -1;
  }
724

725
  // heartbeat timeout
726
  if (syncNodeHeartbeatReplyTimeout(pSyncNode)) {
727 728 729 730 731 732
    terrno = TSDB_CODE_SYN_PROPOSE_NOT_READY;
    sNError(pSyncNode, "failed to sync propose since hearbeat timeout, type:%s, last:%" PRId64 ", cmt:%" PRId64,
            TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
    return -1;
  }

S
Shengliang Guan 已提交
733 734 735
  // optimized one replica
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
    SyncIndex retIndex;
736
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
S
Shengliang Guan 已提交
737 738 739
    if (code == 0) {
      pMsg->info.conn.applyIndex = retIndex;
      pMsg->info.conn.applyTerm = pSyncNode->pRaftStore->currentTerm;
740 741 742
      sTrace("vgId:%d, propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
             TMSG_INFO(pMsg->msgType));
      return 1;
M
Minghao Li 已提交
743
    } else {
S
Shengliang Guan 已提交
744
      terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
745
      sError("vgId:%d, failed to propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
S
Shengliang Guan 已提交
746
             TMSG_INFO(pMsg->msgType));
747
      return -1;
748
    }
S
Shengliang Guan 已提交
749
  } else {
S
Shengliang Guan 已提交
750 751
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
752
    SRpcMsg   rpcMsg = {0};
S
Shengliang Guan 已提交
753
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
754 755 756 757
    if (code != 0) {
      sError("vgId:%d, failed to propose msg while serialize since %s", pSyncNode->vgId, terrstr());
      (void)syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum);
      return -1;
M
Minghao Li 已提交
758
    }
759

760 761 762 763 764
    sNTrace(pSyncNode, "propose msg, type:%s", TMSG_INFO(pMsg->msgType));
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
    if (code != 0) {
      sError("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
      (void)syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum);
M
Minghao Li 已提交
765
    }
M
Minghao Li 已提交
766

S
Shengliang Guan 已提交
767
    if (seq != NULL) *seq = seqNum;
768
    return code;
M
Minghao Li 已提交
769
  }
M
Minghao Li 已提交
770 771
}

S
Shengliang Guan 已提交
772
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId) {
773 774 775 776 777
  pSyncTimer->pTimer = NULL;
  pSyncTimer->counter = 0;
  pSyncTimer->timerMS = pSyncNode->hbBaseLine;
  pSyncTimer->timerCb = syncNodeEqPeerHeartbeatTimer;
  pSyncTimer->destId = destId;
M
Minghao Li 已提交
778
  pSyncTimer->timeStamp = taosGetTimestampMs();
779 780 781 782
  atomic_store_64(&pSyncTimer->logicClock, 0);
  return 0;
}

S
Shengliang Guan 已提交
783
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
784
  int32_t ret = 0;
S
Shengliang Guan 已提交
785
  int64_t tsNow = taosGetTimestampMs();
S
Shengliang Guan 已提交
786
  if (syncIsInit()) {
787 788 789 790 791 792
    SSyncHbTimerData* pData = syncHbTimerDataAcquire(pSyncTimer->hbDataRid);
    if (pData == NULL) {
      pData = taosMemoryMalloc(sizeof(SSyncHbTimerData));
      pData->rid = syncHbTimerDataAdd(pData);
    }
    pSyncTimer->hbDataRid = pData->rid;
S
Shengliang Guan 已提交
793
    pSyncTimer->timeStamp = tsNow;
794 795

    pData->syncNodeRid = pSyncNode->rid;
796 797 798
    pData->pTimer = pSyncTimer;
    pData->destId = pSyncTimer->destId;
    pData->logicClock = pSyncTimer->logicClock;
S
Shengliang Guan 已提交
799
    pData->execTime = tsNow + pSyncTimer->timerMS;
M
Minghao Li 已提交
800

801 802
    taosTmrReset(pSyncTimer->timerCb, pSyncTimer->timerMS / HEARTBEAT_TICK_NUM, (void*)(pData->rid),
                 syncEnv()->pTimerManager, &pSyncTimer->pTimer);
803 804 805 806 807 808
  } else {
    sError("vgId:%d, start ctrl hb timer error, sync env is stop", pSyncNode->vgId);
  }
  return ret;
}

S
Shengliang Guan 已提交
809
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
810 811 812 813
  int32_t ret = 0;
  atomic_add_fetch_64(&pSyncTimer->logicClock, 1);
  taosTmrStop(pSyncTimer->pTimer);
  pSyncTimer->pTimer = NULL;
814 815
  syncHbTimerDataRemove(pSyncTimer->hbDataRid);
  pSyncTimer->hbDataRid = -1;
816 817 818
  return ret;
}

819
int32_t syncNodeLogStoreRestoreOnNeed(SSyncNode* pNode) {
S
Shengliang Guan 已提交
820 821 822
  ASSERTS(pNode->pLogStore != NULL, "log store not created");
  ASSERTS(pNode->pFsm != NULL, "pFsm not registered");
  ASSERTS(pNode->pFsm->FpGetSnapshotInfo != NULL, "FpGetSnapshotInfo not registered");
823 824 825
  SSnapshot snapshot = {0};
  pNode->pFsm->FpGetSnapshotInfo(pNode->pFsm, &snapshot);

826 827 828 829 830 831 832 833 834 835 836 837 838
  SyncIndex commitIndex = snapshot.lastApplyIndex;
  SyncIndex firstVer = pNode->pLogStore->syncLogBeginIndex(pNode->pLogStore);
  SyncIndex lastVer = pNode->pLogStore->syncLogLastIndex(pNode->pLogStore);
  if (lastVer < commitIndex || firstVer > commitIndex + 1) {
    if (pNode->pLogStore->syncLogRestoreFromSnapshot(pNode->pLogStore, commitIndex)) {
      sError("vgId:%d, failed to restore log store from snapshot since %s. lastVer: %" PRId64 ", snapshotVer: %" PRId64,
             pNode->vgId, terrstr(), lastVer, commitIndex);
      return -1;
    }
  }
  return 0;
}

M
Minghao Li 已提交
839
// open/close --------------
S
Shengliang Guan 已提交
840 841
SSyncNode* syncNodeOpen(SSyncInfo* pSyncInfo) {
  SSyncNode* pSyncNode = taosMemoryCalloc(1, sizeof(SSyncNode));
842 843 844 845
  if (pSyncNode == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }
M
Minghao Li 已提交
846

M
Minghao Li 已提交
847 848 849 850
  if (!taosDirExist((char*)(pSyncInfo->path))) {
    if (taosMkDir(pSyncInfo->path) != 0) {
      terrno = TAOS_SYSTEM_ERROR(errno);
      sError("failed to create dir:%s since %s", pSyncInfo->path, terrstr());
851
      goto _error;
M
Minghao Li 已提交
852
    }
853
  }
M
Minghao Li 已提交
854

855 856 857
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
  snprintf(pSyncNode->raftStorePath, sizeof(pSyncNode->raftStorePath), "%s%sraft_store.json", pSyncInfo->path,
           TD_DIRSEP);
S
Shengliang Guan 已提交
858
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
859

860
  if (!taosCheckExistFile(pSyncNode->configPath)) {
M
Minghao Li 已提交
861
    // create a new raft config file
862
    sInfo("vgId:%d, create a new raft config file", pSyncNode->vgId);
863 864 865 866 867 868 869 870 871 872
    pSyncNode->raftCfg.isStandBy = pSyncInfo->isStandBy;
    pSyncNode->raftCfg.snapshotStrategy = pSyncInfo->snapshotStrategy;
    pSyncNode->raftCfg.lastConfigIndex = SYNC_INDEX_INVALID;
    pSyncNode->raftCfg.batchSize = pSyncInfo->batchSize;
    pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
    pSyncNode->raftCfg.configIndexCount = 1;
    pSyncNode->raftCfg.configIndexArr[0] = -1;

    if (syncWriteCfgFile(pSyncNode) != 0) {
      sError("vgId:%d, failed to create sync cfg file", pSyncNode->vgId);
H
Hongze Cheng 已提交
873
      goto _error;
874
    }
875 876
  } else {
    // update syncCfg by raft_config.json
877 878
    if (syncReadCfgFile(pSyncNode) != 0) {
      sError("vgId:%d, failed to read sync cfg file", pSyncNode->vgId);
H
Hongze Cheng 已提交
879
      goto _error;
880
    }
S
Shengliang Guan 已提交
881

882
    if (pSyncInfo->syncCfg.replicaNum > 0 && syncIsConfigChanged(&pSyncNode->raftCfg.cfg, &pSyncInfo->syncCfg)) {
S
Shengliang Guan 已提交
883
      sInfo("vgId:%d, use sync config from input options and write to cfg file", pSyncNode->vgId);
884 885 886
      pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
      if (syncWriteCfgFile(pSyncNode) != 0) {
        sError("vgId:%d, failed to write sync cfg file", pSyncNode->vgId);
S
Shengliang Guan 已提交
887 888
        goto _error;
      }
S
Shengliang Guan 已提交
889
    } else {
890 891
      sInfo("vgId:%d, use sync config from sync cfg file", pSyncNode->vgId);
      pSyncInfo->syncCfg = pSyncNode->raftCfg.cfg;
S
Shengliang Guan 已提交
892
    }
M
Minghao Li 已提交
893 894
  }

M
Minghao Li 已提交
895
  // init by SSyncInfo
M
Minghao Li 已提交
896
  pSyncNode->vgId = pSyncInfo->vgId;
S
Shengliang Guan 已提交
897
  SSyncCfg* pCfg = &pSyncNode->raftCfg.cfg;
S
Shengliang Guan 已提交
898
  sInfo("vgId:%d, start to open sync node, replica:%d selfIndex:%d", pSyncNode->vgId, pCfg->replicaNum, pCfg->myIndex);
S
Shengliang Guan 已提交
899 900
  for (int32_t i = 0; i < pCfg->replicaNum; ++i) {
    SNodeInfo* pNode = &pCfg->nodeInfo[i];
S
Shengliang Guan 已提交
901
    (void)tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort);
902 903
    sInfo("vgId:%d, index:%d ep:%s:%u dnode:%d cluster:%" PRId64, pSyncNode->vgId, i, pNode->nodeFqdn, pNode->nodePort,
          pNode->nodeId, pNode->clusterId);
S
Shengliang Guan 已提交
904 905
  }

M
Minghao Li 已提交
906
  pSyncNode->pWal = pSyncInfo->pWal;
S
Shengliang Guan 已提交
907
  pSyncNode->msgcb = pSyncInfo->msgcb;
S
Shengliang Guan 已提交
908 909 910
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
M
Minghao Li 已提交
911

B
Benguang Zhao 已提交
912 913 914
  // create raft log ring buffer
  pSyncNode->pLogBuf = syncLogBufferCreate();
  if (pSyncNode->pLogBuf == NULL) {
915
    sError("failed to init sync log buffer since %s. vgId:%d", terrstr(), pSyncNode->vgId);
B
Benguang Zhao 已提交
916 917 918
    goto _error;
  }

M
Minghao Li 已提交
919
  // init internal
920
  pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
921
  if (!syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId)) {
S
Shengliang Guan 已提交
922
    sError("vgId:%d, failed to determine my raft member id", pSyncNode->vgId);
H
Hongze Cheng 已提交
923
    goto _error;
924
  }
M
Minghao Li 已提交
925

M
Minghao Li 已提交
926
  // init peersNum, peers, peersId
927
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.replicaNum - 1;
S
Shengliang Guan 已提交
928
  int32_t j = 0;
929 930 931 932
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.replicaNum; ++i) {
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
M
Minghao Li 已提交
933 934 935
      j++;
    }
  }
S
Shengliang Guan 已提交
936
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
937
    if (!syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i])) {
S
Shengliang Guan 已提交
938
      sError("vgId:%d, failed to determine raft member id, peer:%d", pSyncNode->vgId, i);
H
Hongze Cheng 已提交
939
      goto _error;
940
    }
M
Minghao Li 已提交
941
  }
M
Minghao Li 已提交
942

M
Minghao Li 已提交
943
  // init replicaNum, replicasId
944 945 946
  pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.replicaNum; ++i) {
    if (!syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i])) {
S
Shengliang Guan 已提交
947
      sError("vgId:%d, failed to determine raft member id, replica:%d", pSyncNode->vgId, i);
H
Hongze Cheng 已提交
948
      goto _error;
949
    }
M
Minghao Li 已提交
950 951
  }

M
Minghao Li 已提交
952
  // init raft algorithm
M
Minghao Li 已提交
953
  pSyncNode->pFsm = pSyncInfo->pFsm;
954
  pSyncInfo->pFsm = NULL;
955
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
M
Minghao Li 已提交
956 957
  pSyncNode->leaderCache = EMPTY_RAFT_ID;

M
Minghao Li 已提交
958
  // init life cycle outside
M
Minghao Li 已提交
959

M
Minghao Li 已提交
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
  // TLA+ Spec
  // InitHistoryVars == /\ elections = {}
  //                    /\ allLogs   = {}
  //                    /\ voterLog  = [i \in Server |-> [j \in {} |-> <<>>]]
  // InitServerVars == /\ currentTerm = [i \in Server |-> 1]
  //                   /\ state       = [i \in Server |-> Follower]
  //                   /\ votedFor    = [i \in Server |-> Nil]
  // InitCandidateVars == /\ votesResponded = [i \in Server |-> {}]
  //                      /\ votesGranted   = [i \in Server |-> {}]
  // \* The values nextIndex[i][i] and matchIndex[i][i] are never read, since the
  // \* leader does not send itself messages. It's still easier to include these
  // \* in the functions.
  // InitLeaderVars == /\ nextIndex  = [i \in Server |-> [j \in Server |-> 1]]
  //                   /\ matchIndex = [i \in Server |-> [j \in Server |-> 0]]
  // InitLogVars == /\ log          = [i \in Server |-> << >>]
  //                /\ commitIndex  = [i \in Server |-> 0]
  // Init == /\ messages = [m \in {} |-> 0]
  //         /\ InitHistoryVars
  //         /\ InitServerVars
  //         /\ InitCandidateVars
  //         /\ InitLeaderVars
  //         /\ InitLogVars
  //

M
Minghao Li 已提交
984
  // init TLA+ server vars
M
syncInt  
Minghao Li 已提交
985
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
M
Minghao Li 已提交
986
  pSyncNode->pRaftStore = raftStoreOpen(pSyncNode->raftStorePath);
987
  if (pSyncNode->pRaftStore == NULL) {
S
Shengliang Guan 已提交
988
    sError("vgId:%d, failed to open raft store at path %s", pSyncNode->vgId, pSyncNode->raftStorePath);
989 990
    goto _error;
  }
M
Minghao Li 已提交
991

M
Minghao Li 已提交
992
  // init TLA+ candidate vars
M
Minghao Li 已提交
993
  pSyncNode->pVotesGranted = voteGrantedCreate(pSyncNode);
994
  if (pSyncNode->pVotesGranted == NULL) {
S
Shengliang Guan 已提交
995
    sError("vgId:%d, failed to create VotesGranted", pSyncNode->vgId);
996 997
    goto _error;
  }
M
Minghao Li 已提交
998
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
999
  if (pSyncNode->pVotesRespond == NULL) {
S
Shengliang Guan 已提交
1000
    sError("vgId:%d, failed to create VotesRespond", pSyncNode->vgId);
1001 1002
    goto _error;
  }
M
Minghao Li 已提交
1003

M
Minghao Li 已提交
1004 1005
  // init TLA+ leader vars
  pSyncNode->pNextIndex = syncIndexMgrCreate(pSyncNode);
1006
  if (pSyncNode->pNextIndex == NULL) {
S
Shengliang Guan 已提交
1007
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
1008 1009
    goto _error;
  }
M
Minghao Li 已提交
1010
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
1011
  if (pSyncNode->pMatchIndex == NULL) {
S
Shengliang Guan 已提交
1012
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
1013 1014
    goto _error;
  }
M
Minghao Li 已提交
1015 1016 1017

  // init TLA+ log vars
  pSyncNode->pLogStore = logStoreCreate(pSyncNode);
1018
  if (pSyncNode->pLogStore == NULL) {
S
Shengliang Guan 已提交
1019
    sError("vgId:%d, failed to create SyncLogStore", pSyncNode->vgId);
1020 1021
    goto _error;
  }
1022 1023 1024 1025

  SyncIndex commitIndex = SYNC_INDEX_INVALID;
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    SSnapshot snapshot = {0};
1026
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
1027 1028
    if (snapshot.lastApplyIndex > commitIndex) {
      commitIndex = snapshot.lastApplyIndex;
S
Shengliang Guan 已提交
1029
      sNTrace(pSyncNode, "reset commit index by snapshot");
1030 1031 1032
    }
  }
  pSyncNode->commitIndex = commitIndex;
1033
  sInfo("vgId:%d, sync node commitIndex initialized as %" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
M
Minghao Li 已提交
1034

1035 1036 1037
  if (syncNodeLogStoreRestoreOnNeed(pSyncNode) < 0) {
    goto _error;
  }
M
Minghao Li 已提交
1038 1039
  // timer ms init
  pSyncNode->pingBaseLine = PING_TIMER_MS;
1040 1041
  pSyncNode->electBaseLine = tsElectInterval;
  pSyncNode->hbBaseLine = tsHeartbeatInterval;
M
Minghao Li 已提交
1042

M
Minghao Li 已提交
1043
  // init ping timer
M
Minghao Li 已提交
1044
  pSyncNode->pPingTimer = NULL;
M
Minghao Li 已提交
1045
  pSyncNode->pingTimerMS = pSyncNode->pingBaseLine;
M
Minghao Li 已提交
1046 1047
  atomic_store_64(&pSyncNode->pingTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->pingTimerLogicClockUser, 0);
M
Minghao Li 已提交
1048
  pSyncNode->FpPingTimerCB = syncNodeEqPingTimer;
M
Minghao Li 已提交
1049
  pSyncNode->pingTimerCounter = 0;
M
Minghao Li 已提交
1050

M
Minghao Li 已提交
1051 1052
  // init elect timer
  pSyncNode->pElectTimer = NULL;
M
Minghao Li 已提交
1053
  pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
M
Minghao Li 已提交
1054
  atomic_store_64(&pSyncNode->electTimerLogicClock, 0);
M
Minghao Li 已提交
1055
  pSyncNode->FpElectTimerCB = syncNodeEqElectTimer;
M
Minghao Li 已提交
1056 1057 1058 1059
  pSyncNode->electTimerCounter = 0;

  // init heartbeat timer
  pSyncNode->pHeartbeatTimer = NULL;
M
Minghao Li 已提交
1060
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
M
Minghao Li 已提交
1061 1062
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClockUser, 0);
M
Minghao Li 已提交
1063
  pSyncNode->FpHeartbeatTimerCB = syncNodeEqHeartbeatTimer;
M
Minghao Li 已提交
1064 1065
  pSyncNode->heartbeatTimerCounter = 0;

1066 1067 1068 1069 1070
  // init peer heartbeat timer
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
    syncHbTimerInit(pSyncNode, &(pSyncNode->peerHeartbeatTimerArr[i]), (pSyncNode->replicasId)[i]);
  }

M
Minghao Li 已提交
1071
  // tools
M
Minghao Li 已提交
1072
  pSyncNode->pSyncRespMgr = syncRespMgrCreate(pSyncNode, SYNC_RESP_TTL_MS);
1073
  if (pSyncNode->pSyncRespMgr == NULL) {
S
Shengliang Guan 已提交
1074
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
1075 1076
    goto _error;
  }
M
Minghao Li 已提交
1077

1078 1079
  // restore state
  pSyncNode->restoreFinish = false;
1080

M
Minghao Li 已提交
1081
  // snapshot senders
S
Shengliang Guan 已提交
1082
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1083
    SSyncSnapshotSender* pSender = snapshotSenderCreate(pSyncNode, i);
1084 1085 1086 1087
    if (pSender == NULL) return NULL;

    pSyncNode->senders[i] = pSender;
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
M
Minghao Li 已提交
1088 1089 1090
  }

  // snapshot receivers
1091
  pSyncNode->pNewNodeReceiver = snapshotReceiverCreate(pSyncNode, EMPTY_RAFT_ID);
1092 1093 1094
  if (pSyncNode->pNewNodeReceiver == NULL) return NULL;
  sRDebug(pSyncNode->pNewNodeReceiver, "snapshot receiver create while open sync node, data:%p",
          pSyncNode->pNewNodeReceiver);
M
Minghao Li 已提交
1095

M
Minghao Li 已提交
1096 1097 1098
  // is config changing
  pSyncNode->changing = false;

B
Benguang Zhao 已提交
1099 1100 1101
  // replication mgr
  syncNodeLogReplMgrInit(pSyncNode);

M
Minghao Li 已提交
1102 1103 1104
  // peer state
  syncNodePeerStateInit(pSyncNode);

B
Benguang Zhao 已提交
1105
  //
M
Minghao Li 已提交
1106 1107 1108
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
1109
  // start in syncNodeStart
M
Minghao Li 已提交
1110
  // start raft
M
Minghao Li 已提交
1111
  // syncNodeBecomeFollower(pSyncNode);
M
Minghao Li 已提交
1112

M
Minghao Li 已提交
1113 1114
  int64_t timeNow = taosGetTimestampMs();
  pSyncNode->startTime = timeNow;
1115
  pSyncNode->leaderTime = timeNow;
M
Minghao Li 已提交
1116 1117
  pSyncNode->lastReplicateTime = timeNow;

1118 1119 1120
  // snapshotting
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);

B
Benguang Zhao 已提交
1121 1122
  // init log buffer
  if (syncLogBufferInit(pSyncNode->pLogBuf, pSyncNode) < 0) {
1123
    sError("vgId:%d, failed to init sync log buffer since %s", pSyncNode->vgId, terrstr());
1124
    goto _error;
B
Benguang Zhao 已提交
1125 1126
  }

1127
  pSyncNode->isStart = true;
1128 1129 1130
  pSyncNode->electNum = 0;
  pSyncNode->becomeLeaderNum = 0;
  pSyncNode->configChangeNum = 0;
1131 1132
  pSyncNode->hbSlowNum = 0;
  pSyncNode->hbrSlowNum = 0;
M
Minghao Li 已提交
1133
  pSyncNode->tmrRoutineNum = 0;
1134

1135 1136
  sNInfo(pSyncNode, "sync open, node:%p electInterval:%d heartbeatInterval:%d heartbeatTimeout:%d", pSyncNode,
         tsElectInterval, tsHeartbeatInterval, tsHeartbeatTimeout);
M
Minghao Li 已提交
1137
  return pSyncNode;
1138 1139 1140

_error:
  if (pSyncInfo->pFsm) {
H
Hongze Cheng 已提交
1141 1142
    taosMemoryFree(pSyncInfo->pFsm);
    pSyncInfo->pFsm = NULL;
1143 1144 1145 1146
  }
  syncNodeClose(pSyncNode);
  pSyncNode = NULL;
  return NULL;
M
Minghao Li 已提交
1147 1148
}

M
Minghao Li 已提交
1149 1150
void syncNodeMaybeUpdateCommitBySnapshot(SSyncNode* pSyncNode) {
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
1151 1152
    SSnapshot snapshot = {0};
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1153 1154 1155 1156 1157 1158
    if (snapshot.lastApplyIndex > pSyncNode->commitIndex) {
      pSyncNode->commitIndex = snapshot.lastApplyIndex;
    }
  }
}

B
Benguang Zhao 已提交
1159
int32_t syncNodeRestore(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1160 1161
  ASSERTS(pSyncNode->pLogStore != NULL, "log store not created");
  ASSERTS(pSyncNode->pLogBuf != NULL, "ring log buffer not created");
B
Benguang Zhao 已提交
1162 1163 1164 1165

  SyncIndex lastVer = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
  SyncIndex commitIndex = pSyncNode->pLogStore->syncLogCommitIndex(pSyncNode->pLogStore);
  SyncIndex endIndex = pSyncNode->pLogBuf->endIndex;
1166 1167 1168 1169 1170 1171
  if (lastVer != -1 && endIndex != lastVer + 1) {
    terrno = TSDB_CODE_WAL_LOG_INCOMPLETE;
    sError("vgId:%d, failed to restore sync node since %s. expected lastLogIndex: %" PRId64 ", lastVer: %" PRId64 "",
           pSyncNode->vgId, terrstr(), endIndex - 1, lastVer);
    return -1;
  }
B
Benguang Zhao 已提交
1172

1173
  ASSERT(endIndex == lastVer + 1);
1174 1175
  pSyncNode->commitIndex = TMAX(pSyncNode->commitIndex, commitIndex);
  sInfo("vgId:%d, restore sync until commitIndex:%" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
B
Benguang Zhao 已提交
1176

1177
  if (syncLogBufferCommit(pSyncNode->pLogBuf, pSyncNode, pSyncNode->commitIndex) < 0) {
B
Benguang Zhao 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
    return -1;
  }

  return 0;
}

int32_t syncNodeStart(SSyncNode* pSyncNode) {
  // start raft
  if (pSyncNode->replicaNum == 1) {
    raftStoreNextTerm(pSyncNode->pRaftStore);
    syncNodeBecomeLeader(pSyncNode, "one replica start");

    // Raft 3.6.2 Committing entries from previous terms
    syncNodeAppendNoop(pSyncNode);
  } else {
    syncNodeBecomeFollower(pSyncNode, "first start");
  }

  int32_t ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
1198
  ASSERT(ret == 0);
B
Benguang Zhao 已提交
1199 1200 1201 1202
  return ret;
}

void syncNodeStartOld(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1203
  // start raft
1204
  if (pSyncNode->replicaNum == 1) {
M
Minghao Li 已提交
1205
    raftStoreNextTerm(pSyncNode->pRaftStore);
1206
    syncNodeBecomeLeader(pSyncNode, "one replica start");
M
format  
Minghao Li 已提交
1207

1208
    // Raft 3.6.2 Committing entries from previous terms
1209 1210
    syncNodeAppendNoop(pSyncNode);
    syncMaybeAdvanceCommitIndex(pSyncNode);
M
Minghao Li 已提交
1211

M
Minghao Li 已提交
1212 1213
  } else {
    syncNodeBecomeFollower(pSyncNode, "first start");
1214 1215
  }

1216 1217
  int32_t ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
1218
  ASSERT(ret == 0);
M
Minghao Li 已提交
1219 1220
}

B
Benguang Zhao 已提交
1221
int32_t syncNodeStartStandBy(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1222 1223 1224 1225 1226 1227 1228
  // state change
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
  syncNodeStopHeartbeatTimer(pSyncNode);

  // reset elect timer, long enough
  int32_t electMS = TIMER_MAX_MS;
  int32_t ret = syncNodeRestartElectTimer(pSyncNode, electMS);
1229
  ASSERT(ret == 0);
1230

1231 1232
  ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
1233
  ASSERT(ret == 0);
B
Benguang Zhao 已提交
1234
  return ret;
M
Minghao Li 已提交
1235 1236
}

M
Minghao Li 已提交
1237
void syncNodePreClose(SSyncNode* pSyncNode) {
1238 1239 1240 1241
  if (pSyncNode != NULL && pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpApplyQueueItems != NULL) {
    while (1) {
      int32_t aqItems = pSyncNode->pFsm->FpApplyQueueItems(pSyncNode->pFsm);
      sTrace("vgId:%d, pre close, %d items in apply queue", pSyncNode->vgId, aqItems);
1242
      if (aqItems == 0 || aqItems == -1) {
1243 1244 1245 1246 1247 1248
        break;
      }
      taosMsleep(20);
    }
  }

1249
#if 0
1250 1251
  if (pSyncNode->pNewNodeReceiver != NULL) {
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
S
Shengliang Guan 已提交
1252
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
1253 1254
    }

1255 1256
    sDebug("vgId:%d, snapshot receiver destroy while preclose sync node, data:%p", pSyncNode->vgId,
           pSyncNode->pNewNodeReceiver);
1257 1258 1259
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
    pSyncNode->pNewNodeReceiver = NULL;
  }
1260
#endif
1261

M
Minghao Li 已提交
1262 1263 1264 1265 1266
  // stop elect timer
  syncNodeStopElectTimer(pSyncNode);

  // stop heartbeat timer
  syncNodeStopHeartbeatTimer(pSyncNode);
1267 1268 1269

  // clean rsp
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
M
Minghao Li 已提交
1270 1271
}

1272 1273 1274
void syncNodePostClose(SSyncNode* pSyncNode) {
  if (pSyncNode->pNewNodeReceiver != NULL) {
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
S
Shengliang Guan 已提交
1275
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
1276 1277 1278 1279 1280 1281 1282
    }

    sDebug("vgId:%d, snapshot receiver destroy while preclose sync node, data:%p", pSyncNode->vgId,
           pSyncNode->pNewNodeReceiver);
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
    pSyncNode->pNewNodeReceiver = NULL;
  }
M
Minghao Li 已提交
1283 1284
}

1285
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }
M
Minghao Li 已提交
1286

M
Minghao Li 已提交
1287
void syncNodeClose(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1288
  if (pSyncNode == NULL) return;
1289
  sNInfo(pSyncNode, "sync close, node:%p", pSyncNode);
M
Minghao Li 已提交
1290

S
Shengliang Guan 已提交
1291
  int32_t ret = raftStoreClose(pSyncNode->pRaftStore);
1292
  ASSERT(ret == 0);
M
Minghao Li 已提交
1293
  pSyncNode->pRaftStore = NULL;
M
Minghao Li 已提交
1294

B
Benguang Zhao 已提交
1295
  syncNodeLogReplMgrDestroy(pSyncNode);
M
Minghao Li 已提交
1296
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
1297
  pSyncNode->pSyncRespMgr = NULL;
M
Minghao Li 已提交
1298
  voteGrantedDestroy(pSyncNode->pVotesGranted);
1299
  pSyncNode->pVotesGranted = NULL;
M
Minghao Li 已提交
1300
  votesRespondDestory(pSyncNode->pVotesRespond);
1301
  pSyncNode->pVotesRespond = NULL;
M
Minghao Li 已提交
1302
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
1303
  pSyncNode->pNextIndex = NULL;
M
Minghao Li 已提交
1304
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
1305
  pSyncNode->pMatchIndex = NULL;
M
Minghao Li 已提交
1306
  logStoreDestory(pSyncNode->pLogStore);
1307
  pSyncNode->pLogStore = NULL;
B
Benguang Zhao 已提交
1308 1309
  syncLogBufferDestroy(pSyncNode->pLogBuf);
  pSyncNode->pLogBuf = NULL;
M
Minghao Li 已提交
1310 1311 1312 1313 1314

  syncNodeStopPingTimer(pSyncNode);
  syncNodeStopElectTimer(pSyncNode);
  syncNodeStopHeartbeatTimer(pSyncNode);

S
Shengliang Guan 已提交
1315
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
1316 1317
    if (pSyncNode->senders[i] != NULL) {
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", pSyncNode->vgId, pSyncNode->senders[i]);
1318

1319 1320
      if (snapshotSenderIsStart(pSyncNode->senders[i])) {
        snapshotSenderStop(pSyncNode->senders[i], false);
1321 1322
      }

1323 1324
      snapshotSenderDestroy(pSyncNode->senders[i]);
      pSyncNode->senders[i] = NULL;
M
Minghao Li 已提交
1325 1326 1327
    }
  }

M
Minghao Li 已提交
1328
  if (pSyncNode->pNewNodeReceiver != NULL) {
1329
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
S
Shengliang Guan 已提交
1330
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
1331 1332
    }

1333
    sDebug("vgId:%d, snapshot receiver destroy while close, data:%p", pSyncNode->vgId, pSyncNode->pNewNodeReceiver);
M
Minghao Li 已提交
1334 1335 1336 1337
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
    pSyncNode->pNewNodeReceiver = NULL;
  }

1338 1339 1340 1341
  if (pSyncNode->pFsm != NULL) {
    taosMemoryFree(pSyncNode->pFsm);
  }

1342
  taosMemoryFree(pSyncNode);
M
Minghao Li 已提交
1343 1344
}

1345
ESyncStrategy syncNodeStrategy(SSyncNode* pSyncNode) { return pSyncNode->raftCfg.snapshotStrategy; }
M
Minghao Li 已提交
1346

M
Minghao Li 已提交
1347 1348 1349
// timer control --------------
int32_t syncNodeStartPingTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
S
Shengliang Guan 已提交
1350 1351
  if (syncIsInit()) {
    taosTmrReset(pSyncNode->FpPingTimerCB, pSyncNode->pingTimerMS, pSyncNode, syncEnv()->pTimerManager,
1352 1353 1354
                 &pSyncNode->pPingTimer);
    atomic_store_64(&pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1355
    sError("vgId:%d, start ping timer error, sync env is stop", pSyncNode->vgId);
1356
  }
M
Minghao Li 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
  return ret;
}

int32_t syncNodeStopPingTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
  atomic_add_fetch_64(&pSyncNode->pingTimerLogicClockUser, 1);
  taosTmrStop(pSyncNode->pPingTimer);
  pSyncNode->pPingTimer = NULL;
  return ret;
}

int32_t syncNodeStartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
  int32_t ret = 0;
S
Shengliang Guan 已提交
1370
  if (syncIsInit()) {
1371
    pSyncNode->electTimerMS = ms;
S
Shengliang Guan 已提交
1372

1373 1374 1375 1376 1377
    int64_t execTime = taosGetTimestampMs() + ms;
    atomic_store_64(&(pSyncNode->electTimerParam.executeTime), execTime);
    atomic_store_64(&(pSyncNode->electTimerParam.logicClock), pSyncNode->electTimerLogicClock);
    pSyncNode->electTimerParam.pSyncNode = pSyncNode;
    pSyncNode->electTimerParam.pData = NULL;
S
Shengliang Guan 已提交
1378

M
Minghao Li 已提交
1379
    taosTmrReset(pSyncNode->FpElectTimerCB, pSyncNode->electTimerMS, (void*)(pSyncNode->rid), syncEnv()->pTimerManager,
1380
                 &pSyncNode->pElectTimer);
1381

1382
  } else {
M
Minghao Li 已提交
1383
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
1384
  }
M
Minghao Li 已提交
1385 1386 1387 1388 1389
  return ret;
}

int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1390
  atomic_add_fetch_64(&pSyncNode->electTimerLogicClock, 1);
M
Minghao Li 已提交
1391 1392
  taosTmrStop(pSyncNode->pElectTimer);
  pSyncNode->pElectTimer = NULL;
1393

M
Minghao Li 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
  return ret;
}

int32_t syncNodeRestartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
  int32_t ret = 0;
  syncNodeStopElectTimer(pSyncNode);
  syncNodeStartElectTimer(pSyncNode, ms);
  return ret;
}

1404
void syncNodeResetElectTimer(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1405 1406
  int32_t electMS;

1407
  if (pSyncNode->raftCfg.isStandBy) {
M
Minghao Li 已提交
1408 1409 1410 1411
    electMS = TIMER_MAX_MS;
  } else {
    electMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
  }
1412 1413

  (void)syncNodeRestartElectTimer(pSyncNode, electMS);
1414

S
Shengliang Guan 已提交
1415 1416
  sNTrace(pSyncNode, "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine,
          electMS);
M
Minghao Li 已提交
1417 1418
}

M
Minghao Li 已提交
1419
static int32_t syncNodeDoStartHeartbeatTimer(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1420
  int32_t ret = 0;
S
Shengliang Guan 已提交
1421 1422
  if (syncIsInit()) {
    taosTmrReset(pSyncNode->FpHeartbeatTimerCB, pSyncNode->heartbeatTimerMS, pSyncNode, syncEnv()->pTimerManager,
1423 1424 1425
                 &pSyncNode->pHeartbeatTimer);
    atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1426
    sError("vgId:%d, start heartbeat timer error, sync env is stop", pSyncNode->vgId);
1427
  }
1428

S
Shengliang Guan 已提交
1429
  sNTrace(pSyncNode, "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
M
Minghao Li 已提交
1430 1431 1432
  return ret;
}

M
Minghao Li 已提交
1433
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
1434
  int32_t ret = 0;
M
Minghao Li 已提交
1435

1436
#if 0
M
Minghao Li 已提交
1437
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
1438 1439
  ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
#endif
1440

S
Shengliang Guan 已提交
1441
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1442
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1443 1444 1445
    if (pSyncTimer != NULL) {
      syncHbTimerStart(pSyncNode, pSyncTimer);
    }
1446
  }
1447

M
Minghao Li 已提交
1448 1449 1450
  return ret;
}

M
Minghao Li 已提交
1451 1452
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
1453 1454

#if 0
M
Minghao Li 已提交
1455 1456 1457
  atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1);
  taosTmrStop(pSyncNode->pHeartbeatTimer);
  pSyncNode->pHeartbeatTimer = NULL;
1458
#endif
1459

S
Shengliang Guan 已提交
1460
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1461
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1462 1463 1464
    if (pSyncTimer != NULL) {
      syncHbTimerStop(pSyncNode, pSyncTimer);
    }
1465
  }
1466

M
Minghao Li 已提交
1467 1468 1469
  return ret;
}

1470 1471 1472 1473 1474 1475
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode) {
  syncNodeStopHeartbeatTimer(pSyncNode);
  syncNodeStartHeartbeatTimer(pSyncNode);
  return 0;
}

1476 1477 1478 1479 1480 1481 1482 1483
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pNode, SRpcMsg* pMsg) {
  SEpSet* epSet = NULL;
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
    if (destRaftId->addr == pNode->peersId[i].addr) {
      epSet = &pNode->peersEpset[i];
      break;
    }
  }
1484

S
Shengliang Guan 已提交
1485
  int32_t code = -1;
1486
  if (pNode->syncSendMSg != NULL && epSet != NULL) {
M
Minghao Li 已提交
1487
    syncUtilMsgHtoN(pMsg->pCont);
1488
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1489 1490 1491 1492 1493 1494
    code = pNode->syncSendMSg(epSet, pMsg);
  }

  if (code < 0) {
    sError("vgId:%d, sync send msg by id error, epset:%p dnode:%d addr:%" PRId64 " err:0x%x", pNode->vgId, epSet,
           DID(destRaftId), destRaftId->addr, terrno);
S
Shengliang Guan 已提交
1495
    rpcFreeCont(pMsg->pCont);
1496
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
M
Minghao Li 已提交
1497
  }
S
Shengliang Guan 已提交
1498 1499

  return code;
M
Minghao Li 已提交
1500 1501
}

1502
inline bool syncNodeInConfig(SSyncNode* pNode, const SSyncCfg* pCfg) {
1503 1504 1505
  bool b1 = false;
  bool b2 = false;

1506 1507 1508
  for (int32_t i = 0; i < pCfg->replicaNum; ++i) {
    if (strcmp(pCfg->nodeInfo[i].nodeFqdn, pNode->myNodeInfo.nodeFqdn) == 0 &&
        pCfg->nodeInfo[i].nodePort == pNode->myNodeInfo.nodePort) {
1509 1510 1511 1512 1513
      b1 = true;
      break;
    }
  }

1514 1515 1516 1517 1518
  for (int32_t i = 0; i < pCfg->replicaNum; ++i) {
    SRaftId raftId = {
        .addr = SYNC_ADDR(&pCfg->nodeInfo[i]),
        .vgId = pNode->vgId,
    };
1519

1520
    if (syncUtilSameId(&raftId, &pNode->myRaftId)) {
1521 1522 1523 1524 1525
      b2 = true;
      break;
    }
  }

1526
  ASSERT(b1 == b2);
1527 1528 1529
  return b1;
}

1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
static bool syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg) {
  if (pOldCfg->replicaNum != pNewCfg->replicaNum) return true;
  if (pOldCfg->myIndex != pNewCfg->myIndex) return true;
  for (int32_t i = 0; i < pOldCfg->replicaNum; ++i) {
    const SNodeInfo* pOldInfo = &pOldCfg->nodeInfo[i];
    const SNodeInfo* pNewInfo = &pNewCfg->nodeInfo[i];
    if (strcmp(pOldInfo->nodeFqdn, pNewInfo->nodeFqdn) != 0) return true;
    if (pOldInfo->nodePort != pNewInfo->nodePort) return true;
  }

  return false;
}

M
Minghao Li 已提交
1543
void syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncIndex lastConfigChangeIndex) {
1544
  SSyncCfg oldConfig = pSyncNode->raftCfg.cfg;
1545 1546 1547 1548
  if (!syncIsConfigChanged(&oldConfig, pNewConfig)) {
    sInfo("vgId:1, sync not reconfig since not changed");
    return;
  }
S
Shengliang Guan 已提交
1549

1550 1551
  pSyncNode->raftCfg.cfg = *pNewConfig;
  pSyncNode->raftCfg.lastConfigIndex = lastConfigChangeIndex;
1552

1553 1554
  pSyncNode->configChangeNum++;

M
Minghao Li 已提交
1555 1556
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
M
Minghao Li 已提交
1557

M
Minghao Li 已提交
1558 1559
  bool isDrop = false;
  bool isAdd = false;
M
Minghao Li 已提交
1560

M
Minghao Li 已提交
1561 1562 1563 1564
  if (IamInOld && !IamInNew) {
    isDrop = true;
  } else {
    isDrop = false;
1565
  }
1566

M
Minghao Li 已提交
1567 1568 1569 1570 1571
  if (!IamInOld && IamInNew) {
    isAdd = true;
  } else {
    isAdd = false;
  }
M
Minghao Li 已提交
1572

M
Minghao Li 已提交
1573
  // log begin config change
1574 1575
  sNInfo(pSyncNode, "begin do config change, from %d to %d", pSyncNode->vgId, oldConfig.replicaNum,
         pNewConfig->replicaNum);
M
Minghao Li 已提交
1576

M
Minghao Li 已提交
1577
  if (IamInNew) {
1578
    pSyncNode->raftCfg.isStandBy = 0;  // change isStandBy to normal
M
Minghao Li 已提交
1579
  }
M
Minghao Li 已提交
1580
  if (isDrop) {
1581
    pSyncNode->raftCfg.isStandBy = 1;  // set standby
M
Minghao Li 已提交
1582 1583
  }

M
Minghao Li 已提交
1584
  // add last config index
1585
  syncAddCfgIndex(pSyncNode, lastConfigChangeIndex);
M
Minghao Li 已提交
1586

M
Minghao Li 已提交
1587 1588 1589 1590 1591 1592 1593 1594 1595
  if (IamInNew) {
    //-----------------------------------------
    int32_t ret = 0;

    // save snapshot senders
    int32_t oldReplicaNum = pSyncNode->replicaNum;
    SRaftId oldReplicasId[TSDB_MAX_REPLICA];
    memcpy(oldReplicasId, pSyncNode->replicasId, sizeof(oldReplicasId));
    SSyncSnapshotSender* oldSenders[TSDB_MAX_REPLICA];
S
Shengliang Guan 已提交
1596
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
1597
      oldSenders[i] = pSyncNode->senders[i];
S
Shengliang Guan 已提交
1598
      sSTrace(oldSenders[i], "snapshot sender save old");
M
Minghao Li 已提交
1599
    }
1600

M
Minghao Li 已提交
1601
    // init internal
1602
    pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
1603
    syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId);
M
Minghao Li 已提交
1604 1605

    // init peersNum, peers, peersId
1606
    pSyncNode->peersNum = pSyncNode->raftCfg.cfg.replicaNum - 1;
S
Shengliang Guan 已提交
1607
    int32_t j = 0;
1608 1609 1610 1611
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.replicaNum; ++i) {
      if (i != pSyncNode->raftCfg.cfg.myIndex) {
        pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
        syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
M
Minghao Li 已提交
1612 1613 1614
        j++;
      }
    }
S
Shengliang Guan 已提交
1615
    for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1616
      syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]);
M
Minghao Li 已提交
1617
    }
1618

M
Minghao Li 已提交
1619
    // init replicaNum, replicasId
1620 1621 1622
    pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.replicaNum; ++i) {
      syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]);
M
Minghao Li 已提交
1623
    }
1624

1625
    // update quorum first
1626
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
1627

M
Minghao Li 已提交
1628 1629 1630 1631
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
M
Minghao Li 已提交
1632

M
Minghao Li 已提交
1633
    // reset snapshot senders
1634

M
Minghao Li 已提交
1635
    // clear new
S
Shengliang Guan 已提交
1636
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
1637
      pSyncNode->senders[i] = NULL;
M
Minghao Li 已提交
1638
    }
M
Minghao Li 已提交
1639

M
Minghao Li 已提交
1640
    // reset new
S
Shengliang Guan 已提交
1641
    for (int32_t i = 0; i < pSyncNode->replicaNum; ++i) {
M
Minghao Li 已提交
1642 1643
      // reset sender
      bool reset = false;
S
Shengliang Guan 已提交
1644
      for (int32_t j = 0; j < TSDB_MAX_REPLICA; ++j) {
M
Minghao Li 已提交
1645
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
1646 1647
          sNTrace(pSyncNode, "snapshot sender reset for:%" PRId64 ", newIndex:%d, dnode:%d, %p",
                  (pSyncNode->replicasId)[i].addr, i, DID(&pSyncNode->replicasId[i]), oldSenders[j]);
M
Minghao Li 已提交
1648

1649
          pSyncNode->senders[i] = oldSenders[j];
M
Minghao Li 已提交
1650 1651 1652 1653
          oldSenders[j] = NULL;
          reset = true;

          // reset replicaIndex
1654 1655
          int32_t oldreplicaIndex = pSyncNode->senders[i]->replicaIndex;
          pSyncNode->senders[i]->replicaIndex = i;
M
Minghao Li 已提交
1656

1657 1658
          sNTrace(pSyncNode, "snapshot sender udpate replicaIndex from %d to %d, dnode:%d, %p, reset:%d",
                  oldreplicaIndex, i, DID(&pSyncNode->replicasId[i]), pSyncNode->senders[i], reset);
M
Minghao Li 已提交
1659 1660

          break;
M
Minghao Li 已提交
1661
        }
1662 1663
      }
    }
1664

M
Minghao Li 已提交
1665
    // create new
S
Shengliang Guan 已提交
1666
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
1667 1668 1669 1670 1671 1672 1673 1674
      if (pSyncNode->senders[i] == NULL) {
        pSyncNode->senders[i] = snapshotSenderCreate(pSyncNode, i);
        if (pSyncNode->senders[i] == NULL) {
          // will be created later while send snapshot
          sSError(pSyncNode->senders[i], "snapshot sender create failed while reconfig");
        } else {
          sSDebug(pSyncNode->senders[i], "snapshot sender create while reconfig, data:%p", pSyncNode->senders[i]);
        }
S
Shengliang Guan 已提交
1675
      } else {
1676
        sSDebug(pSyncNode->senders[i], "snapshot sender already exist, data:%p", pSyncNode->senders[i]);
M
Minghao Li 已提交
1677
      }
1678 1679
    }

M
Minghao Li 已提交
1680
    // free old
S
Shengliang Guan 已提交
1681
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1682
      if (oldSenders[i] != NULL) {
1683
        sSDebug(oldSenders[i], "snapshot sender destroy old, data:%p replica-index:%d", oldSenders[i], i);
M
Minghao Li 已提交
1684 1685 1686
        snapshotSenderDestroy(oldSenders[i]);
        oldSenders[i] = NULL;
      }
1687 1688
    }

1689
    // persist cfg
1690
    syncWriteCfgFile(pSyncNode);
1691

M
Minghao Li 已提交
1692 1693
    // change isStandBy to normal (election timeout)
    if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
1694
      syncNodeBecomeLeader(pSyncNode, "");
1695 1696 1697

      // Raft 3.6.2 Committing entries from previous terms
      syncNodeAppendNoop(pSyncNode);
1698
      // syncMaybeAdvanceCommitIndex(pSyncNode);
1699

M
Minghao Li 已提交
1700
    } else {
1701
      syncNodeBecomeFollower(pSyncNode, "");
M
Minghao Li 已提交
1702 1703
    }
  } else {
1704
    // persist cfg
1705 1706
    syncWriteCfgFile(pSyncNode);
    sNInfo(pSyncNode, "do not config change from %d to %d", oldConfig.replicaNum, pNewConfig->replicaNum);
1707
  }
1708

M
Minghao Li 已提交
1709
_END:
M
Minghao Li 已提交
1710
  // log end config change
1711 1712
  sNInfo(pSyncNode, "end do config change, from %d to %d", pSyncNode->vgId, oldConfig.replicaNum,
         pNewConfig->replicaNum);
M
Minghao Li 已提交
1713 1714
}

M
Minghao Li 已提交
1715 1716 1717 1718
// raft state change --------------
void syncNodeUpdateTerm(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
1719
    char tmpBuf[64];
1720
    snprintf(tmpBuf, sizeof(tmpBuf), "update term to %" PRId64, term);
1721
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
M
Minghao Li 已提交
1722 1723 1724 1725
    raftStoreClearVote(pSyncNode->pRaftStore);
  }
}

1726 1727 1728 1729 1730 1731
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
  }
}

M
Minghao Li 已提交
1732
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm) {
M
Minghao Li 已提交
1733
  if (pSyncNode->pRaftStore->currentTerm > newTerm) {
1734
    sNTrace(pSyncNode, "step down, ignore, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1735
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1736 1737
    return;
  }
M
Minghao Li 已提交
1738 1739

  do {
1740
    sNTrace(pSyncNode, "step down, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1741
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1742 1743 1744 1745 1746
  } while (0);

  if (pSyncNode->pRaftStore->currentTerm < newTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, newTerm);
    char tmpBuf[64];
1747
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
M
Minghao Li 已提交
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
    raftStoreClearVote(pSyncNode->pRaftStore);

  } else {
    if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
      syncNodeBecomeFollower(pSyncNode, "step down");
    }
  }
}

1758 1759
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }

1760
void syncNodeBecomeFollower(SSyncNode* pSyncNode, const char* debugStr) {
M
Minghao Li 已提交
1761
  // maybe clear leader cache
M
Minghao Li 已提交
1762 1763 1764 1765
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
  }

1766 1767
  pSyncNode->hbSlowNum = 0;

M
Minghao Li 已提交
1768
  // state change
M
Minghao Li 已提交
1769 1770 1771
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
  syncNodeStopHeartbeatTimer(pSyncNode);

M
Minghao Li 已提交
1772 1773
  // reset elect timer
  syncNodeResetElectTimer(pSyncNode);
M
Minghao Li 已提交
1774

1775 1776 1777
  // send rsp to client
  syncNodeLeaderChangeRsp(pSyncNode);

1778 1779 1780 1781 1782
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1783 1784 1785
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

B
Benguang Zhao 已提交
1786 1787 1788
  // reset log buffer
  syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode);

M
Minghao Li 已提交
1789
  // trace log
S
Shengliang Guan 已提交
1790
  sNTrace(pSyncNode, "become follower %s", debugStr);
M
Minghao Li 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
}

// TLA+ Spec
// \* Candidate i transitions to leader.
// BecomeLeader(i) ==
//     /\ state[i] = Candidate
//     /\ votesGranted[i] \in Quorum
//     /\ state'      = [state EXCEPT ![i] = Leader]
//     /\ nextIndex'  = [nextIndex EXCEPT ![i] =
//                          [j \in Server |-> Len(log[i]) + 1]]
//     /\ matchIndex' = [matchIndex EXCEPT ![i] =
//                          [j \in Server |-> 0]]
//     /\ elections'  = elections \cup
//                          {[eterm     |-> currentTerm[i],
//                            eleader   |-> i,
//                            elog      |-> log[i],
//                            evotes    |-> votesGranted[i],
//                            evoterLog |-> voterLog[i]]}
//     /\ UNCHANGED <<messages, currentTerm, votedFor, candidateVars, logVars>>
//
1811
void syncNodeBecomeLeader(SSyncNode* pSyncNode, const char* debugStr) {
1812 1813
  pSyncNode->leaderTime = taosGetTimestampMs();

1814
  pSyncNode->becomeLeaderNum++;
1815
  pSyncNode->hbrSlowNum = 0;
1816

1817 1818 1819
  // reset restoreFinish
  pSyncNode->restoreFinish = false;

M
Minghao Li 已提交
1820
  // state change
M
Minghao Li 已提交
1821
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
M
Minghao Li 已提交
1822 1823

  // set leader cache
M
Minghao Li 已提交
1824 1825
  pSyncNode->leaderCache = pSyncNode->myRaftId;

S
Shengliang Guan 已提交
1826
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1827 1828
    // maybe overwrite myself, no harm
    // just do it!
1829 1830 1831 1832 1833 1834 1835

    // pSyncNode->pNextIndex->index[i] = pSyncNode->pLogStore->getLastIndex(pSyncNode->pLogStore) + 1;

    // maybe wal is deleted
    SyncIndex lastIndex;
    SyncTerm  lastTerm;
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
1836
    ASSERT(code == 0);
1837
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
M
Minghao Li 已提交
1838 1839
  }

S
Shengliang Guan 已提交
1840
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1841 1842
    // maybe overwrite myself, no harm
    // just do it!
M
Minghao Li 已提交
1843 1844 1845
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
  }

M
Minghao Li 已提交
1846 1847 1848
  // init peer mgr
  syncNodePeerStateInit(pSyncNode);

M
Minghao Li 已提交
1849
#if 0
1850 1851
  // update sender private term
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
1852
  if (pMySender != NULL) {
S
Shengliang Guan 已提交
1853
    for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
1854 1855
      if (pSyncNode->senders[i]->privateTerm > pMySender->privateTerm) {
        pMySender->privateTerm = pSyncNode->senders[i]->privateTerm;
1856
      }
1857
    }
1858
    (pMySender->privateTerm) += 100;
1859
  }
M
Minghao Li 已提交
1860
#endif
1861

1862
  // close receiver
M
Minghao Li 已提交
1863 1864
  if (pSyncNode != NULL && pSyncNode->pNewNodeReceiver != NULL &&
      snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
S
Shengliang Guan 已提交
1865
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
1866 1867
  }

M
Minghao Li 已提交
1868
  // stop elect timer
M
Minghao Li 已提交
1869
  syncNodeStopElectTimer(pSyncNode);
M
Minghao Li 已提交
1870

M
Minghao Li 已提交
1871 1872
  // start heartbeat timer
  syncNodeStartHeartbeatTimer(pSyncNode);
M
Minghao Li 已提交
1873

M
Minghao Li 已提交
1874 1875
  // send heartbeat right now
  syncNodeHeartbeatPeers(pSyncNode);
M
Minghao Li 已提交
1876

1877 1878 1879 1880 1881
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1882 1883 1884
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

B
Benguang Zhao 已提交
1885 1886 1887
  // reset log buffer
  syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode);

M
Minghao Li 已提交
1888
  // trace log
1889
  sNInfo(pSyncNode, "become leader %s", debugStr);
M
Minghao Li 已提交
1890 1891 1892
}

void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
1893 1894
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
  ASSERT(voteGrantedMajority(pSyncNode->pVotesGranted));
1895
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");
M
Minghao Li 已提交
1896

S
Shengliang Guan 已提交
1897
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
M
Minghao Li 已提交
1898

B
Benguang Zhao 已提交
1899
  int32_t ret = syncNodeAppendNoop(pSyncNode);
1900 1901 1902 1903
  if (ret < 0) {
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, terrstr());
  }

B
Benguang Zhao 已提交
1904
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1905
  ASSERT(lastIndex >= 0);
B
Benguang Zhao 已提交
1906 1907
  sInfo("vgId:%d, become leader. term: %" PRId64 ", commit index: %" PRId64 ", last index: %" PRId64 "",
        pSyncNode->vgId, pSyncNode->pRaftStore->currentTerm, pSyncNode->commitIndex, lastIndex);
B
Benguang Zhao 已提交
1908 1909 1910
}

void syncNodeCandidate2LeaderOld(SSyncNode* pSyncNode) {
1911 1912
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
  ASSERT(voteGrantedMajority(pSyncNode->pVotesGranted));
B
Benguang Zhao 已提交
1913 1914
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");

M
Minghao Li 已提交
1915
  // Raft 3.6.2 Committing entries from previous terms
1916 1917
  syncNodeAppendNoop(pSyncNode);
  syncMaybeAdvanceCommitIndex(pSyncNode);
1918 1919

  if (pSyncNode->replicaNum > 1) {
M
Minghao Li 已提交
1920
    syncNodeReplicate(pSyncNode);
1921
  }
M
Minghao Li 已提交
1922 1923
}

M
Minghao Li 已提交
1924 1925
bool syncNodeIsMnode(SSyncNode* pSyncNode) { return (pSyncNode->vgId == 1); }

M
Minghao Li 已提交
1926
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1927
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1928 1929 1930 1931 1932
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
    pSyncNode->peerStates[i].lastSendTime = 0;
  }

  return 0;
M
Minghao Li 已提交
1933 1934 1935
}

void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
1936
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER);
M
Minghao Li 已提交
1937
  pSyncNode->state = TAOS_SYNC_STATE_CANDIDATE;
B
Benguang Zhao 已提交
1938 1939 1940
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
  sInfo("vgId:%d, become candidate from follower. term: %" PRId64 ", commit index: %" PRId64 ", last index: %" PRId64,
        pSyncNode->vgId, pSyncNode->pRaftStore->currentTerm, pSyncNode->commitIndex, lastIndex);
M
Minghao Li 已提交
1941

S
Shengliang Guan 已提交
1942
  sNTrace(pSyncNode, "follower to candidate");
M
Minghao Li 已提交
1943 1944 1945
}

void syncNodeLeader2Follower(SSyncNode* pSyncNode) {
1946
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_LEADER);
1947
  syncNodeBecomeFollower(pSyncNode, "leader to follower");
B
Benguang Zhao 已提交
1948 1949 1950 1951
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
  sInfo("vgId:%d, become follower from leader. term: %" PRId64 ", commit index: %" PRId64 ", last index: %" PRId64,
        pSyncNode->vgId, pSyncNode->pRaftStore->currentTerm, pSyncNode->commitIndex, lastIndex);

S
Shengliang Guan 已提交
1952
  sNTrace(pSyncNode, "leader to follower");
M
Minghao Li 已提交
1953 1954 1955
}

void syncNodeCandidate2Follower(SSyncNode* pSyncNode) {
1956
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
1957
  syncNodeBecomeFollower(pSyncNode, "candidate to follower");
B
Benguang Zhao 已提交
1958 1959 1960 1961
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
  sInfo("vgId:%d, become follower from candidate. term: %" PRId64 ", commit index: %" PRId64 ", last index: %" PRId64,
        pSyncNode->vgId, pSyncNode->pRaftStore->currentTerm, pSyncNode->commitIndex, lastIndex);

S
Shengliang Guan 已提交
1962
  sNTrace(pSyncNode, "candidate to follower");
M
Minghao Li 已提交
1963 1964
}

M
Minghao Li 已提交
1965 1966
// just called by syncNodeVoteForSelf
// need assert
M
Minghao Li 已提交
1967
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
1968 1969
  ASSERT(term == pSyncNode->pRaftStore->currentTerm);
  ASSERT(!raftStoreHasVoted(pSyncNode->pRaftStore));
M
Minghao Li 已提交
1970 1971 1972 1973

  raftStoreVote(pSyncNode->pRaftStore, pRaftId);
}

M
Minghao Li 已提交
1974
// simulate get vote from outside
M
Minghao Li 已提交
1975
void syncNodeVoteForSelf(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1976
  syncNodeVoteForTerm(pSyncNode, pSyncNode->pRaftStore->currentTerm, &pSyncNode->myRaftId);
M
Minghao Li 已提交
1977

S
Shengliang Guan 已提交
1978 1979
  SRpcMsg rpcMsg = {0};
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
S
Shengliang Guan 已提交
1980
  if (ret != 0) return;
M
Minghao Li 已提交
1981

S
Shengliang Guan 已提交
1982
  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
M
Minghao Li 已提交
1983 1984 1985 1986 1987 1988 1989
  pMsg->srcId = pSyncNode->myRaftId;
  pMsg->destId = pSyncNode->myRaftId;
  pMsg->term = pSyncNode->pRaftStore->currentTerm;
  pMsg->voteGranted = true;

  voteGrantedVote(pSyncNode->pVotesGranted, pMsg);
  votesRespondAdd(pSyncNode->pVotesRespond, pMsg);
S
Shengliang Guan 已提交
1990
  rpcFreeCont(rpcMsg.pCont);
M
Minghao Li 已提交
1991 1992
}

M
Minghao Li 已提交
1993
// return if has a snapshot
M
Minghao Li 已提交
1994 1995
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
  bool      ret = false;
1996
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1997 1998
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1999 2000 2001 2002 2003 2004 2005
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
      ret = true;
    }
  }
  return ret;
}

M
Minghao Li 已提交
2006 2007
// return max(logLastIndex, snapshotLastIndex)
// if no snapshot and log, return -1
2008
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
M
Minghao Li 已提交
2009
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2010 2011
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
2012 2013 2014 2015 2016 2017 2018
  }
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);

  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
  return lastIndex;
}

M
Minghao Li 已提交
2019 2020
// return the last term of snapshot and log
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
M
Minghao Li 已提交
2021 2022
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
  SyncTerm lastTerm = 0;
M
Minghao Li 已提交
2023 2024
  if (syncNodeHasSnapshot(pSyncNode)) {
    // has snapshot
2025
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2026 2027
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
2028 2029
    }

M
Minghao Li 已提交
2030 2031 2032
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
    if (logLastIndex > snapshot.lastApplyIndex) {
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
M
Minghao Li 已提交
2033 2034 2035 2036
    } else {
      lastTerm = snapshot.lastApplyTerm;
    }

M
Minghao Li 已提交
2037
  } else {
M
Minghao Li 已提交
2038 2039
    // no snapshot
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
2040
  }
M
Minghao Li 已提交
2041

M
Minghao Li 已提交
2042 2043 2044 2045 2046 2047 2048
  return lastTerm;
}

// get last index and term along with snapshot
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
2049 2050
  return 0;
}
M
Minghao Li 已提交
2051

M
Minghao Li 已提交
2052
// return append-entries first try index
M
Minghao Li 已提交
2053 2054 2055 2056 2057
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
  return syncStartIndex;
}

M
Minghao Li 已提交
2058 2059
// if index > 0, return index - 1
// else, return -1
2060 2061 2062 2063 2064 2065 2066 2067 2068
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
  SyncIndex preIndex = index - 1;
  if (preIndex < SYNC_INDEX_INVALID) {
    preIndex = SYNC_INDEX_INVALID;
  }

  return preIndex;
}

M
Minghao Li 已提交
2069 2070 2071 2072
// if index < 0, return SYNC_TERM_INVALID
// if index == 0, return 0
// if index > 0, return preTerm
// if error, return SYNC_TERM_INVALID
2073 2074 2075 2076 2077 2078 2079 2080 2081
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
  if (index < SYNC_INDEX_BEGIN) {
    return SYNC_TERM_INVALID;
  }

  if (index == SYNC_INDEX_BEGIN) {
    return 0;
  }

2082 2083 2084
  SyncTerm  preTerm = 0;
  SyncIndex preIndex = index - 1;

2085
  SSyncRaftEntry* pPreEntry = NULL;
2086 2087 2088 2089 2090 2091 2092
  SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
  LRUHandle*      h = taosLRUCacheLookup(pCache, &preIndex, sizeof(preIndex));
  int32_t         code = 0;
  if (h) {
    pPreEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
    code = 0;

2093
    pSyncNode->pLogStore->cacheHit++;
2094 2095 2096
    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);

  } else {
2097
    pSyncNode->pLogStore->cacheMiss++;
2098 2099 2100 2101
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);

    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
  }
M
Minghao Li 已提交
2102 2103 2104 2105 2106 2107

  SSnapshot snapshot = {.data = NULL,
                        .lastApplyIndex = SYNC_INDEX_INVALID,
                        .lastApplyTerm = SYNC_TERM_INVALID,
                        .lastConfigIndex = SYNC_INDEX_INVALID};

2108
  if (code == 0) {
2109
    ASSERT(pPreEntry != NULL);
2110
    preTerm = pPreEntry->term;
2111 2112 2113 2114

    if (h) {
      taosLRUCacheRelease(pCache, h, false);
    } else {
2115
      syncEntryDestroy(pPreEntry);
2116 2117
    }

2118 2119
    return preTerm;
  } else {
2120 2121 2122 2123
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
      if (snapshot.lastApplyIndex == preIndex) {
        return snapshot.lastApplyTerm;
2124 2125 2126 2127
      }
    }
  }

2128
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
S
Shengliang Guan 已提交
2129
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
2130 2131
  return SYNC_TERM_INVALID;
}
M
Minghao Li 已提交
2132 2133 2134 2135

// get pre index and term of "index"
int32_t syncNodeGetPreIndexTerm(SSyncNode* pSyncNode, SyncIndex index, SyncIndex* pPreIndex, SyncTerm* pPreTerm) {
  *pPreIndex = syncNodeGetPreIndex(pSyncNode, index);
M
Minghao Li 已提交
2136
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
M
Minghao Li 已提交
2137 2138 2139
  return 0;
}

M
Minghao Li 已提交
2140
static void syncNodeEqPingTimer(void* param, void* tmrId) {
S
Shengliang Guan 已提交
2141
  if (!syncIsInit()) return;
M
Minghao Li 已提交
2142

S
Shengliang Guan 已提交
2143 2144 2145
  SSyncNode* pNode = param;
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
    SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
2146
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
S
Shengliang Guan 已提交
2147 2148
                                    pNode->pingTimerMS, pNode);
    if (code != 0) {
M
Minghao Li 已提交
2149
      sError("failed to build ping msg");
S
Shengliang Guan 已提交
2150 2151
      rpcFreeCont(rpcMsg.pCont);
      return;
M
Minghao Li 已提交
2152
    }
M
Minghao Li 已提交
2153

M
Minghao Li 已提交
2154
    // sTrace("enqueue ping msg");
S
Shengliang Guan 已提交
2155 2156
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
    if (code != 0) {
M
Minghao Li 已提交
2157
      sError("failed to sync enqueue ping msg since %s", terrstr());
S
Shengliang Guan 已提交
2158 2159
      rpcFreeCont(rpcMsg.pCont);
      return;
2160
    }
M
Minghao Li 已提交
2161

S
Shengliang Guan 已提交
2162
    taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, pNode, syncEnv()->pTimerManager, &pNode->pPingTimer);
2163
  }
M
Minghao Li 已提交
2164 2165
}

M
Minghao Li 已提交
2166
static void syncNodeEqElectTimer(void* param, void* tmrId) {
S
Shengliang Guan 已提交
2167
  if (!syncIsInit()) return;
M
Minghao Li 已提交
2168

M
Minghao Li 已提交
2169 2170
  int64_t    rid = (int64_t)param;
  SSyncNode* pNode = syncNodeAcquire(rid);
M
Minghao Li 已提交
2171

2172
  if (pNode == NULL) return;
M
Minghao Li 已提交
2173 2174 2175 2176 2177

  if (pNode->syncEqMsg == NULL) {
    syncNodeRelease(pNode);
    return;
  }
2178

2179
  int64_t tsNow = taosGetTimestampMs();
M
Minghao Li 已提交
2180 2181 2182 2183
  if (tsNow < pNode->electTimerParam.executeTime) {
    syncNodeRelease(pNode);
    return;
  }
M
Minghao Li 已提交
2184

S
Shengliang Guan 已提交
2185
  SRpcMsg rpcMsg = {0};
2186 2187
  int32_t code =
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
S
Shengliang Guan 已提交
2188

S
Shengliang Guan 已提交
2189
  if (code != 0) {
M
Minghao Li 已提交
2190
    sError("failed to build elect msg");
M
Minghao Li 已提交
2191
    syncNodeRelease(pNode);
S
Shengliang Guan 已提交
2192
    return;
M
Minghao Li 已提交
2193 2194
  }

S
Shengliang Guan 已提交
2195
  SyncTimeout* pTimeout = rpcMsg.pCont;
S
Shengliang Guan 已提交
2196
  sNTrace(pNode, "enqueue elect msg lc:%" PRId64, pTimeout->logicClock);
S
Shengliang Guan 已提交
2197 2198 2199

  code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
  if (code != 0) {
M
Minghao Li 已提交
2200
    sError("failed to sync enqueue elect msg since %s", terrstr());
S
Shengliang Guan 已提交
2201
    rpcFreeCont(rpcMsg.pCont);
M
Minghao Li 已提交
2202
    syncNodeRelease(pNode);
2203
    return;
M
Minghao Li 已提交
2204
  }
M
Minghao Li 已提交
2205 2206

  syncNodeRelease(pNode);
M
Minghao Li 已提交
2207 2208
}

M
Minghao Li 已提交
2209
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
S
Shengliang Guan 已提交
2210
  if (!syncIsInit()) return;
2211

S
Shengliang Guan 已提交
2212 2213 2214 2215
  SSyncNode* pNode = param;
  if (pNode->replicaNum > 1) {
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
      SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
2216
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
S
Shengliang Guan 已提交
2217 2218 2219
                                      pNode->heartbeatTimerMS, pNode);

      if (code != 0) {
M
Minghao Li 已提交
2220
        sError("failed to build heartbeat msg");
S
Shengliang Guan 已提交
2221
        return;
2222
      }
M
Minghao Li 已提交
2223

2224
      sTrace("vgId:%d, enqueue heartbeat timer", pNode->vgId);
S
Shengliang Guan 已提交
2225 2226
      code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
      if (code != 0) {
M
Minghao Li 已提交
2227
        sError("failed to enqueue heartbeat msg since %s", terrstr());
S
Shengliang Guan 已提交
2228 2229
        rpcFreeCont(rpcMsg.pCont);
        return;
2230
      }
S
Shengliang Guan 已提交
2231 2232 2233 2234

      taosTmrReset(syncNodeEqHeartbeatTimer, pNode->heartbeatTimerMS, pNode, syncEnv()->pTimerManager,
                   &pNode->pHeartbeatTimer);

2235
    } else {
S
Shengliang Guan 已提交
2236 2237
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
2238
    }
M
Minghao Li 已提交
2239 2240 2241
  }
}

2242
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
2243
  int64_t hbDataRid = (int64_t)param;
2244
  int64_t tsNow = taosGetTimestampMs();
2245

2246 2247
  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
  if (pData == NULL) {
M
Minghao Li 已提交
2248
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
2249 2250
    return;
  }
2251

2252
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
M
Minghao Li 已提交
2253
  if (pSyncNode == NULL) {
2254
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2255
    sError("hb timer get pSyncNode NULL");
2256 2257 2258 2259 2260 2261 2262 2263
    return;
  }

  SSyncTimer* pSyncTimer = pData->pTimer;

  if (!pSyncNode->isStart) {
    syncNodeRelease(pSyncNode);
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2264
    sError("vgId:%d, hb timer sync node already stop", pSyncNode->vgId);
M
Minghao Li 已提交
2265 2266 2267
    return;
  }

M
Minghao Li 已提交
2268
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
2269 2270
    syncNodeRelease(pSyncNode);
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2271
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
M
Minghao Li 已提交
2272 2273 2274
    return;
  }

M
Minghao Li 已提交
2275
  if (pSyncNode->pRaftStore == NULL) {
2276 2277
    syncNodeRelease(pSyncNode);
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2278
    sError("vgId:%d, hb timer raft store already stop", pSyncNode->vgId);
M
Minghao Li 已提交
2279 2280 2281
    return;
  }

M
Minghao Li 已提交
2282
  // sTrace("vgId:%d, eq peer hb timer", pSyncNode->vgId);
2283 2284

  if (pSyncNode->replicaNum > 1) {
M
Minghao Li 已提交
2285 2286 2287
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);

2288
    if (timerLogicClock == msgLogicClock) {
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
      if (tsNow > pData->execTime) {
#if 0        
        sTrace(
            "vgId:%d, hbDataRid:%ld,  EXECUTE this step-------- heartbeat tsNow:%ld, exec:%ld, tsNow-exec:%ld, "
            "---------",
            pSyncNode->vgId, hbDataRid, tsNow, pData->execTime, tsNow - pData->execTime);
#endif

        pData->execTime += pSyncTimer->timerMS;

        SRpcMsg rpcMsg = {0};
        (void)syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId);

        SyncHeartbeat* pSyncMsg = rpcMsg.pCont;
        pSyncMsg->srcId = pSyncNode->myRaftId;
        pSyncMsg->destId = pData->destId;
        pSyncMsg->term = pSyncNode->pRaftStore->currentTerm;
        pSyncMsg->commitIndex = pSyncNode->commitIndex;
        pSyncMsg->minMatchIndex = syncMinMatchIndex(pSyncNode);
        pSyncMsg->privateTerm = 0;
2309
        pSyncMsg->timeStamp = tsNow;
2310 2311 2312 2313 2314 2315

        // update reset time
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
        pSyncTimer->timeStamp = tsNow;

        // send msg
2316 2317
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime);
        syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
2318 2319 2320 2321 2322 2323 2324 2325
      } else {
#if 0        
        sTrace(
            "vgId:%d, hbDataRid:%ld,  pass this step-------- heartbeat tsNow:%ld, exec:%ld, tsNow-exec:%ld, ---------",
            pSyncNode->vgId, hbDataRid, tsNow, pData->execTime, tsNow - pData->execTime);
#endif
      }

M
Minghao Li 已提交
2326 2327
      if (syncIsInit()) {
        // sTrace("vgId:%d, reset peer hb timer", pSyncNode->vgId);
2328 2329
        taosTmrReset(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS / HEARTBEAT_TICK_NUM, (void*)hbDataRid,
                     syncEnv()->pTimerManager, &pSyncTimer->pTimer);
M
Minghao Li 已提交
2330 2331 2332 2333
      } else {
        sError("sync env is stop, reset peer hb timer error");
      }

2334
    } else {
M
Minghao Li 已提交
2335 2336
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64 "", pSyncNode->vgId,
             timerLogicClock, msgLogicClock);
2337 2338
    }
  }
2339 2340 2341

  syncHbTimerDataRelease(pData);
  syncNodeRelease(pSyncNode);
2342 2343
}

2344 2345 2346 2347 2348
static int32_t syncNodeEqNoop(SSyncNode* pNode) {
  if (pNode->state == TAOS_SYNC_STATE_LEADER) {
    terrno = TSDB_CODE_SYN_NOT_LEADER;
    return -1;
  }
M
Minghao Li 已提交
2349

2350 2351 2352 2353
  SyncIndex       index = pNode->pLogStore->syncLogWriteIndex(pNode->pLogStore);
  SyncTerm        term = pNode->pRaftStore->currentTerm;
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, pNode->vgId);
  if (pEntry == NULL) return -1;
M
Minghao Li 已提交
2354

S
Shengliang Guan 已提交
2355
  SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
2356
  int32_t code = syncBuildClientRequestFromNoopEntry(&rpcMsg, pEntry, pNode->vgId);
2357
  syncEntryDestroy(pEntry);
M
Minghao Li 已提交
2358

2359 2360 2361
  sNTrace(pNode, "propose msg, type:noop");
  code = (*pNode->syncEqMsg)(pNode->msgcb, &rpcMsg);
  if (code != 0) {
M
Minghao Li 已提交
2362
    sError("failed to propose noop msg while enqueue since %s", terrstr());
2363
  }
M
Minghao Li 已提交
2364

2365
  return code;
M
Minghao Li 已提交
2366 2367
}

2368 2369
static void deleteCacheEntry(const void* key, size_t keyLen, void* value) { taosMemoryFree(value); }

2370 2371 2372 2373
int32_t syncCacheEntry(SSyncLogStore* pLogStore, SSyncRaftEntry* pEntry, LRUHandle** h) {
  SSyncLogStoreData* pData = pLogStore->data;
  sNTrace(pData->pSyncNode, "in cache index:%" PRId64 ", bytes:%u, %p", pEntry->index, pEntry->bytes, pEntry);

S
Shengliang Guan 已提交
2374 2375
  int32_t   code = 0;
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2376 2377 2378 2379 2380 2381 2382 2383 2384
  LRUStatus status = taosLRUCacheInsert(pLogStore->pCache, &pEntry->index, sizeof(pEntry->index), pEntry, entryLen,
                                        deleteCacheEntry, h, TAOS_LRU_PRIORITY_LOW);
  if (status != TAOS_LRU_STATUS_OK) {
    code = -1;
  }

  return code;
}

B
Benguang Zhao 已提交
2385
int32_t syncNodeAppend(SSyncNode* ths, SSyncRaftEntry* pEntry) {
2386 2387 2388 2389 2390 2391 2392
  if (pEntry->dataLen < sizeof(SMsgHead)) {
    sError("vgId:%d, cannot append an invalid client request with no msg head. type:%s, dataLen:%d", ths->vgId,
           TMSG_INFO(pEntry->originalRpcType), pEntry->dataLen);
    syncEntryDestroy(pEntry);
    return -1;
  }

B
Benguang Zhao 已提交
2393 2394
  // append to log buffer
  if (syncLogBufferAppend(ths->pLogBuf, ths, pEntry) < 0) {
2395 2396 2397 2398 2399
    sError("vgId:%d, failed to enqueue sync log buffer, index:%" PRId64, ths->vgId, pEntry->index);
    terrno = TSDB_CODE_SYN_BUFFER_FULL;
    (void)syncLogFsmExecute(ths, ths->pFsm, ths->state, ths->pRaftStore->currentTerm, pEntry,
                            TSDB_CODE_SYN_BUFFER_FULL);
    syncEntryDestroy(pEntry);
B
Benguang Zhao 已提交
2400 2401 2402 2403
    return -1;
  }

  // proceed match index, with replicating on needed
2404
  SyncIndex matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL);
B
Benguang Zhao 已提交
2405

2406
  sTrace("vgId:%d, append raft entry. index: %" PRId64 ", term: %" PRId64 " pBuf: [%" PRId64 " %" PRId64 " %" PRId64
2407 2408 2409
         ", %" PRId64 ")",
         ths->vgId, pEntry->index, pEntry->term, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
         ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex);
B
Benguang Zhao 已提交
2410

B
Benguang Zhao 已提交
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
  // multi replica
  if (ths->replicaNum > 1) {
    return 0;
  }

  // single replica
  (void)syncNodeUpdateCommitIndex(ths, matchIndex);

  if (syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex) < 0) {
    sError("vgId:%d, failed to commit until commitIndex:%" PRId64 "", ths->vgId, ths->commitIndex);
    return -1;
  }

  return 0;
}

2427
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
  if (pSyncNode->replicaNum == 1) {
    return false;
  }

  int32_t toCount = 0;
  int64_t tsNow = taosGetTimestampMs();
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
    if (recvTime == 0 || recvTime == -1) {
      continue;
    }

2440
    if (tsNow - recvTime > tsHeartbeatTimeout) {
2441 2442 2443 2444 2445 2446 2447 2448 2449
      toCount++;
    }
  }

  bool b = (toCount >= pSyncNode->quorum ? true : false);

  return b;
}

2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
bool syncNodeSnapshotSending(SSyncNode* pSyncNode) {
  if (pSyncNode == NULL) return false;
  bool b = false;
  for (int32_t i = 0; i < pSyncNode->replicaNum; ++i) {
    if (pSyncNode->senders[i] != NULL && pSyncNode->senders[i]->start) {
      b = true;
      break;
    }
  }
  return b;
}

bool syncNodeSnapshotRecving(SSyncNode* pSyncNode) {
  if (pSyncNode == NULL) return false;
  if (pSyncNode->pNewNodeReceiver == NULL) return false;
  if (pSyncNode->pNewNodeReceiver->start) return true;
  return false;
}

M
Minghao Li 已提交
2469
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
B
Benguang Zhao 已提交
2470 2471 2472 2473 2474 2475 2476 2477 2478
  SyncIndex index = syncLogBufferGetEndIndex(ths->pLogBuf);
  SyncTerm  term = ths->pRaftStore->currentTerm;

  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
  if (pEntry == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }

B
Benguang Zhao 已提交
2479 2480
  int32_t ret = syncNodeAppend(ths, pEntry);
  return 0;
B
Benguang Zhao 已提交
2481 2482 2483
}

static int32_t syncNodeAppendNoopOld(SSyncNode* ths) {
M
Minghao Li 已提交
2484 2485
  int32_t ret = 0;

2486
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2487
  SyncTerm        term = ths->pRaftStore->currentTerm;
M
Minghao Li 已提交
2488
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
2489
  ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2490

2491 2492
  LRUHandle* h = NULL;

M
Minghao Li 已提交
2493
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2494
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
2495
    if (code != 0) {
M
Minghao Li 已提交
2496
      sError("append noop error");
2497 2498
      return -1;
    }
2499 2500

    syncCacheEntry(ths->pLogStore, pEntry, &h);
M
Minghao Li 已提交
2501 2502
  }

2503 2504 2505
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
B
Benguang Zhao 已提交
2506
    syncEntryDestroy(pEntry);
2507 2508
  }

M
Minghao Li 已提交
2509 2510 2511
  return ret;
}

S
Shengliang Guan 已提交
2512 2513
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
2514

M
Minghao Li 已提交
2515 2516 2517 2518
  const STraceId* trace = &pRpcMsg->info.traceId;
  char            tbuf[40] = {0};
  TRACE_TO_STR(trace, tbuf);

2519
  int64_t tsMs = taosGetTimestampMs();
M
Minghao Li 已提交
2520
  int64_t timeDiff = tsMs - pMsg->timeStamp;
M
Minghao Li 已提交
2521
  syncLogRecvHeartbeat(ths, pMsg, timeDiff, tbuf);
2522

2523 2524 2525 2526
  SRpcMsg rpcMsg = {0};
  (void)syncBuildHeartbeatReply(&rpcMsg, ths->vgId);

  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
2527 2528 2529 2530
  pMsgReply->destId = pMsg->srcId;
  pMsgReply->srcId = ths->myRaftId;
  pMsgReply->term = ths->pRaftStore->currentTerm;
  pMsgReply->privateTerm = 8864;  // magic number
2531
  pMsgReply->startTime = ths->startTime;
2532
  pMsgReply->timeStamp = tsMs;
2533

M
Minghao Li 已提交
2534
  if (pMsg->term == ths->pRaftStore->currentTerm && ths->state != TAOS_SYNC_STATE_LEADER) {
2535 2536
    syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);

2537
    syncNodeResetElectTimer(ths);
M
Minghao Li 已提交
2538
    ths->minMatchIndex = pMsg->minMatchIndex;
2539 2540

    if (ths->state == TAOS_SYNC_STATE_FOLLOWER) {
2541
      // syncNodeFollowerCommit(ths, pMsg->commitIndex);
S
Shengliang Guan 已提交
2542 2543 2544 2545
      SRpcMsg rpcMsgLocalCmd = {0};
      (void)syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId);

      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
2546
      pSyncMsg->cmd = SYNC_LOCAL_CMD_FOLLOWER_CMT;
2547 2548 2549
      pSyncMsg->commitIndex = pMsg->commitIndex;
      pSyncMsg->currentTerm = pMsg->term;
      SyncIndex fcIndex = pSyncMsg->commitIndex;
2550 2551 2552 2553 2554 2555 2556

      if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
        int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
        if (code != 0) {
          sError("vgId:%d, sync enqueue fc-commit msg error, code:%d", ths->vgId, code);
          rpcFreeCont(rpcMsgLocalCmd.pCont);
        } else {
2557
          sTrace("vgId:%d, sync enqueue fc-commit msg, fc-index:%" PRId64, ths->vgId, fcIndex);
2558 2559
        }
      }
2560 2561 2562
    }
  }

M
Minghao Li 已提交
2563
  if (pMsg->term >= ths->pRaftStore->currentTerm && ths->state != TAOS_SYNC_STATE_FOLLOWER) {
2564
    // syncNodeStepDown(ths, pMsg->term);
S
Shengliang Guan 已提交
2565 2566 2567 2568
    SRpcMsg rpcMsgLocalCmd = {0};
    (void)syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId);

    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
2569
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
2570 2571
    pSyncMsg->currentTerm = pMsg->term;
    pSyncMsg->commitIndex = pMsg->commitIndex;
2572

S
Shengliang Guan 已提交
2573 2574
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
2575 2576 2577 2578
      if (code != 0) {
        sError("vgId:%d, sync enqueue step-down msg error, code:%d", ths->vgId, code);
        rpcFreeCont(rpcMsgLocalCmd.pCont);
      } else {
2579
        sTrace("vgId:%d, sync enqueue step-down msg, new-term: %" PRId64, ths->vgId, pSyncMsg->currentTerm);
2580
      }
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595
    }
  }

  /*
    // htonl
    SMsgHead* pHead = rpcMsg.pCont;
    pHead->contLen = htonl(pHead->contLen);
    pHead->vgId = htonl(pHead->vgId);
  */

  // reply
  syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg);
  return 0;
}

2596
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
S
Shengliang Guan 已提交
2597 2598 2599 2600
  const STraceId* trace = &pRpcMsg->info.traceId;
  char            tbuf[40] = {0};
  TRACE_TO_STR(trace, tbuf);

2601
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
B
Benguang Zhao 已提交
2602
  SSyncLogReplMgr*    pMgr = syncNodeGetLogReplMgr(ths, &pMsg->srcId);
2603 2604 2605 2606
  if (pMgr == NULL) {
    sError("vgId:%d, failed to get log repl mgr for the peer at addr 0x016%" PRIx64 "", ths->vgId, pMsg->srcId.addr);
    return -1;
  }
2607 2608

  int64_t tsMs = taosGetTimestampMs();
S
Shengliang Guan 已提交
2609
  syncLogRecvHeartbeatReply(ths, pMsg, tsMs - pMsg->timeStamp, tbuf);
2610

2611 2612
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);

2613 2614 2615
  return syncLogReplMgrProcessHeartbeatReply(pMgr, ths, pMsg);
}

2616
int32_t syncNodeOnHeartbeatReplyOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
2617
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
2618

M
Minghao Li 已提交
2619 2620 2621 2622
  const STraceId* trace = &pRpcMsg->info.traceId;
  char            tbuf[40] = {0};
  TRACE_TO_STR(trace, tbuf);

M
Minghao Li 已提交
2623
  int64_t tsMs = taosGetTimestampMs();
M
Minghao Li 已提交
2624
  int64_t timeDiff = tsMs - pMsg->timeStamp;
M
Minghao Li 已提交
2625
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff, tbuf);
M
Minghao Li 已提交
2626

2627
  // update last reply time, make decision whether the other node is alive or not
M
Minghao Li 已提交
2628
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
2629 2630 2631
  return 0;
}

S
Shengliang Guan 已提交
2632 2633
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
2634 2635
  syncLogRecvLocalCmd(ths, pMsg, "");

2636
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
2637
    syncNodeStepDown(ths, pMsg->currentTerm);
2638 2639

  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT) {
2640 2641 2642 2643
    SyncTerm matchTerm = syncLogBufferGetLastMatchTerm(ths->pLogBuf);
    if (pMsg->currentTerm == matchTerm) {
      (void)syncNodeUpdateCommitIndex(ths, pMsg->commitIndex);
    }
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
    if (syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex) < 0) {
      sError("vgId:%d, failed to commit raft log since %s. commit index: %" PRId64 "", ths->vgId, terrstr(),
             ths->commitIndex);
    }
  } else {
    sError("error local cmd");
  }

  return 0;
}

int32_t syncNodeOnLocalCmdOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
2656
  ASSERT(false && "deprecated");
2657 2658 2659
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
  syncLogRecvLocalCmd(ths, pMsg, "");

M
Minghao Li 已提交
2660
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
2661
    syncNodeStepDown(ths, pMsg->currentTerm);
M
Minghao Li 已提交
2662

2663
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT) {
2664
    syncNodeFollowerCommit(ths, pMsg->commitIndex);
2665

M
Minghao Li 已提交
2666
  } else {
M
Minghao Li 已提交
2667
    sError("error local cmd");
M
Minghao Li 已提交
2668
  }
2669 2670 2671 2672

  return 0;
}

M
Minghao Li 已提交
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
// TLA+ Spec
// ClientRequest(i, v) ==
//     /\ state[i] = Leader
//     /\ LET entry == [term  |-> currentTerm[i],
//                      value |-> v]
//            newLog == Append(log[i], entry)
//        IN  log' = [log EXCEPT ![i] = newLog]
//     /\ UNCHANGED <<messages, serverVars, candidateVars,
//                    leaderVars, commitIndex>>
//
M
Minghao Li 已提交
2683

2684
int32_t syncNodeOnClientRequest(SSyncNode* ths, SRpcMsg* pMsg, SyncIndex* pRetIndex) {
S
Shengliang Guan 已提交
2685
  sNTrace(ths, "on client request");
2686

B
Benguang Zhao 已提交
2687 2688
  int32_t code = 0;

B
Benguang Zhao 已提交
2689 2690 2691
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
  SyncTerm        term = ths->pRaftStore->currentTerm;
  SSyncRaftEntry* pEntry = NULL;
2692 2693 2694 2695
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index);
  } else {
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
B
Benguang Zhao 已提交
2696 2697
  }

2698 2699 2700 2701 2702
  if (pEntry == NULL) {
    sError("vgId:%d, failed to process client request since %s.", ths->vgId, terrstr());
    return -1;
  }

B
Benguang Zhao 已提交
2703 2704 2705 2706 2707
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
    if (pRetIndex) {
      (*pRetIndex) = index;
    }

2708 2709
    int32_t code = syncNodeAppend(ths, pEntry);
    return code;
2710 2711 2712
  } else {
    syncEntryDestroy(pEntry);
    pEntry = NULL;
2713
    return -1;
B
Benguang Zhao 已提交
2714 2715 2716
  }
}

2717 2718
int32_t syncNodeOnClientRequestOld(SSyncNode* ths, SRpcMsg* pMsg, SyncIndex* pRetIndex) {
  sNTrace(ths, "on client request");
B
Benguang Zhao 已提交
2719

M
Minghao Li 已提交
2720
  int32_t ret = 0;
2721
  int32_t code = 0;
M
Minghao Li 已提交
2722

M
Minghao Li 已提交
2723
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2724
  SyncTerm        term = ths->pRaftStore->currentTerm;
2725 2726 2727 2728 2729 2730 2731
  SSyncRaftEntry* pEntry;

  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index);
  } else {
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
  }
M
Minghao Li 已提交
2732

2733 2734
  LRUHandle* h = NULL;

M
Minghao Li 已提交
2735
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2736 2737 2738
    // append entry
    code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
    if (code != 0) {
2739 2740 2741 2742
      if (ths->replicaNum == 1) {
        if (h) {
          taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
        } else {
2743
          syncEntryDestroy(pEntry);
2744
        }
2745

2746 2747 2748 2749
        return -1;

      } else {
        // del resp mgr, call FpCommitCb
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
        SFsmCbMeta cbMeta = {
            .index = pEntry->index,
            .lastConfigIndex = SYNC_INDEX_INVALID,
            .isWeak = pEntry->isWeak,
            .code = -1,
            .state = ths->state,
            .seqNum = pEntry->seqNum,
            .term = pEntry->term,
            .currentTerm = ths->pRaftStore->currentTerm,
            .flag = 0,
        };
2761
        ths->pFsm->FpCommitCb(ths->pFsm, pMsg, &cbMeta);
2762 2763 2764 2765

        if (h) {
          taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
        } else {
2766
          syncEntryDestroy(pEntry);
2767 2768
        }

2769 2770
        return -1;
      }
2771
    }
M
Minghao Li 已提交
2772

2773 2774
    syncCacheEntry(ths->pLogStore, pEntry, &h);

2775 2776
    // if mulit replica, start replicate right now
    if (ths->replicaNum > 1) {
M
Minghao Li 已提交
2777
      syncNodeReplicate(ths);
2778
    }
2779

2780 2781
    // if only myself, maybe commit right now
    if (ths->replicaNum == 1) {
2782 2783 2784 2785 2786
      if (syncNodeIsMnode(ths)) {
        syncMaybeAdvanceCommitIndex(ths);
      } else {
        syncOneReplicaAdvance(ths);
      }
2787
    }
M
Minghao Li 已提交
2788 2789
  }

2790 2791 2792 2793 2794 2795 2796 2797
  if (pRetIndex != NULL) {
    if (ret == 0 && pEntry != NULL) {
      *pRetIndex = pEntry->index;
    } else {
      *pRetIndex = SYNC_INDEX_INVALID;
    }
  }

2798 2799 2800
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
B
Benguang Zhao 已提交
2801
    syncEntryDestroy(pEntry);
2802 2803
  }

M
Minghao Li 已提交
2804
  return ret;
2805
}
M
Minghao Li 已提交
2806

S
Shengliang Guan 已提交
2807 2808 2809
const char* syncStr(ESyncState state) {
  switch (state) {
    case TAOS_SYNC_STATE_FOLLOWER:
2810
      return "follower";
S
Shengliang Guan 已提交
2811
    case TAOS_SYNC_STATE_CANDIDATE:
2812
      return "candidate";
S
Shengliang Guan 已提交
2813
    case TAOS_SYNC_STATE_LEADER:
2814
      return "leader";
S
Shengliang Guan 已提交
2815
    case TAOS_SYNC_STATE_ERROR:
2816
      return "error";
S
Shengliang Guan 已提交
2817 2818 2819 2820
    case TAOS_SYNC_STATE_OFFLINE:
      return "offline";
    default:
      return "unknown";
S
Shengliang Guan 已提交
2821
  }
M
Minghao Li 已提交
2822
}
2823

2824
#if 0
2825
int32_t syncDoLeaderTransfer(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry) {
2826
  if (ths->state != TAOS_SYNC_STATE_FOLLOWER) {
S
Shengliang Guan 已提交
2827
    sNTrace(ths, "I am not follower, can not do leader transfer");
2828 2829
    return 0;
  }
2830 2831

  if (!ths->restoreFinish) {
S
Shengliang Guan 已提交
2832
    sNTrace(ths, "restore not finish, can not do leader transfer");
2833 2834 2835
    return 0;
  }

2836
  if (pEntry->term < ths->pRaftStore->currentTerm) {
2837
    sNTrace(ths, "little term:%" PRId64 ", can not do leader transfer", pEntry->term);
2838 2839 2840 2841
    return 0;
  }

  if (pEntry->index < syncNodeGetLastIndex(ths)) {
S
Shengliang Guan 已提交
2842
    sNTrace(ths, "little index:%" PRId64 ", can not do leader transfer", pEntry->index);
2843 2844 2845
    return 0;
  }

2846 2847
  /*
    if (ths->vgId > 1) {
S
Shengliang Guan 已提交
2848
      sNTrace(ths, "I am vnode, can not do leader transfer");
2849 2850 2851 2852
      return 0;
    }
  */

2853
  SyncLeaderTransfer* pSyncLeaderTransfer = pRpcMsg->pCont;
S
Shengliang Guan 已提交
2854
  sNTrace(ths, "do leader transfer, index:%" PRId64, pEntry->index);
M
Minghao Li 已提交
2855

M
Minghao Li 已提交
2856 2857 2858
  bool sameId = syncUtilSameId(&(pSyncLeaderTransfer->newLeaderId), &(ths->myRaftId));
  bool sameNodeInfo = strcmp(pSyncLeaderTransfer->newNodeInfo.nodeFqdn, ths->myNodeInfo.nodeFqdn) == 0 &&
                      pSyncLeaderTransfer->newNodeInfo.nodePort == ths->myNodeInfo.nodePort;
M
Minghao Li 已提交
2859

M
Minghao Li 已提交
2860 2861
  bool same = sameId || sameNodeInfo;
  if (same) {
M
Minghao Li 已提交
2862 2863 2864
    // reset elect timer now!
    int32_t electMS = 1;
    int32_t ret = syncNodeRestartElectTimer(ths, electMS);
2865
    ASSERT(ret == 0);
M
Minghao Li 已提交
2866

2867
    sNTrace(ths, "maybe leader transfer to %s:%d %" PRId64, pSyncLeaderTransfer->newNodeInfo.nodeFqdn,
S
Shengliang Guan 已提交
2868
            pSyncLeaderTransfer->newNodeInfo.nodePort, pSyncLeaderTransfer->newLeaderId.addr);
2869 2870
  }

M
Minghao Li 已提交
2871
  if (ths->pFsm->FpLeaderTransferCb != NULL) {
S
Shengliang Guan 已提交
2872
    SFsmCbMeta cbMeta = {
S
Shengliang Guan 已提交
2873 2874 2875 2876 2877 2878 2879 2880 2881
        .code = 0,
        .currentTerm = ths->pRaftStore->currentTerm,
        .flag = 0,
        .index = pEntry->index,
        .lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, pEntry->index),
        .isWeak = pEntry->isWeak,
        .seqNum = pEntry->seqNum,
        .state = ths->state,
        .term = pEntry->term,
S
Shengliang Guan 已提交
2882 2883
    };
    ths->pFsm->FpLeaderTransferCb(ths->pFsm, pRpcMsg, &cbMeta);
2884 2885
  }

2886 2887 2888
  return 0;
}

2889 2890
#endif

2891
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
S
Shengliang Guan 已提交
2892
  for (int32_t i = 0; i < pNewCfg->replicaNum; ++i) {
2893 2894 2895 2896
    SRaftId raftId = {
        .addr = SYNC_ADDR(&pNewCfg->nodeInfo[i]),
        .vgId = ths->vgId,
    };
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906

    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
      pNewCfg->myIndex = i;
      return 0;
    }
  }

  return -1;
}

2907 2908 2909 2910
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
}

M
Minghao Li 已提交
2911
int32_t syncNodeDoCommit(SSyncNode* ths, SyncIndex beginIndex, SyncIndex endIndex, uint64_t flag) {
2912
  ASSERT(false);
2913 2914 2915 2916
  if (beginIndex > endIndex) {
    return 0;
  }

M
Minghao Li 已提交
2917 2918 2919 2920 2921 2922 2923 2924 2925
  if (ths == NULL) {
    return -1;
  }

  if (ths->pFsm != NULL && ths->pFsm->FpGetSnapshotInfo != NULL) {
    // advance commit index to sanpshot first
    SSnapshot snapshot = {0};
    ths->pFsm->FpGetSnapshotInfo(ths->pFsm, &snapshot);
    if (snapshot.lastApplyIndex >= 0 && snapshot.lastApplyIndex >= beginIndex) {
S
Shengliang Guan 已提交
2926
      sNTrace(ths, "commit by snapshot from index:%" PRId64 " to index:%" PRId64, beginIndex, snapshot.lastApplyIndex);
2927

M
Minghao Li 已提交
2928 2929 2930
      // update begin index
      beginIndex = snapshot.lastApplyIndex + 1;
    }
2931 2932
  }

2933 2934
  int32_t    code = 0;
  ESyncState state = flag;
M
Minghao Li 已提交
2935

S
Shengliang Guan 已提交
2936
  sNTrace(ths, "commit by wal from index:%" PRId64 " to index:%" PRId64, beginIndex, endIndex);
2937 2938 2939 2940 2941 2942

  // execute fsm
  if (ths->pFsm != NULL) {
    for (SyncIndex i = beginIndex; i <= endIndex; ++i) {
      if (i != SYNC_INDEX_INVALID) {
        SSyncRaftEntry* pEntry;
2943 2944 2945 2946
        SLRUCache*      pCache = ths->pLogStore->pCache;
        LRUHandle*      h = taosLRUCacheLookup(pCache, &i, sizeof(i));
        if (h) {
          pEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2947

2948
          ths->pLogStore->cacheHit++;
2949 2950
          sNTrace(ths, "hit cache index:%" PRId64 ", bytes:%u, %p", i, pEntry->bytes, pEntry);

2951
        } else {
2952
          ths->pLogStore->cacheMiss++;
2953 2954
          sNTrace(ths, "miss cache index:%" PRId64, i);

2955
          code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, i, &pEntry);
2956 2957
          // ASSERT(code == 0);
          // ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2958
          if (code != 0 || pEntry == NULL) {
S
Shengliang Guan 已提交
2959
            sNError(ths, "get log entry error");
2960
            sFatal("vgId:%d, get log entry %" PRId64 " error when commit since %s", ths->vgId, i, terrstr());
M
Minghao Li 已提交
2961 2962
            continue;
          }
2963
        }
2964

2965
        SRpcMsg rpcMsg = {0};
2966 2967
        syncEntry2OriginalRpc(pEntry, &rpcMsg);

2968
        sTrace("do commit index:%" PRId64 ", type:%s", i, TMSG_INFO(pEntry->msgType));
M
Minghao Li 已提交
2969

2970
        // user commit
2971 2972
        if ((ths->pFsm->FpCommitCb != NULL) && syncUtilUserCommit(pEntry->originalRpcType)) {
          bool internalExecute = true;
S
Shengliang Guan 已提交
2973
          if ((ths->replicaNum == 1) && ths->restoreFinish && ths->vgId != 1) {
2974 2975 2976
            internalExecute = false;
          }

M
Minghao Li 已提交
2977 2978
          sNTrace(ths, "user commit index:%" PRId64 ", internal:%d, type:%s", i, internalExecute,
                  TMSG_INFO(pEntry->msgType));
2979

2980 2981
          // execute fsm in apply thread, or execute outside syncPropose
          if (internalExecute) {
S
Shengliang Guan 已提交
2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
            SFsmCbMeta cbMeta = {
                .index = pEntry->index,
                .lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, pEntry->index),
                .isWeak = pEntry->isWeak,
                .code = 0,
                .state = ths->state,
                .seqNum = pEntry->seqNum,
                .term = pEntry->term,
                .currentTerm = ths->pRaftStore->currentTerm,
                .flag = flag,
            };

S
Shengliang Guan 已提交
2994
            syncRespMgrGetAndDel(ths->pSyncRespMgr, cbMeta.seqNum, &rpcMsg.info);
S
Shengliang Guan 已提交
2995
            ths->pFsm->FpCommitCb(ths->pFsm, &rpcMsg, &cbMeta);
M
Minghao Li 已提交
2996
          }
2997
        }
2998

2999 3000
#if 0
        // execute in pre-commit
M
Minghao Li 已提交
3001
        // leader transfer
3002 3003
        if (pEntry->originalRpcType == TDMT_SYNC_LEADER_TRANSFER) {
          code = syncDoLeaderTransfer(ths, &rpcMsg, pEntry);
3004
          ASSERT(code == 0);
3005
        }
3006
#endif
3007 3008

        // restore finish
3009
        // if only snapshot, a noop entry will be append, so syncLogLastIndex is always ok
3010 3011 3012 3013 3014 3015
        if (pEntry->index == ths->pLogStore->syncLogLastIndex(ths->pLogStore)) {
          if (ths->restoreFinish == false) {
            if (ths->pFsm->FpRestoreFinishCb != NULL) {
              ths->pFsm->FpRestoreFinishCb(ths->pFsm);
            }
            ths->restoreFinish = true;
M
Minghao Li 已提交
3016

3017
            int64_t restoreDelay = taosGetTimestampMs() - ths->leaderTime;
S
Shengliang Guan 已提交
3018
            sNTrace(ths, "restore finish, index:%" PRId64 ", elapsed:%" PRId64 " ms", pEntry->index, restoreDelay);
3019 3020 3021 3022
          }
        }

        rpcFreeCont(rpcMsg.pCont);
3023 3024 3025
        if (h) {
          taosLRUCacheRelease(pCache, h, false);
        } else {
B
Benguang Zhao 已提交
3026
          syncEntryDestroy(pEntry);
3027
        }
3028 3029 3030 3031
      }
    }
  }
  return 0;
3032 3033 3034
}

bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
S
Shengliang Guan 已提交
3035
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
3036 3037 3038 3039 3040
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
      return true;
    }
  }
  return false;
M
Minghao Li 已提交
3041 3042 3043 3044
}

SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
  SSyncSnapshotSender* pSender = NULL;
S
Shengliang Guan 已提交
3045
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
3046 3047 3048 3049 3050
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pSender = (ths->senders)[i];
    }
  }
  return pSender;
M
Minghao Li 已提交
3051
}
M
Minghao Li 已提交
3052

3053 3054
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
  SSyncTimer* pTimer = NULL;
S
Shengliang Guan 已提交
3055
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
3056 3057 3058 3059 3060 3061 3062
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
    }
  }
  return pTimer;
}

M
Minghao Li 已提交
3063 3064
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
  SPeerState* pState = NULL;
S
Shengliang Guan 已提交
3065
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
3066 3067 3068 3069 3070 3071 3072 3073 3074
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pState = &((ths->peerStates)[i]);
    }
  }
  return pState;
}

bool syncNodeNeedSendAppendEntries(SSyncNode* ths, const SRaftId* pDestId, const SyncAppendEntries* pMsg) {
  SPeerState* pState = syncNodeGetPeerState(ths, pDestId);
M
Minghao Li 已提交
3075
  if (pState == NULL) {
3076
    sError("vgId:%d, replica maybe dropped", ths->vgId);
M
Minghao Li 已提交
3077 3078
    return false;
  }
M
Minghao Li 已提交
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089

  SyncIndex sendIndex = pMsg->prevLogIndex + 1;
  int64_t   tsNow = taosGetTimestampMs();

  if (pState->lastSendIndex == sendIndex && tsNow - pState->lastSendTime < SYNC_APPEND_ENTRIES_TIMEOUT_MS) {
    return false;
  }

  return true;
}

M
Minghao Li 已提交
3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103
bool syncNodeCanChange(SSyncNode* pSyncNode) {
  if (pSyncNode->changing) {
    sError("sync cannot change");
    return false;
  }

  if ((pSyncNode->commitIndex >= SYNC_INDEX_BEGIN)) {
    SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);
    if (pSyncNode->commitIndex != lastIndex) {
      sError("sync cannot change2");
      return false;
    }
  }

S
Shengliang Guan 已提交
3104
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
M
Minghao Li 已提交
3105
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
M
Minghao Li 已提交
3106
    if (pSender != NULL && pSender->start) {
M
Minghao Li 已提交
3107 3108 3109 3110 3111 3112
      sError("sync cannot change3");
      return false;
    }
  }

  return true;
M
Minghao Li 已提交
3113
}