syncMain.c 86.2 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"
M
Minghao Li 已提交
26
#include "syncRaftCfg.h"
M
Minghao Li 已提交
27
#include "syncRaftLog.h"
M
Minghao Li 已提交
28
#include "syncRaftStore.h"
M
Minghao Li 已提交
29
#include "syncReplication.h"
M
Minghao Li 已提交
30 31
#include "syncRequestVote.h"
#include "syncRequestVoteReply.h"
M
Minghao Li 已提交
32
#include "syncRespMgr.h"
M
Minghao Li 已提交
33
#include "syncSnapshot.h"
M
Minghao Li 已提交
34
#include "syncTimeout.h"
M
Minghao Li 已提交
35
#include "syncUtil.h"
M
Minghao Li 已提交
36
#include "syncVoteMgr.h"
M
Minghao Li 已提交
37

M
Minghao Li 已提交
38 39 40 41 42
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);
43
static void    syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId);
S
Shengliang Guan 已提交
44
static bool    syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg);
S
Shengliang Guan 已提交
45 46 47
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 已提交
48 49 50 51 52 53 54 55 56 57 58 59
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);
static SyncIndex     syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex);
M
Minghao Li 已提交
60

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

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

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

M
Minghao Li 已提交
83
void syncStart(int64_t rid) {
S
Shengliang Guan 已提交
84 85 86 87
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode != NULL) {
    syncNodeStart(pSyncNode);
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
88 89 90
  }
}

M
Minghao Li 已提交
91
void syncStop(int64_t rid) {
S
Shengliang Guan 已提交
92
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
93
  if (pSyncNode != NULL) {
94
    pSyncNode->isStart = false;
S
Shengliang Guan 已提交
95
    syncNodeRelease(pSyncNode);
S
Shengliang Guan 已提交
96
    syncNodeRemove(rid);
M
Minghao Li 已提交
97
  }
S
Shengliang Guan 已提交
98
}
M
Minghao Li 已提交
99

M
Minghao Li 已提交
100 101
void syncPreStop(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
102 103 104 105
  if (pSyncNode != NULL) {
    syncNodePreClose(pSyncNode);
    syncNodeRelease(pSyncNode);
  }
M
Minghao Li 已提交
106 107
}

S
Shengliang Guan 已提交
108 109 110
static bool syncNodeCheckNewConfig(SSyncNode* pSyncNode, const SSyncCfg* pCfg) {
  if (!syncNodeInConfig(pSyncNode, pCfg)) return false;
  return abs(pCfg->replicaNum - pSyncNode->replicaNum) <= 1;
M
Minghao Li 已提交
111 112
}

S
Shengliang Guan 已提交
113
int32_t syncReconfig(int64_t rid, SSyncCfg* pNewCfg) {
S
Shengliang Guan 已提交
114
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
115
  if (pSyncNode == NULL) return -1;
M
Minghao Li 已提交
116

M
Minghao Li 已提交
117
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
S
Shengliang Guan 已提交
118
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
119
    terrno = TSDB_CODE_SYN_NEW_CONFIG_ERROR;
S
Shengliang Guan 已提交
120
    sError("vgId:%d, failed to reconfig since invalid new config", pSyncNode->vgId);
M
Minghao Li 已提交
121
    return -1;
M
Minghao Li 已提交
122
  }
123

S
Shengliang Guan 已提交
124 125
  syncNodeUpdateNewConfigIndex(pSyncNode, pNewCfg);
  syncNodeDoConfigChange(pSyncNode, pNewCfg, SYNC_INDEX_INVALID);
S
Shengliang Guan 已提交
126

M
Minghao Li 已提交
127 128 129 130
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    syncNodeStopHeartbeatTimer(pSyncNode);

    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
S
Shengliang Guan 已提交
131
      syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]);
M
Minghao Li 已提交
132 133 134 135 136
    }

    syncNodeStartHeartbeatTimer(pSyncNode);
    syncNodeReplicate(pSyncNode);
  }
S
Shengliang Guan 已提交
137

S
Shengliang Guan 已提交
138
  syncNodeRelease(pSyncNode);
S
Shengliang Guan 已提交
139
  return 0;
M
Minghao Li 已提交
140
}
M
Minghao Li 已提交
141

S
Shengliang Guan 已提交
142 143 144 145
int32_t syncProcessMsg(int64_t rid, SRpcMsg* pMsg) {
  int32_t code = -1;
  if (!syncIsInit()) return code;

S
Shengliang Guan 已提交
146
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
147 148
  if (pSyncNode == NULL) return code;

S
Shengliang Guan 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
  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:
      code = syncNodeOnSnapshotReply(pSyncNode, pMsg);
      break;
    case TDMT_SYNC_LOCAL_CMD:
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
      break;
    default:
      sError("vgId:%d, failed to process msg:%p since invalid type:%s", pSyncNode->vgId, pMsg,
             TMSG_INFO(pMsg->msgType));
      code = -1;
M
Minghao Li 已提交
187 188
  }

S
Shengliang Guan 已提交
189
  syncNodeRelease(pSyncNode);
S
Shengliang Guan 已提交
190
  return code;
191 192
}

S
Shengliang Guan 已提交
193
int32_t syncLeaderTransfer(int64_t rid) {
S
Shengliang Guan 已提交
194
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
195
  if (pSyncNode == NULL) return -1;
196

S
Shengliang Guan 已提交
197
  int32_t ret = syncNodeLeaderTransfer(pSyncNode);
S
Shengliang Guan 已提交
198
  syncNodeRelease(pSyncNode);
199 200 201
  return ret;
}

M
Minghao Li 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
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;
}

218
int32_t syncBeginSnapshot(int64_t rid, int64_t lastApplyIndex) {
S
Shengliang Guan 已提交
219
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
220
  if (pSyncNode == NULL) {
221
    sError("sync begin snapshot error");
222 223
    return -1;
  }
224

225 226
  int32_t code = 0;

M
Minghao Li 已提交
227
  if (syncNodeIsMnode(pSyncNode)) {
M
Minghao Li 已提交
228 229 230
    // mnode
    int64_t logRetention = SYNC_MNODE_LOG_RETENTION;

M
Minghao Li 已提交
231 232 233
    SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
    SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore);
    int64_t   logNum = endIndex - beginIndex;
M
Minghao Li 已提交
234 235 236
    bool      isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore);

    if (isEmpty || (!isEmpty && logNum < logRetention)) {
S
Shengliang Guan 已提交
237 238
      sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", log-num:%" PRId64 ", empty:%d, do not delete wal",
              lastApplyIndex, logNum, isEmpty);
S
Shengliang Guan 已提交
239
      syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
240 241 242
      return 0;
    }

M
Minghao Li 已提交
243 244 245
    goto _DEL_WAL;

  } else {
246 247 248 249 250 251 252 253 254 255 256 257
    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 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271
    // 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) {
            do {
              char     host[64];
              uint16_t port;
              syncUtilU642Addr(pSyncNode->peersId[i].addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
272 273 274 275
              sNTrace(pSyncNode,
                      "new-snapshot-index:%" PRId64 " is greater than match-index:%" PRId64
                      " of %s:%d, do not delete wal",
                      lastApplyIndex, matchIndex, host, port);
M
Minghao Li 已提交
276 277
            } while (0);

S
Shengliang Guan 已提交
278
            syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
279 280 281 282 283 284
            return 0;
          }
        }

      } else if (pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER) {
        if (lastApplyIndex > pSyncNode->minMatchIndex) {
S
Shengliang Guan 已提交
285 286 287
          sNTrace(pSyncNode,
                  "new-snapshot-index:%" PRId64 " is greater than min-match-index:%" PRId64 ", do not delete wal",
                  lastApplyIndex, pSyncNode->minMatchIndex);
S
Shengliang Guan 已提交
288
          syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
289 290 291 292
          return 0;
        }

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

      } else {
S
Shengliang Guan 已提交
298
        sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " unknown state, do not delete wal", lastApplyIndex);
S
Shengliang Guan 已提交
299
        syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
300 301 302 303 304 305 306 307 308
        return 0;
      }

      goto _DEL_WAL;

    } else {
      // one replica

      goto _DEL_WAL;
309 310 311
    }
  }

M
Minghao Li 已提交
312
_DEL_WAL:
313

M
Minghao Li 已提交
314
  do {
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    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);
        }
335

M
Minghao Li 已提交
336
      } else {
337 338
        sNTrace(pSyncNode, "snapshotting for %" PRId64 ", do not delete wal for new-snapshot-index:%" PRId64,
                snapshottingIndex, lastApplyIndex);
M
Minghao Li 已提交
339
      }
340
    }
M
Minghao Li 已提交
341
  } while (0);
342

S
Shengliang Guan 已提交
343
  syncNodeRelease(pSyncNode);
344 345 346 347
  return code;
}

int32_t syncEndSnapshot(int64_t rid) {
S
Shengliang Guan 已提交
348
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
349
  if (pSyncNode == NULL) {
350
    sError("sync end snapshot error");
351 352 353
    return -1;
  }

354 355 356 357
  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 已提交
358
    if (code != 0) {
359
      sNError(pSyncNode, "wal snapshot end error since:%s", terrstr());
S
Shengliang Guan 已提交
360
      syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
361 362
      return -1;
    } else {
S
Shengliang Guan 已提交
363
      sNTrace(pSyncNode, "wal snapshot end, index:%" PRId64, atomic_load_64(&pSyncNode->snapshottingIndex));
M
Minghao Li 已提交
364 365
      atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
    }
366
  }
367

S
Shengliang Guan 已提交
368
  syncNodeRelease(pSyncNode);
369 370 371
  return code;
}

M
Minghao Li 已提交
372
int32_t syncStepDown(int64_t rid, SyncTerm newTerm) {
S
Shengliang Guan 已提交
373
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
M
Minghao Li 已提交
374
  if (pSyncNode == NULL) {
375
    sError("sync step down error");
M
Minghao Li 已提交
376 377 378 379
    return -1;
  }

  syncNodeStepDown(pSyncNode, newTerm);
S
Shengliang Guan 已提交
380
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
381 382 383
  return 0;
}

384 385 386
bool syncIsReadyForRead(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode == NULL) {
387
    sError("sync ready for read error");
388 389 390 391 392 393 394 395 396 397
    return false;
  }

  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && pSyncNode->restoreFinish) {
    syncNodeRelease(pSyncNode);
    return true;
  }

  bool ready = false;
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && !pSyncNode->restoreFinish) {
398 399 400
    if (!pSyncNode->pFsm->FpApplyQueueEmptyCb(pSyncNode->pFsm)) {
      // apply queue not empty
      ready = false;
401

402 403
    } else {
      if (!pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore)) {
404
        SyncIndex       lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
405
        SSyncRaftEntry* pEntry = NULL;
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        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;

          sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", lastIndex, pEntry->bytes, pEntry);

        } else {
          sNTrace(pSyncNode, "miss cache index:%" PRId64, lastIndex);

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

421 422 423 424 425
        if (code == 0 && pEntry != NULL) {
          if (pEntry->originalRpcType == TDMT_SYNC_NOOP && pEntry->term == pSyncNode->pRaftStore->currentTerm) {
            ready = true;
          }

426 427 428 429 430
          if (h) {
            taosLRUCacheRelease(pCache, h, false);
          } else {
            syncEntryDestory(pEntry);
          }
431
        }
432 433 434 435
      }
    }
  }

436 437 438 439 440 441 442 443
  if (!ready) {
    if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
      terrno = TSDB_CODE_SYN_NOT_LEADER;
    } else {
      terrno = TSDB_CODE_APP_NOT_READY;
    }
  }

444 445 446 447
  syncNodeRelease(pSyncNode);
  return ready;
}

