syncMain.c 86.6 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
        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;

413
          pSyncNode->pLogStore->cacheHit++;
414 415 416
          sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", lastIndex, pEntry->bytes, pEntry);

        } else {
417
          pSyncNode->pLogStore->cacheMiss++;
418 419 420 421 422
          sNTrace(pSyncNode, "miss cache index:%" PRId64, lastIndex);

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

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

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

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

446 447 448 449
  syncNodeRelease(pSyncNode);
  return ready;
}

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

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

M
Minghao Li 已提交
470 471 472 473 474
  return ret;
}

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

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

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

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

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

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

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

505
  return state;
M
Minghao Li 已提交
506 507
}

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

S
Shengliang Guan 已提交
514
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
515 516 517 518 519 520 521 522 523 524 525
  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 已提交
526
    syncNodeRelease(pSyncNode);
527 528 529 530 531 532 533 534 535 536
    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 已提交
537
  syncNodeRelease(pSyncNode);
538 539 540
  return 0;
}

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

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

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

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

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

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

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

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

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

  return lastIndex;
}

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

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

S
Shengliang Guan 已提交
602
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
S
Shengliang Guan 已提交
603 604 605 606 607
    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);
608
  }
M
Minghao Li 已提交
609 610 611
  if (pEpSet->numOfEps > 0) {
    pEpSet->inUse = (pSyncNode->pRaftCfg->cfg.myIndex + 1) % pEpSet->numOfEps;
  }
M
Minghao Li 已提交
612

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

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

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

629
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak) {
S
Shengliang Guan 已提交
630 631 632 633 634
  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 已提交
635

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

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

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

686 687
    return code;
  }
M
Minghao Li 已提交
688 689
}

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

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

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

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

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

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

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

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

    if (pSyncInfo->syncCfg.replicaNum > 0 && syncIsConfigChanged(&pSyncNode->pRaftCfg->cfg, &pSyncInfo->syncCfg)) {
S
Shengliang Guan 已提交
777 778 779 780 781 782
      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 已提交
783 784 785 786
    } else {
      sInfo("vgId:%d, use sync config from raft cfg file", pSyncNode->vgId);
      pSyncInfo->syncCfg = pSyncNode->pRaftCfg->cfg;
    }
787 788

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

S
Shengliang Guan 已提交
792 793
  // init by SSyncInfo
  pSyncNode->vgId = pSyncInfo->vgId;
S
Shengliang Guan 已提交
794 795 796 797 798 799 800
  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 已提交
801
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
S
Shengliang Guan 已提交
802 803 804
  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 已提交
805

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

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

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

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

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

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

M
Minghao Li 已提交
857
  // init life cycle outside
M
Minghao Li 已提交
858

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

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

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

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

  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);
926
    if (code != 0) {
S
Shengliang Guan 已提交
927
      sError("vgId:%d, failed to get snapshot info, code:%d", pSyncNode->vgId, code);
H
Hongze Cheng 已提交
928
      goto _error;
929
    }
930 931
    if (snapshot.lastApplyIndex > commitIndex) {
      commitIndex = snapshot.lastApplyIndex;
S
Shengliang Guan 已提交
932
      sNTrace(pSyncNode, "reset commit index by snapshot");
933 934 935
    }
  }
  pSyncNode->commitIndex = commitIndex;
M
Minghao Li 已提交
936

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

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

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

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

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

977 978
  // restore state
  pSyncNode->restoreFinish = false;
979

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

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

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

M
Minghao Li 已提交
994 995 996
  // peer state
  syncNodePeerStateInit(pSyncNode);

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

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

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

1009 1010 1011
  // snapshotting
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);

1012
  pSyncNode->isStart = true;
1013 1014 1015 1016
  pSyncNode->electNum = 0;
  pSyncNode->becomeLeaderNum = 0;
  pSyncNode->configChangeNum = 0;

S
Shengliang Guan 已提交
1017
  sNTrace(pSyncNode, "sync open, node:%p", pSyncNode);
1018

M
Minghao Li 已提交
1019
  return pSyncNode;
1020 1021 1022

_error:
  if (pSyncInfo->pFsm) {
H
Hongze Cheng 已提交
1023 1024
    taosMemoryFree(pSyncInfo->pFsm);
    pSyncInfo->pFsm = NULL;
1025 1026 1027 1028
  }
  syncNodeClose(pSyncNode);
  pSyncNode = NULL;
  return NULL;
M
Minghao Li 已提交
1029 1030
}

M
Minghao Li 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
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 已提交
1042 1043
void syncNodeStart(SSyncNode* pSyncNode) {
  // start raft
1044
  if (pSyncNode->replicaNum == 1) {
M
Minghao Li 已提交
1045
    raftStoreNextTerm(pSyncNode->pRaftStore);
1046
    syncNodeBecomeLeader(pSyncNode, "one replica start");
M
format  
Minghao Li 已提交
1047

1048
    // Raft 3.6.2 Committing entries from previous terms
1049 1050
    syncNodeAppendNoop(pSyncNode);
    syncMaybeAdvanceCommitIndex(pSyncNode);
M
Minghao Li 已提交
1051

M
Minghao Li 已提交
1052 1053
  } else {
    syncNodeBecomeFollower(pSyncNode, "first start");
1054 1055
  }

1056 1057 1058
  int32_t ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
  ASSERT(ret == 0);
M
Minghao Li 已提交
1059 1060
}

M
Minghao Li 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069
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);
1070

1071 1072 1073
  ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
  ASSERT(ret == 0);
M
Minghao Li 已提交
1074 1075
}

M
Minghao Li 已提交
1076 1077 1078 1079 1080 1081 1082 1083
void syncNodePreClose(SSyncNode* pSyncNode) {
  // stop elect timer
  syncNodeStopElectTimer(pSyncNode);

  // stop heartbeat timer
  syncNodeStopHeartbeatTimer(pSyncNode);
}

1084 1085
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }

M
Minghao Li 已提交
1086
void syncNodeClose(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1087 1088
  if (pSyncNode == NULL) return;
  sNTrace(pSyncNode, "sync close, data:%p", pSyncNode);
M
Minghao Li 已提交
1089

S
Shengliang Guan 已提交
1090
  int32_t ret = raftStoreClose(pSyncNode->pRaftStore);
M
Minghao Li 已提交
1091
  ASSERT(ret == 0);
M
Minghao Li 已提交
1092
  pSyncNode->pRaftStore = NULL;
M
Minghao Li 已提交
1093

M
Minghao Li 已提交
1094
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
1095
  pSyncNode->pSyncRespMgr = NULL;
M
Minghao Li 已提交
1096
  voteGrantedDestroy(pSyncNode->pVotesGranted);
1097
  pSyncNode->pVotesGranted = NULL;
M
Minghao Li 已提交
1098
  votesRespondDestory(pSyncNode->pVotesRespond);
1099
  pSyncNode->pVotesRespond = NULL;
M
Minghao Li 已提交
1100
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
1101
  pSyncNode->pNextIndex = NULL;
M
Minghao Li 已提交
1102
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
1103
  pSyncNode->pMatchIndex = NULL;
M
Minghao Li 已提交
1104
  logStoreDestory(pSyncNode->pLogStore);
1105
  pSyncNode->pLogStore = NULL;
M
Minghao Li 已提交
1106
  raftCfgClose(pSyncNode->pRaftCfg);
1107
  pSyncNode->pRaftCfg = NULL;
M
Minghao Li 已提交
1108 1109 1110 1111 1112

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

M
Minghao Li 已提交
1113 1114 1115 1116
  if (pSyncNode->pFsm != NULL) {
    taosMemoryFree(pSyncNode->pFsm);
  }

S
Shengliang Guan 已提交
1117
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1118
    if ((pSyncNode->senders)[i] != NULL) {
S
Shengliang Guan 已提交
1119
      sSTrace((pSyncNode->senders)[i], "snapshot sender destroy while close, data:%p", (pSyncNode->senders)[i]);
M
Minghao Li 已提交
1120 1121 1122 1123 1124
      snapshotSenderDestroy((pSyncNode->senders)[i]);
      (pSyncNode->senders)[i] = NULL;
    }
  }

M
Minghao Li 已提交
1125 1126 1127 1128 1129
  if (pSyncNode->pNewNodeReceiver != NULL) {
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
    pSyncNode->pNewNodeReceiver = NULL;
  }

1130
  taosMemoryFree(pSyncNode);
M
Minghao Li 已提交
1131 1132
}

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

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

1161 1162 1163 1164 1165
    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 已提交
1166

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

1170
  } else {
M
Minghao Li 已提交
1171
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
1172
  }
M
Minghao Li 已提交
1173 1174 1175 1176 1177
  return ret;
}

int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1178
  atomic_add_fetch_64(&pSyncNode->electTimerLogicClock, 1);
M
Minghao Li 已提交
1179 1180
  taosTmrStop(pSyncNode->pElectTimer);
  pSyncNode->pElectTimer = NULL;
1181

M
Minghao Li 已提交
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  return ret;
}

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

M
Minghao Li 已提交
1192 1193
int32_t syncNodeResetElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1194 1195 1196 1197 1198 1199 1200
  int32_t electMS;

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

S
Shengliang Guan 已提交
1203 1204
  sNTrace(pSyncNode, "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine,
          electMS);
M
Minghao Li 已提交
1205 1206 1207
  return ret;
}

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

S
Shengliang Guan 已提交
1218
  sNTrace(pSyncNode, "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
M
Minghao Li 已提交
1219 1220 1221
  return ret;
}

M
Minghao Li 已提交
1222
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
1223
  int32_t ret = 0;
M
Minghao Li 已提交
1224

1225
#if 0
M
Minghao Li 已提交
1226
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
1227 1228
  ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
#endif
1229

S
Shengliang Guan 已提交
1230
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1231
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1232 1233 1234
    if (pSyncTimer != NULL) {
      syncHbTimerStart(pSyncNode, pSyncTimer);
    }
1235
  }
1236

M
Minghao Li 已提交
1237 1238 1239
  return ret;
}

M
Minghao Li 已提交
1240 1241
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
1242 1243

#if 0
M
Minghao Li 已提交
1244 1245 1246
  atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1);
  taosTmrStop(pSyncNode->pHeartbeatTimer);
  pSyncNode->pHeartbeatTimer = NULL;
1247
#endif
1248

S
Shengliang Guan 已提交
1249
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1250
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1251 1252 1253
    if (pSyncTimer != NULL) {
      syncHbTimerStop(pSyncNode, pSyncTimer);
    }
1254
  }
1255

M
Minghao Li 已提交
1256 1257 1258
  return ret;
}

1259 1260 1261 1262 1263 1264
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode) {
  syncNodeStopHeartbeatTimer(pSyncNode);
  syncNodeStartHeartbeatTimer(pSyncNode);
  return 0;
}

M
Minghao Li 已提交
1265 1266 1267
// utils --------------
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
1268
  syncUtilRaftId2EpSet(destRaftId, &epSet);
S
Shengliang Guan 已提交
1269
  if (pSyncNode->syncSendMSg != NULL) {
M
Minghao Li 已提交
1270 1271 1272
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

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

M
Minghao Li 已提交
1281 1282 1283 1284 1285
  return 0;
}

int32_t syncNodeSendMsgByInfo(const SNodeInfo* nodeInfo, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
1286
  syncUtilNodeInfo2EpSet(nodeInfo, &epSet);
S
Shengliang Guan 已提交
1287
  if (pSyncNode->syncSendMSg != NULL) {
M
Minghao Li 已提交
1288 1289 1290
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

1291
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1292
    pSyncNode->syncSendMSg(&epSet, pMsg);
M
Minghao Li 已提交
1293
  } else {
M
Minghao Li 已提交
1294
    sError("vgId:%d, sync send msg by info error, fp-send-msg is null", pSyncNode->vgId);
M
Minghao Li 已提交
1295
  }
M
Minghao Li 已提交
1296 1297 1298
  return 0;
}