M
Minghao Li 已提交
448 449
int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode) {
  if (pSyncNode->peersNum == 0) {
S
Shengliang Guan 已提交
450
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
M
Minghao Li 已提交
451 452 453 454
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
  }

455
  int32_t ret = 0;
456
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && pSyncNode->replicaNum > 1) {
457
    SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
458 459 460 461 462 463 464
    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];
      }
    }
465 466 467
    ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
  }

M
Minghao Li 已提交
468 469 470 471 472
  return ret;
}

int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader) {
  if (pSyncNode->replicaNum == 1) {
S
Shengliang Guan 已提交
473
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
M
Minghao Li 已提交
474 475 476 477
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
  }

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

480 481 482 483
  SRpcMsg rpcMsg = {0};
  (void)syncBuildLeaderTransfer(&rpcMsg, pSyncNode->vgId);

  SyncLeaderTransfer* pMsg = rpcMsg.pCont;
M
Minghao Li 已提交
484 485 486 487
  pMsg->newLeaderId.addr = syncUtilAddr2U64(newLeader.nodeFqdn, newLeader.nodePort);
  pMsg->newLeaderId.vgId = pSyncNode->vgId;
  pMsg->newNodeInfo = newLeader;

S
Shengliang Guan 已提交
488 489 490
  int32_t ret = syncNodePropose(pSyncNode, &rpcMsg, false);
  rpcFreeCont(rpcMsg.pCont);
  return ret;
M
Minghao Li 已提交
491 492
}

493 494
SSyncState syncGetState(int64_t rid) {
  SSyncState state = {.state = TAOS_SYNC_STATE_ERROR};
M
Minghao Li 已提交
495

S
Shengliang Guan 已提交
496
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
497 498 499 500
  if (pSyncNode != NULL) {
    state.state = pSyncNode->state;
    state.restored = pSyncNode->restoreFinish;
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
501 502
  }

503
  return state;
M
Minghao Li 已提交
504 505
}

506
#if 0
507 508 509 510 511
int32_t syncGetSnapshotByIndex(int64_t rid, SyncIndex index, SSnapshot* pSnapshot) {
  if (index < SYNC_INDEX_BEGIN) {
    return -1;
  }

S
Shengliang Guan 已提交
512
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
513 514 515 516 517 518 519 520 521 522 523
  if (pSyncNode == NULL) {
    return -1;
  }
  ASSERT(rid == pSyncNode->rid);

  SSyncRaftEntry* pEntry = NULL;
  int32_t         code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, index, &pEntry);
  if (code != 0) {
    if (pEntry != NULL) {
      syncEntryDestory(pEntry);
    }
S
Shengliang Guan 已提交
524
    syncNodeRelease(pSyncNode);
525 526 527 528 529 530 531 532 533 534
    return -1;
  }
  ASSERT(pEntry != NULL);

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

  syncEntryDestory(pEntry);
S
Shengliang Guan 已提交
535
  syncNodeRelease(pSyncNode);
536 537 538
  return 0;
}

539
int32_t syncGetSnapshotMeta(int64_t rid, struct SSnapshotMeta* sMeta) {
S
Shengliang Guan 已提交
540
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
541 542 543
  if (pSyncNode == NULL) {
    return -1;
  }
M
Minghao Li 已提交
544
  ASSERT(rid == pSyncNode->rid);
545 546
  sMeta->lastConfigIndex = pSyncNode->pRaftCfg->lastConfigIndex;

S
Shengliang Guan 已提交
547
  sTrace("vgId:%d, get snapshot meta, lastConfigIndex:%" PRId64, pSyncNode->vgId, pSyncNode->pRaftCfg->lastConfigIndex);
548

S
Shengliang Guan 已提交
549
  syncNodeRelease(pSyncNode);
550 551 552
  return 0;
}

553
int32_t syncGetSnapshotMetaByIndex(int64_t rid, SyncIndex snapshotIndex, struct SSnapshotMeta* sMeta) {
S
Shengliang Guan 已提交
554
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
555 556 557
  if (pSyncNode == NULL) {
    return -1;
  }
M
Minghao Li 已提交
558
  ASSERT(rid == pSyncNode->rid);
559 560 561 562

  ASSERT(pSyncNode->pRaftCfg->configIndexCount >= 1);
  SyncIndex lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[0];

S
Shengliang Guan 已提交
563
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->configIndexCount; ++i) {
564 565 566 567 568 569
    if ((pSyncNode->pRaftCfg->configIndexArr)[i] > lastIndex &&
        (pSyncNode->pRaftCfg->configIndexArr)[i] <= snapshotIndex) {
      lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[i];
    }
  }
  sMeta->lastConfigIndex = lastIndex;
570
  sTrace("vgId:%d, get snapshot meta by index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId, snapshotIndex,
S
Shengliang Guan 已提交
571
         sMeta->lastConfigIndex);
572

S
Shengliang Guan 已提交
573
  syncNodeRelease(pSyncNode);
574 575
  return 0;
}
576
#endif
577

578 579 580 581
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
  ASSERT(pSyncNode->pRaftCfg->configIndexCount >= 1);
  SyncIndex lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[0];

S
Shengliang Guan 已提交
582
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->configIndexCount; ++i) {
583 584 585 586 587
    if ((pSyncNode->pRaftCfg->configIndexArr)[i] > lastIndex &&
        (pSyncNode->pRaftCfg->configIndexArr)[i] <= snapshotLastApplyIndex) {
      lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[i];
    }
  }
S
Shengliang Guan 已提交
588
  sTrace("vgId:%d, sync get last config index, index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId,
S
Shengliang Guan 已提交
589
         snapshotLastApplyIndex, lastIndex);
590 591 592 593

  return lastIndex;
}

S
Shengliang Guan 已提交
594
void syncGetRetryEpSet(int64_t rid, SEpSet* pEpSet) {
M
Minghao Li 已提交
595
  pEpSet->numOfEps = 0;
596

S
Shengliang Guan 已提交
597
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
598
  if (pSyncNode == NULL) return;
599

S
Shengliang Guan 已提交
600
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
S
Shengliang Guan 已提交
601 602 603 604 605
    SEp* pEp = &pEpSet->eps[i];
    tstrncpy(pEp->fqdn, pSyncNode->pRaftCfg->cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
    pEp->port = (pSyncNode->pRaftCfg->cfg.nodeInfo)[i].nodePort;
    pEpSet->numOfEps++;
    sInfo("vgId:%d, sync get retry epset, index:%d %s:%d", pSyncNode->vgId, i, pEp->fqdn, pEp->port);
606
  }
M
Minghao Li 已提交
607 608 609
  if (pEpSet->numOfEps > 0) {
    pEpSet->inUse = (pSyncNode->pRaftCfg->cfg.myIndex + 1) % pEpSet->numOfEps;
  }
M
Minghao Li 已提交
610

S
Shengliang Guan 已提交
611
  sInfo("vgId:%d, sync get retry epset numOfEps:%d inUse:%d", pSyncNode->vgId, pEpSet->numOfEps, pEpSet->inUse);
S
Shengliang Guan 已提交
612
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
613
}
614

M
Minghao Li 已提交
615
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak) {
S
Shengliang Guan 已提交
616
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
617
  if (pSyncNode == NULL) {
618
    sError("sync propose error");
M
Minghao Li 已提交
619
    return -1;
620
  }
M
Minghao Li 已提交
621

622
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak);
S
Shengliang Guan 已提交
623
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
624 625 626
  return ret;
}

627
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak) {
S
Shengliang Guan 已提交
628 629 630 631 632
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
    terrno = TSDB_CODE_SYN_NOT_LEADER;
    sNError(pSyncNode, "sync propose not leader, %s, type:%s", syncStr(pSyncNode->state), TMSG_INFO(pMsg->msgType));
    return -1;
  }
M
Minghao Li 已提交
633

S
Shengliang Guan 已提交
634 635 636 637 638 639 640 641
  // 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;
  }

642
  // heartbeat timeout
643
  if (syncNodeHeartbeatReplyTimeout(pSyncNode)) {
644 645 646 647 648 649
    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 已提交
650 651 652
  // optimized one replica
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
    SyncIndex retIndex;
653
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
S
Shengliang Guan 已提交
654 655 656
    if (code == 0) {
      pMsg->info.conn.applyIndex = retIndex;
      pMsg->info.conn.applyTerm = pSyncNode->pRaftStore->currentTerm;
657 658 659
      sTrace("vgId:%d, propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
             TMSG_INFO(pMsg->msgType));
      return 1;
S
Shengliang Guan 已提交
660 661
    } else {
      terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
662
      sError("vgId:%d, failed to propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
S
Shengliang Guan 已提交
663
             TMSG_INFO(pMsg->msgType));
664
      return -1;
665
    }
S
Shengliang Guan 已提交
666
  } else {
S
Shengliang Guan 已提交
667 668
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
669
    SRpcMsg   rpcMsg = {0};
S
Shengliang Guan 已提交
670
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
671 672 673 674 675
    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 已提交
676

677 678 679 680 681
    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 已提交
682
    }
M
Minghao Li 已提交
683

684 685
    return code;
  }
M
Minghao Li 已提交
686 687
}

S
Shengliang Guan 已提交
688
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId) {
689 690 691 692 693
  pSyncTimer->pTimer = NULL;
  pSyncTimer->counter = 0;
  pSyncTimer->timerMS = pSyncNode->hbBaseLine;
  pSyncTimer->timerCb = syncNodeEqPeerHeartbeatTimer;
  pSyncTimer->destId = destId;
M
Minghao Li 已提交
694
  pSyncTimer->timeStamp = taosGetTimestampMs();
695 696 697 698
  atomic_store_64(&pSyncTimer->logicClock, 0);
  return 0;
}

S
Shengliang Guan 已提交
699
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
700
  int32_t ret = 0;
S
Shengliang Guan 已提交
701
  int64_t tsNow = taosGetTimestampMs();
S
Shengliang Guan 已提交
702
  if (syncIsInit()) {
703 704 705 706 707 708
    SSyncHbTimerData* pData = syncHbTimerDataAcquire(pSyncTimer->hbDataRid);
    if (pData == NULL) {
      pData = taosMemoryMalloc(sizeof(SSyncHbTimerData));
      pData->rid = syncHbTimerDataAdd(pData);
    }
    pSyncTimer->hbDataRid = pData->rid;
S
Shengliang Guan 已提交
709
    pSyncTimer->timeStamp = tsNow;
710 711

    pData->syncNodeRid = pSyncNode->rid;
712 713 714
    pData->pTimer = pSyncTimer;
    pData->destId = pSyncTimer->destId;
    pData->logicClock = pSyncTimer->logicClock;
S
Shengliang Guan 已提交
715
    pData->execTime = tsNow + pSyncTimer->timerMS;
M
Minghao Li 已提交
716

717 718
    taosTmrReset(pSyncTimer->timerCb, pSyncTimer->timerMS / HEARTBEAT_TICK_NUM, (void*)(pData->rid),
                 syncEnv()->pTimerManager, &pSyncTimer->pTimer);
719 720 721 722 723 724
  } else {
    sError("vgId:%d, start ctrl hb timer error, sync env is stop", pSyncNode->vgId);
  }
  return ret;
}

S
Shengliang Guan 已提交
725
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
726 727 728 729
  int32_t ret = 0;
  atomic_add_fetch_64(&pSyncTimer->logicClock, 1);
  taosTmrStop(pSyncTimer->pTimer);
  pSyncTimer->pTimer = NULL;
730 731
  syncHbTimerDataRemove(pSyncTimer->hbDataRid);
  pSyncTimer->hbDataRid = -1;
732 733 734
  return ret;
}

S
Shengliang Guan 已提交
735 736
SSyncNode* syncNodeOpen(SSyncInfo* pSyncInfo) {
  SSyncNode* pSyncNode = taosMemoryCalloc(1, sizeof(SSyncNode));
737 738 739 740
  if (pSyncNode == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }
M
Minghao Li 已提交
741

M
Minghao Li 已提交
742 743 744 745
  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());
746
      goto _error;
M
Minghao Li 已提交
747
    }
748
  }
M
Minghao Li 已提交
749

S
Shengliang Guan 已提交
750
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
751
  if (!taosCheckExistFile(pSyncNode->configPath)) {
M
Minghao Li 已提交
752
    // create a new raft config file
S
Shengliang Guan 已提交
753
    SRaftCfgMeta meta = {0};
M
Minghao Li 已提交
754
    meta.isStandBy = pSyncInfo->isStandBy;
M
Minghao Li 已提交
755
    meta.snapshotStrategy = pSyncInfo->snapshotStrategy;
756
    meta.lastConfigIndex = SYNC_INDEX_INVALID;
M
Minghao Li 已提交
757
    meta.batchSize = pSyncInfo->batchSize;
S
Shengliang Guan 已提交
758 759
    if (raftCfgCreateFile(&pSyncInfo->syncCfg, meta, pSyncNode->configPath) != 0) {
      sError("vgId:%d, failed to create raft cfg file at %s", pSyncNode->vgId, pSyncNode->configPath);
H
Hongze Cheng 已提交
760
      goto _error;
761
    }
762
    if (pSyncInfo->syncCfg.replicaNum == 0) {
S
Shengliang Guan 已提交
763
      sInfo("vgId:%d, sync config not input", pSyncNode->vgId);
764 765
      pSyncInfo->syncCfg = pSyncNode->pRaftCfg->cfg;
    }
766 767 768
  } else {
    // update syncCfg by raft_config.json
    pSyncNode->pRaftCfg = raftCfgOpen(pSyncNode->configPath);
769
    if (pSyncNode->pRaftCfg == NULL) {
S
Shengliang Guan 已提交
770
      sError("vgId:%d, failed to open raft cfg file at %s", pSyncNode->vgId, pSyncNode->configPath);
H
Hongze Cheng 已提交
771
      goto _error;
772
    }
S
Shengliang Guan 已提交
773 774

    if (pSyncInfo->syncCfg.replicaNum > 0 && syncIsConfigChanged(&pSyncNode->pRaftCfg->cfg, &pSyncInfo->syncCfg)) {
S
Shengliang Guan 已提交
775 776 777 778 779 780
      sInfo("vgId:%d, use sync config from input options and write to cfg file", pSyncNode->vgId);
      pSyncNode->pRaftCfg->cfg = pSyncInfo->syncCfg;
      if (raftCfgPersist(pSyncNode->pRaftCfg) != 0) {
        sError("vgId:%d, failed to persist raft cfg file at %s", pSyncNode->vgId, pSyncNode->configPath);
        goto _error;
      }
S
Shengliang Guan 已提交
781 782 783 784
    } else {
      sInfo("vgId:%d, use sync config from raft cfg file", pSyncNode->vgId);
      pSyncInfo->syncCfg = pSyncNode->pRaftCfg->cfg;
    }
785 786

    raftCfgClose(pSyncNode->pRaftCfg);
787
    pSyncNode->pRaftCfg = NULL;
M
Minghao Li 已提交
788 789
  }

S
Shengliang Guan 已提交
790 791
  // init by SSyncInfo
  pSyncNode->vgId = pSyncInfo->vgId;
S
Shengliang Guan 已提交
792 793 794 795 796 797 798
  SSyncCfg* pCfg = &pSyncInfo->syncCfg;
  sDebug("vgId:%d, replica:%d selfIndex:%d", pSyncNode->vgId, pCfg->replicaNum, pCfg->myIndex);
  for (int32_t i = 0; i < pCfg->replicaNum; ++i) {
    SNodeInfo* pNode = &pCfg->nodeInfo[i];
    sDebug("vgId:%d, index:%d ep:%s:%u", pSyncNode->vgId, i, pNode->nodeFqdn, pNode->nodePort);
  }

M
Minghao Li 已提交
799
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
S
Shengliang Guan 已提交
800 801 802
  snprintf(pSyncNode->raftStorePath, sizeof(pSyncNode->raftStorePath), "%s%sraft_store.json", pSyncInfo->path,
           TD_DIRSEP);
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
M
Minghao Li 已提交
803

M
Minghao Li 已提交
804
  pSyncNode->pWal = pSyncInfo->pWal;
S
Shengliang Guan 已提交
805
  pSyncNode->msgcb = pSyncInfo->msgcb;
S
Shengliang Guan 已提交
806 807 808
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
M
Minghao Li 已提交
809

M
Minghao Li 已提交
810 811
  // init raft config
  pSyncNode->pRaftCfg = raftCfgOpen(pSyncNode->configPath);
812
  if (pSyncNode->pRaftCfg == NULL) {
S
Shengliang Guan 已提交
813
    sError("vgId:%d, failed to open raft cfg file at %s", pSyncNode->vgId, pSyncNode->configPath);
814 815
    goto _error;
  }
M
Minghao Li 已提交
816

M
Minghao Li 已提交
817
  // init internal
M
Minghao Li 已提交
818
  pSyncNode->myNodeInfo = pSyncNode->pRaftCfg->cfg.nodeInfo[pSyncNode->pRaftCfg->cfg.myIndex];
819
  if (!syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId)) {
S
Shengliang Guan 已提交
820
    sError("vgId:%d, failed to determine my raft member id", pSyncNode->vgId);
H
Hongze Cheng 已提交
821
    goto _error;
822
  }
M
Minghao Li 已提交
823

M
Minghao Li 已提交
824
  // init peersNum, peers, peersId
M
Minghao Li 已提交
825
  pSyncNode->peersNum = pSyncNode->pRaftCfg->cfg.replicaNum - 1;
S
Shengliang Guan 已提交
826 827
  int32_t j = 0;
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
M
Minghao Li 已提交
828 829
    if (i != pSyncNode->pRaftCfg->cfg.myIndex) {
      pSyncNode->peersNodeInfo[j] = pSyncNode->pRaftCfg->cfg.nodeInfo[i];
M
Minghao Li 已提交
830 831 832
      j++;
    }
  }
S
Shengliang Guan 已提交
833
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
834
    if (!syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i])) {
S
Shengliang Guan 已提交
835
      sError("vgId:%d, failed to determine raft member id, peer:%d", pSyncNode->vgId, i);
H
Hongze Cheng 已提交
836
      goto _error;
837
    }
M
Minghao Li 已提交
838
  }
M
Minghao Li 已提交
839

M
Minghao Li 已提交
840
  // init replicaNum, replicasId
M
Minghao Li 已提交
841
  pSyncNode->replicaNum = pSyncNode->pRaftCfg->cfg.replicaNum;
S
Shengliang Guan 已提交
842
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
843
    if (!syncUtilNodeInfo2RaftId(&pSyncNode->pRaftCfg->cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i])) {
S
Shengliang Guan 已提交
844
      sError("vgId:%d, failed to determine raft member id, replica:%d", pSyncNode->vgId, i);
H
Hongze Cheng 已提交
845
      goto _error;
846
    }
M
Minghao Li 已提交
847 848
  }

M
Minghao Li 已提交
849
  // init raft algorithm
M
Minghao Li 已提交
850
  pSyncNode->pFsm = pSyncInfo->pFsm;
851
  pSyncInfo->pFsm = NULL;
M
Minghao Li 已提交
852
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->pRaftCfg->cfg.replicaNum);
M
Minghao Li 已提交
853 854
  pSyncNode->leaderCache = EMPTY_RAFT_ID;

M
Minghao Li 已提交
855
  // init life cycle outside
M
Minghao Li 已提交
856

M
Minghao Li 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
  // 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 已提交
881
  // init TLA+ server vars
M
syncInt  
Minghao Li 已提交
882
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
M
Minghao Li 已提交
883
  pSyncNode->pRaftStore = raftStoreOpen(pSyncNode->raftStorePath);
884
  if (pSyncNode->pRaftStore == NULL) {
S
Shengliang Guan 已提交
885
    sError("vgId:%d, failed to open raft store at path %s", pSyncNode->vgId, pSyncNode->raftStorePath);
886 887
    goto _error;
  }
M
Minghao Li 已提交
888

M
Minghao Li 已提交
889
  // init TLA+ candidate vars
M
Minghao Li 已提交
890
  pSyncNode->pVotesGranted = voteGrantedCreate(pSyncNode);
891
  if (pSyncNode->pVotesGranted == NULL) {
S
Shengliang Guan 已提交
892
    sError("vgId:%d, failed to create VotesGranted", pSyncNode->vgId);
893 894
    goto _error;
  }
M
Minghao Li 已提交
895
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
896
  if (pSyncNode->pVotesRespond == NULL) {
S
Shengliang Guan 已提交
897
    sError("vgId:%d, failed to create VotesRespond", pSyncNode->vgId);
898 899
    goto _error;
  }
M
Minghao Li 已提交
900

M
Minghao Li 已提交
901 902
  // init TLA+ leader vars
  pSyncNode->pNextIndex = syncIndexMgrCreate(pSyncNode);
903
  if (pSyncNode->pNextIndex == NULL) {
S
Shengliang Guan 已提交
904
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
905 906
    goto _error;
  }
M
Minghao Li 已提交
907
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
908
  if (pSyncNode->pMatchIndex == NULL) {
S
Shengliang Guan 已提交
909
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
910 911
    goto _error;
  }
M
Minghao Li 已提交
912 913 914

  // init TLA+ log vars
  pSyncNode->pLogStore = logStoreCreate(pSyncNode);
915
  if (pSyncNode->pLogStore == NULL) {
S
Shengliang Guan 已提交
916
    sError("vgId:%d, failed to create SyncLogStore", pSyncNode->vgId);
917 918
    goto _error;
  }
919 920 921 922 923

  SyncIndex commitIndex = SYNC_INDEX_INVALID;
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    SSnapshot snapshot = {0};
    int32_t   code = pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
924
    if (code != 0) {
S
Shengliang Guan 已提交
925
      sError("vgId:%d, failed to get snapshot info, code:%d", pSyncNode->vgId, code);
H
Hongze Cheng 已提交
926
      goto _error;
927
    }
928 929
    if (snapshot.lastApplyIndex > commitIndex) {
      commitIndex = snapshot.lastApplyIndex;
S
Shengliang Guan 已提交
930
      sNTrace(pSyncNode, "reset commit index by snapshot");
931 932 933
    }
  }
  pSyncNode->commitIndex = commitIndex;
M
Minghao Li 已提交
934

M
Minghao Li 已提交
935 936 937 938 939
  // timer ms init
  pSyncNode->pingBaseLine = PING_TIMER_MS;
  pSyncNode->electBaseLine = ELECT_TIMER_MS_MIN;
  pSyncNode->hbBaseLine = HEARTBEAT_TIMER_MS;

M
Minghao Li 已提交
940
  // init ping timer
M
Minghao Li 已提交
941
  pSyncNode->pPingTimer = NULL;
M
Minghao Li 已提交
942
  pSyncNode->pingTimerMS = pSyncNode->pingBaseLine;
M
Minghao Li 已提交
943 944
  atomic_store_64(&pSyncNode->pingTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->pingTimerLogicClockUser, 0);
M
Minghao Li 已提交
945
  pSyncNode->FpPingTimerCB = syncNodeEqPingTimer;
M
Minghao Li 已提交
946
  pSyncNode->pingTimerCounter = 0;
M
Minghao Li 已提交
947

M
Minghao Li 已提交
948 949
  // init elect timer
  pSyncNode->pElectTimer = NULL;
M
Minghao Li 已提交
950
  pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
M
Minghao Li 已提交
951
  atomic_store_64(&pSyncNode->electTimerLogicClock, 0);
M
Minghao Li 已提交
952
  pSyncNode->FpElectTimerCB = syncNodeEqElectTimer;