1299
inline bool syncNodeInConfig(SSyncNode* pSyncNode, const SSyncCfg* config) {
1300 1301 1302
  bool b1 = false;
  bool b2 = false;

S
Shengliang Guan 已提交
1303
  for (int32_t i = 0; i < config->replicaNum; ++i) {
1304 1305 1306 1307 1308 1309 1310
    if (strcmp((config->nodeInfo)[i].nodeFqdn, pSyncNode->myNodeInfo.nodeFqdn) == 0 &&
        (config->nodeInfo)[i].nodePort == pSyncNode->myNodeInfo.nodePort) {
      b1 = true;
      break;
    }
  }

S
Shengliang Guan 已提交
1311
  for (int32_t i = 0; i < config->replicaNum; ++i) {
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    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;
}

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

1346
  pSyncNode->pRaftCfg->cfg = *pNewConfig;
1347 1348
  pSyncNode->pRaftCfg->lastConfigIndex = lastConfigChangeIndex;

1349 1350
  pSyncNode->configChangeNum++;

M
Minghao Li 已提交
1351 1352
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
M
Minghao Li 已提交
1353

M
Minghao Li 已提交
1354 1355
  bool isDrop = false;
  bool isAdd = false;
M
Minghao Li 已提交
1356

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

M
Minghao Li 已提交
1363 1364 1365 1366 1367
  if (!IamInOld && IamInNew) {
    isAdd = true;
  } else {
    isAdd = false;
  }
M
Minghao Li 已提交
1368

M
Minghao Li 已提交
1369
  // log begin config change
S
Shengliang Guan 已提交
1370 1371 1372 1373
  char oldCfgStr[1024] = {0};
  char newCfgStr[1024] = {0};
  syncCfg2SimpleStr(&oldConfig, oldCfgStr, sizeof(oldCfgStr));
  syncCfg2SimpleStr(pNewConfig, oldCfgStr, sizeof(oldCfgStr));
1374
  sNInfo(pSyncNode, "begin do config change, from %s to %s", oldCfgStr, oldCfgStr);
M
Minghao Li 已提交
1375

M
Minghao Li 已提交
1376 1377
  if (IamInNew) {
    pSyncNode->pRaftCfg->isStandBy = 0;  // change isStandBy to normal
M
Minghao Li 已提交
1378
  }
M
Minghao Li 已提交
1379 1380
  if (isDrop) {
    pSyncNode->pRaftCfg->isStandBy = 1;  // set standby
M
Minghao Li 已提交
1381 1382
  }

M
Minghao Li 已提交
1383
  // add last config index
M
Minghao Li 已提交
1384
  raftCfgAddConfigIndex(pSyncNode->pRaftCfg, lastConfigChangeIndex);
M
Minghao Li 已提交
1385

M
Minghao Li 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394
  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 已提交
1395
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1396
      oldSenders[i] = (pSyncNode->senders)[i];
S
Shengliang Guan 已提交
1397
      sSTrace(oldSenders[i], "snapshot sender save old");
M
Minghao Li 已提交
1398
    }
1399

M
Minghao Li 已提交
1400 1401
    // init internal
    pSyncNode->myNodeInfo = pSyncNode->pRaftCfg->cfg.nodeInfo[pSyncNode->pRaftCfg->cfg.myIndex];
1402
    syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId);
M
Minghao Li 已提交
1403 1404 1405

    // init peersNum, peers, peersId
    pSyncNode->peersNum = pSyncNode->pRaftCfg->cfg.replicaNum - 1;
S
Shengliang Guan 已提交
1406 1407
    int32_t j = 0;
    for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
M
Minghao Li 已提交
1408 1409 1410 1411 1412
      if (i != pSyncNode->pRaftCfg->cfg.myIndex) {
        pSyncNode->peersNodeInfo[j] = pSyncNode->pRaftCfg->cfg.nodeInfo[i];
        j++;
      }
    }
S
Shengliang Guan 已提交
1413
    for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1414
      syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]);
M
Minghao Li 已提交
1415
    }
1416

M
Minghao Li 已提交
1417 1418
    // init replicaNum, replicasId
    pSyncNode->replicaNum = pSyncNode->pRaftCfg->cfg.replicaNum;
S
Shengliang Guan 已提交
1419
    for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
1420
      syncUtilNodeInfo2RaftId(&pSyncNode->pRaftCfg->cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]);
M
Minghao Li 已提交
1421
    }
1422

1423 1424 1425
    // update quorum first
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->pRaftCfg->cfg.replicaNum);

M
Minghao Li 已提交
1426 1427 1428 1429
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
M
Minghao Li 已提交
1430

M
Minghao Li 已提交
1431
    // reset snapshot senders
1432

M
Minghao Li 已提交
1433
    // clear new
S
Shengliang Guan 已提交
1434
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1435 1436
      (pSyncNode->senders)[i] = NULL;
    }
M
Minghao Li 已提交
1437

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

          (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 已提交
1458 1459
          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 已提交
1460 1461

          break;
M
Minghao Li 已提交
1462
        }
1463 1464
      }
    }
1465

M
Minghao Li 已提交
1466
    // create new
S
Shengliang Guan 已提交
1467
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1468 1469
      if ((pSyncNode->senders)[i] == NULL) {
        (pSyncNode->senders)[i] = snapshotSenderCreate(pSyncNode, i);
S
Shengliang Guan 已提交
1470 1471 1472
        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 已提交
1473
      }
1474 1475
    }

M
Minghao Li 已提交
1476
    // free old
S
Shengliang Guan 已提交
1477
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1478
      if (oldSenders[i] != NULL) {
S
Shengliang Guan 已提交
1479
        sNTrace(pSyncNode, "snapshot sender destroy old, data:%p replica-index:%d", oldSenders[i], i);
M
Minghao Li 已提交
1480 1481 1482
        snapshotSenderDestroy(oldSenders[i]);
        oldSenders[i] = NULL;
      }
1483 1484
    }

1485
    // persist cfg
M
Minghao Li 已提交
1486
    raftCfgPersist(pSyncNode->pRaftCfg);
1487

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

M
Minghao Li 已提交
1492 1493 1494
    // change isStandBy to normal (election timeout)
    if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
      syncNodeBecomeLeader(pSyncNode, tmpbuf);
1495 1496 1497 1498 1499

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

M
Minghao Li 已提交
1500 1501 1502 1503
    } else {
      syncNodeBecomeFollower(pSyncNode, tmpbuf);
    }
  } else {
1504
    // persist cfg
M
Minghao Li 已提交
1505
    raftCfgPersist(pSyncNode->pRaftCfg);
1506 1507
    sNInfo(pSyncNode, "do not config change from %d to %d, index:%" PRId64 ", %s  -->  %s", oldConfig.replicaNum,
           pNewConfig->replicaNum, lastConfigChangeIndex, oldCfgStr, newCfgStr);
1508
  }
1509

M
Minghao Li 已提交
1510
_END:
M
Minghao Li 已提交
1511
  // log end config change
1512
  sNInfo(pSyncNode, "end do config change, from %s to %s", oldCfgStr, newCfgStr);
M
Minghao Li 已提交
1513 1514
}

M
Minghao Li 已提交
1515 1516 1517 1518
// raft state change --------------
void syncNodeUpdateTerm(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
1519
    char tmpBuf[64];
1520
    snprintf(tmpBuf, sizeof(tmpBuf), "update term to %" PRId64, term);
1521
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
M
Minghao Li 已提交
1522 1523 1524 1525
    raftStoreClearVote(pSyncNode->pRaftStore);
  }
}

1526 1527 1528 1529 1530 1531
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
  }
}