M
Minghao Li 已提交
953 954 955 956
  pSyncNode->electTimerCounter = 0;

  // init heartbeat timer
  pSyncNode->pHeartbeatTimer = NULL;
M
Minghao Li 已提交
957
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
M
Minghao Li 已提交
958 959
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClockUser, 0);
M
Minghao Li 已提交
960
  pSyncNode->FpHeartbeatTimerCB = syncNodeEqHeartbeatTimer;
M
Minghao Li 已提交
961 962
  pSyncNode->heartbeatTimerCounter = 0;

963 964 965 966 967
  // 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 已提交
968
  // tools
M
Minghao Li 已提交
969
  pSyncNode->pSyncRespMgr = syncRespMgrCreate(pSyncNode, SYNC_RESP_TTL_MS);
970
  if (pSyncNode->pSyncRespMgr == NULL) {
S
Shengliang Guan 已提交
971
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
972 973
    goto _error;
  }
M
Minghao Li 已提交
974

975 976
  // restore state
  pSyncNode->restoreFinish = false;
977

M
Minghao Li 已提交
978
  // snapshot senders
S
Shengliang Guan 已提交
979
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
980 981 982
    SSyncSnapshotSender* pSender = snapshotSenderCreate(pSyncNode, i);
    // ASSERT(pSender != NULL);
    (pSyncNode->senders)[i] = pSender;
S
Shengliang Guan 已提交
983
    sSTrace(pSender, "snapshot sender create new while open, data:%p", pSender);
M
Minghao Li 已提交
984 985 986
  }

  // snapshot receivers
987
  pSyncNode->pNewNodeReceiver = snapshotReceiverCreate(pSyncNode, EMPTY_RAFT_ID);
M
Minghao Li 已提交
988

M
Minghao Li 已提交
989 990 991
  // is config changing
  pSyncNode->changing = false;

M
Minghao Li 已提交
992 993 994
  // peer state
  syncNodePeerStateInit(pSyncNode);

M
Minghao Li 已提交
995 996 997
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
998
  // start in syncNodeStart
M
Minghao Li 已提交
999
  // start raft
M
Minghao Li 已提交
1000
  // syncNodeBecomeFollower(pSyncNode);
M
Minghao Li 已提交
1001

M
Minghao Li 已提交
1002 1003
  int64_t timeNow = taosGetTimestampMs();
  pSyncNode->startTime = timeNow;
1004
  pSyncNode->leaderTime = timeNow;
M
Minghao Li 已提交
1005 1006
  pSyncNode->lastReplicateTime = timeNow;

1007 1008 1009
  // snapshotting
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);

1010
  pSyncNode->isStart = true;
S
Shengliang Guan 已提交
1011
  sNTrace(pSyncNode, "sync open, node:%p", pSyncNode);
1012

M
Minghao Li 已提交
1013
  return pSyncNode;
1014 1015 1016

_error:
  if (pSyncInfo->pFsm) {
H
Hongze Cheng 已提交
1017 1018
    taosMemoryFree(pSyncInfo->pFsm);
    pSyncInfo->pFsm = NULL;
1019 1020 1021 1022
  }
  syncNodeClose(pSyncNode);
  pSyncNode = NULL;
  return NULL;
M
Minghao Li 已提交
1023 1024
}

M
Minghao Li 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
void syncNodeMaybeUpdateCommitBySnapshot(SSyncNode* pSyncNode) {
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    SSnapshot snapshot;
    int32_t   code = pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
    ASSERT(code == 0);
    if (snapshot.lastApplyIndex > pSyncNode->commitIndex) {
      pSyncNode->commitIndex = snapshot.lastApplyIndex;
    }
  }
}

M
Minghao Li 已提交
1036 1037
void syncNodeStart(SSyncNode* pSyncNode) {
  // start raft
1038
  if (pSyncNode->replicaNum == 1) {
M
Minghao Li 已提交
1039
    raftStoreNextTerm(pSyncNode->pRaftStore);
1040
    syncNodeBecomeLeader(pSyncNode, "one replica start");
M
format  
Minghao Li 已提交
1041

1042
    // Raft 3.6.2 Committing entries from previous terms
1043 1044
    syncNodeAppendNoop(pSyncNode);
    syncMaybeAdvanceCommitIndex(pSyncNode);
M
Minghao Li 已提交
1045

M
Minghao Li 已提交
1046 1047
  } else {
    syncNodeBecomeFollower(pSyncNode, "first start");
1048 1049
  }

1050 1051 1052
  int32_t ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
  ASSERT(ret == 0);
M
Minghao Li 已提交
1053 1054
}

M
Minghao Li 已提交
1055 1056 1057 1058 1059 1060 1061 1062 1063
void syncNodeStartStandBy(SSyncNode* pSyncNode) {
  // 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);
  ASSERT(ret == 0);
1064

1065 1066 1067
  ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
  ASSERT(ret == 0);
M
Minghao Li 已提交
1068 1069
}

M
Minghao Li 已提交
1070 1071 1072 1073 1074 1075 1076 1077
void syncNodePreClose(SSyncNode* pSyncNode) {
  // stop elect timer
  syncNodeStopElectTimer(pSyncNode);

  // stop heartbeat timer
  syncNodeStopHeartbeatTimer(pSyncNode);
}

1078 1079
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }

M
Minghao Li 已提交
1080
void syncNodeClose(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1081 1082
  if (pSyncNode == NULL) return;
  sNTrace(pSyncNode, "sync close, data:%p", pSyncNode);
M
Minghao Li 已提交
1083

S
Shengliang Guan 已提交
1084
  int32_t ret = raftStoreClose(pSyncNode->pRaftStore);
M
Minghao Li 已提交
1085
  ASSERT(ret == 0);
M
Minghao Li 已提交
1086
  pSyncNode->pRaftStore = NULL;
M
Minghao Li 已提交
1087

M
Minghao Li 已提交
1088
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
1089
  pSyncNode->pSyncRespMgr = NULL;
M
Minghao Li 已提交
1090
  voteGrantedDestroy(pSyncNode->pVotesGranted);
1091
  pSyncNode->pVotesGranted = NULL;
M
Minghao Li 已提交
1092
  votesRespondDestory(pSyncNode->pVotesRespond);
1093
  pSyncNode->pVotesRespond = NULL;
M
Minghao Li 已提交
1094
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
1095
  pSyncNode->pNextIndex = NULL;
M
Minghao Li 已提交
1096
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
1097
  pSyncNode->pMatchIndex = NULL;
M
Minghao Li 已提交
1098
  logStoreDestory(pSyncNode->pLogStore);
1099
  pSyncNode->pLogStore = NULL;
M
Minghao Li 已提交
1100
  raftCfgClose(pSyncNode->pRaftCfg);
1101
  pSyncNode->pRaftCfg = NULL;
M
Minghao Li 已提交
1102 1103 1104 1105 1106

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

M
Minghao Li 已提交
1107 1108 1109 1110
  if (pSyncNode->pFsm != NULL) {
    taosMemoryFree(pSyncNode->pFsm);
  }

S
Shengliang Guan 已提交
1111
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1112
    if ((pSyncNode->senders)[i] != NULL) {
S
Shengliang Guan 已提交
1113
      sSTrace((pSyncNode->senders)[i], "snapshot sender destroy while close, data:%p", (pSyncNode->senders)[i]);
M
Minghao Li 已提交
1114 1115 1116 1117 1118
      snapshotSenderDestroy((pSyncNode->senders)[i]);
      (pSyncNode->senders)[i] = NULL;
    }
  }

M
Minghao Li 已提交
1119 1120 1121 1122 1123
  if (pSyncNode->pNewNodeReceiver != NULL) {
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
    pSyncNode->pNewNodeReceiver = NULL;
  }

1124
  taosMemoryFree(pSyncNode);
M
Minghao Li 已提交
1125 1126
}

M
Minghao Li 已提交
1127
ESyncStrategy syncNodeStrategy(SSyncNode* pSyncNode) { return pSyncNode->pRaftCfg->snapshotStrategy; }
M
Minghao Li 已提交
1128

M
Minghao Li 已提交
1129 1130 1131
// timer control --------------
int32_t syncNodeStartPingTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
S
Shengliang Guan 已提交
1132 1133
  if (syncIsInit()) {
    taosTmrReset(pSyncNode->FpPingTimerCB, pSyncNode->pingTimerMS, pSyncNode, syncEnv()->pTimerManager,
1134 1135 1136
                 &pSyncNode->pPingTimer);
    atomic_store_64(&pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1137
    sError("vgId:%d, start ping timer error, sync env is stop", pSyncNode->vgId);
1138
  }
M
Minghao Li 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
  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 已提交
1152
  if (syncIsInit()) {
1153
    pSyncNode->electTimerMS = ms;
S
Shengliang Guan 已提交
1154

1155 1156 1157 1158 1159
    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 已提交
1160

M
Minghao Li 已提交
1161
    taosTmrReset(pSyncNode->FpElectTimerCB, pSyncNode->electTimerMS, (void*)(pSyncNode->rid), syncEnv()->pTimerManager,
1162
                 &pSyncNode->pElectTimer);
S
Shengliang Guan 已提交
1163

1164
  } else {
M
Minghao Li 已提交
1165
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
1166
  }
M
Minghao Li 已提交
1167 1168 1169 1170 1171
  return ret;
}

int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1172
  atomic_add_fetch_64(&pSyncNode->electTimerLogicClock, 1);
M
Minghao Li 已提交
1173 1174
  taosTmrStop(pSyncNode->pElectTimer);
  pSyncNode->pElectTimer = NULL;
1175

M
Minghao Li 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  return ret;
}

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

M
Minghao Li 已提交
1186 1187
int32_t syncNodeResetElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1188 1189 1190 1191 1192 1193 1194
  int32_t electMS;

  if (pSyncNode->pRaftCfg->isStandBy) {
    electMS = TIMER_MAX_MS;
  } else {
    electMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
  }
M
Minghao Li 已提交
1195
  ret = syncNodeRestartElectTimer(pSyncNode, electMS);
1196

S
Shengliang Guan 已提交
1197 1198
  sNTrace(pSyncNode, "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine,
          electMS);
M
Minghao Li 已提交
1199 1200 1201
  return ret;
}

M
Minghao Li 已提交
1202
static int32_t syncNodeDoStartHeartbeatTimer(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1203
  int32_t ret = 0;
S
Shengliang Guan 已提交
1204 1205
  if (syncIsInit()) {
    taosTmrReset(pSyncNode->FpHeartbeatTimerCB, pSyncNode->heartbeatTimerMS, pSyncNode, syncEnv()->pTimerManager,
1206 1207 1208
                 &pSyncNode->pHeartbeatTimer);
    atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1209
    sError("vgId:%d, start heartbeat timer error, sync env is stop", pSyncNode->vgId);
1210
  }
1211

S
Shengliang Guan 已提交
1212
  sNTrace(pSyncNode, "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
M
Minghao Li 已提交
1213 1214 1215
  return ret;
}

M
Minghao Li 已提交
1216
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
1217
  int32_t ret = 0;
M
Minghao Li 已提交
1218

1219
#if 0
M
Minghao Li 已提交
1220
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
1221 1222
  ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
#endif
1223

S
Shengliang Guan 已提交
1224
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1225
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1226 1227 1228
    if (pSyncTimer != NULL) {
      syncHbTimerStart(pSyncNode, pSyncTimer);
    }
1229
  }
1230

M
Minghao Li 已提交
1231 1232 1233
  return ret;
}

M
Minghao Li 已提交
1234 1235
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
1236 1237

#if 0
M
Minghao Li 已提交
1238 1239 1240
  atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1);
  taosTmrStop(pSyncNode->pHeartbeatTimer);
  pSyncNode->pHeartbeatTimer = NULL;
1241
#endif
1242