M
Minghao Li 已提交
1532
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm) {
M
Minghao Li 已提交
1533
  if (pSyncNode->pRaftStore->currentTerm > newTerm) {
1534
    sNTrace(pSyncNode, "step down, ignore, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1535
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1536 1537
    return;
  }
M
Minghao Li 已提交
1538 1539

  do {
1540
    sNTrace(pSyncNode, "step down, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1541
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1542 1543 1544 1545 1546
  } while (0);

  if (pSyncNode->pRaftStore->currentTerm < newTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, newTerm);
    char tmpBuf[64];
1547
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
M
Minghao Li 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
    raftStoreClearVote(pSyncNode->pRaftStore);

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

1558 1559
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }

1560
void syncNodeBecomeFollower(SSyncNode* pSyncNode, const char* debugStr) {
M
Minghao Li 已提交
1561
  // maybe clear leader cache
M
Minghao Li 已提交
1562 1563 1564 1565
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
  }

M
Minghao Li 已提交
1566
  // state change
M
Minghao Li 已提交
1567 1568 1569
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
  syncNodeStopHeartbeatTimer(pSyncNode);

M
Minghao Li 已提交
1570 1571
  // reset elect timer
  syncNodeResetElectTimer(pSyncNode);
M
Minghao Li 已提交
1572

1573 1574 1575
  // send rsp to client
  syncNodeLeaderChangeRsp(pSyncNode);

1576 1577 1578 1579 1580
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1581 1582 1583
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
1584
  // trace log
S
Shengliang Guan 已提交
1585
  sNTrace(pSyncNode, "become follower %s", debugStr);
M
Minghao Li 已提交
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
}

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

1609 1610
  pSyncNode->becomeLeaderNum++;

1611 1612 1613
  // reset restoreFinish
  pSyncNode->restoreFinish = false;

M
Minghao Li 已提交
1614
  // state change
M
Minghao Li 已提交
1615
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
M
Minghao Li 已提交
1616 1617

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

S
Shengliang Guan 已提交
1620
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1621 1622
    // maybe overwrite myself, no harm
    // just do it!
1623 1624 1625 1626 1627 1628 1629 1630 1631

    // 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 已提交
1632 1633
  }

S
Shengliang Guan 已提交
1634
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1635 1636
    // maybe overwrite myself, no harm
    // just do it!
M
Minghao Li 已提交
1637 1638 1639
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
  }

M
Minghao Li 已提交
1640 1641 1642
  // init peer mgr
  syncNodePeerStateInit(pSyncNode);

M
Minghao Li 已提交
1643
#if 0
1644 1645
  // update sender private term
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
1646
  if (pMySender != NULL) {
S
Shengliang Guan 已提交
1647
    for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
1648 1649 1650
      if ((pSyncNode->senders)[i]->privateTerm > pMySender->privateTerm) {
        pMySender->privateTerm = (pSyncNode->senders)[i]->privateTerm;
      }
1651
    }
1652
    (pMySender->privateTerm) += 100;
1653
  }
M
Minghao Li 已提交
1654
#endif
1655

1656 1657 1658 1659 1660
  // close receiver
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
    snapshotReceiverForceStop(pSyncNode->pNewNodeReceiver);
  }

M
Minghao Li 已提交
1661
  // stop elect timer
M
Minghao Li 已提交
1662
  syncNodeStopElectTimer(pSyncNode);
M
Minghao Li 已提交
1663

M
Minghao Li 已提交
1664 1665
  // start heartbeat timer
  syncNodeStartHeartbeatTimer(pSyncNode);
M
Minghao Li 已提交
1666

M
Minghao Li 已提交
1667 1668
  // send heartbeat right now
  syncNodeHeartbeatPeers(pSyncNode);
M
Minghao Li 已提交
1669

1670 1671 1672 1673 1674
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1675 1676 1677
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
1678
  // trace log
1679
  sNInfo(pSyncNode, "become leader %s", debugStr);
M
Minghao Li 已提交
1680 1681 1682
}

void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1683 1684
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
  ASSERT(voteGrantedMajority(pSyncNode->pVotesGranted));
1685
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");
M
Minghao Li 已提交
1686

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

M
Minghao Li 已提交
1689
  // Raft 3.6.2 Committing entries from previous terms
1690 1691
  syncNodeAppendNoop(pSyncNode);
  syncMaybeAdvanceCommitIndex(pSyncNode);
1692 1693

  if (pSyncNode->replicaNum > 1) {
M
Minghao Li 已提交
1694
    syncNodeReplicate(pSyncNode);
1695
  }
M
Minghao Li 已提交
1696 1697
}

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

M
Minghao Li 已提交
1700
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1701
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1702 1703 1704 1705 1706
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
    pSyncNode->peerStates[i].lastSendTime = 0;
  }

  return 0;
M
Minghao Li 已提交
1707 1708 1709
}

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

void syncNodeLeader2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1716
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_LEADER);
1717
  syncNodeBecomeFollower(pSyncNode, "leader to follower");
S
Shengliang Guan 已提交
1718
  sNTrace(pSyncNode, "leader to follower");
M
Minghao Li 已提交
1719 1720 1721
}

void syncNodeCandidate2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1722
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
1723
  syncNodeBecomeFollower(pSyncNode, "candidate to follower");
S
Shengliang Guan 已提交
1724
  sNTrace(pSyncNode, "candidate to follower");
M
Minghao Li 已提交
1725 1726
}

M
Minghao Li 已提交
1727 1728
// just called by syncNodeVoteForSelf
// need assert
M
Minghao Li 已提交
1729
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
M
Minghao Li 已提交
1730 1731
  ASSERT(term == pSyncNode->pRaftStore->currentTerm);
  ASSERT(!raftStoreHasVoted(pSyncNode->pRaftStore));
M
Minghao Li 已提交
1732 1733 1734 1735

  raftStoreVote(pSyncNode->pRaftStore, pRaftId);
}

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

S
Shengliang Guan 已提交
1740 1741
  SRpcMsg rpcMsg = {0};
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
S
Shengliang Guan 已提交
1742
  if (ret != 0) return;
S
Shengliang Guan 已提交
1743 1744

  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
M
Minghao Li 已提交
1745 1746 1747 1748 1749 1750 1751
  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 已提交
1752
  rpcFreeCont(rpcMsg.pCont);
M
Minghao Li 已提交
1753 1754
}

M
Minghao Li 已提交
1755
// return if has a snapshot
M
Minghao Li 已提交
1756 1757
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
  bool      ret = false;
1758
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1759 1760
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1761 1762 1763 1764 1765 1766 1767
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
      ret = true;
    }
  }
  return ret;
}

M
Minghao Li 已提交
1768 1769
// return max(logLastIndex, snapshotLastIndex)
// if no snapshot and log, return -1
1770
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1771
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1772 1773
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1774 1775 1776 1777 1778 1779 1780
  }
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);

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

M
Minghao Li 已提交
1781 1782
// return the last term of snapshot and log
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
M
Minghao Li 已提交
1783 1784
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
  SyncTerm lastTerm = 0;