S
Shengliang Guan 已提交
1243
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1244
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1245 1246 1247
    if (pSyncTimer != NULL) {
      syncHbTimerStop(pSyncNode, pSyncTimer);
    }
1248
  }
1249

M
Minghao Li 已提交
1250 1251 1252
  return ret;
}

1253 1254 1255 1256 1257 1258
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode) {
  syncNodeStopHeartbeatTimer(pSyncNode);
  syncNodeStartHeartbeatTimer(pSyncNode);
  return 0;
}

M
Minghao Li 已提交
1259 1260 1261
// utils --------------
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
1262
  syncUtilRaftId2EpSet(destRaftId, &epSet);
S
Shengliang Guan 已提交
1263
  if (pSyncNode->syncSendMSg != NULL) {
M
Minghao Li 已提交
1264 1265 1266
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

1267
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1268
    pSyncNode->syncSendMSg(&epSet, pMsg);
M
Minghao Li 已提交
1269
  } else {
M
Minghao Li 已提交
1270
    sError("vgId:%d, sync send msg by id error, fp-send-msg is null", pSyncNode->vgId);
S
Shengliang Guan 已提交
1271
    rpcFreeCont(pMsg->pCont);
M
Minghao Li 已提交
1272
    return -1;
M
Minghao Li 已提交
1273
  }
M
Minghao Li 已提交
1274

M
Minghao Li 已提交
1275 1276 1277 1278 1279
  return 0;
}

int32_t syncNodeSendMsgByInfo(const SNodeInfo* nodeInfo, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
1280
  syncUtilNodeInfo2EpSet(nodeInfo, &epSet);
S
Shengliang Guan 已提交
1281
  if (pSyncNode->syncSendMSg != NULL) {
M
Minghao Li 已提交
1282 1283 1284
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

1285
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1286
    pSyncNode->syncSendMSg(&epSet, pMsg);
M
Minghao Li 已提交
1287
  } else {
M
Minghao Li 已提交
1288
    sError("vgId:%d, sync send msg by info error, fp-send-msg is null", pSyncNode->vgId);
M
Minghao Li 已提交
1289
  }
M
Minghao Li 已提交
1290 1291 1292
  return 0;
}

1293
inline bool syncNodeInConfig(SSyncNode* pSyncNode, const SSyncCfg* config) {
1294 1295 1296
  bool b1 = false;
  bool b2 = false;

S
Shengliang Guan 已提交
1297
  for (int32_t i = 0; i < config->replicaNum; ++i) {
1298 1299 1300 1301 1302 1303 1304
    if (strcmp((config->nodeInfo)[i].nodeFqdn, pSyncNode->myNodeInfo.nodeFqdn) == 0 &&
        (config->nodeInfo)[i].nodePort == pSyncNode->myNodeInfo.nodePort) {
      b1 = true;
      break;
    }
  }

S
Shengliang Guan 已提交
1305
  for (int32_t i = 0; i < config->replicaNum; ++i) {
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    SRaftId raftId;
    raftId.addr = syncUtilAddr2U64((config->nodeInfo)[i].nodeFqdn, (config->nodeInfo)[i].nodePort);
    raftId.vgId = pSyncNode->vgId;

    if (syncUtilSameId(&raftId, &(pSyncNode->myRaftId))) {
      b2 = true;
      break;
    }
  }

  ASSERT(b1 == b2);
  return b1;
}

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
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 已提交
1333
void syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncIndex lastConfigChangeIndex) {
1334
  SSyncCfg oldConfig = pSyncNode->pRaftCfg->cfg;
1335 1336 1337 1338
  if (!syncIsConfigChanged(&oldConfig, pNewConfig)) {
    sInfo("vgId:1, sync not reconfig since not changed");
    return;
  }
S
Shengliang Guan 已提交
1339

1340
  pSyncNode->pRaftCfg->cfg = *pNewConfig;
1341 1342
  pSyncNode->pRaftCfg->lastConfigIndex = lastConfigChangeIndex;

M
Minghao Li 已提交
1343 1344
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
M
Minghao Li 已提交
1345

M
Minghao Li 已提交
1346 1347
  bool isDrop = false;
  bool isAdd = false;
M
Minghao Li 已提交
1348

M
Minghao Li 已提交
1349 1350 1351 1352
  if (IamInOld && !IamInNew) {
    isDrop = true;
  } else {
    isDrop = false;
1353
  }
1354

M
Minghao Li 已提交
1355 1356 1357 1358 1359
  if (!IamInOld && IamInNew) {
    isAdd = true;
  } else {
    isAdd = false;
  }
M
Minghao Li 已提交
1360

M
Minghao Li 已提交
1361
  // log begin config change
S
Shengliang Guan 已提交
1362 1363 1364 1365 1366
  char oldCfgStr[1024] = {0};
  char newCfgStr[1024] = {0};
  syncCfg2SimpleStr(&oldConfig, oldCfgStr, sizeof(oldCfgStr));
  syncCfg2SimpleStr(pNewConfig, oldCfgStr, sizeof(oldCfgStr));
  sNTrace(pSyncNode, "begin do config change, from %s to %s", oldCfgStr, oldCfgStr);
M
Minghao Li 已提交
1367

M
Minghao Li 已提交
1368 1369
  if (IamInNew) {
    pSyncNode->pRaftCfg->isStandBy = 0;  // change isStandBy to normal
M
Minghao Li 已提交
1370
  }
M
Minghao Li 已提交
1371 1372
  if (isDrop) {
    pSyncNode->pRaftCfg->isStandBy = 1;  // set standby
M
Minghao Li 已提交
1373 1374
  }

M
Minghao Li 已提交
1375
  // add last config index
M
Minghao Li 已提交
1376
  raftCfgAddConfigIndex(pSyncNode->pRaftCfg, lastConfigChangeIndex);
M
Minghao Li 已提交
1377

M
Minghao Li 已提交
1378 1379 1380 1381 1382 1383 1384 1385 1386
  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 已提交
1387
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1388
      oldSenders[i] = (pSyncNode->senders)[i];
S
Shengliang Guan 已提交
1389
      sSTrace(oldSenders[i], "snapshot sender save old");
M
Minghao Li 已提交
1390
    }
1391

M
Minghao Li 已提交
1392 1393
    // init internal
    pSyncNode->myNodeInfo = pSyncNode->pRaftCfg->cfg.nodeInfo[pSyncNode->pRaftCfg->cfg.myIndex];
1394
    syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId);
M
Minghao Li 已提交
1395 1396 1397

    // init peersNum, peers, peersId
    pSyncNode->peersNum = pSyncNode->pRaftCfg->cfg.replicaNum - 1;
S
Shengliang Guan 已提交
1398 1399
    int32_t j = 0;
    for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
M
Minghao Li 已提交
1400 1401 1402 1403 1404
      if (i != pSyncNode->pRaftCfg->cfg.myIndex) {
        pSyncNode->peersNodeInfo[j] = pSyncNode->pRaftCfg->cfg.nodeInfo[i];
        j++;
      }
    }
S
Shengliang Guan 已提交
1405
    for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1406
      syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]);
M
Minghao Li 已提交
1407
    }
1408

M
Minghao Li 已提交
1409 1410
    // init replicaNum, replicasId
    pSyncNode->replicaNum = pSyncNode->pRaftCfg->cfg.replicaNum;
S
Shengliang Guan 已提交
1411
    for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
1412
      syncUtilNodeInfo2RaftId(&pSyncNode->pRaftCfg->cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]);
M
Minghao Li 已提交
1413
    }
1414

1415 1416 1417
    // update quorum first
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->pRaftCfg->cfg.replicaNum);

M
Minghao Li 已提交
1418 1419 1420 1421
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
M
Minghao Li 已提交
1422

M
Minghao Li 已提交
1423
    // reset snapshot senders
1424

M
Minghao Li 已提交
1425
    // clear new
S
Shengliang Guan 已提交
1426
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1427 1428
      (pSyncNode->senders)[i] = NULL;
    }
M
Minghao Li 已提交
1429

M
Minghao Li 已提交
1430
    // reset new
S
Shengliang Guan 已提交
1431
    for (int32_t i = 0; i < pSyncNode->replicaNum; ++i) {
M
Minghao Li 已提交
1432 1433
      // reset sender
      bool reset = false;
S
Shengliang Guan 已提交
1434
      for (int32_t j = 0; j < TSDB_MAX_REPLICA; ++j) {
M
Minghao Li 已提交
1435
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
M
Minghao Li 已提交
1436 1437 1438
          char     host[128];
          uint16_t port;
          syncUtilU642Addr((pSyncNode->replicasId)[i].addr, host, sizeof(host), &port);
1439
          sNTrace(pSyncNode, "snapshot sender reset for: %" PRId64 ", newIndex:%d, %s:%d, %p",
S
Shengliang Guan 已提交
1440
                  (pSyncNode->replicasId)[i].addr, i, host, port, oldSenders[j]);
M
Minghao Li 已提交
1441 1442 1443 1444 1445 1446 1447 1448 1449

          (pSyncNode->senders)[i] = oldSenders[j];
          oldSenders[j] = NULL;
          reset = true;

          // reset replicaIndex
          int32_t oldreplicaIndex = (pSyncNode->senders)[i]->replicaIndex;
          (pSyncNode->senders)[i]->replicaIndex = i;

S
Shengliang Guan 已提交
1450 1451
          sNTrace(pSyncNode, "snapshot sender udpate replicaIndex from %d to %d, %s:%d, %p, reset:%d", oldreplicaIndex,
                  i, host, port, (pSyncNode->senders)[i], reset);
M
Minghao Li 已提交
1452 1453

          break;
M
Minghao Li 已提交
1454
        }
1455 1456
      }
    }
1457

M
Minghao Li 已提交
1458
    // create new
S
Shengliang Guan 已提交
1459
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1460 1461
      if ((pSyncNode->senders)[i] == NULL) {
        (pSyncNode->senders)[i] = snapshotSenderCreate(pSyncNode, i);
S
Shengliang Guan 已提交
1462 1463 1464
        sSTrace((pSyncNode->senders)[i], "snapshot sender create new while reconfig, data:%p", (pSyncNode->senders)[i]);
      } else {
        sSTrace((pSyncNode->senders)[i], "snapshot sender already exist, data:%p", (pSyncNode->senders)[i]);
M
Minghao Li 已提交
1465
      }
1466 1467
    }

M
Minghao Li 已提交
1468
    // free old
S
Shengliang Guan 已提交
1469
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1470
      if (oldSenders[i] != NULL) {
S
Shengliang Guan 已提交
1471
        sNTrace(pSyncNode, "snapshot sender destroy old, data:%p replica-index:%d", oldSenders[i], i);
M
Minghao Li 已提交
1472 1473 1474
        snapshotSenderDestroy(oldSenders[i]);
        oldSenders[i] = NULL;
      }
1475 1476
    }

1477
    // persist cfg
M
Minghao Li 已提交
1478
    raftCfgPersist(pSyncNode->pRaftCfg);
1479

S
Shengliang Guan 已提交
1480
    char tmpbuf[1024] = {0};
1481
    snprintf(tmpbuf, sizeof(tmpbuf), "config change from %d to %d, index:%" PRId64 ", %s  -->  %s",
S
Shengliang Guan 已提交
1482
             oldConfig.replicaNum, pNewConfig->replicaNum, lastConfigChangeIndex, oldCfgStr, newCfgStr);
M
Minghao Li 已提交
1483

M
Minghao Li 已提交
1484 1485 1486
    // change isStandBy to normal (election timeout)
    if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
      syncNodeBecomeLeader(pSyncNode, tmpbuf);
1487 1488 1489 1490 1491

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

M
Minghao Li 已提交
1492 1493 1494 1495
    } else {
      syncNodeBecomeFollower(pSyncNode, tmpbuf);
    }
  } else {
1496
    // persist cfg
M
Minghao Li 已提交
1497
    raftCfgPersist(pSyncNode->pRaftCfg);
S
Shengliang Guan 已提交
1498 1499
    sNTrace(pSyncNode, "do not config change from %d to %d, index:%" PRId64 ", %s  -->  %s", oldConfig.replicaNum,
            pNewConfig->replicaNum, lastConfigChangeIndex, oldCfgStr, newCfgStr);
1500
  }
1501

M
Minghao Li 已提交
1502
_END:
M
Minghao Li 已提交
1503
  // log end config change
S
Shengliang Guan 已提交
1504
  sNTrace(pSyncNode, "end do config change, from %s to %s", oldCfgStr, newCfgStr);
M
Minghao Li 已提交
1505 1506
}

M
Minghao Li 已提交
1507 1508 1509 1510
// raft state change --------------
void syncNodeUpdateTerm(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
1511
    char tmpBuf[64];
1512
    snprintf(tmpBuf, sizeof(tmpBuf), "update term to %" PRId64, term);
1513
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
M
Minghao Li 已提交
1514 1515 1516 1517
    raftStoreClearVote(pSyncNode->pRaftStore);
  }
}

1518 1519 1520 1521 1522 1523
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
  }
}

M
Minghao Li 已提交
1524
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm) {
M
Minghao Li 已提交
1525
  if (pSyncNode->pRaftStore->currentTerm > newTerm) {
1526
    sNTrace(pSyncNode, "step down, ignore, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1527
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1528 1529
    return;
  }
M
Minghao Li 已提交
1530 1531

  do {
1532
    sNTrace(pSyncNode, "step down, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1533
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1534 1535 1536 1537 1538
  } while (0);

  if (pSyncNode->pRaftStore->currentTerm < newTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, newTerm);
    char tmpBuf[64];
1539
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
M
Minghao Li 已提交
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
    raftStoreClearVote(pSyncNode->pRaftStore);

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

1550 1551
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }

1552
void syncNodeBecomeFollower(SSyncNode* pSyncNode, const char* debugStr) {
M
Minghao Li 已提交
1553
  // maybe clear leader cache
M
Minghao Li 已提交
1554 1555 1556 1557
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
  }

M
Minghao Li 已提交
1558
  // state change
M
Minghao Li 已提交
1559 1560 1561
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
  syncNodeStopHeartbeatTimer(pSyncNode);

M
Minghao Li 已提交
1562 1563
  // reset elect timer
  syncNodeResetElectTimer(pSyncNode);
M
Minghao Li 已提交
1564

1565 1566 1567
  // send rsp to client
  syncNodeLeaderChangeRsp(pSyncNode);

1568 1569 1570 1571 1572
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1573 1574 1575
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
1576
  // trace log
S
Shengliang Guan 已提交
1577
  sNTrace(pSyncNode, "become follower %s", debugStr);
M
Minghao Li 已提交
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
}

// 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>>
//
1598
void syncNodeBecomeLeader(SSyncNode* pSyncNode, const char* debugStr) {
1599 1600
  pSyncNode->leaderTime = taosGetTimestampMs();

1601 1602 1603
  // reset restoreFinish
  pSyncNode->restoreFinish = false;

M
Minghao Li 已提交
1604
  // state change
M
Minghao Li 已提交
1605
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
M
Minghao Li 已提交
1606 1607

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

S
Shengliang Guan 已提交
1610
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1611 1612
    // maybe overwrite myself, no harm
    // just do it!
1613 1614 1615 1616 1617 1618 1619 1620 1621

    // 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);
    ASSERT(code == 0);
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
M
Minghao Li 已提交
1622 1623
  }

S
Shengliang Guan 已提交
1624
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1625 1626
    // maybe overwrite myself, no harm
    // just do it!
M
Minghao Li 已提交
1627 1628 1629
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
  }

M
Minghao Li 已提交
1630 1631 1632
  // init peer mgr
  syncNodePeerStateInit(pSyncNode);

M
Minghao Li 已提交
1633
#if 0
1634 1635
  // update sender private term
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
1636
  if (pMySender != NULL) {
S
Shengliang Guan 已提交
1637
    for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
1638 1639 1640
      if ((pSyncNode->senders)[i]->privateTerm > pMySender->privateTerm) {
        pMySender->privateTerm = (pSyncNode->senders)[i]->privateTerm;
      }
1641
    }
1642
    (pMySender->privateTerm) += 100;
1643
  }
M
Minghao Li 已提交
1644
#endif
1645

1646 1647 1648 1649 1650
  // close receiver
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
    snapshotReceiverForceStop(pSyncNode->pNewNodeReceiver);
  }

M
Minghao Li 已提交
1651
  // stop elect timer
M
Minghao Li 已提交
1652
  syncNodeStopElectTimer(pSyncNode);
M
Minghao Li 已提交
1653

M
Minghao Li 已提交
1654 1655
  // start heartbeat timer
  syncNodeStartHeartbeatTimer(pSyncNode);
M
Minghao Li 已提交
1656

M
Minghao Li 已提交
1657 1658
  // send heartbeat right now
  syncNodeHeartbeatPeers(pSyncNode);
M
Minghao Li 已提交
1659

1660 1661 1662 1663 1664
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1665 1666 1667
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
1668
  // trace log
S
Shengliang Guan 已提交
1669
  sNTrace(pSyncNode, "become leader %s", debugStr);
M
Minghao Li 已提交
1670 1671 1672
}

void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1673 1674
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
  ASSERT(voteGrantedMajority(pSyncNode->pVotesGranted));
1675
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");
M
Minghao Li 已提交
1676

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

M
Minghao Li 已提交
1679
  // Raft 3.6.2 Committing entries from previous terms
1680 1681
  syncNodeAppendNoop(pSyncNode);
  syncMaybeAdvanceCommitIndex(pSyncNode);
1682 1683

  if (pSyncNode->replicaNum > 1) {
M
Minghao Li 已提交
1684
    syncNodeReplicate(pSyncNode);
1685
  }
M
Minghao Li 已提交
1686 1687
}

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

M
Minghao Li 已提交
1690
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1691
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1692 1693 1694 1695 1696
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
    pSyncNode->peerStates[i].lastSendTime = 0;
  }

  return 0;
M
Minghao Li 已提交
1697 1698 1699
}

void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1700
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER);
M
Minghao Li 已提交
1701
  pSyncNode->state = TAOS_SYNC_STATE_CANDIDATE;
S
Shengliang Guan 已提交
1702
  sNTrace(pSyncNode, "follower to candidate");
M
Minghao Li 已提交
1703 1704 1705
}

void syncNodeLeader2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1706
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_LEADER);
1707
  syncNodeBecomeFollower(pSyncNode, "leader to follower");
S
Shengliang Guan 已提交
1708
  sNTrace(pSyncNode, "leader to follower");
M
Minghao Li 已提交
1709 1710 1711
}

void syncNodeCandidate2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1712
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
1713
  syncNodeBecomeFollower(pSyncNode, "candidate to follower");
S
Shengliang Guan 已提交
1714
  sNTrace(pSyncNode, "candidate to follower");
M
Minghao Li 已提交
1715 1716
}

M
Minghao Li 已提交
1717 1718
// just called by syncNodeVoteForSelf
// need assert
M
Minghao Li 已提交
1719
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
M
Minghao Li 已提交
1720 1721
  ASSERT(term == pSyncNode->pRaftStore->currentTerm);
  ASSERT(!raftStoreHasVoted(pSyncNode->pRaftStore));
M
Minghao Li 已提交
1722 1723 1724 1725

  raftStoreVote(pSyncNode->pRaftStore, pRaftId);
}

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

S
Shengliang Guan 已提交
1730 1731
  SRpcMsg rpcMsg = {0};
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
S
Shengliang Guan 已提交
1732
  if (ret != 0) return;
S
Shengliang Guan 已提交
1733 1734

  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
M
Minghao Li 已提交
1735 1736 1737 1738 1739 1740 1741
  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 已提交
1742
  rpcFreeCont(rpcMsg.pCont);
M
Minghao Li 已提交
1743 1744
}

M
Minghao Li 已提交
1745
// return if has a snapshot
M
Minghao Li 已提交
1746 1747
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
  bool      ret = false;
1748
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1749 1750
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1751 1752 1753 1754 1755 1756 1757
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
      ret = true;
    }
  }
  return ret;
}

M
Minghao Li 已提交
1758 1759
// return max(logLastIndex, snapshotLastIndex)
// if no snapshot and log, return -1
1760
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1761
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1762 1763
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1764 1765 1766 1767 1768 1769 1770
  }
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);

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

M
Minghao Li 已提交
1771 1772
// return the last term of snapshot and log
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
M
Minghao Li 已提交
1773 1774
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
  SyncTerm lastTerm = 0;
M
Minghao Li 已提交
1775 1776
  if (syncNodeHasSnapshot(pSyncNode)) {
    // has snapshot
1777
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1778 1779
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1780 1781
    }

M
Minghao Li 已提交
1782 1783 1784
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
    if (logLastIndex > snapshot.lastApplyIndex) {
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
M
Minghao Li 已提交
1785 1786 1787 1788
    } else {
      lastTerm = snapshot.lastApplyTerm;
    }

M
Minghao Li 已提交
1789
  } else {
M
Minghao Li 已提交
1790 1791
    // no snapshot
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1792
  }
M
Minghao Li 已提交
1793

M
Minghao Li 已提交
1794 1795 1796 1797 1798 1799 1800
  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);
1801 1802
  return 0;
}
M
Minghao Li 已提交
1803

M
Minghao Li 已提交
1804
// return append-entries first try index
M
Minghao Li 已提交
1805 1806 1807 1808 1809
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
  return syncStartIndex;
}

M
Minghao Li 已提交
1810 1811
// if index > 0, return index - 1
// else, return -1
1812 1813 1814 1815 1816 1817 1818 1819 1820
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
  SyncIndex preIndex = index - 1;
  if (preIndex < SYNC_INDEX_INVALID) {
    preIndex = SYNC_INDEX_INVALID;
  }

  return preIndex;
}

M
Minghao Li 已提交
1821 1822 1823 1824
// if index < 0, return SYNC_TERM_INVALID
// if index == 0, return 0
// if index > 0, return preTerm
// if error, return SYNC_TERM_INVALID
1825 1826 1827 1828 1829 1830 1831 1832 1833
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
  if (index < SYNC_INDEX_BEGIN) {
    return SYNC_TERM_INVALID;
  }

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

1834 1835 1836
  SyncTerm  preTerm = 0;
  SyncIndex preIndex = index - 1;

1837
  SSyncRaftEntry* pPreEntry = NULL;
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
  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;

    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);

  } else {
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);

    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
  }
M
Minghao Li 已提交
1852 1853 1854 1855 1856 1857

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

1858 1859 1860
  if (code == 0) {
    ASSERT(pPreEntry != NULL);
    preTerm = pPreEntry->term;
1861 1862 1863 1864 1865 1866 1867

    if (h) {
      taosLRUCacheRelease(pCache, h, false);
    } else {
      syncEntryDestory(pPreEntry);
    }

1868 1869
    return preTerm;
  } else {
1870 1871 1872 1873
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
      if (snapshot.lastApplyIndex == preIndex) {
        return snapshot.lastApplyTerm;
1874 1875 1876 1877
      }
    }
  }

1878
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
S
Shengliang Guan 已提交
1879
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
1880 1881
  return SYNC_TERM_INVALID;
}
M
Minghao Li 已提交
1882 1883 1884 1885

// 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 已提交
1886
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
M
Minghao Li 已提交
1887 1888 1889
  return 0;
}