M
Minghao Li 已提交
1785 1786
  if (syncNodeHasSnapshot(pSyncNode)) {
    // has snapshot
1787
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1788 1789
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1790 1791
    }

M
Minghao Li 已提交
1792 1793 1794
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
    if (logLastIndex > snapshot.lastApplyIndex) {
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
M
Minghao Li 已提交
1795 1796 1797 1798
    } else {
      lastTerm = snapshot.lastApplyTerm;
    }

M
Minghao Li 已提交
1799
  } else {
M
Minghao Li 已提交
1800 1801
    // no snapshot
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1802
  }
M
Minghao Li 已提交
1803

M
Minghao Li 已提交
1804 1805 1806 1807 1808 1809 1810
  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);
1811 1812
  return 0;
}
M
Minghao Li 已提交
1813

M
Minghao Li 已提交
1814
// return append-entries first try index
M
Minghao Li 已提交
1815 1816 1817 1818 1819
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
  return syncStartIndex;
}

M
Minghao Li 已提交
1820 1821
// if index > 0, return index - 1
// else, return -1
1822 1823 1824 1825 1826 1827 1828 1829 1830
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
  SyncIndex preIndex = index - 1;
  if (preIndex < SYNC_INDEX_INVALID) {
    preIndex = SYNC_INDEX_INVALID;
  }

  return preIndex;
}

M
Minghao Li 已提交
1831 1832 1833 1834
// if index < 0, return SYNC_TERM_INVALID
// if index == 0, return 0
// if index > 0, return preTerm
// if error, return SYNC_TERM_INVALID
1835 1836 1837 1838 1839 1840 1841 1842 1843
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
  if (index < SYNC_INDEX_BEGIN) {
    return SYNC_TERM_INVALID;
  }

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

1844 1845 1846
  SyncTerm  preTerm = 0;
  SyncIndex preIndex = index - 1;

1847
  SSyncRaftEntry* pPreEntry = NULL;
1848 1849 1850 1851 1852 1853 1854
  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;

1855
    pSyncNode->pLogStore->cacheHit++;
1856 1857 1858
    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);

  } else {
1859
    pSyncNode->pLogStore->cacheMiss++;
1860 1861 1862 1863
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);

    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
  }
M
Minghao Li 已提交
1864 1865 1866 1867 1868 1869

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

1870 1871 1872
  if (code == 0) {
    ASSERT(pPreEntry != NULL);
    preTerm = pPreEntry->term;
1873 1874 1875 1876 1877 1878 1879

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

1880 1881
    return preTerm;
  } else {
1882 1883 1884 1885
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
      if (snapshot.lastApplyIndex == preIndex) {
        return snapshot.lastApplyTerm;
1886 1887 1888 1889
      }
    }
  }

1890
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
S
Shengliang Guan 已提交
1891
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
1892 1893
  return SYNC_TERM_INVALID;
}
M
Minghao Li 已提交
1894 1895 1896 1897

// 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 已提交
1898
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
M
Minghao Li 已提交
1899 1900 1901
  return 0;
}

M
Minghao Li 已提交
1902
static void syncNodeEqPingTimer(void* param, void* tmrId) {
S
Shengliang Guan 已提交
1903 1904 1905 1906 1907
  if (!syncIsInit()) return;

  SSyncNode* pNode = param;
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
    SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
1908
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
S
Shengliang Guan 已提交
1909 1910
                                    pNode->pingTimerMS, pNode);
    if (code != 0) {
M
Minghao Li 已提交
1911
      sError("failed to build ping msg");
S
Shengliang Guan 已提交
1912 1913
      rpcFreeCont(rpcMsg.pCont);
      return;
M
Minghao Li 已提交
1914
    }
M
Minghao Li 已提交
1915

M
Minghao Li 已提交
1916
    // sTrace("enqueue ping msg");
S
Shengliang Guan 已提交
1917 1918
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
    if (code != 0) {
M
Minghao Li 已提交
1919
      sError("failed to sync enqueue ping msg since %s", terrstr());
S
Shengliang Guan 已提交
1920 1921
      rpcFreeCont(rpcMsg.pCont);
      return;
1922 1923
    }

S
Shengliang Guan 已提交
1924
    taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, pNode, syncEnv()->pTimerManager, &pNode->pPingTimer);
M
Minghao Li 已提交
1925 1926 1927 1928
  }
}

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

M
Minghao Li 已提交
1931 1932
  int64_t    rid = (int64_t)param;
  SSyncNode* pNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
1933

1934
  if (pNode == NULL) return;
M
Minghao Li 已提交
1935 1936 1937 1938 1939

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

1941
  int64_t tsNow = taosGetTimestampMs();
M
Minghao Li 已提交
1942 1943 1944 1945
  if (tsNow < pNode->electTimerParam.executeTime) {
    syncNodeRelease(pNode);
    return;
  }
1946

S
Shengliang Guan 已提交
1947
  SRpcMsg rpcMsg = {0};
1948 1949
  int32_t code =
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
S
Shengliang Guan 已提交
1950

S
Shengliang Guan 已提交
1951
  if (code != 0) {
M
Minghao Li 已提交
1952
    sError("failed to build elect msg");
M
Minghao Li 已提交
1953
    syncNodeRelease(pNode);
S
Shengliang Guan 已提交
1954 1955 1956 1957
    return;
  }

  SyncTimeout* pTimeout = rpcMsg.pCont;
S
Shengliang Guan 已提交
1958
  sNTrace(pNode, "enqueue elect msg lc:%" PRId64, pTimeout->logicClock);
S
Shengliang Guan 已提交
1959 1960 1961

  code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
  if (code != 0) {
M
Minghao Li 已提交
1962
    sError("failed to sync enqueue elect msg since %s", terrstr());
S
Shengliang Guan 已提交
1963
    rpcFreeCont(rpcMsg.pCont);
M
Minghao Li 已提交
1964
    syncNodeRelease(pNode);
1965
    return;
S
Shengliang Guan 已提交
1966
  }
M
Minghao Li 已提交
1967 1968

  syncNodeRelease(pNode);
M
Minghao Li 已提交
1969 1970
}

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

S
Shengliang Guan 已提交
1974 1975 1976 1977
  SSyncNode* pNode = param;
  if (pNode->replicaNum > 1) {
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
      SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
1978
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
S
Shengliang Guan 已提交
1979 1980 1981
                                      pNode->heartbeatTimerMS, pNode);

      if (code != 0) {
M
Minghao Li 已提交
1982
        sError("failed to build heartbeat msg");
S
Shengliang Guan 已提交
1983
        return;
1984
      }
M
Minghao Li 已提交
1985

1986
      sTrace("vgId:%d, enqueue heartbeat timer", pNode->vgId);
S
Shengliang Guan 已提交
1987 1988
      code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
      if (code != 0) {
M
Minghao Li 已提交
1989
        sError("failed to enqueue heartbeat msg since %s", terrstr());
S
Shengliang Guan 已提交
1990 1991
        rpcFreeCont(rpcMsg.pCont);
        return;
1992
      }
S
Shengliang Guan 已提交
1993 1994 1995 1996

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

1997
    } else {
S
Shengliang Guan 已提交
1998 1999
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
2000
    }
M
Minghao Li 已提交
2001 2002 2003
  }
}

2004
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
2005
  int64_t hbDataRid = (int64_t)param;
2006
  int64_t tsNow = taosGetTimestampMs();
2007 2008 2009

  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
  if (pData == NULL) {
M
Minghao Li 已提交
2010
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
2011 2012
    return;
  }
2013

2014
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
M
Minghao Li 已提交
2015
  if (pSyncNode == NULL) {
2016
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2017
    sError("hb timer get pSyncNode NULL");
2018 2019 2020 2021 2022 2023 2024 2025
    return;
  }

  SSyncTimer* pSyncTimer = pData->pTimer;

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

M
Minghao Li 已提交
2030
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
2031 2032
    syncNodeRelease(pSyncNode);
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2033
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
M
Minghao Li 已提交
2034 2035 2036
    return;
  }

M
Minghao Li 已提交
2037
  if (pSyncNode->pRaftStore == NULL) {
2038 2039
    syncNodeRelease(pSyncNode);
    syncHbTimerDataRelease(pData);
M
Minghao Li 已提交
2040
    sError("vgId:%d, hb timer raft store already stop", pSyncNode->vgId);
M
Minghao Li 已提交
2041 2042 2043
    return;
  }

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

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

2050
    if (timerLogicClock == msgLogicClock) {
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
      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;
2071
        pSyncMsg->timeStamp = tsNow;
2072 2073 2074 2075 2076 2077

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

        // send msg
2078 2079
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime);
        syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
2080 2081 2082 2083 2084 2085 2086 2087
      } 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 已提交
2088 2089
      if (syncIsInit()) {
        // sTrace("vgId:%d, reset peer hb timer", pSyncNode->vgId);
2090 2091
        taosTmrReset(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS / HEARTBEAT_TICK_NUM, (void*)hbDataRid,
                     syncEnv()->pTimerManager, &pSyncTimer->pTimer);
M
Minghao Li 已提交
2092 2093 2094 2095
      } else {
        sError("sync env is stop, reset peer hb timer error");
      }

2096
    } else {
M
Minghao Li 已提交
2097 2098
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64 "", pSyncNode->vgId,
             timerLogicClock, msgLogicClock);
2099 2100
    }
  }
2101 2102 2103

  syncHbTimerDataRelease(pData);
  syncNodeRelease(pSyncNode);
2104 2105
}

2106 2107 2108 2109 2110
static int32_t syncNodeEqNoop(SSyncNode* pNode) {
  if (pNode->state == TAOS_SYNC_STATE_LEADER) {
    terrno = TSDB_CODE_SYN_NOT_LEADER;
    return -1;
  }
M
Minghao Li 已提交
2111

2112 2113 2114 2115
  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 已提交
2116

S
Shengliang Guan 已提交
2117
  SRpcMsg rpcMsg = {0};
S
Shengliang Guan 已提交
2118
  int32_t code = syncBuildClientRequestFromNoopEntry(&rpcMsg, pEntry, pNode->vgId);
M
Minghao Li 已提交
2119
  syncEntryDestory(pEntry);
M
Minghao Li 已提交
2120

2121 2122 2123
  sNTrace(pNode, "propose msg, type:noop");
  code = (*pNode->syncEqMsg)(pNode->msgcb, &rpcMsg);
  if (code != 0) {
M
Minghao Li 已提交
2124
    sError("failed to propose noop msg while enqueue since %s", terrstr());
2125 2126 2127
  }

  return code;
M
Minghao Li 已提交
2128 2129
}

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

2132 2133 2134 2135
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 已提交
2136 2137
  int32_t   code = 0;
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2138 2139 2140 2141 2142 2143 2144 2145 2146
  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;
}

2147
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
  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 已提交
2170 2171 2172
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
  int32_t ret = 0;

2173
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2174
  SyncTerm        term = ths->pRaftStore->currentTerm;
M
Minghao Li 已提交
2175
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
M
Minghao Li 已提交
2176
  ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2177

2178 2179
  LRUHandle* h = NULL;

M
Minghao Li 已提交
2180
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2181
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
2182
    if (code != 0) {
M
Minghao Li 已提交
2183
      sError("append noop error");
2184 2185
      return -1;
    }
2186 2187

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

2190 2191 2192 2193 2194 2195
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2196 2197 2198
  return ret;
}

S
Shengliang Guan 已提交
2199 2200
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
2201 2202

  int64_t tsMs = taosGetTimestampMs();
M
Minghao Li 已提交
2203
  int64_t timeDiff = tsMs - pMsg->timeStamp;
2204
  syncLogRecvHeartbeat(ths, pMsg, timeDiff);
2205

2206 2207 2208 2209
  SRpcMsg rpcMsg = {0};
  (void)syncBuildHeartbeatReply(&rpcMsg, ths->vgId);

  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
2210 2211 2212 2213
  pMsgReply->destId = pMsg->srcId;
  pMsgReply->srcId = ths->myRaftId;
  pMsgReply->term = ths->pRaftStore->currentTerm;
  pMsgReply->privateTerm = 8864;  // magic number
2214
  pMsgReply->timeStamp = tsMs;
2215

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

2219
    syncNodeResetElectTimer(ths);
M
Minghao Li 已提交
2220
    ths->minMatchIndex = pMsg->minMatchIndex;
2221 2222

    if (ths->state == TAOS_SYNC_STATE_FOLLOWER) {
2223
      // syncNodeFollowerCommit(ths, pMsg->commitIndex);
S
Shengliang Guan 已提交
2224 2225 2226 2227
      SRpcMsg rpcMsgLocalCmd = {0};
      (void)syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId);

      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
2228 2229
      pSyncMsg->cmd = SYNC_LOCAL_CMD_FOLLOWER_CMT;
      pSyncMsg->fcIndex = pMsg->commitIndex;
2230
      SyncIndex fcIndex = pSyncMsg->fcIndex;
2231 2232 2233 2234 2235 2236 2237

      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 {
2238
          sTrace("vgId:%d, sync enqueue fc-commit msg, fc-index:%" PRId64, ths->vgId, fcIndex);
2239 2240
        }
      }
2241 2242 2243
    }
  }