M
Minghao Li 已提交
1890
static void syncNodeEqPingTimer(void* param, void* tmrId) {
S
Shengliang Guan 已提交
1891 1892 1893 1894 1895
  if (!syncIsInit()) return;

  SSyncNode* pNode = param;
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
    SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
1896
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
S
Shengliang Guan 已提交
1897 1898
                                    pNode->pingTimerMS, pNode);
    if (code != 0) {
M
Minghao Li 已提交
1899
      sError("failed to build ping msg");
S
Shengliang Guan 已提交
1900 1901
      rpcFreeCont(rpcMsg.pCont);
      return;
M
Minghao Li 已提交
1902
    }
M
Minghao Li 已提交
1903

M
Minghao Li 已提交
1904
    // sTrace("enqueue ping msg");
S
Shengliang Guan 已提交
1905 1906
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
    if (code != 0) {
M
Minghao Li 已提交
1907
      sError("failed to sync enqueue ping msg since %s", terrstr());
S
Shengliang Guan 已提交
1908 1909
      rpcFreeCont(rpcMsg.pCont);
      return;
1910 1911
    }

S
Shengliang Guan 已提交
1912
    taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, pNode, syncEnv()->pTimerManager, &pNode->pPingTimer);
M
Minghao Li 已提交
1913 1914 1915 1916
  }
}

static void syncNodeEqElectTimer(void* param, void* tmrId) {
S
Shengliang Guan 已提交
1917
  if (!syncIsInit()) return;
S
Shengliang Guan 已提交
1918

M
Minghao Li 已提交
1919 1920
  int64_t    rid = (int64_t)param;
  SSyncNode* pNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
1921

1922
  if (pNode == NULL) return;
M
Minghao Li 已提交
1923 1924 1925 1926 1927

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

1929
  int64_t tsNow = taosGetTimestampMs();
M
Minghao Li 已提交
1930 1931 1932 1933
  if (tsNow < pNode->electTimerParam.executeTime) {
    syncNodeRelease(pNode);
    return;
  }
1934

S
Shengliang Guan 已提交
1935
  SRpcMsg rpcMsg = {0};
1936 1937
  int32_t code =
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
S
Shengliang Guan 已提交
1938

S
Shengliang Guan 已提交
1939
  if (code != 0) {
M
Minghao Li 已提交
1940
    sError("failed to build elect msg");
M
Minghao Li 已提交
1941
    syncNodeRelease(pNode);
S
Shengliang Guan 已提交
1942 1943 1944 1945
    return;
  }

  SyncTimeout* pTimeout = rpcMsg.pCont;
S
Shengliang Guan 已提交
1946
  sNTrace(pNode, "enqueue elect msg lc:%" PRId64, pTimeout->logicClock);
S
Shengliang Guan 已提交
1947 1948 1949

  code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
  if (code != 0) {
M
Minghao Li 已提交
1950
    sError("failed to sync enqueue elect msg since %s", terrstr());
S
Shengliang Guan 已提交
1951
    rpcFreeCont(rpcMsg.pCont);
M
Minghao Li 已提交
1952
    syncNodeRelease(pNode);
1953
    return;
S
Shengliang Guan 已提交
1954
  }
M
Minghao Li 已提交
1955 1956

  syncNodeRelease(pNode);
M
Minghao Li 已提交
1957 1958
}

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

S
Shengliang Guan 已提交
1962 1963 1964 1965
  SSyncNode* pNode = param;
  if (pNode->replicaNum > 1) {
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
      SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
1966
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
S
Shengliang Guan 已提交
1967 1968 1969
                                      pNode->heartbeatTimerMS, pNode);

      if (code != 0) {
M
Minghao Li 已提交
1970
        sError("failed to build heartbeat msg");
S
Shengliang Guan 已提交
1971
        return;
1972
      }
M
Minghao Li 已提交
1973

1974
      sTrace("enqueue heartbeat timer");
S
Shengliang Guan 已提交
1975 1976
      code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
      if (code != 0) {
M
Minghao Li 已提交
1977
        sError("failed to enqueue heartbeat msg since %s", terrstr());
S
Shengliang Guan 已提交
1978 1979
        rpcFreeCont(rpcMsg.pCont);
        return;
1980
      }
S
Shengliang Guan 已提交
1981 1982 1983 1984

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

1985
    } else {
S
Shengliang Guan 已提交
1986 1987
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
1988
    }
M
Minghao Li 已提交
1989 1990 1991
  }
}

1992
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
1993
  int64_t hbDataRid = (int64_t)param;
1994
  int64_t tsNow = taosGetTimestampMs();
1995 1996 1997

  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
  if (pData == NULL) {
M
Minghao Li 已提交
1998
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
1999 2000
    return;
  }
2001

2002
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
M
Minghao Li 已提交
2003
  if (pSyncNode == NULL) {
2004
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2005
    sError("hb timer get pSyncNode NULL");
2006 2007 2008 2009 2010 2011 2012 2013
    return;
  }

  SSyncTimer* pSyncTimer = pData->pTimer;

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

M
Minghao Li 已提交
2018
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
2019 2020
    syncNodeRelease(pSyncNode);
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2021
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
M
Minghao Li 已提交
2022 2023 2024
    return;
  }

M
Minghao Li 已提交
2025
  if (pSyncNode->pRaftStore == NULL) {
2026 2027
    syncNodeRelease(pSyncNode);
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2028
    sError("vgId:%d, hb timer raft store already stop", pSyncNode->vgId);
M
Minghao Li 已提交
2029 2030 2031
    return;
  }

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

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

2038
    if (timerLogicClock == msgLogicClock) {
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
      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;
2059
        pSyncMsg->timeStamp = tsNow;
2060 2061 2062 2063 2064 2065

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

        // send msg
2066 2067
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime);
        syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
2068 2069 2070 2071 2072 2073 2074 2075
      } 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 已提交
2076 2077
      if (syncIsInit()) {
        // sTrace("vgId:%d, reset peer hb timer", pSyncNode->vgId);
2078 2079
        taosTmrReset(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS / HEARTBEAT_TICK_NUM, (void*)hbDataRid,
                     syncEnv()->pTimerManager, &pSyncTimer->pTimer);
M
Minghao Li 已提交
2080 2081 2082 2083
      } else {
        sError("sync env is stop, reset peer hb timer error");
      }

2084
    } else {
M
Minghao Li 已提交
2085 2086
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64 "", pSyncNode->vgId,
             timerLogicClock, msgLogicClock);
2087 2088
    }
  }
2089 2090 2091

  syncHbTimerDataRelease(pData);
  syncNodeRelease(pSyncNode);
2092 2093
}

2094 2095 2096 2097 2098
static int32_t syncNodeEqNoop(SSyncNode* pNode) {
  if (pNode->state == TAOS_SYNC_STATE_LEADER) {
    terrno = TSDB_CODE_SYN_NOT_LEADER;
    return -1;
  }
M
Minghao Li 已提交
2099

2100 2101 2102 2103
  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 已提交
2104

S
Shengliang Guan 已提交
2105
  SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
2106
  int32_t code = syncBuildClientRequestFromNoopEntry(&rpcMsg, pEntry, pNode->vgId);
M
Minghao Li 已提交
2107
  syncEntryDestory(pEntry);
M
Minghao Li 已提交
2108

2109 2110 2111
  sNTrace(pNode, "propose msg, type:noop");
  code = (*pNode->syncEqMsg)(pNode->msgcb, &rpcMsg);
  if (code != 0) {
M
Minghao Li 已提交
2112
    sError("failed to propose noop msg while enqueue since %s", terrstr());
2113 2114 2115
  }

  return code;
M
Minghao Li 已提交
2116 2117
}

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

2120 2121 2122 2123
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 已提交
2124 2125
  int32_t   code = 0;
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2126 2127 2128 2129 2130 2131 2132 2133 2134
  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;
}

2135
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
  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;
    }

    if (tsNow - recvTime > SYNC_HEART_TIMEOUT_MS) {
      toCount++;
    }
  }

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

  return b;
}

M
Minghao Li 已提交
2158 2159 2160
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
  int32_t ret = 0;

2161
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2162
  SyncTerm        term = ths->pRaftStore->currentTerm;
M
Minghao Li 已提交
2163
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
M
Minghao Li 已提交
2164
  ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2165

2166 2167
  LRUHandle* h = NULL;

M
Minghao Li 已提交
2168
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2169
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
2170
    if (code != 0) {
M
Minghao Li 已提交
2171
      sError("append noop error");
2172 2173
      return -1;
    }
2174 2175

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

2178 2179 2180 2181 2182 2183
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2184 2185 2186
  return ret;
}

S
Shengliang Guan 已提交
2187 2188
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
2189 2190

  int64_t tsMs = taosGetTimestampMs();
M
Minghao Li 已提交
2191
  int64_t timeDiff = tsMs - pMsg->timeStamp;
2192
  syncLogRecvHeartbeat(ths, pMsg, timeDiff);
2193

2194 2195 2196 2197
  SRpcMsg rpcMsg = {0};
  (void)syncBuildHeartbeatReply(&rpcMsg, ths->vgId);

  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
2198 2199 2200 2201
  pMsgReply->destId = pMsg->srcId;
  pMsgReply->srcId = ths->myRaftId;
  pMsgReply->term = ths->pRaftStore->currentTerm;
  pMsgReply->privateTerm = 8864;  // magic number
2202
  pMsgReply->timeStamp = tsMs;
2203

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

2207
    syncNodeResetElectTimer(ths);
M
Minghao Li 已提交
2208
    ths->minMatchIndex = pMsg->minMatchIndex;
2209 2210

    if (ths->state == TAOS_SYNC_STATE_FOLLOWER) {
2211
      // syncNodeFollowerCommit(ths, pMsg->commitIndex);
S
Shengliang Guan 已提交
2212 2213 2214 2215
      SRpcMsg rpcMsgLocalCmd = {0};
      (void)syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId);

      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
2216 2217
      pSyncMsg->cmd = SYNC_LOCAL_CMD_FOLLOWER_CMT;
      pSyncMsg->fcIndex = pMsg->commitIndex;
2218
      SyncIndex fcIndex = pSyncMsg->fcIndex;
2219 2220 2221 2222 2223 2224 2225

      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 {
2226
          sTrace("vgId:%d, sync enqueue fc-commit msg, fc-index:%" PRId64, ths->vgId, fcIndex);
2227 2228
        }
      }
2229 2230 2231
    }
  }

M
Minghao Li 已提交
2232
  if (pMsg->term >= ths->pRaftStore->currentTerm && ths->state != TAOS_SYNC_STATE_FOLLOWER) {
2233
    // syncNodeStepDown(ths, pMsg->term);
S
Shengliang Guan 已提交
2234 2235 2236 2237
    SRpcMsg rpcMsgLocalCmd = {0};
    (void)syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId);

    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
2238 2239 2240
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
    pSyncMsg->sdNewTerm = pMsg->term;

S
Shengliang Guan 已提交
2241 2242
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
2243 2244 2245 2246
      if (code != 0) {
        sError("vgId:%d, sync enqueue step-down msg error, code:%d", ths->vgId, code);
        rpcFreeCont(rpcMsgLocalCmd.pCont);
      } else {
2247
        sTrace("vgId:%d, sync enqueue step-down msg, new-term: %" PRId64, ths->vgId, pSyncMsg->sdNewTerm);
2248 2249
      }
    }
M
Minghao Li 已提交
2250 2251
  }

2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
  /*
    // htonl
    SMsgHead* pHead = rpcMsg.pCont;
    pHead->contLen = htonl(pHead->contLen);
    pHead->vgId = htonl(pHead->vgId);
  */

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

2264 2265
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
2266

M
Minghao Li 已提交
2267
  int64_t tsMs = taosGetTimestampMs();
M
Minghao Li 已提交
2268
  int64_t timeDiff = tsMs - pMsg->timeStamp;
S
Shengliang Guan 已提交
2269
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff);
M
Minghao Li 已提交
2270

2271
  // update last reply time, make decision whether the other node is alive or not