M
Minghao Li 已提交
2244
  if (pMsg->term >= ths->pRaftStore->currentTerm && ths->state != TAOS_SYNC_STATE_FOLLOWER) {
2245
    // syncNodeStepDown(ths, pMsg->term);
S
Shengliang Guan 已提交
2246 2247 2248 2249
    SRpcMsg rpcMsgLocalCmd = {0};
    (void)syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId);

    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
2250 2251 2252
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
    pSyncMsg->sdNewTerm = pMsg->term;

S
Shengliang Guan 已提交
2253 2254
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
2255 2256 2257 2258
      if (code != 0) {
        sError("vgId:%d, sync enqueue step-down msg error, code:%d", ths->vgId, code);
        rpcFreeCont(rpcMsgLocalCmd.pCont);
      } else {
2259
        sTrace("vgId:%d, sync enqueue step-down msg, new-term: %" PRId64, ths->vgId, pSyncMsg->sdNewTerm);
2260 2261
      }
    }
M
Minghao Li 已提交
2262 2263
  }

2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
  /*
    // htonl
    SMsgHead* pHead = rpcMsg.pCont;
    pHead->contLen = htonl(pHead->contLen);
    pHead->vgId = htonl(pHead->vgId);
  */

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

2276 2277
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
2278

M
Minghao Li 已提交
2279
  int64_t tsMs = taosGetTimestampMs();
M
Minghao Li 已提交
2280
  int64_t timeDiff = tsMs - pMsg->timeStamp;
S
Shengliang Guan 已提交
2281
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff);
M
Minghao Li 已提交
2282

2283
  // update last reply time, make decision whether the other node is alive or not
M
Minghao Li 已提交
2284
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
2285 2286 2287
  return 0;
}

S
Shengliang Guan 已提交
2288 2289
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
2290 2291
  syncLogRecvLocalCmd(ths, pMsg, "");

M
Minghao Li 已提交
2292 2293 2294
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
    syncNodeStepDown(ths, pMsg->sdNewTerm);

2295 2296 2297
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT) {
    syncNodeFollowerCommit(ths, pMsg->fcIndex);

M
Minghao Li 已提交
2298
  } else {
M
Minghao Li 已提交
2299
    sError("error local cmd");
M
Minghao Li 已提交
2300 2301 2302 2303 2304
  }

  return 0;
}

M
Minghao Li 已提交
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
// 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 已提交
2315

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

M
Minghao Li 已提交
2319
  int32_t ret = 0;
2320
  int32_t code = 0;
M
Minghao Li 已提交
2321

M
Minghao Li 已提交
2322
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2323
  SyncTerm        term = ths->pRaftStore->currentTerm;
2324 2325 2326 2327 2328 2329 2330
  SSyncRaftEntry* pEntry;

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

2332 2333
  LRUHandle* h = NULL;

M
Minghao Li 已提交
2334
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2335 2336 2337
    // append entry
    code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
    if (code != 0) {
2338 2339 2340 2341 2342 2343
      if (ths->replicaNum == 1) {
        if (h) {
          taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }
2344

2345 2346 2347 2348
        return -1;

      } else {
        // del resp mgr, call FpCommitCb
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
        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,
        };
2360
        ths->pFsm->FpCommitCb(ths->pFsm, pMsg, &cbMeta);
2361 2362 2363 2364 2365 2366 2367

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

2368 2369
        return -1;
      }
2370
    }
M
Minghao Li 已提交
2371

2372 2373
    syncCacheEntry(ths->pLogStore, pEntry, &h);

2374 2375
    // if mulit replica, start replicate right now
    if (ths->replicaNum > 1) {
M
Minghao Li 已提交
2376
      syncNodeReplicate(ths);
2377
    }
2378

2379 2380
    // if only myself, maybe commit right now
    if (ths->replicaNum == 1) {
2381 2382 2383 2384 2385
      if (syncNodeIsMnode(ths)) {
        syncMaybeAdvanceCommitIndex(ths);
      } else {
        syncOneReplicaAdvance(ths);
      }
2386
    }
M
Minghao Li 已提交
2387 2388
  }

2389 2390 2391 2392 2393 2394 2395 2396
  if (pRetIndex != NULL) {
    if (ret == 0 && pEntry != NULL) {
      *pRetIndex = pEntry->index;
    } else {
      *pRetIndex = SYNC_INDEX_INVALID;
    }
  }

2397 2398 2399 2400 2401 2402
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2403
  return ret;
2404
}
M
Minghao Li 已提交
2405

S
Shengliang Guan 已提交
2406 2407 2408
const char* syncStr(ESyncState state) {
  switch (state) {
    case TAOS_SYNC_STATE_FOLLOWER:
2409
      return "follower";
S
Shengliang Guan 已提交
2410
    case TAOS_SYNC_STATE_CANDIDATE:
2411
      return "candidate";
S
Shengliang Guan 已提交
2412
    case TAOS_SYNC_STATE_LEADER:
2413
      return "leader";
S
Shengliang Guan 已提交
2414
    default:
2415
      return "error";
S
Shengliang Guan 已提交
2416
  }
M
Minghao Li 已提交
2417
}
2418

2419
#if 0
2420
int32_t syncDoLeaderTransfer(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry) {
2421
  if (ths->state != TAOS_SYNC_STATE_FOLLOWER) {
S
Shengliang Guan 已提交
2422
    sNTrace(ths, "I am not follower, can not do leader transfer");
2423 2424
    return 0;
  }
2425 2426

  if (!ths->restoreFinish) {
S
Shengliang Guan 已提交
2427
    sNTrace(ths, "restore not finish, can not do leader transfer");
2428 2429 2430
    return 0;
  }

2431
  if (pEntry->term < ths->pRaftStore->currentTerm) {
2432
    sNTrace(ths, "little term:%" PRId64 ", can not do leader transfer", pEntry->term);
2433 2434 2435 2436
    return 0;
  }

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

2441 2442
  /*
    if (ths->vgId > 1) {
S
Shengliang Guan 已提交
2443
      sNTrace(ths, "I am vnode, can not do leader transfer");
2444 2445 2446 2447
      return 0;
    }
  */

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

M
Minghao Li 已提交
2451 2452 2453
  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 已提交
2454

M
Minghao Li 已提交
2455 2456
  bool same = sameId || sameNodeInfo;
  if (same) {
M
Minghao Li 已提交
2457 2458 2459 2460
    // reset elect timer now!
    int32_t electMS = 1;
    int32_t ret = syncNodeRestartElectTimer(ths, electMS);
    ASSERT(ret == 0);
M
Minghao Li 已提交
2461

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

M
Minghao Li 已提交
2466
  if (ths->pFsm->FpLeaderTransferCb != NULL) {
S
Shengliang Guan 已提交
2467
    SFsmCbMeta cbMeta = {
S
Shengliang Guan 已提交
2468 2469 2470 2471 2472 2473 2474 2475 2476
        .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 已提交
2477 2478
    };
    ths->pFsm->FpLeaderTransferCb(ths->pFsm, pRpcMsg, &cbMeta);
2479 2480
  }

2481 2482 2483
  return 0;
}

2484 2485
#endif

2486
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
S
Shengliang Guan 已提交
2487
  for (int32_t i = 0; i < pNewCfg->replicaNum; ++i) {
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
    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;
}

2501 2502 2503 2504
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
}