M
Minghao Li 已提交
2272
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
2273 2274 2275
  return 0;
}

S
Shengliang Guan 已提交
2276 2277
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
2278 2279
  syncLogRecvLocalCmd(ths, pMsg, "");

M
Minghao Li 已提交
2280 2281 2282
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
    syncNodeStepDown(ths, pMsg->sdNewTerm);

2283 2284 2285
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT) {
    syncNodeFollowerCommit(ths, pMsg->fcIndex);

M
Minghao Li 已提交
2286
  } else {
M
Minghao Li 已提交
2287
    sError("error local cmd");
M
Minghao Li 已提交
2288 2289 2290 2291 2292
  }

  return 0;
}

M
Minghao Li 已提交
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
// 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 已提交
2303

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

M
Minghao Li 已提交
2307
  int32_t ret = 0;
2308
  int32_t code = 0;
M
Minghao Li 已提交
2309

M
Minghao Li 已提交
2310
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2311
  SyncTerm        term = ths->pRaftStore->currentTerm;
2312 2313 2314 2315 2316 2317 2318
  SSyncRaftEntry* pEntry;

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

2320 2321
  LRUHandle* h = NULL;

M
Minghao Li 已提交
2322
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2323 2324 2325
    // append entry
    code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
    if (code != 0) {
2326 2327 2328 2329 2330 2331
      if (ths->replicaNum == 1) {
        if (h) {
          taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }
2332

2333 2334 2335 2336
        return -1;

      } else {
        // del resp mgr, call FpCommitCb
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
        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,
        };
2348
        ths->pFsm->FpCommitCb(ths->pFsm, pMsg, &cbMeta);
2349 2350 2351 2352 2353 2354 2355

        if (h) {
          taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }

2356 2357
        return -1;
      }
2358
    }
M
Minghao Li 已提交
2359

2360 2361
    syncCacheEntry(ths->pLogStore, pEntry, &h);

2362 2363
    // if mulit replica, start replicate right now
    if (ths->replicaNum > 1) {
M
Minghao Li 已提交
2364
      syncNodeReplicate(ths);
2365
    }
2366

2367 2368
    // if only myself, maybe commit right now
    if (ths->replicaNum == 1) {
2369 2370 2371 2372 2373
      if (syncNodeIsMnode(ths)) {
        syncMaybeAdvanceCommitIndex(ths);
      } else {
        syncOneReplicaAdvance(ths);
      }
2374
    }
M
Minghao Li 已提交
2375 2376
  }

2377 2378 2379 2380 2381 2382 2383 2384
  if (pRetIndex != NULL) {
    if (ret == 0 && pEntry != NULL) {
      *pRetIndex = pEntry->index;
    } else {
      *pRetIndex = SYNC_INDEX_INVALID;
    }
  }

2385 2386 2387 2388 2389 2390
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2391
  return ret;
2392
}
M
Minghao Li 已提交
2393

S
Shengliang Guan 已提交
2394 2395 2396
const char* syncStr(ESyncState state) {
  switch (state) {
    case TAOS_SYNC_STATE_FOLLOWER:
2397
      return "follower";
S
Shengliang Guan 已提交
2398
    case TAOS_SYNC_STATE_CANDIDATE:
2399
      return "candidate";
S
Shengliang Guan 已提交
2400
    case TAOS_SYNC_STATE_LEADER:
2401
      return "leader";
S
Shengliang Guan 已提交
2402
    default:
2403
      return "error";
S
Shengliang Guan 已提交
2404
  }
M
Minghao Li 已提交
2405
}
2406

2407
#if 0
2408
int32_t syncDoLeaderTransfer(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry) {
2409
  if (ths->state != TAOS_SYNC_STATE_FOLLOWER) {
S
Shengliang Guan 已提交
2410
    sNTrace(ths, "I am not follower, can not do leader transfer");
2411 2412
    return 0;
  }
2413 2414

  if (!ths->restoreFinish) {
S
Shengliang Guan 已提交
2415
    sNTrace(ths, "restore not finish, can not do leader transfer");
2416 2417 2418
    return 0;
  }

2419
  if (pEntry->term < ths->pRaftStore->currentTerm) {
2420
    sNTrace(ths, "little term:%" PRId64 ", can not do leader transfer", pEntry->term);
2421 2422 2423 2424
    return 0;
  }

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

2429 2430
  /*
    if (ths->vgId > 1) {
S
Shengliang Guan 已提交
2431
      sNTrace(ths, "I am vnode, can not do leader transfer");
2432 2433 2434 2435
      return 0;
    }
  */

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

M
Minghao Li 已提交
2439 2440 2441
  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 已提交
2442

M
Minghao Li 已提交
2443 2444
  bool same = sameId || sameNodeInfo;
  if (same) {
M
Minghao Li 已提交
2445 2446 2447 2448
    // reset elect timer now!
    int32_t electMS = 1;
    int32_t ret = syncNodeRestartElectTimer(ths, electMS);
    ASSERT(ret == 0);
M
Minghao Li 已提交
2449

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

M
Minghao Li 已提交
2454
  if (ths->pFsm->FpLeaderTransferCb != NULL) {
S
Shengliang Guan 已提交
2455
    SFsmCbMeta cbMeta = {
S
Shengliang Guan 已提交
2456 2457 2458 2459 2460 2461 2462 2463 2464
        .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 已提交
2465 2466
    };
    ths->pFsm->FpLeaderTransferCb(ths->pFsm, pRpcMsg, &cbMeta);
2467 2468
  }

2469 2470 2471
  return 0;
}

2472 2473
#endif

2474
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
S
Shengliang Guan 已提交
2475
  for (int32_t i = 0; i < pNewCfg->replicaNum; ++i) {
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    SRaftId raftId;
    raftId.addr = syncUtilAddr2U64((pNewCfg->nodeInfo)[i].nodeFqdn, (pNewCfg->nodeInfo)[i].nodePort);
    raftId.vgId = ths->vgId;

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

  return -1;
}

2489 2490 2491 2492
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
}

M
Minghao Li 已提交
2493
int32_t syncNodeDoCommit(SSyncNode* ths, SyncIndex beginIndex, SyncIndex endIndex, uint64_t flag) {
2494 2495 2496 2497
  if (beginIndex > endIndex) {
    return 0;
  }

M
Minghao Li 已提交
2498 2499 2500 2501 2502 2503 2504 2505 2506
  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 已提交
2507
      sNTrace(ths, "commit by snapshot from index:%" PRId64 " to index:%" PRId64, beginIndex, snapshot.lastApplyIndex);
2508

M
Minghao Li 已提交
2509 2510 2511
      // update begin index
      beginIndex = snapshot.lastApplyIndex + 1;
    }
2512 2513
  }

2514 2515
  int32_t    code = 0;
  ESyncState state = flag;
M
Minghao Li 已提交
2516

S
Shengliang Guan 已提交
2517
  sNTrace(ths, "commit by wal from index:%" PRId64 " to index:%" PRId64, beginIndex, endIndex);
2518 2519 2520 2521 2522 2523

  // execute fsm
  if (ths->pFsm != NULL) {
    for (SyncIndex i = beginIndex; i <= endIndex; ++i) {
      if (i != SYNC_INDEX_INVALID) {
        SSyncRaftEntry* pEntry;
2524 2525 2526 2527
        SLRUCache*      pCache = ths->pLogStore->pCache;
        LRUHandle*      h = taosLRUCacheLookup(pCache, &i, sizeof(i));
        if (h) {
          pEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2528 2529 2530

          sNTrace(ths, "hit cache index:%" PRId64 ", bytes:%u, %p", i, pEntry->bytes, pEntry);

2531
        } else {
2532 2533
          sNTrace(ths, "miss cache index:%" PRId64, i);

2534
          code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, i, &pEntry);
M
Minghao Li 已提交
2535 2536 2537
          // ASSERT(code == 0);
          // ASSERT(pEntry != NULL);
          if (code != 0 || pEntry == NULL) {
S
Shengliang Guan 已提交
2538
            sNError(ths, "get log entry error");
2539
            sFatal("vgId:%d, get log entry %" PRId64 " error when commit since %s", ths->vgId, i, terrstr());
M
Minghao Li 已提交
2540 2541
            continue;
          }
2542
        }
2543

2544
        SRpcMsg rpcMsg = {0};
2545 2546
        syncEntry2OriginalRpc(pEntry, &rpcMsg);

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

2549
        // user commit
2550 2551
        if ((ths->pFsm->FpCommitCb != NULL) && syncUtilUserCommit(pEntry->originalRpcType)) {
          bool internalExecute = true;
S
Shengliang Guan 已提交
2552
          if ((ths->replicaNum == 1) && ths->restoreFinish && ths->vgId != 1) {
2553 2554 2555
            internalExecute = false;
          }

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

2559 2560
          // execute fsm in apply thread, or execute outside syncPropose
          if (internalExecute) {
S
Shengliang Guan 已提交
2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
            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 已提交
2573
            syncRespMgrGetAndDel(ths->pSyncRespMgr, cbMeta.seqNum, &rpcMsg.info);
S
Shengliang Guan 已提交
2574
            ths->pFsm->FpCommitCb(ths->pFsm, &rpcMsg, &cbMeta);
2575
          }
2576 2577
        }

2578 2579
#if 0
        // execute in pre-commit
M
Minghao Li 已提交
2580
        // leader transfer
2581 2582 2583
        if (pEntry->originalRpcType == TDMT_SYNC_LEADER_TRANSFER) {
          code = syncDoLeaderTransfer(ths, &rpcMsg, pEntry);
          ASSERT(code == 0);
2584
        }
2585
#endif
2586 2587

        // restore finish
2588
        // if only snapshot, a noop entry will be append, so syncLogLastIndex is always ok
2589 2590 2591 2592 2593 2594
        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 已提交
2595

2596
            int64_t restoreDelay = taosGetTimestampMs() - ths->leaderTime;
S
Shengliang Guan 已提交
2597
            sNTrace(ths, "restore finish, index:%" PRId64 ", elapsed:%" PRId64 " ms", pEntry->index, restoreDelay);
2598 2599 2600 2601
          }
        }

        rpcFreeCont(rpcMsg.pCont);
2602 2603 2604 2605 2606
        if (h) {
          taosLRUCacheRelease(pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }
2607 2608 2609 2610
      }
    }
  }
  return 0;
2611 2612 2613
}

bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
S
Shengliang Guan 已提交
2614
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
2615 2616 2617 2618 2619
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
      return true;
    }
  }
  return false;
M
Minghao Li 已提交
2620 2621 2622 2623
}

SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
  SSyncSnapshotSender* pSender = NULL;
S
Shengliang Guan 已提交
2624
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
2625 2626 2627 2628 2629
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pSender = (ths->senders)[i];
    }
  }
  return pSender;
M
Minghao Li 已提交
2630
}
M
Minghao Li 已提交
2631

2632 2633
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
  SSyncTimer* pTimer = NULL;
S
Shengliang Guan 已提交
2634
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
2635 2636 2637 2638 2639 2640 2641
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
    }
  }
  return pTimer;
}

M
Minghao Li 已提交
2642 2643
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
  SPeerState* pState = NULL;
S
Shengliang Guan 已提交
2644
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
2645 2646 2647 2648 2649 2650 2651 2652 2653
    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 已提交
2654
  if (pState == NULL) {
2655
    sError("vgId:%d, replica maybe dropped", ths->vgId);
M
Minghao Li 已提交
2656 2657
    return false;
  }
M
Minghao Li 已提交
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668

  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 已提交
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
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 已提交
2683
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
M
Minghao Li 已提交
2684
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
M
Minghao Li 已提交
2685
    if (pSender != NULL && pSender->start) {
M
Minghao Li 已提交
2686 2687 2688 2689 2690 2691
      sError("sync cannot change3");
      return false;
    }
  }

  return true;
M
Minghao Li 已提交
2692
}