M
Minghao Li 已提交
2505
int32_t syncNodeDoCommit(SSyncNode* ths, SyncIndex beginIndex, SyncIndex endIndex, uint64_t flag) {
2506 2507 2508 2509
  if (beginIndex > endIndex) {
    return 0;
  }

M
Minghao Li 已提交
2510 2511 2512 2513 2514 2515 2516 2517 2518
  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 已提交
2519
      sNTrace(ths, "commit by snapshot from index:%" PRId64 " to index:%" PRId64, beginIndex, snapshot.lastApplyIndex);
2520

M
Minghao Li 已提交
2521 2522 2523
      // update begin index
      beginIndex = snapshot.lastApplyIndex + 1;
    }
2524 2525
  }

2526 2527
  int32_t    code = 0;
  ESyncState state = flag;
M
Minghao Li 已提交
2528

S
Shengliang Guan 已提交
2529
  sNTrace(ths, "commit by wal from index:%" PRId64 " to index:%" PRId64, beginIndex, endIndex);
2530 2531 2532 2533 2534 2535

  // execute fsm
  if (ths->pFsm != NULL) {
    for (SyncIndex i = beginIndex; i <= endIndex; ++i) {
      if (i != SYNC_INDEX_INVALID) {
        SSyncRaftEntry* pEntry;
2536 2537 2538 2539
        SLRUCache*      pCache = ths->pLogStore->pCache;
        LRUHandle*      h = taosLRUCacheLookup(pCache, &i, sizeof(i));
        if (h) {
          pEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2540

2541
          ths->pLogStore->cacheHit++;
2542 2543
          sNTrace(ths, "hit cache index:%" PRId64 ", bytes:%u, %p", i, pEntry->bytes, pEntry);

2544
        } else {
2545
          ths->pLogStore->cacheMiss++;
2546 2547
          sNTrace(ths, "miss cache index:%" PRId64, i);

2548
          code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, i, &pEntry);
M
Minghao Li 已提交
2549 2550 2551
          // ASSERT(code == 0);
          // ASSERT(pEntry != NULL);
          if (code != 0 || pEntry == NULL) {
S
Shengliang Guan 已提交
2552
            sNError(ths, "get log entry error");
2553
            sFatal("vgId:%d, get log entry %" PRId64 " error when commit since %s", ths->vgId, i, terrstr());
M
Minghao Li 已提交
2554 2555
            continue;
          }
2556
        }
2557

2558
        SRpcMsg rpcMsg = {0};
2559 2560
        syncEntry2OriginalRpc(pEntry, &rpcMsg);

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

2563
        // user commit
2564 2565
        if ((ths->pFsm->FpCommitCb != NULL) && syncUtilUserCommit(pEntry->originalRpcType)) {
          bool internalExecute = true;
S
Shengliang Guan 已提交
2566
          if ((ths->replicaNum == 1) && ths->restoreFinish && ths->vgId != 1) {
2567 2568 2569
            internalExecute = false;
          }

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

2573 2574
          // execute fsm in apply thread, or execute outside syncPropose
          if (internalExecute) {
S
Shengliang Guan 已提交
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
            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 已提交
2587
            syncRespMgrGetAndDel(ths->pSyncRespMgr, cbMeta.seqNum, &rpcMsg.info);
S
Shengliang Guan 已提交
2588
            ths->pFsm->FpCommitCb(ths->pFsm, &rpcMsg, &cbMeta);
2589
          }
2590 2591
        }

2592 2593
#if 0
        // execute in pre-commit
M
Minghao Li 已提交
2594
        // leader transfer
2595 2596 2597
        if (pEntry->originalRpcType == TDMT_SYNC_LEADER_TRANSFER) {
          code = syncDoLeaderTransfer(ths, &rpcMsg, pEntry);
          ASSERT(code == 0);
2598
        }
2599
#endif
2600 2601

        // restore finish
2602
        // if only snapshot, a noop entry will be append, so syncLogLastIndex is always ok
2603 2604 2605 2606 2607 2608
        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 已提交
2609

2610
            int64_t restoreDelay = taosGetTimestampMs() - ths->leaderTime;
S
Shengliang Guan 已提交
2611
            sNTrace(ths, "restore finish, index:%" PRId64 ", elapsed:%" PRId64 " ms", pEntry->index, restoreDelay);
2612 2613 2614 2615
          }
        }

        rpcFreeCont(rpcMsg.pCont);
2616 2617 2618 2619 2620
        if (h) {
          taosLRUCacheRelease(pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }
2621 2622 2623 2624
      }
    }
  }
  return 0;
2625 2626 2627
}

bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
S
Shengliang Guan 已提交
2628
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
2629 2630 2631 2632 2633
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
      return true;
    }
  }
  return false;
M
Minghao Li 已提交
2634 2635 2636 2637
}

SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
  SSyncSnapshotSender* pSender = NULL;
S
Shengliang Guan 已提交
2638
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
2639 2640 2641 2642 2643
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pSender = (ths->senders)[i];
    }
  }
  return pSender;
M
Minghao Li 已提交
2644
}
M
Minghao Li 已提交
2645

2646 2647
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
  SSyncTimer* pTimer = NULL;
S
Shengliang Guan 已提交
2648
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
2649 2650 2651 2652 2653 2654 2655
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
    }
  }
  return pTimer;
}

M
Minghao Li 已提交
2656 2657
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
  SPeerState* pState = NULL;
S
Shengliang Guan 已提交
2658
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
2659 2660 2661 2662 2663 2664 2665 2666 2667
    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 已提交
2668
  if (pState == NULL) {
2669
    sError("vgId:%d, replica maybe dropped", ths->vgId);
M
Minghao Li 已提交
2670 2671
    return false;
  }
M
Minghao Li 已提交
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682

  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 已提交
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
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 已提交
2697
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
M
Minghao Li 已提交
2698
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
M
Minghao Li 已提交
2699
    if (pSender != NULL && pSender->start) {
M
Minghao Li 已提交
2700 2701 2702 2703 2704 2705
      sError("sync cannot change3");
      return false;
    }
  }

  return true;
M
Minghao Li 已提交
2706
}