syncMain.c 92.2 KB
Newer Older
M
Minghao Li 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

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

M
Minghao Li 已提交
38 39 40 41 42
static void    syncNodeEqPingTimer(void* param, void* tmrId);
static void    syncNodeEqElectTimer(void* param, void* tmrId);
static void    syncNodeEqHeartbeatTimer(void* param, void* tmrId);
static int32_t syncNodeEqNoop(SSyncNode* ths);
static int32_t syncNodeAppendNoop(SSyncNode* ths);
43
static void    syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId);
S
Shengliang Guan 已提交
44
static bool    syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg);
S
Shengliang Guan 已提交
45 46 47
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId);
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
M
Minghao Li 已提交
48

49
int64_t syncOpen(SSyncInfo* pSyncInfo) {
S
Shengliang Guan 已提交
50 51
  SSyncNode* pSyncNode = syncNodeOpen(pSyncInfo);
  if (pSyncNode == NULL) {
S
Shengliang Guan 已提交
52
    sError("vgId:%d, failed to open sync node", pSyncInfo->vgId);
53 54
    return -1;
  }
M
Minghao Li 已提交
55

S
Shengliang Guan 已提交
56 57 58
  pSyncNode->rid = syncNodeAdd(pSyncNode);
  if (pSyncNode->rid < 0) {
    syncNodeClose(pSyncNode);
M
Minghao Li 已提交
59 60 61
    return -1;
  }

S
Shengliang Guan 已提交
62 63 64 65 66 67
  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 已提交
68
  return pSyncNode->rid;
M
Minghao Li 已提交
69
}
M
Minghao Li 已提交
70

M
Minghao Li 已提交
71
void syncStart(int64_t rid) {
S
Shengliang Guan 已提交
72 73 74 75
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode != NULL) {
    syncNodeStart(pSyncNode);
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
76 77 78
  }
}

M
Minghao Li 已提交
79
void syncStop(int64_t rid) {
S
Shengliang Guan 已提交
80
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
81
  if (pSyncNode != NULL) {
S
Shengliang Guan 已提交
82
    syncNodeRelease(pSyncNode);
S
Shengliang Guan 已提交
83
    syncNodeRemove(rid);
M
Minghao Li 已提交
84
  }
S
Shengliang Guan 已提交
85
}
M
Minghao Li 已提交
86

M
Minghao Li 已提交
87 88
void syncPreStop(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
89 90 91 92
  if (pSyncNode != NULL) {
    syncNodePreClose(pSyncNode);
    syncNodeRelease(pSyncNode);
  }
M
Minghao Li 已提交
93 94
}

S
Shengliang Guan 已提交
95 96 97
static bool syncNodeCheckNewConfig(SSyncNode* pSyncNode, const SSyncCfg* pCfg) {
  if (!syncNodeInConfig(pSyncNode, pCfg)) return false;
  return abs(pCfg->replicaNum - pSyncNode->replicaNum) <= 1;
M
Minghao Li 已提交
98 99
}

S
Shengliang Guan 已提交
100
int32_t syncReconfig(int64_t rid, SSyncCfg* pNewCfg) {
S
Shengliang Guan 已提交
101
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
102
  if (pSyncNode == NULL) return -1;
M
Minghao Li 已提交
103

M
Minghao Li 已提交
104
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
S
Shengliang Guan 已提交
105
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
106
    terrno = TSDB_CODE_SYN_NEW_CONFIG_ERROR;
S
Shengliang Guan 已提交
107
    sError("vgId:%d, failed to reconfig since invalid new config", pSyncNode->vgId);
M
Minghao Li 已提交
108
    return -1;
M
Minghao Li 已提交
109
  }
110

S
Shengliang Guan 已提交
111 112
  syncNodeUpdateNewConfigIndex(pSyncNode, pNewCfg);
  syncNodeDoConfigChange(pSyncNode, pNewCfg, SYNC_INDEX_INVALID);
S
Shengliang Guan 已提交
113

M
Minghao Li 已提交
114 115 116 117
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    syncNodeStopHeartbeatTimer(pSyncNode);

    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
S
Shengliang Guan 已提交
118
      syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]);
M
Minghao Li 已提交
119 120 121 122 123
    }

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

S
Shengliang Guan 已提交
125
  syncNodeRelease(pSyncNode);
S
Shengliang Guan 已提交
126
  return 0;
M
Minghao Li 已提交
127
}
M
Minghao Li 已提交
128

S
Shengliang Guan 已提交
129 130 131 132
int32_t syncProcessMsg(int64_t rid, SRpcMsg* pMsg) {
  int32_t code = -1;
  if (!syncIsInit()) return code;

S
Shengliang Guan 已提交
133
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  if (pSyncNode == NULL) return code;

  if (pMsg->msgType == TDMT_SYNC_HEARTBEAT) {
    SyncHeartbeat* pSyncMsg = syncHeartbeatFromRpcMsg2(pMsg);
    code = syncNodeOnHeartbeat(pSyncNode, pSyncMsg);
    syncHeartbeatDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_HEARTBEAT_REPLY) {
    SyncHeartbeatReply* pSyncMsg = syncHeartbeatReplyFromRpcMsg2(pMsg);
    code = syncNodeOnHeartbeatReply(pSyncNode, pSyncMsg);
    syncHeartbeatReplyDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_TIMEOUT) {
    SyncTimeout* pSyncMsg = syncTimeoutFromRpcMsg2(pMsg);
    code = syncNodeOnTimer(pSyncNode, pSyncMsg);
    syncTimeoutDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_PING) {
    SyncPing* pSyncMsg = syncPingFromRpcMsg2(pMsg);
    code = syncNodeOnPing(pSyncNode, pSyncMsg);
    syncPingDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_PING_REPLY) {
    SyncPingReply* pSyncMsg = syncPingReplyFromRpcMsg2(pMsg);
    code = syncNodeOnPingReply(pSyncNode, pSyncMsg);
    syncPingReplyDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
157
    code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
S
Shengliang Guan 已提交
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 187 188
  } else if (pMsg->msgType == TDMT_SYNC_REQUEST_VOTE) {
    SyncRequestVote* pSyncMsg = syncRequestVoteFromRpcMsg2(pMsg);
    code = syncNodeOnRequestVote(pSyncNode, pSyncMsg);
    syncRequestVoteDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_REQUEST_VOTE_REPLY) {
    SyncRequestVoteReply* pSyncMsg = syncRequestVoteReplyFromRpcMsg2(pMsg);
    code = syncNodeOnRequestVoteReply(pSyncNode, pSyncMsg);
    syncRequestVoteReplyDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_APPEND_ENTRIES) {
    SyncAppendEntries* pSyncMsg = syncAppendEntriesFromRpcMsg2(pMsg);
    code = syncNodeOnAppendEntries(pSyncNode, pSyncMsg);
    syncAppendEntriesDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_APPEND_ENTRIES_REPLY) {
    SyncAppendEntriesReply* pSyncMsg = syncAppendEntriesReplyFromRpcMsg2(pMsg);
    code = syncNodeOnAppendEntriesReply(pSyncNode, pSyncMsg);
    syncAppendEntriesReplyDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_SNAPSHOT_SEND) {
    SyncSnapshotSend* pSyncMsg = syncSnapshotSendFromRpcMsg2(pMsg);
    code = syncNodeOnSnapshot(pSyncNode, pSyncMsg);
    syncSnapshotSendDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_SNAPSHOT_RSP) {
    SyncSnapshotRsp* pSyncMsg = syncSnapshotRspFromRpcMsg2(pMsg);
    code = syncNodeOnSnapshotReply(pSyncNode, pSyncMsg);
    syncSnapshotRspDestroy(pSyncMsg);
  } else if (pMsg->msgType == TDMT_SYNC_LOCAL_CMD) {
    SyncLocalCmd* pSyncMsg = syncLocalCmdFromRpcMsg2(pMsg);
    code = syncNodeOnLocalCmd(pSyncNode, pSyncMsg);
    syncLocalCmdDestroy(pSyncMsg);
  } else {
    sError("vgId:%d, failed to process msg:%p since invalid type:%s", pSyncNode->vgId, pMsg, TMSG_INFO(pMsg->msgType));
    code = -1;
M
Minghao Li 已提交
189 190
  }

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

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

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

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

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

227 228
  int32_t code = 0;

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

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

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

M
Minghao Li 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    goto _DEL_WAL;

  } else {
    // 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 已提交
262 263 264 265
              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 已提交
266 267
            } while (0);

S
Shengliang Guan 已提交
268
            syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
269 270 271 272 273 274
            return 0;
          }
        }

      } else if (pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER) {
        if (lastApplyIndex > pSyncNode->minMatchIndex) {
S
Shengliang Guan 已提交
275 276 277
          sNTrace(pSyncNode,
                  "new-snapshot-index:%" PRId64 " is greater than min-match-index:%" PRId64 ", do not delete wal",
                  lastApplyIndex, pSyncNode->minMatchIndex);
S
Shengliang Guan 已提交
278
          syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
279 280 281 282
          return 0;
        }

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

      } else {
S
Shengliang Guan 已提交
288
        sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " unknown state, do not delete wal", lastApplyIndex);
S
Shengliang Guan 已提交
289
        syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
290 291 292 293 294 295 296 297 298
        return 0;
      }

      goto _DEL_WAL;

    } else {
      // one replica

      goto _DEL_WAL;
299 300 301
    }
  }

M
Minghao Li 已提交
302
_DEL_WAL:
303

M
Minghao Li 已提交
304
  do {
305 306 307 308
    SyncIndex snapshottingIndex = atomic_load_64(&pSyncNode->snapshottingIndex);

    if (snapshottingIndex == SYNC_INDEX_INVALID) {
      atomic_store_64(&pSyncNode->snapshottingIndex, lastApplyIndex);
M
Minghao Li 已提交
309
      pSyncNode->snapshottingTime = taosGetTimestampMs();
310

M
Minghao Li 已提交
311 312 313
      SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
      code = walBeginSnapshot(pData->pWal, lastApplyIndex);
      if (code == 0) {
S
Shengliang Guan 已提交
314 315
        sNTrace(pSyncNode, "wal snapshot begin, index:%" PRId64 ", last apply index:%" PRId64,
                pSyncNode->snapshottingIndex, lastApplyIndex);
M
Minghao Li 已提交
316
      } else {
S
Shengliang Guan 已提交
317
        sNError(pSyncNode, "wal snapshot begin error since:%s, index:%" PRId64 ", last apply index:%" PRId64,
S
Shengliang Guan 已提交
318
                terrstr(terrno), pSyncNode->snapshottingIndex, lastApplyIndex);
M
Minghao Li 已提交
319 320
        atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
      }
321 322

    } else {
S
Shengliang Guan 已提交
323 324
      sNTrace(pSyncNode, "snapshotting for %" PRId64 ", do not delete wal for new-snapshot-index:%" PRId64,
              snapshottingIndex, lastApplyIndex);
325
    }
M
Minghao Li 已提交
326
  } while (0);
327

S
Shengliang Guan 已提交
328
  syncNodeRelease(pSyncNode);
329 330 331 332
  return code;
}

int32_t syncEndSnapshot(int64_t rid) {
S
Shengliang Guan 已提交
333
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
334
  if (pSyncNode == NULL) {
335
    sError("sync end snapshot error");
336 337 338
    return -1;
  }

339 340 341 342
  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 已提交
343
    if (code != 0) {
344
      sNError(pSyncNode, "wal snapshot end error since:%s", terrstr());
S
Shengliang Guan 已提交
345
      syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
346 347
      return -1;
    } else {
S
Shengliang Guan 已提交
348
      sNTrace(pSyncNode, "wal snapshot end, index:%" PRId64, atomic_load_64(&pSyncNode->snapshottingIndex));
M
Minghao Li 已提交
349 350
      atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
    }
351
  }
352

S
Shengliang Guan 已提交
353
  syncNodeRelease(pSyncNode);
354 355 356
  return code;
}

M
Minghao Li 已提交
357
int32_t syncStepDown(int64_t rid, SyncTerm newTerm) {
S
Shengliang Guan 已提交
358
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
M
Minghao Li 已提交
359
  if (pSyncNode == NULL) {
360
    sError("sync step down error");
M
Minghao Li 已提交
361 362 363 364
    return -1;
  }

  syncNodeStepDown(pSyncNode, newTerm);
S
Shengliang Guan 已提交
365
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
366 367 368
  return 0;
}

369 370 371
bool syncIsReadyForRead(int64_t rid) {
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
  if (pSyncNode == NULL) {
372
    sError("sync ready for read error");
373 374 375 376 377 378 379 380 381 382
    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) {
383 384 385
    if (!pSyncNode->pFsm->FpApplyQueueEmptyCb(pSyncNode->pFsm)) {
      // apply queue not empty
      ready = false;
386

387 388 389 390
    } else {
      if (!pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore)) {
        SSyncRaftEntry* pEntry = NULL;
        int32_t         code = pSyncNode->pLogStore->syncLogGetEntry(
391
            pSyncNode->pLogStore, pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore), &pEntry);
392 393 394 395 396 397 398
        if (code == 0 && pEntry != NULL) {
          if (pEntry->originalRpcType == TDMT_SYNC_NOOP && pEntry->term == pSyncNode->pRaftStore->currentTerm) {
            ready = true;
          }

          syncEntryDestory(pEntry);
        }
399 400 401 402
      }
    }
  }

403 404 405 406 407 408 409 410
  if (!ready) {
    if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
      terrno = TSDB_CODE_SYN_NOT_LEADER;
    } else {
      terrno = TSDB_CODE_APP_NOT_READY;
    }
  }

411 412 413 414
  syncNodeRelease(pSyncNode);
  return ready;
}

M
Minghao Li 已提交
415 416
int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode) {
  if (pSyncNode->peersNum == 0) {
417
    sDebug("only one replica, cannot leader transfer");
M
Minghao Li 已提交
418 419 420 421
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
  }

422 423 424 425 426 427
  int32_t ret = 0;
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
    ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
  }

M
Minghao Li 已提交
428 429 430 431 432
  return ret;
}

int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader) {
  if (pSyncNode->replicaNum == 1) {
433
    sDebug("only one replica, cannot leader transfer");
M
Minghao Li 已提交
434 435 436 437
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
  }

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

M
Minghao Li 已提交
440 441 442 443 444 445 446 447 448
  SyncLeaderTransfer* pMsg = syncLeaderTransferBuild(pSyncNode->vgId);
  pMsg->newLeaderId.addr = syncUtilAddr2U64(newLeader.nodeFqdn, newLeader.nodePort);
  pMsg->newLeaderId.vgId = pSyncNode->vgId;
  pMsg->newNodeInfo = newLeader;
  ASSERT(pMsg != NULL);
  SRpcMsg rpcMsg = {0};
  syncLeaderTransfer2RpcMsg(pMsg, &rpcMsg);
  syncLeaderTransferDestroy(pMsg);

449
  int32_t ret = syncNodePropose(pSyncNode, &rpcMsg, false);
M
Minghao Li 已提交
450 451 452
  return ret;
}

453 454
SSyncState syncGetState(int64_t rid) {
  SSyncState state = {.state = TAOS_SYNC_STATE_ERROR};
M
Minghao Li 已提交
455

S
Shengliang Guan 已提交
456
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
457 458 459 460
  if (pSyncNode != NULL) {
    state.state = pSyncNode->state;
    state.restored = pSyncNode->restoreFinish;
    syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
461 462
  }

463
  return state;
M
Minghao Li 已提交
464 465
}

466
#if 0
467 468 469 470 471
int32_t syncGetSnapshotByIndex(int64_t rid, SyncIndex index, SSnapshot* pSnapshot) {
  if (index < SYNC_INDEX_BEGIN) {
    return -1;
  }

S
Shengliang Guan 已提交
472
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
473 474 475 476 477 478 479 480 481 482 483
  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 已提交
484
    syncNodeRelease(pSyncNode);
485 486 487 488 489 490 491 492 493 494
    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 已提交
495
  syncNodeRelease(pSyncNode);
496 497 498
  return 0;
}

499
int32_t syncGetSnapshotMeta(int64_t rid, struct SSnapshotMeta* sMeta) {
S
Shengliang Guan 已提交
500
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
501 502 503
  if (pSyncNode == NULL) {
    return -1;
  }
M
Minghao Li 已提交
504
  ASSERT(rid == pSyncNode->rid);
505 506
  sMeta->lastConfigIndex = pSyncNode->pRaftCfg->lastConfigIndex;

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

S
Shengliang Guan 已提交
509
  syncNodeRelease(pSyncNode);
510 511 512
  return 0;
}

513
int32_t syncGetSnapshotMetaByIndex(int64_t rid, SyncIndex snapshotIndex, struct SSnapshotMeta* sMeta) {
S
Shengliang Guan 已提交
514
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
515 516 517
  if (pSyncNode == NULL) {
    return -1;
  }
M
Minghao Li 已提交
518
  ASSERT(rid == pSyncNode->rid);
519 520 521 522

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

S
Shengliang Guan 已提交
523
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->configIndexCount; ++i) {
524 525 526 527 528 529
    if ((pSyncNode->pRaftCfg->configIndexArr)[i] > lastIndex &&
        (pSyncNode->pRaftCfg->configIndexArr)[i] <= snapshotIndex) {
      lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[i];
    }
  }
  sMeta->lastConfigIndex = lastIndex;
530
  sTrace("vgId:%d, get snapshot meta by index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId, snapshotIndex,
S
Shengliang Guan 已提交
531
         sMeta->lastConfigIndex);
532

S
Shengliang Guan 已提交
533
  syncNodeRelease(pSyncNode);
534 535
  return 0;
}
536
#endif
537

538 539 540 541
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
  ASSERT(pSyncNode->pRaftCfg->configIndexCount >= 1);
  SyncIndex lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[0];

S
Shengliang Guan 已提交
542
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->configIndexCount; ++i) {
543 544 545 546 547
    if ((pSyncNode->pRaftCfg->configIndexArr)[i] > lastIndex &&
        (pSyncNode->pRaftCfg->configIndexArr)[i] <= snapshotLastApplyIndex) {
      lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[i];
    }
  }
S
Shengliang Guan 已提交
548
  sTrace("vgId:%d, sync get last config index, index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId,
S
Shengliang Guan 已提交
549
         snapshotLastApplyIndex, lastIndex);
550 551 552 553

  return lastIndex;
}

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

S
Shengliang Guan 已提交
557
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
S
Shengliang Guan 已提交
558
  if (pSyncNode == NULL) return;
559

S
Shengliang Guan 已提交
560
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
S
Shengliang Guan 已提交
561 562 563 564 565
    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);
566
  }
M
Minghao Li 已提交
567 568 569
  if (pEpSet->numOfEps > 0) {
    pEpSet->inUse = (pSyncNode->pRaftCfg->cfg.myIndex + 1) % pEpSet->numOfEps;
  }
M
Minghao Li 已提交
570

S
Shengliang Guan 已提交
571
  sInfo("vgId:%d, sync get retry epset numOfEps:%d inUse:%d", pSyncNode->vgId, pEpSet->numOfEps, pEpSet->inUse);
S
Shengliang Guan 已提交
572
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
573
}
574

M
Minghao Li 已提交
575
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak) {
S
Shengliang Guan 已提交
576
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
577
  if (pSyncNode == NULL) {
578
    sError("sync propose error");
M
Minghao Li 已提交
579
    return -1;
580
  }
M
Minghao Li 已提交
581

582
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak);
S
Shengliang Guan 已提交
583
  syncNodeRelease(pSyncNode);
M
Minghao Li 已提交
584 585 586
  return ret;
}

587
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak) {
S
Shengliang Guan 已提交
588 589 590 591 592
  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 已提交
593

S
Shengliang Guan 已提交
594 595 596 597 598 599 600 601 602 603 604
  // 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;
  }

  // optimized one replica
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
    SyncIndex retIndex;
605
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
S
Shengliang Guan 已提交
606 607 608
    if (code == 0) {
      pMsg->info.conn.applyIndex = retIndex;
      pMsg->info.conn.applyTerm = pSyncNode->pRaftStore->currentTerm;
609 610 611
      sTrace("vgId:%d, propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
             TMSG_INFO(pMsg->msgType));
      return 1;
S
Shengliang Guan 已提交
612 613
    } else {
      terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
614
      sError("vgId:%d, failed to propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
S
Shengliang Guan 已提交
615
             TMSG_INFO(pMsg->msgType));
616
      return -1;
617
    }
S
Shengliang Guan 已提交
618
  } else {
S
Shengliang Guan 已提交
619 620
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
621 622 623 624 625 626 627
    SRpcMsg   rpcMsg = {0};
    int32_t   code = syncClientRequestBuildFromRpcMsg(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
    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 已提交
628

629 630 631 632 633
    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 已提交
634
    }
M
Minghao Li 已提交
635

636 637
    return code;
  }
M
Minghao Li 已提交
638 639
}

S
Shengliang Guan 已提交
640
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId) {
641 642 643 644 645 646 647 648 649
  pSyncTimer->pTimer = NULL;
  pSyncTimer->counter = 0;
  pSyncTimer->timerMS = pSyncNode->hbBaseLine;
  pSyncTimer->timerCb = syncNodeEqPeerHeartbeatTimer;
  pSyncTimer->destId = destId;
  atomic_store_64(&pSyncTimer->logicClock, 0);
  return 0;
}

S
Shengliang Guan 已提交
650
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
651
  int32_t ret = 0;
S
Shengliang Guan 已提交
652
  if (syncIsInit()) {
M
Minghao Li 已提交
653
    SSyncHbTimerData* pData = taosMemoryMalloc(sizeof(SSyncHbTimerData));
654 655 656 657
    pData->pSyncNode = pSyncNode;
    pData->pTimer = pSyncTimer;
    pData->destId = pSyncTimer->destId;
    pData->logicClock = pSyncTimer->logicClock;
M
Minghao Li 已提交
658

659
    pSyncTimer->pData = pData;
S
Shengliang Guan 已提交
660
    taosTmrReset(pSyncTimer->timerCb, pSyncTimer->timerMS, pData, syncEnv()->pTimerManager, &pSyncTimer->pTimer);
661 662 663 664 665 666
  } else {
    sError("vgId:%d, start ctrl hb timer error, sync env is stop", pSyncNode->vgId);
  }
  return ret;
}

S
Shengliang Guan 已提交
667
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
668 669 670 671
  int32_t ret = 0;
  atomic_add_fetch_64(&pSyncTimer->logicClock, 1);
  taosTmrStop(pSyncTimer->pTimer);
  pSyncTimer->pTimer = NULL;
M
Minghao Li 已提交
672
  // taosMemoryFree(pSyncTimer->pData);
673 674 675
  return ret;
}

S
Shengliang Guan 已提交
676 677
SSyncNode* syncNodeOpen(SSyncInfo* pSyncInfo) {
  SSyncNode* pSyncNode = taosMemoryCalloc(1, sizeof(SSyncNode));
678 679 680 681
  if (pSyncNode == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }
M
Minghao Li 已提交
682

M
Minghao Li 已提交
683 684 685 686
  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());
687
      goto _error;
M
Minghao Li 已提交
688
    }
689
  }
M
Minghao Li 已提交
690

S
Shengliang Guan 已提交
691
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
692
  if (!taosCheckExistFile(pSyncNode->configPath)) {
M
Minghao Li 已提交
693
    // create a new raft config file
S
Shengliang Guan 已提交
694
    SRaftCfgMeta meta = {0};
M
Minghao Li 已提交
695
    meta.isStandBy = pSyncInfo->isStandBy;
M
Minghao Li 已提交
696
    meta.snapshotStrategy = pSyncInfo->snapshotStrategy;
697
    meta.lastConfigIndex = SYNC_INDEX_INVALID;
M
Minghao Li 已提交
698
    meta.batchSize = pSyncInfo->batchSize;
S
Shengliang Guan 已提交
699 700
    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 已提交
701
      goto _error;
702
    }
703
    if (pSyncInfo->syncCfg.replicaNum == 0) {
S
Shengliang Guan 已提交
704
      sInfo("vgId:%d, sync config not input", pSyncNode->vgId);
705 706
      pSyncInfo->syncCfg = pSyncNode->pRaftCfg->cfg;
    }
707 708 709
  } else {
    // update syncCfg by raft_config.json
    pSyncNode->pRaftCfg = raftCfgOpen(pSyncNode->configPath);
710
    if (pSyncNode->pRaftCfg == NULL) {
S
Shengliang Guan 已提交
711
      sError("vgId:%d, failed to open raft cfg file at %s", pSyncNode->vgId, pSyncNode->configPath);
H
Hongze Cheng 已提交
712
      goto _error;
713
    }
S
Shengliang Guan 已提交
714 715

    if (pSyncInfo->syncCfg.replicaNum > 0 && syncIsConfigChanged(&pSyncNode->pRaftCfg->cfg, &pSyncInfo->syncCfg)) {
S
Shengliang Guan 已提交
716 717 718 719 720 721
      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 已提交
722 723 724 725
    } else {
      sInfo("vgId:%d, use sync config from raft cfg file", pSyncNode->vgId);
      pSyncInfo->syncCfg = pSyncNode->pRaftCfg->cfg;
    }
726 727

    raftCfgClose(pSyncNode->pRaftCfg);
728
    pSyncNode->pRaftCfg = NULL;
M
Minghao Li 已提交
729 730
  }

S
Shengliang Guan 已提交
731 732
  // init by SSyncInfo
  pSyncNode->vgId = pSyncInfo->vgId;
S
Shengliang Guan 已提交
733 734 735 736 737 738 739
  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 已提交
740
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
S
Shengliang Guan 已提交
741 742 743
  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 已提交
744

M
Minghao Li 已提交
745
  pSyncNode->pWal = pSyncInfo->pWal;
S
Shengliang Guan 已提交
746
  pSyncNode->msgcb = pSyncInfo->msgcb;
S
Shengliang Guan 已提交
747 748 749
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
M
Minghao Li 已提交
750

M
Minghao Li 已提交
751 752
  // init raft config
  pSyncNode->pRaftCfg = raftCfgOpen(pSyncNode->configPath);
753
  if (pSyncNode->pRaftCfg == NULL) {
S
Shengliang Guan 已提交
754
    sError("vgId:%d, failed to open raft cfg file at %s", pSyncNode->vgId, pSyncNode->configPath);
755 756
    goto _error;
  }
M
Minghao Li 已提交
757

M
Minghao Li 已提交
758
  // init internal
M
Minghao Li 已提交
759
  pSyncNode->myNodeInfo = pSyncNode->pRaftCfg->cfg.nodeInfo[pSyncNode->pRaftCfg->cfg.myIndex];
760
  if (!syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId)) {
S
Shengliang Guan 已提交
761
    sError("vgId:%d, failed to determine my raft member id", pSyncNode->vgId);
H
Hongze Cheng 已提交
762
    goto _error;
763
  }
M
Minghao Li 已提交
764

M
Minghao Li 已提交
765
  // init peersNum, peers, peersId
M
Minghao Li 已提交
766
  pSyncNode->peersNum = pSyncNode->pRaftCfg->cfg.replicaNum - 1;
S
Shengliang Guan 已提交
767 768
  int32_t j = 0;
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
M
Minghao Li 已提交
769 770
    if (i != pSyncNode->pRaftCfg->cfg.myIndex) {
      pSyncNode->peersNodeInfo[j] = pSyncNode->pRaftCfg->cfg.nodeInfo[i];
M
Minghao Li 已提交
771 772 773
      j++;
    }
  }
S
Shengliang Guan 已提交
774
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
775
    if (!syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i])) {
S
Shengliang Guan 已提交
776
      sError("vgId:%d, failed to determine raft member id, peer:%d", pSyncNode->vgId, i);
H
Hongze Cheng 已提交
777
      goto _error;
778
    }
M
Minghao Li 已提交
779
  }
M
Minghao Li 已提交
780

M
Minghao Li 已提交
781
  // init replicaNum, replicasId
M
Minghao Li 已提交
782
  pSyncNode->replicaNum = pSyncNode->pRaftCfg->cfg.replicaNum;
S
Shengliang Guan 已提交
783
  for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
784
    if (!syncUtilNodeInfo2RaftId(&pSyncNode->pRaftCfg->cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i])) {
S
Shengliang Guan 已提交
785
      sError("vgId:%d, failed to determine raft member id, replica:%d", pSyncNode->vgId, i);
H
Hongze Cheng 已提交
786
      goto _error;
787
    }
M
Minghao Li 已提交
788 789
  }

M
Minghao Li 已提交
790
  // init raft algorithm
M
Minghao Li 已提交
791
  pSyncNode->pFsm = pSyncInfo->pFsm;
792
  pSyncInfo->pFsm = NULL;
M
Minghao Li 已提交
793
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->pRaftCfg->cfg.replicaNum);
M
Minghao Li 已提交
794 795
  pSyncNode->leaderCache = EMPTY_RAFT_ID;

M
Minghao Li 已提交
796
  // init life cycle outside
M
Minghao Li 已提交
797

M
Minghao Li 已提交
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
  // 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 已提交
822
  // init TLA+ server vars
M
syncInt  
Minghao Li 已提交
823
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
M
Minghao Li 已提交
824
  pSyncNode->pRaftStore = raftStoreOpen(pSyncNode->raftStorePath);
825
  if (pSyncNode->pRaftStore == NULL) {
S
Shengliang Guan 已提交
826
    sError("vgId:%d, failed to open raft store at path %s", pSyncNode->vgId, pSyncNode->raftStorePath);
827 828
    goto _error;
  }
M
Minghao Li 已提交
829

M
Minghao Li 已提交
830
  // init TLA+ candidate vars
M
Minghao Li 已提交
831
  pSyncNode->pVotesGranted = voteGrantedCreate(pSyncNode);
832
  if (pSyncNode->pVotesGranted == NULL) {
S
Shengliang Guan 已提交
833
    sError("vgId:%d, failed to create VotesGranted", pSyncNode->vgId);
834 835
    goto _error;
  }
M
Minghao Li 已提交
836
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
837
  if (pSyncNode->pVotesRespond == NULL) {
S
Shengliang Guan 已提交
838
    sError("vgId:%d, failed to create VotesRespond", pSyncNode->vgId);
839 840
    goto _error;
  }
M
Minghao Li 已提交
841

M
Minghao Li 已提交
842 843
  // init TLA+ leader vars
  pSyncNode->pNextIndex = syncIndexMgrCreate(pSyncNode);
844
  if (pSyncNode->pNextIndex == NULL) {
S
Shengliang Guan 已提交
845
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
846 847
    goto _error;
  }
M
Minghao Li 已提交
848
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
849
  if (pSyncNode->pMatchIndex == NULL) {
S
Shengliang Guan 已提交
850
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
851 852
    goto _error;
  }
M
Minghao Li 已提交
853 854 855

  // init TLA+ log vars
  pSyncNode->pLogStore = logStoreCreate(pSyncNode);
856
  if (pSyncNode->pLogStore == NULL) {
S
Shengliang Guan 已提交
857
    sError("vgId:%d, failed to create SyncLogStore", pSyncNode->vgId);
858 859
    goto _error;
  }
860 861 862 863 864

  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);
865
    if (code != 0) {
S
Shengliang Guan 已提交
866
      sError("vgId:%d, failed to get snapshot info, code:%d", pSyncNode->vgId, code);
H
Hongze Cheng 已提交
867
      goto _error;
868
    }
869 870
    if (snapshot.lastApplyIndex > commitIndex) {
      commitIndex = snapshot.lastApplyIndex;
S
Shengliang Guan 已提交
871
      sNTrace(pSyncNode, "reset commit index by snapshot");
872 873 874
    }
  }
  pSyncNode->commitIndex = commitIndex;
M
Minghao Li 已提交
875

M
Minghao Li 已提交
876 877 878 879 880
  // timer ms init
  pSyncNode->pingBaseLine = PING_TIMER_MS;
  pSyncNode->electBaseLine = ELECT_TIMER_MS_MIN;
  pSyncNode->hbBaseLine = HEARTBEAT_TIMER_MS;

M
Minghao Li 已提交
881
  // init ping timer
M
Minghao Li 已提交
882
  pSyncNode->pPingTimer = NULL;
M
Minghao Li 已提交
883
  pSyncNode->pingTimerMS = pSyncNode->pingBaseLine;
M
Minghao Li 已提交
884 885
  atomic_store_64(&pSyncNode->pingTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->pingTimerLogicClockUser, 0);
M
Minghao Li 已提交
886
  pSyncNode->FpPingTimerCB = syncNodeEqPingTimer;
M
Minghao Li 已提交
887
  pSyncNode->pingTimerCounter = 0;
M
Minghao Li 已提交
888

M
Minghao Li 已提交
889 890
  // init elect timer
  pSyncNode->pElectTimer = NULL;
M
Minghao Li 已提交
891
  pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
M
Minghao Li 已提交
892
  atomic_store_64(&pSyncNode->electTimerLogicClock, 0);
M
Minghao Li 已提交
893
  pSyncNode->FpElectTimerCB = syncNodeEqElectTimer;
M
Minghao Li 已提交
894 895 896 897
  pSyncNode->electTimerCounter = 0;

  // init heartbeat timer
  pSyncNode->pHeartbeatTimer = NULL;
M
Minghao Li 已提交
898
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
M
Minghao Li 已提交
899 900
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClockUser, 0);
M
Minghao Li 已提交
901
  pSyncNode->FpHeartbeatTimerCB = syncNodeEqHeartbeatTimer;
M
Minghao Li 已提交
902 903
  pSyncNode->heartbeatTimerCounter = 0;

904 905 906 907 908
  // 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 已提交
909
  // init callback
M
Minghao Li 已提交
910 911
  pSyncNode->FpOnPing = syncNodeOnPing;
  pSyncNode->FpOnPingReply = syncNodeOnPingReply;
M
Minghao Li 已提交
912
  pSyncNode->FpOnClientRequest = syncNodeOnClientRequest;
913
  pSyncNode->FpOnTimeout = syncNodeOnTimer;
M
Minghao Li 已提交
914 915 916 917 918 919
  pSyncNode->FpOnSnapshot = syncNodeOnSnapshot;
  pSyncNode->FpOnSnapshotReply = syncNodeOnSnapshotReply;
  pSyncNode->FpOnRequestVote = syncNodeOnRequestVote;
  pSyncNode->FpOnRequestVoteReply = syncNodeOnRequestVoteReply;
  pSyncNode->FpOnAppendEntries = syncNodeOnAppendEntries;
  pSyncNode->FpOnAppendEntriesReply = syncNodeOnAppendEntriesReply;
M
Minghao Li 已提交
920

M
Minghao Li 已提交
921
  // tools
M
Minghao Li 已提交
922
  pSyncNode->pSyncRespMgr = syncRespMgrCreate(pSyncNode, SYNC_RESP_TTL_MS);
923
  if (pSyncNode->pSyncRespMgr == NULL) {
S
Shengliang Guan 已提交
924
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
925 926
    goto _error;
  }
M
Minghao Li 已提交
927

928 929
  // restore state
  pSyncNode->restoreFinish = false;
930

M
Minghao Li 已提交
931
  // snapshot senders
S
Shengliang Guan 已提交
932
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
933 934 935 936 937 938
    SSyncSnapshotSender* pSender = snapshotSenderCreate(pSyncNode, i);
    // ASSERT(pSender != NULL);
    (pSyncNode->senders)[i] = pSender;
  }

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

M
Minghao Li 已提交
941 942 943
  // is config changing
  pSyncNode->changing = false;

M
Minghao Li 已提交
944 945 946
  // peer state
  syncNodePeerStateInit(pSyncNode);

M
Minghao Li 已提交
947 948 949
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
950
  // start in syncNodeStart
M
Minghao Li 已提交
951
  // start raft
M
Minghao Li 已提交
952
  // syncNodeBecomeFollower(pSyncNode);
M
Minghao Li 已提交
953

M
Minghao Li 已提交
954 955
  int64_t timeNow = taosGetTimestampMs();
  pSyncNode->startTime = timeNow;
956
  pSyncNode->leaderTime = timeNow;
M
Minghao Li 已提交
957 958
  pSyncNode->lastReplicateTime = timeNow;

959 960 961
  // snapshotting
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);

S
Shengliang Guan 已提交
962
  sNTrace(pSyncNode, "sync open");
963

M
Minghao Li 已提交
964
  return pSyncNode;
965 966 967

_error:
  if (pSyncInfo->pFsm) {
H
Hongze Cheng 已提交
968 969
    taosMemoryFree(pSyncInfo->pFsm);
    pSyncInfo->pFsm = NULL;
970 971 972 973
  }
  syncNodeClose(pSyncNode);
  pSyncNode = NULL;
  return NULL;
M
Minghao Li 已提交
974 975
}

M
Minghao Li 已提交
976 977 978 979 980 981 982 983 984 985 986
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 已提交
987 988
void syncNodeStart(SSyncNode* pSyncNode) {
  // start raft
989
  if (pSyncNode->replicaNum == 1) {
M
Minghao Li 已提交
990
    raftStoreNextTerm(pSyncNode->pRaftStore);
991
    syncNodeBecomeLeader(pSyncNode, "one replica start");
M
format  
Minghao Li 已提交
992

993
    // Raft 3.6.2 Committing entries from previous terms
994 995
    syncNodeAppendNoop(pSyncNode);
    syncMaybeAdvanceCommitIndex(pSyncNode);
M
Minghao Li 已提交
996

M
Minghao Li 已提交
997 998
  } else {
    syncNodeBecomeFollower(pSyncNode, "first start");
999 1000
  }

1001 1002 1003
  int32_t ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
  ASSERT(ret == 0);
M
Minghao Li 已提交
1004 1005
}

M
Minghao Li 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014
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);
1015

1016 1017 1018
  ret = 0;
  ret = syncNodeStartPingTimer(pSyncNode);
  ASSERT(ret == 0);
M
Minghao Li 已提交
1019 1020
}

M
Minghao Li 已提交
1021 1022 1023 1024 1025 1026 1027 1028
void syncNodePreClose(SSyncNode* pSyncNode) {
  // stop elect timer
  syncNodeStopElectTimer(pSyncNode);

  // stop heartbeat timer
  syncNodeStopHeartbeatTimer(pSyncNode);
}

M
Minghao Li 已提交
1029
void syncNodeClose(SSyncNode* pSyncNode) {
1030 1031 1032
  if (pSyncNode == NULL) {
    return;
  }
M
Minghao Li 已提交
1033 1034
  int32_t ret;

S
Shengliang Guan 已提交
1035
  sNTrace(pSyncNode, "sync close");
M
Minghao Li 已提交
1036

M
Minghao Li 已提交
1037
  ret = raftStoreClose(pSyncNode->pRaftStore);
M
Minghao Li 已提交
1038
  ASSERT(ret == 0);
M
Minghao Li 已提交
1039
  pSyncNode->pRaftStore = NULL;
M
Minghao Li 已提交
1040

M
Minghao Li 已提交
1041
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
1042
  pSyncNode->pSyncRespMgr = NULL;
M
Minghao Li 已提交
1043
  voteGrantedDestroy(pSyncNode->pVotesGranted);
1044
  pSyncNode->pVotesGranted = NULL;
M
Minghao Li 已提交
1045
  votesRespondDestory(pSyncNode->pVotesRespond);
1046
  pSyncNode->pVotesRespond = NULL;
M
Minghao Li 已提交
1047
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
1048
  pSyncNode->pNextIndex = NULL;
M
Minghao Li 已提交
1049
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
1050
  pSyncNode->pMatchIndex = NULL;
M
Minghao Li 已提交
1051
  logStoreDestory(pSyncNode->pLogStore);
1052
  pSyncNode->pLogStore = NULL;
M
Minghao Li 已提交
1053
  raftCfgClose(pSyncNode->pRaftCfg);
1054
  pSyncNode->pRaftCfg = NULL;
M
Minghao Li 已提交
1055 1056 1057 1058 1059

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

M
Minghao Li 已提交
1060 1061 1062 1063
  if (pSyncNode->pFsm != NULL) {
    taosMemoryFree(pSyncNode->pFsm);
  }

S
Shengliang Guan 已提交
1064
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1065 1066 1067 1068 1069 1070
    if ((pSyncNode->senders)[i] != NULL) {
      snapshotSenderDestroy((pSyncNode->senders)[i]);
      (pSyncNode->senders)[i] = NULL;
    }
  }

M
Minghao Li 已提交
1071 1072 1073 1074 1075
  if (pSyncNode->pNewNodeReceiver != NULL) {
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
    pSyncNode->pNewNodeReceiver = NULL;
  }

1076
  taosMemoryFree(pSyncNode);
M
Minghao Li 已提交
1077 1078
}

M
Minghao Li 已提交
1079
// option
M
Minghao Li 已提交
1080 1081
// bool syncNodeSnapshotEnable(SSyncNode* pSyncNode) { return pSyncNode->pRaftCfg->snapshotEnable; }

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

M
Minghao Li 已提交
1084 1085 1086
// timer control --------------
int32_t syncNodeStartPingTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
S
Shengliang Guan 已提交
1087 1088
  if (syncIsInit()) {
    taosTmrReset(pSyncNode->FpPingTimerCB, pSyncNode->pingTimerMS, pSyncNode, syncEnv()->pTimerManager,
1089 1090 1091
                 &pSyncNode->pPingTimer);
    atomic_store_64(&pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1092
    sError("vgId:%d, start ping timer error, sync env is stop", pSyncNode->vgId);
1093
  }
M
Minghao Li 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  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 已提交
1107
  if (syncIsInit()) {
1108
    pSyncNode->electTimerMS = ms;
M
Minghao Li 已提交
1109 1110 1111 1112 1113 1114

    SElectTimer* pElectTimer = taosMemoryMalloc(sizeof(SElectTimer));
    pElectTimer->logicClock = pSyncNode->electTimerLogicClock;
    pElectTimer->pSyncNode = pSyncNode;
    pElectTimer->pData = NULL;

S
Shengliang Guan 已提交
1115
    taosTmrReset(pSyncNode->FpElectTimerCB, pSyncNode->electTimerMS, pElectTimer, syncEnv()->pTimerManager,
1116
                 &pSyncNode->pElectTimer);
1117

1118
  } else {
M
Minghao Li 已提交
1119
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
1120
  }
M
Minghao Li 已提交
1121 1122 1123 1124 1125
  return ret;
}

int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1126
  atomic_add_fetch_64(&pSyncNode->electTimerLogicClock, 1);
M
Minghao Li 已提交
1127 1128
  taosTmrStop(pSyncNode->pElectTimer);
  pSyncNode->pElectTimer = NULL;
1129

M
Minghao Li 已提交
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  return ret;
}

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

M
Minghao Li 已提交
1140 1141
int32_t syncNodeResetElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1142 1143 1144 1145 1146 1147 1148
  int32_t electMS;

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

S
Shengliang Guan 已提交
1151 1152
  sNTrace(pSyncNode, "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine,
          electMS);
M
Minghao Li 已提交
1153 1154 1155
  return ret;
}

M
Minghao Li 已提交
1156
static int32_t syncNodeDoStartHeartbeatTimer(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1157
  int32_t ret = 0;
S
Shengliang Guan 已提交
1158 1159
  if (syncIsInit()) {
    taosTmrReset(pSyncNode->FpHeartbeatTimerCB, pSyncNode->heartbeatTimerMS, pSyncNode, syncEnv()->pTimerManager,
1160 1161 1162
                 &pSyncNode->pHeartbeatTimer);
    atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1163
    sError("vgId:%d, start heartbeat timer error, sync env is stop", pSyncNode->vgId);
1164
  }
1165

S
Shengliang Guan 已提交
1166
  sNTrace(pSyncNode, "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
M
Minghao Li 已提交
1167 1168 1169
  return ret;
}

M
Minghao Li 已提交
1170
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
1171
  int32_t ret = 0;
M
Minghao Li 已提交
1172

1173
#if 0
M
Minghao Li 已提交
1174
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
1175 1176
  ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
#endif
1177

S
Shengliang Guan 已提交
1178
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1179
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1180 1181 1182
    if (pSyncTimer != NULL) {
      syncHbTimerStart(pSyncNode, pSyncTimer);
    }
1183
  }
1184

M
Minghao Li 已提交
1185 1186 1187
  return ret;
}

M
Minghao Li 已提交
1188 1189
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
1190 1191

#if 0
M
Minghao Li 已提交
1192 1193 1194
  atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1);
  taosTmrStop(pSyncNode->pHeartbeatTimer);
  pSyncNode->pHeartbeatTimer = NULL;
1195
#endif
1196

S
Shengliang Guan 已提交
1197
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1198
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
M
Minghao Li 已提交
1199 1200 1201
    if (pSyncTimer != NULL) {
      syncHbTimerStop(pSyncNode, pSyncTimer);
    }
1202
  }
1203

M
Minghao Li 已提交
1204 1205 1206
  return ret;
}

1207 1208 1209 1210 1211 1212
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode) {
  syncNodeStopHeartbeatTimer(pSyncNode);
  syncNodeStartHeartbeatTimer(pSyncNode);
  return 0;
}

M
Minghao Li 已提交
1213 1214 1215
// utils --------------
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
1216
  syncUtilRaftId2EpSet(destRaftId, &epSet);
S
Shengliang Guan 已提交
1217
  if (pSyncNode->syncSendMSg != NULL) {
M
Minghao Li 已提交
1218 1219 1220
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

1221
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1222
    pSyncNode->syncSendMSg(&epSet, pMsg);
M
Minghao Li 已提交
1223
  } else {
M
Minghao Li 已提交
1224 1225
    sError("vgId:%d, sync send msg by id error, fp-send-msg is null", pSyncNode->vgId);
    return -1;
M
Minghao Li 已提交
1226
  }
M
Minghao Li 已提交
1227

M
Minghao Li 已提交
1228 1229 1230 1231 1232
  return 0;
}

int32_t syncNodeSendMsgByInfo(const SNodeInfo* nodeInfo, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
1233
  syncUtilNodeInfo2EpSet(nodeInfo, &epSet);
S
Shengliang Guan 已提交
1234
  if (pSyncNode->syncSendMSg != NULL) {
M
Minghao Li 已提交
1235 1236 1237
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

1238
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1239
    pSyncNode->syncSendMSg(&epSet, pMsg);
M
Minghao Li 已提交
1240
  } else {
M
Minghao Li 已提交
1241
    sError("vgId:%d, sync send msg by info error, fp-send-msg is null", pSyncNode->vgId);
M
Minghao Li 已提交
1242
  }
M
Minghao Li 已提交
1243 1244 1245
  return 0;
}

1246
inline bool syncNodeInConfig(SSyncNode* pSyncNode, const SSyncCfg* config) {
1247 1248 1249
  bool b1 = false;
  bool b2 = false;

S
Shengliang Guan 已提交
1250
  for (int32_t i = 0; i < config->replicaNum; ++i) {
1251 1252 1253 1254 1255 1256 1257
    if (strcmp((config->nodeInfo)[i].nodeFqdn, pSyncNode->myNodeInfo.nodeFqdn) == 0 &&
        (config->nodeInfo)[i].nodePort == pSyncNode->myNodeInfo.nodePort) {
      b1 = true;
      break;
    }
  }

S
Shengliang Guan 已提交
1258
  for (int32_t i = 0; i < config->replicaNum; ++i) {
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    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;
}

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
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 已提交
1286
void syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncIndex lastConfigChangeIndex) {
1287
  SSyncCfg oldConfig = pSyncNode->pRaftCfg->cfg;
1288 1289 1290 1291
  if (!syncIsConfigChanged(&oldConfig, pNewConfig)) {
    sInfo("vgId:1, sync not reconfig since not changed");
    return;
  }
S
Shengliang Guan 已提交
1292

1293
  pSyncNode->pRaftCfg->cfg = *pNewConfig;
1294 1295
  pSyncNode->pRaftCfg->lastConfigIndex = lastConfigChangeIndex;

M
Minghao Li 已提交
1296 1297
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
M
Minghao Li 已提交
1298

M
Minghao Li 已提交
1299 1300
  bool isDrop = false;
  bool isAdd = false;
M
Minghao Li 已提交
1301

M
Minghao Li 已提交
1302 1303 1304 1305
  if (IamInOld && !IamInNew) {
    isDrop = true;
  } else {
    isDrop = false;
1306
  }
1307

M
Minghao Li 已提交
1308 1309 1310 1311 1312
  if (!IamInOld && IamInNew) {
    isAdd = true;
  } else {
    isAdd = false;
  }
M
Minghao Li 已提交
1313

M
Minghao Li 已提交
1314
  // log begin config change
S
Shengliang Guan 已提交
1315 1316 1317 1318 1319
  char oldCfgStr[1024] = {0};
  char newCfgStr[1024] = {0};
  syncCfg2SimpleStr(&oldConfig, oldCfgStr, sizeof(oldCfgStr));
  syncCfg2SimpleStr(pNewConfig, oldCfgStr, sizeof(oldCfgStr));
  sNTrace(pSyncNode, "begin do config change, from %s to %s", oldCfgStr, oldCfgStr);
M
Minghao Li 已提交
1320

M
Minghao Li 已提交
1321 1322
  if (IamInNew) {
    pSyncNode->pRaftCfg->isStandBy = 0;  // change isStandBy to normal
M
Minghao Li 已提交
1323
  }
M
Minghao Li 已提交
1324 1325
  if (isDrop) {
    pSyncNode->pRaftCfg->isStandBy = 1;  // set standby
M
Minghao Li 已提交
1326 1327
  }

M
Minghao Li 已提交
1328
  // add last config index
M
Minghao Li 已提交
1329
  raftCfgAddConfigIndex(pSyncNode->pRaftCfg, lastConfigChangeIndex);
M
Minghao Li 已提交
1330

M
Minghao Li 已提交
1331 1332 1333 1334 1335 1336 1337 1338 1339
  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 已提交
1340
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1341
      oldSenders[i] = (pSyncNode->senders)[i];
S
Shengliang Guan 已提交
1342
      sSTrace(oldSenders[i], "snapshot sender save old");
M
Minghao Li 已提交
1343
    }
1344

M
Minghao Li 已提交
1345 1346
    // init internal
    pSyncNode->myNodeInfo = pSyncNode->pRaftCfg->cfg.nodeInfo[pSyncNode->pRaftCfg->cfg.myIndex];
1347
    syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId);
M
Minghao Li 已提交
1348 1349 1350

    // init peersNum, peers, peersId
    pSyncNode->peersNum = pSyncNode->pRaftCfg->cfg.replicaNum - 1;
S
Shengliang Guan 已提交
1351 1352
    int32_t j = 0;
    for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
M
Minghao Li 已提交
1353 1354 1355 1356 1357
      if (i != pSyncNode->pRaftCfg->cfg.myIndex) {
        pSyncNode->peersNodeInfo[j] = pSyncNode->pRaftCfg->cfg.nodeInfo[i];
        j++;
      }
    }
S
Shengliang Guan 已提交
1358
    for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
1359
      syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]);
M
Minghao Li 已提交
1360
    }
1361

M
Minghao Li 已提交
1362 1363
    // init replicaNum, replicasId
    pSyncNode->replicaNum = pSyncNode->pRaftCfg->cfg.replicaNum;
S
Shengliang Guan 已提交
1364
    for (int32_t i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
1365
      syncUtilNodeInfo2RaftId(&pSyncNode->pRaftCfg->cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]);
M
Minghao Li 已提交
1366
    }
1367

1368 1369 1370
    // update quorum first
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->pRaftCfg->cfg.replicaNum);

M
Minghao Li 已提交
1371 1372 1373 1374
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
M
Minghao Li 已提交
1375

M
Minghao Li 已提交
1376
    // reset snapshot senders
1377

M
Minghao Li 已提交
1378
    // clear new
S
Shengliang Guan 已提交
1379
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1380 1381
      (pSyncNode->senders)[i] = NULL;
    }
M
Minghao Li 已提交
1382

M
Minghao Li 已提交
1383
    // reset new
S
Shengliang Guan 已提交
1384
    for (int32_t i = 0; i < pSyncNode->replicaNum; ++i) {
M
Minghao Li 已提交
1385 1386
      // reset sender
      bool reset = false;
S
Shengliang Guan 已提交
1387
      for (int32_t j = 0; j < TSDB_MAX_REPLICA; ++j) {
M
Minghao Li 已提交
1388 1389 1390 1391
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j])) {
          char     host[128];
          uint16_t port;
          syncUtilU642Addr((pSyncNode->replicasId)[i].addr, host, sizeof(host), &port);
1392
          sNTrace(pSyncNode, "snapshot sender reset for: %" PRId64 ", newIndex:%d, %s:%d, %p",
S
Shengliang Guan 已提交
1393
                  (pSyncNode->replicasId)[i].addr, i, host, port, oldSenders[j]);
M
Minghao Li 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402

          (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 已提交
1403 1404
          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 已提交
1405
        }
1406 1407
      }
    }
1408

M
Minghao Li 已提交
1409
    // create new
S
Shengliang Guan 已提交
1410
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1411 1412
      if ((pSyncNode->senders)[i] == NULL) {
        (pSyncNode->senders)[i] = snapshotSenderCreate(pSyncNode, i);
S
Shengliang Guan 已提交
1413
        sSTrace((pSyncNode->senders)[i], "snapshot sender create new");
M
Minghao Li 已提交
1414
      }
1415 1416
    }

M
Minghao Li 已提交
1417
    // free old
S
Shengliang Guan 已提交
1418
    for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1419 1420
      if (oldSenders[i] != NULL) {
        snapshotSenderDestroy(oldSenders[i]);
S
Shengliang Guan 已提交
1421
        sNTrace(pSyncNode, "snapshot sender delete old %p replica-index:%d", oldSenders[i], i);
M
Minghao Li 已提交
1422 1423
        oldSenders[i] = NULL;
      }
1424 1425
    }

1426
    // persist cfg
M
Minghao Li 已提交
1427
    raftCfgPersist(pSyncNode->pRaftCfg);
1428

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

M
Minghao Li 已提交
1433 1434 1435
    // change isStandBy to normal (election timeout)
    if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
      syncNodeBecomeLeader(pSyncNode, tmpbuf);
1436 1437 1438 1439 1440

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

M
Minghao Li 已提交
1441 1442 1443 1444
    } else {
      syncNodeBecomeFollower(pSyncNode, tmpbuf);
    }
  } else {
1445
    // persist cfg
M
Minghao Li 已提交
1446
    raftCfgPersist(pSyncNode->pRaftCfg);
S
Shengliang Guan 已提交
1447 1448
    sNTrace(pSyncNode, "do not config change from %d to %d, index:%" PRId64 ", %s  -->  %s", oldConfig.replicaNum,
            pNewConfig->replicaNum, lastConfigChangeIndex, oldCfgStr, newCfgStr);
1449
  }
1450

M
Minghao Li 已提交
1451
_END:
M
Minghao Li 已提交
1452
  // log end config change
S
Shengliang Guan 已提交
1453
  sNTrace(pSyncNode, "end do config change, from %s to %s", oldCfgStr, newCfgStr);
M
Minghao Li 已提交
1454 1455
}

M
Minghao Li 已提交
1456 1457 1458 1459
// raft state change --------------
void syncNodeUpdateTerm(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
1460
    char tmpBuf[64];
1461
    snprintf(tmpBuf, sizeof(tmpBuf), "update term to %" PRId64, term);
1462
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
M
Minghao Li 已提交
1463 1464 1465 1466
    raftStoreClearVote(pSyncNode->pRaftStore);
  }
}

1467 1468 1469 1470 1471 1472
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
  }
}

M
Minghao Li 已提交
1473
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm) {
M
Minghao Li 已提交
1474
  if (pSyncNode->pRaftStore->currentTerm > newTerm) {
1475
    sNTrace(pSyncNode, "step down, ignore, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1476
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1477 1478
    return;
  }
M
Minghao Li 已提交
1479 1480

  do {
1481
    sNTrace(pSyncNode, "step down, new-term:%" PRId64 ", current-term:%" PRId64, newTerm,
S
Shengliang Guan 已提交
1482
            pSyncNode->pRaftStore->currentTerm);
M
Minghao Li 已提交
1483 1484 1485 1486 1487
  } while (0);

  if (pSyncNode->pRaftStore->currentTerm < newTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, newTerm);
    char tmpBuf[64];
1488
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
M
Minghao Li 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
    raftStoreClearVote(pSyncNode->pRaftStore);

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

1499 1500
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }

1501
void syncNodeBecomeFollower(SSyncNode* pSyncNode, const char* debugStr) {
M
Minghao Li 已提交
1502
  // maybe clear leader cache
M
Minghao Li 已提交
1503 1504 1505 1506
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
  }

M
Minghao Li 已提交
1507
  // state change
M
Minghao Li 已提交
1508 1509 1510
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
  syncNodeStopHeartbeatTimer(pSyncNode);

M
Minghao Li 已提交
1511 1512
  // reset elect timer
  syncNodeResetElectTimer(pSyncNode);
M
Minghao Li 已提交
1513

1514 1515 1516
  // send rsp to client
  syncNodeLeaderChangeRsp(pSyncNode);

1517 1518 1519 1520 1521
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1522 1523 1524
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
1525
  // trace log
S
Shengliang Guan 已提交
1526
  sNTrace(pSyncNode, "become follower %s", debugStr);
M
Minghao Li 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
}

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

1550 1551 1552
  // reset restoreFinish
  pSyncNode->restoreFinish = false;

M
Minghao Li 已提交
1553
  // state change
M
Minghao Li 已提交
1554
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
M
Minghao Li 已提交
1555 1556

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

S
Shengliang Guan 已提交
1559
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1560 1561
    // maybe overwrite myself, no harm
    // just do it!
1562 1563 1564 1565 1566 1567 1568 1569 1570

    // 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 已提交
1571 1572
  }

S
Shengliang Guan 已提交
1573
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
M
Minghao Li 已提交
1574 1575
    // maybe overwrite myself, no harm
    // just do it!
M
Minghao Li 已提交
1576 1577 1578
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
  }

M
Minghao Li 已提交
1579 1580 1581
  // init peer mgr
  syncNodePeerStateInit(pSyncNode);

M
Minghao Li 已提交
1582
#if 0
1583 1584
  // update sender private term
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
1585
  if (pMySender != NULL) {
S
Shengliang Guan 已提交
1586
    for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
1587 1588 1589
      if ((pSyncNode->senders)[i]->privateTerm > pMySender->privateTerm) {
        pMySender->privateTerm = (pSyncNode->senders)[i]->privateTerm;
      }
1590
    }
1591
    (pMySender->privateTerm) += 100;
1592
  }
M
Minghao Li 已提交
1593
#endif
1594

1595 1596 1597 1598 1599
  // close receiver
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
    snapshotReceiverForceStop(pSyncNode->pNewNodeReceiver);
  }

M
Minghao Li 已提交
1600
  // stop elect timer
M
Minghao Li 已提交
1601
  syncNodeStopElectTimer(pSyncNode);
M
Minghao Li 已提交
1602

M
Minghao Li 已提交
1603 1604
  // start heartbeat timer
  syncNodeStartHeartbeatTimer(pSyncNode);
M
Minghao Li 已提交
1605

M
Minghao Li 已提交
1606 1607
  // send heartbeat right now
  syncNodeHeartbeatPeers(pSyncNode);
M
Minghao Li 已提交
1608

1609 1610 1611 1612 1613
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1614 1615 1616
  // min match index
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;

M
Minghao Li 已提交
1617
  // trace log
S
Shengliang Guan 已提交
1618
  sNTrace(pSyncNode, "become leader %s", debugStr);
M
Minghao Li 已提交
1619 1620 1621
}

void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1622 1623
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
  ASSERT(voteGrantedMajority(pSyncNode->pVotesGranted));
1624
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");
M
Minghao Li 已提交
1625

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

M
Minghao Li 已提交
1628
  // Raft 3.6.2 Committing entries from previous terms
1629 1630
  syncNodeAppendNoop(pSyncNode);
  syncMaybeAdvanceCommitIndex(pSyncNode);
1631 1632

  if (pSyncNode->replicaNum > 1) {
M
Minghao Li 已提交
1633
    syncNodeReplicate(pSyncNode);
1634
  }
M
Minghao Li 已提交
1635 1636
}

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

M
Minghao Li 已提交
1639
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
S
Shengliang Guan 已提交
1640
  for (int32_t i = 0; i < TSDB_MAX_REPLICA; ++i) {
M
Minghao Li 已提交
1641 1642 1643 1644 1645
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
    pSyncNode->peerStates[i].lastSendTime = 0;
  }

  return 0;
M
Minghao Li 已提交
1646 1647 1648
}

void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1649
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER);
M
Minghao Li 已提交
1650
  pSyncNode->state = TAOS_SYNC_STATE_CANDIDATE;
S
Shengliang Guan 已提交
1651
  sNTrace(pSyncNode, "follower to candidate");
M
Minghao Li 已提交
1652 1653 1654
}

void syncNodeLeader2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1655
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_LEADER);
1656
  syncNodeBecomeFollower(pSyncNode, "leader to follower");
S
Shengliang Guan 已提交
1657
  sNTrace(pSyncNode, "leader to follower");
M
Minghao Li 已提交
1658 1659 1660
}

void syncNodeCandidate2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1661
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
1662
  syncNodeBecomeFollower(pSyncNode, "candidate to follower");
S
Shengliang Guan 已提交
1663
  sNTrace(pSyncNode, "candidate to follower");
M
Minghao Li 已提交
1664 1665 1666
}

// raft vote --------------
M
Minghao Li 已提交
1667 1668 1669

// just called by syncNodeVoteForSelf
// need assert
M
Minghao Li 已提交
1670
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
M
Minghao Li 已提交
1671 1672
  ASSERT(term == pSyncNode->pRaftStore->currentTerm);
  ASSERT(!raftStoreHasVoted(pSyncNode->pRaftStore));
M
Minghao Li 已提交
1673 1674 1675 1676

  raftStoreVote(pSyncNode->pRaftStore, pRaftId);
}

M
Minghao Li 已提交
1677
// simulate get vote from outside
M
Minghao Li 已提交
1678 1679 1680
void syncNodeVoteForSelf(SSyncNode* pSyncNode) {
  syncNodeVoteForTerm(pSyncNode, pSyncNode->pRaftStore->currentTerm, &(pSyncNode->myRaftId));

M
Minghao Li 已提交
1681
  SyncRequestVoteReply* pMsg = syncRequestVoteReplyBuild(pSyncNode->vgId);
M
Minghao Li 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
  pMsg->srcId = pSyncNode->myRaftId;
  pMsg->destId = pSyncNode->myRaftId;
  pMsg->term = pSyncNode->pRaftStore->currentTerm;
  pMsg->voteGranted = true;

  voteGrantedVote(pSyncNode->pVotesGranted, pMsg);
  votesRespondAdd(pSyncNode->pVotesRespond, pMsg);
  syncRequestVoteReplyDestroy(pMsg);
}

M
Minghao Li 已提交
1692
// snapshot --------------
M
Minghao Li 已提交
1693 1694

// return if has a snapshot
M
Minghao Li 已提交
1695 1696
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
  bool      ret = false;
1697
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1698 1699
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1700 1701 1702 1703 1704 1705 1706
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
      ret = true;
    }
  }
  return ret;
}

M
Minghao Li 已提交
1707 1708
// return max(logLastIndex, snapshotLastIndex)
// if no snapshot and log, return -1
1709
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1710
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1711 1712
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1713 1714 1715 1716 1717 1718 1719
  }
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);

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

M
Minghao Li 已提交
1720 1721
// return the last term of snapshot and log
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
M
Minghao Li 已提交
1722 1723
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
  SyncTerm lastTerm = 0;
M
Minghao Li 已提交
1724 1725
  if (syncNodeHasSnapshot(pSyncNode)) {
    // has snapshot
1726
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1727 1728
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
1729 1730
    }

M
Minghao Li 已提交
1731 1732 1733
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
    if (logLastIndex > snapshot.lastApplyIndex) {
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
M
Minghao Li 已提交
1734 1735 1736 1737
    } else {
      lastTerm = snapshot.lastApplyTerm;
    }

M
Minghao Li 已提交
1738
  } else {
M
Minghao Li 已提交
1739 1740
    // no snapshot
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1741
  }
M
Minghao Li 已提交
1742

M
Minghao Li 已提交
1743 1744 1745 1746 1747 1748 1749
  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);
1750 1751
  return 0;
}
M
Minghao Li 已提交
1752

M
Minghao Li 已提交
1753
// return append-entries first try index
M
Minghao Li 已提交
1754 1755 1756 1757 1758
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
  return syncStartIndex;
}

M
Minghao Li 已提交
1759 1760
// if index > 0, return index - 1
// else, return -1
1761 1762 1763 1764 1765 1766 1767 1768 1769
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
  SyncIndex preIndex = index - 1;
  if (preIndex < SYNC_INDEX_INVALID) {
    preIndex = SYNC_INDEX_INVALID;
  }

  return preIndex;
}

M
Minghao Li 已提交
1770 1771 1772 1773
// if index < 0, return SYNC_TERM_INVALID
// if index == 0, return 0
// if index > 0, return preTerm
// if error, return SYNC_TERM_INVALID
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
  if (index < SYNC_INDEX_BEGIN) {
    return SYNC_TERM_INVALID;
  }

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

  SyncTerm        preTerm = 0;
  SyncIndex       preIndex = index - 1;
  SSyncRaftEntry* pPreEntry = NULL;
  int32_t         code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
M
Minghao Li 已提交
1787 1788 1789 1790 1791 1792

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

1793 1794 1795 1796 1797 1798
  if (code == 0) {
    ASSERT(pPreEntry != NULL);
    preTerm = pPreEntry->term;
    taosMemoryFree(pPreEntry);
    return preTerm;
  } else {
1799 1800 1801 1802
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
      if (snapshot.lastApplyIndex == preIndex) {
        return snapshot.lastApplyTerm;
1803 1804 1805 1806
      }
    }
  }

1807
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
S
Shengliang Guan 已提交
1808
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
1809 1810
  return SYNC_TERM_INVALID;
}
M
Minghao Li 已提交
1811 1812 1813 1814

// 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 已提交
1815
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
M
Minghao Li 已提交
1816 1817 1818
  return 0;
}

M
Minghao Li 已提交
1819 1820
static void syncNodeEqPingTimer(void* param, void* tmrId) {
  SSyncNode* pSyncNode = (SSyncNode*)param;
M
Minghao Li 已提交
1821
  if (atomic_load_64(&pSyncNode->pingTimerLogicClockUser) <= atomic_load_64(&pSyncNode->pingTimerLogicClock)) {
M
Minghao Li 已提交
1822
    SyncTimeout* pSyncMsg = syncTimeoutBuild2(SYNC_TIMEOUT_PING, atomic_load_64(&pSyncNode->pingTimerLogicClock),
M
Minghao Li 已提交
1823
                                              pSyncNode->pingTimerMS, pSyncNode->vgId, pSyncNode);
M
Minghao Li 已提交
1824 1825
    SRpcMsg      rpcMsg;
    syncTimeout2RpcMsg(pSyncMsg, &rpcMsg);
1826
    sNTrace(pSyncNode, "enqueue ping timer");
S
Shengliang Guan 已提交
1827 1828
    if (pSyncNode->syncEqMsg != NULL) {
      int32_t code = pSyncNode->syncEqMsg(pSyncNode->msgcb, &rpcMsg);
1829
      if (code != 0) {
S
Shengliang Guan 已提交
1830
        sError("vgId:%d, sync enqueue ping msg error, code:%d", pSyncNode->vgId, code);
1831 1832 1833 1834
        rpcFreeCont(rpcMsg.pCont);
        syncTimeoutDestroy(pSyncMsg);
        return;
      }
M
Minghao Li 已提交
1835
    } else {
S
Shengliang Guan 已提交
1836
      sTrace("syncNodeEqPingTimer pSyncNode->syncEqMsg is NULL");
M
Minghao Li 已提交
1837
    }
M
Minghao Li 已提交
1838 1839
    syncTimeoutDestroy(pSyncMsg);

S
Shengliang Guan 已提交
1840 1841
    if (syncIsInit()) {
      taosTmrReset(syncNodeEqPingTimer, pSyncNode->pingTimerMS, pSyncNode, syncEnv()->pTimerManager,
1842 1843 1844 1845 1846
                   &pSyncNode->pPingTimer);
    } else {
      sError("sync env is stop, syncNodeEqPingTimer");
    }

M
Minghao Li 已提交
1847
  } else {
1848
    sTrace("==syncNodeEqPingTimer== pingTimerLogicClock:%" PRId64 ", pingTimerLogicClockUser:%" PRId64,
M
Minghao Li 已提交
1849
           pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
M
Minghao Li 已提交
1850 1851 1852 1853
  }
}

static void syncNodeEqElectTimer(void* param, void* tmrId) {
M
Minghao Li 已提交
1854 1855
  SElectTimer* pElectTimer = (SElectTimer*)param;
  SSyncNode*   pSyncNode = pElectTimer->pSyncNode;
M
Minghao Li 已提交
1856

M
Minghao Li 已提交
1857 1858
  SyncTimeout* pSyncMsg = syncTimeoutBuild2(SYNC_TIMEOUT_ELECTION, pElectTimer->logicClock, pSyncNode->electTimerMS,
                                            pSyncNode->vgId, pSyncNode);
M
Minghao Li 已提交
1859 1860
  SRpcMsg      rpcMsg;
  syncTimeout2RpcMsg(pSyncMsg, &rpcMsg);
1861
  if (pSyncNode->syncEqMsg != NULL && pSyncNode->msgcb != NULL && pSyncNode->msgcb->putToQueueFp != NULL) {
S
Shengliang Guan 已提交
1862
    int32_t code = pSyncNode->syncEqMsg(pSyncNode->msgcb, &rpcMsg);
M
Minghao Li 已提交
1863 1864 1865 1866
    if (code != 0) {
      sError("vgId:%d, sync enqueue elect msg error, code:%d", pSyncNode->vgId, code);
      rpcFreeCont(rpcMsg.pCont);
      syncTimeoutDestroy(pSyncMsg);
M
Minghao Li 已提交
1867
      taosMemoryFree(pElectTimer);
M
Minghao Li 已提交
1868
      return;
1869
    }
1870
    sNTrace(pSyncNode, "eq elect timer lc:%" PRId64, pSyncMsg->logicClock);
M
Minghao Li 已提交
1871
  } else {
S
Shengliang Guan 已提交
1872
    sTrace("syncNodeEqElectTimer syncEqMsg is NULL");
M
Minghao Li 已提交
1873
  }
M
Minghao Li 已提交
1874

M
Minghao Li 已提交
1875
  syncTimeoutDestroy(pSyncMsg);
M
Minghao Li 已提交
1876
  taosMemoryFree(pElectTimer);
M
Minghao Li 已提交
1877

M
Minghao Li 已提交
1878
#if 0
M
Minghao Li 已提交
1879
  // reset timer ms
S
Shengliang Guan 已提交
1880
  if (syncIsInit() && pSyncNode->electBaseLine > 0) {
M
Minghao Li 已提交
1881
    pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
S
Shengliang Guan 已提交
1882
    taosTmrReset(syncNodeEqElectTimer, pSyncNode->electTimerMS, pSyncNode, syncEnv()->pTimerManager,
M
Minghao Li 已提交
1883 1884 1885
                 &pSyncNode->pElectTimer);
  } else {
    sError("sync env is stop, syncNodeEqElectTimer");
M
Minghao Li 已提交
1886
  }
M
Minghao Li 已提交
1887
#endif
M
Minghao Li 已提交
1888 1889
}

M
Minghao Li 已提交
1890 1891
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
  SSyncNode* pSyncNode = (SSyncNode*)param;
S
Shengliang Guan 已提交
1892
  sNTrace(pSyncNode, "eq hb timer");
1893

1894 1895 1896 1897 1898 1899 1900 1901
  if (pSyncNode->replicaNum > 1) {
    if (atomic_load_64(&pSyncNode->heartbeatTimerLogicClockUser) <=
        atomic_load_64(&pSyncNode->heartbeatTimerLogicClock)) {
      SyncTimeout* pSyncMsg =
          syncTimeoutBuild2(SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pSyncNode->heartbeatTimerLogicClock),
                            pSyncNode->heartbeatTimerMS, pSyncNode->vgId, pSyncNode);
      SRpcMsg rpcMsg;
      syncTimeout2RpcMsg(pSyncMsg, &rpcMsg);
1902
      sNTrace(pSyncNode, "enqueue heartbeat timer");
S
Shengliang Guan 已提交
1903 1904
      if (pSyncNode->syncEqMsg != NULL) {
        int32_t code = pSyncNode->syncEqMsg(pSyncNode->msgcb, &rpcMsg);
1905
        if (code != 0) {
S
Shengliang Guan 已提交
1906
          sError("vgId:%d, sync enqueue timer msg error, code:%d", pSyncNode->vgId, code);
1907 1908 1909 1910 1911
          rpcFreeCont(rpcMsg.pCont);
          syncTimeoutDestroy(pSyncMsg);
          return;
        }
      } else {
S
Shengliang Guan 已提交
1912
        sError("vgId:%d, enqueue msg cb ptr (i.e. syncEqMsg) not set.", pSyncNode->vgId);
1913
      }
1914
      syncTimeoutDestroy(pSyncMsg);
M
Minghao Li 已提交
1915

S
Shengliang Guan 已提交
1916 1917
      if (syncIsInit()) {
        taosTmrReset(syncNodeEqHeartbeatTimer, pSyncNode->heartbeatTimerMS, pSyncNode, syncEnv()->pTimerManager,
1918 1919 1920 1921
                     &pSyncNode->pHeartbeatTimer);
      } else {
        sError("sync env is stop, syncNodeEqHeartbeatTimer");
      }
1922
    } else {
1923
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64
1924 1925
             "",
             pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
1926
    }
M
Minghao Li 已提交
1927 1928 1929
  }
}

1930 1931 1932 1933 1934
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
  SSyncHbTimerData* pData = (SSyncHbTimerData*)param;
  SSyncNode*        pSyncNode = pData->pSyncNode;
  SSyncTimer*       pSyncTimer = pData->pTimer;

M
Minghao Li 已提交
1935 1936 1937 1938
  if (pSyncNode == NULL) {
    return;
  }

M
Minghao Li 已提交
1939 1940 1941 1942
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
    return;
  }

M
Minghao Li 已提交
1943 1944 1945 1946
  if (pSyncNode->pRaftStore == NULL) {
    return;
  }

S
Shengliang Guan 已提交
1947
  // sNTrace(pSyncNode, "eq peer hb timer");
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958

  int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
  int64_t msgLogicClock = atomic_load_64(&pData->logicClock);

  if (pSyncNode->replicaNum > 1) {
    if (timerLogicClock == msgLogicClock) {
      SyncHeartbeat* pSyncMsg = syncHeartbeatBuild(pSyncNode->vgId);
      pSyncMsg->srcId = pSyncNode->myRaftId;
      pSyncMsg->destId = pData->destId;
      pSyncMsg->term = pSyncNode->pRaftStore->currentTerm;
      pSyncMsg->commitIndex = pSyncNode->commitIndex;
M
Minghao Li 已提交
1959
      pSyncMsg->minMatchIndex = syncMinMatchIndex(pSyncNode);
1960 1961 1962 1963 1964 1965 1966
      pSyncMsg->privateTerm = 0;

      SRpcMsg rpcMsg;
      syncHeartbeat2RpcMsg(pSyncMsg, &rpcMsg);

// eq msg
#if 0
S
Shengliang Guan 已提交
1967 1968
      if (pSyncNode->syncEqCtrlMsg != NULL) {
        int32_t code = pSyncNode->syncEqCtrlMsg(pSyncNode->msgcb, &rpcMsg);
1969 1970 1971 1972 1973 1974 1975
        if (code != 0) {
          sError("vgId:%d, sync ctrl enqueue timer msg error, code:%d", pSyncNode->vgId, code);
          rpcFreeCont(rpcMsg.pCont);
          syncHeartbeatDestroy(pSyncMsg);
          return;
        }
      } else {
S
Shengliang Guan 已提交
1976
        sError("vgId:%d, enqueue ctrl msg cb ptr (i.e. syncEqMsg) not set.", pSyncNode->vgId);
1977 1978 1979 1980
      }
#endif

      // send msg
M
Minghao Li 已提交
1981
      syncNodeSendHeartbeat(pSyncNode, &(pSyncMsg->destId), pSyncMsg);
1982 1983 1984

      syncHeartbeatDestroy(pSyncMsg);

S
Shengliang Guan 已提交
1985 1986
      if (syncIsInit()) {
        taosTmrReset(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS, pData, syncEnv()->pTimerManager,
1987 1988 1989 1990 1991 1992
                     &pSyncTimer->pTimer);
      } else {
        sError("sync env is stop, syncNodeEqHeartbeatTimer");
      }

    } else {
1993
      sTrace("==syncNodeEqPeerHeartbeatTimer== timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64 "", timerLogicClock,
1994 1995 1996 1997 1998
             msgLogicClock);
    }
  }
}

1999 2000 2001 2002 2003
static int32_t syncNodeEqNoop(SSyncNode* pNode) {
  if (pNode->state == TAOS_SYNC_STATE_LEADER) {
    terrno = TSDB_CODE_SYN_NOT_LEADER;
    return -1;
  }
M
Minghao Li 已提交
2004

2005 2006 2007 2008
  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 已提交
2009

S
Shengliang Guan 已提交
2010
  SRpcMsg rpcMsg = {0};
2011
  int32_t code = syncClientRequestBuildFromNoopEntry(&rpcMsg, pEntry, pNode->vgId);
M
Minghao Li 已提交
2012
  syncEntryDestory(pEntry);
M
Minghao Li 已提交
2013

2014 2015 2016 2017 2018 2019 2020
  sNTrace(pNode, "propose msg, type:noop");
  code = (*pNode->syncEqMsg)(pNode->msgcb, &rpcMsg);
  if (code != 0) {
    sNError(pNode, "failed to propose noop msg while enqueue since %s", terrstr());
  }

  return code;
M
Minghao Li 已提交
2021 2022
}

2023 2024 2025
static void deleteCacheEntry(const void* key, size_t keyLen, void* value) { taosMemoryFree(value); }

static int32_t syncCacheEntry(SSyncLogStore* pLogStore, SSyncRaftEntry* pEntry, LRUHandle** h) {
S
Shengliang Guan 已提交
2026 2027
  int32_t   code = 0;
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2028 2029 2030 2031 2032 2033 2034 2035 2036
  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;
}

M
Minghao Li 已提交
2037 2038 2039
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
  int32_t ret = 0;

2040
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2041
  SyncTerm        term = ths->pRaftStore->currentTerm;
M
Minghao Li 已提交
2042
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
M
Minghao Li 已提交
2043
  ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2044

2045 2046 2047
  LRUHandle* h = NULL;
  syncCacheEntry(ths->pLogStore, pEntry, &h);

M
Minghao Li 已提交
2048
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2049
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
2050
    if (code != 0) {
S
Shengliang Guan 已提交
2051
      sNError(ths, "append noop error");
2052 2053
      return -1;
    }
M
Minghao Li 已提交
2054 2055
  }

2056 2057 2058 2059 2060 2061
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2062 2063 2064
  return ret;
}

M
Minghao Li 已提交
2065
// on message ----
M
Minghao Li 已提交
2066 2067 2068
int32_t syncNodeOnPing(SSyncNode* ths, SyncPing* pMsg) {
  sTrace("vgId:%d, recv sync-ping", ths->vgId);

M
Minghao Li 已提交
2069
  SyncPingReply* pMsgReply = syncPingReplyBuild3(&ths->myRaftId, &pMsg->srcId, ths->vgId);
M
Minghao Li 已提交
2070 2071
  SRpcMsg        rpcMsg;
  syncPingReply2RpcMsg(pMsgReply, &rpcMsg);
M
Minghao Li 已提交
2072 2073

  /*
M
Minghao Li 已提交
2074 2075 2076 2077 2078
    // htonl
    SMsgHead* pHead = rpcMsg.pCont;
    pHead->contLen = htonl(pHead->contLen);
    pHead->vgId = htonl(pHead->vgId);
  */
M
Minghao Li 已提交
2079

M
Minghao Li 已提交
2080
  syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg);
M
Minghao Li 已提交
2081
  syncPingReplyDestroy(pMsgReply);
M
Minghao Li 已提交
2082

M
Minghao Li 已提交
2083
  return 0;
M
Minghao Li 已提交
2084 2085
}

M
Minghao Li 已提交
2086
int32_t syncNodeOnPingReply(SSyncNode* ths, SyncPingReply* pMsg) {
M
Minghao Li 已提交
2087
  int32_t ret = 0;
M
Minghao Li 已提交
2088
  sTrace("vgId:%d, recv sync-ping-reply", ths->vgId);
M
Minghao Li 已提交
2089 2090
  return ret;
}
M
Minghao Li 已提交
2091

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
int32_t syncNodeOnHeartbeat(SSyncNode* ths, SyncHeartbeat* pMsg) {
  syncLogRecvHeartbeat(ths, pMsg, "");

  SyncHeartbeatReply* pMsgReply = syncHeartbeatReplyBuild(ths->vgId);
  pMsgReply->destId = pMsg->srcId;
  pMsgReply->srcId = ths->myRaftId;
  pMsgReply->term = ths->pRaftStore->currentTerm;
  pMsgReply->privateTerm = 8864;  // magic number

  SRpcMsg rpcMsg;
  syncHeartbeatReply2RpcMsg(pMsgReply, &rpcMsg);

M
Minghao Li 已提交
2104
  if (pMsg->term == ths->pRaftStore->currentTerm && ths->state != TAOS_SYNC_STATE_LEADER) {
2105
    syncNodeResetElectTimer(ths);
M
Minghao Li 已提交
2106
    ths->minMatchIndex = pMsg->minMatchIndex;
2107 2108

    if (ths->state == TAOS_SYNC_STATE_FOLLOWER) {
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
      // syncNodeFollowerCommit(ths, pMsg->commitIndex);
      SyncLocalCmd* pSyncMsg = syncLocalCmdBuild(ths->vgId);
      pSyncMsg->cmd = SYNC_LOCAL_CMD_FOLLOWER_CMT;
      pSyncMsg->fcIndex = pMsg->commitIndex;

      SRpcMsg rpcMsgLocalCmd;
      syncLocalCmd2RpcMsg(pSyncMsg, &rpcMsgLocalCmd);

      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 {
2123
          sTrace("vgId:%d, sync enqueue fc-commit msg, fc-index:%" PRId64, ths->vgId, pSyncMsg->fcIndex);
2124 2125
        }
      }
2126 2127 2128
    }
  }

M
Minghao Li 已提交
2129
  if (pMsg->term >= ths->pRaftStore->currentTerm && ths->state != TAOS_SYNC_STATE_FOLLOWER) {
2130 2131 2132 2133 2134 2135 2136 2137
    // syncNodeStepDown(ths, pMsg->term);
    SyncLocalCmd* pSyncMsg = syncLocalCmdBuild(ths->vgId);
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
    pSyncMsg->sdNewTerm = pMsg->term;

    SRpcMsg rpcMsgLocalCmd;
    syncLocalCmd2RpcMsg(pSyncMsg, &rpcMsgLocalCmd);

S
Shengliang Guan 已提交
2138 2139
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
2140 2141 2142 2143
      if (code != 0) {
        sError("vgId:%d, sync enqueue step-down msg error, code:%d", ths->vgId, code);
        rpcFreeCont(rpcMsgLocalCmd.pCont);
      } else {
2144
        sTrace("vgId:%d, sync enqueue step-down msg, new-term: %" PRId64, ths->vgId, pSyncMsg->sdNewTerm);
2145 2146 2147 2148
      }
    }

    syncLocalCmdDestroy(pSyncMsg);
M
Minghao Li 已提交
2149 2150
  }

2151 2152 2153 2154 2155 2156 2157 2158 2159
  /*
    // htonl
    SMsgHead* pHead = rpcMsg.pCont;
    pHead->contLen = htonl(pHead->contLen);
    pHead->vgId = htonl(pHead->vgId);
  */

  // reply
  syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg);
M
Minghao Li 已提交
2160
  syncHeartbeatReplyDestroy(pMsgReply);
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173

  return 0;
}

int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, SyncHeartbeatReply* pMsg) {
  syncLogRecvHeartbeatReply(ths, pMsg, "");

  // update last reply time, make decision whether the other node is alive or not
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &(pMsg->destId), pMsg->startTime);

  return 0;
}

M
Minghao Li 已提交
2174
int32_t syncNodeOnLocalCmd(SSyncNode* ths, SyncLocalCmd* pMsg) {
2175 2176
  syncLogRecvLocalCmd(ths, pMsg, "");

M
Minghao Li 已提交
2177 2178 2179
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
    syncNodeStepDown(ths, pMsg->sdNewTerm);

2180 2181 2182
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT) {
    syncNodeFollowerCommit(ths, pMsg->fcIndex);

M
Minghao Li 已提交
2183
  } else {
S
Shengliang Guan 已提交
2184
    sNError(ths, "error local cmd");
M
Minghao Li 已提交
2185 2186 2187 2188 2189
  }

  return 0;
}

M
Minghao Li 已提交
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
// 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 已提交
2200

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

M
Minghao Li 已提交
2204
  int32_t ret = 0;
2205
  int32_t code = 0;
M
Minghao Li 已提交
2206

M
Minghao Li 已提交
2207
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2208
  SyncTerm        term = ths->pRaftStore->currentTerm;
2209 2210 2211 2212 2213 2214 2215
  SSyncRaftEntry* pEntry;

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

2217 2218 2219
  LRUHandle* h = NULL;
  syncCacheEntry(ths->pLogStore, pEntry, &h);

M
Minghao Li 已提交
2220
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2221 2222 2223
    // append entry
    code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
    if (code != 0) {
2224 2225 2226 2227 2228 2229
      if (ths->replicaNum == 1) {
        if (h) {
          taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }
2230

2231 2232 2233 2234
        return -1;

      } else {
        // del resp mgr, call FpCommitCb
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
        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,
        };
2246
        ths->pFsm->FpCommitCb(ths->pFsm, pMsg, &cbMeta);
2247 2248 2249 2250 2251 2252 2253

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

2254 2255
        return -1;
      }
2256
    }
M
Minghao Li 已提交
2257

2258 2259
    // if mulit replica, start replicate right now
    if (ths->replicaNum > 1) {
M
Minghao Li 已提交
2260
      syncNodeReplicate(ths);
2261
    }
2262

2263 2264
    // if only myself, maybe commit right now
    if (ths->replicaNum == 1) {
2265 2266 2267 2268 2269
      if (syncNodeIsMnode(ths)) {
        syncMaybeAdvanceCommitIndex(ths);
      } else {
        syncOneReplicaAdvance(ths);
      }
2270
    }
M
Minghao Li 已提交
2271 2272
  }

2273 2274 2275 2276 2277 2278 2279 2280
  if (pRetIndex != NULL) {
    if (ret == 0 && pEntry != NULL) {
      *pRetIndex = pEntry->index;
    } else {
      *pRetIndex = SYNC_INDEX_INVALID;
    }
  }

2281 2282 2283 2284 2285 2286
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2287
  return ret;
2288
}
M
Minghao Li 已提交
2289

S
Shengliang Guan 已提交
2290 2291 2292
const char* syncStr(ESyncState state) {
  switch (state) {
    case TAOS_SYNC_STATE_FOLLOWER:
2293
      return "follower";
S
Shengliang Guan 已提交
2294
    case TAOS_SYNC_STATE_CANDIDATE:
2295
      return "candidate";
S
Shengliang Guan 已提交
2296
    case TAOS_SYNC_STATE_LEADER:
2297
      return "leader";
S
Shengliang Guan 已提交
2298
    default:
2299
      return "error";
S
Shengliang Guan 已提交
2300
  }
M
Minghao Li 已提交
2301
}
2302

2303
int32_t syncDoLeaderTransfer(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry) {
2304
  if (ths->state != TAOS_SYNC_STATE_FOLLOWER) {
S
Shengliang Guan 已提交
2305
    sNTrace(ths, "I am not follower, can not do leader transfer");
2306 2307
    return 0;
  }
2308 2309

  if (!ths->restoreFinish) {
S
Shengliang Guan 已提交
2310
    sNTrace(ths, "restore not finish, can not do leader transfer");
2311 2312 2313
    return 0;
  }

2314
  if (pEntry->term < ths->pRaftStore->currentTerm) {
2315
    sNTrace(ths, "little term:%" PRId64 ", can not do leader transfer", pEntry->term);
2316 2317 2318 2319
    return 0;
  }

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

2324 2325
  /*
    if (ths->vgId > 1) {
S
Shengliang Guan 已提交
2326
      sNTrace(ths, "I am vnode, can not do leader transfer");
2327 2328 2329 2330
      return 0;
    }
  */

M
Minghao Li 已提交
2331
  SyncLeaderTransfer* pSyncLeaderTransfer = syncLeaderTransferFromRpcMsg2(pRpcMsg);
S
Shengliang Guan 已提交
2332
  sNTrace(ths, "do leader transfer, index:%" PRId64, pEntry->index);
M
Minghao Li 已提交
2333

M
Minghao Li 已提交
2334 2335 2336
  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 已提交
2337

M
Minghao Li 已提交
2338 2339
  bool same = sameId || sameNodeInfo;
  if (same) {
M
Minghao Li 已提交
2340 2341 2342 2343
    // reset elect timer now!
    int32_t electMS = 1;
    int32_t ret = syncNodeRestartElectTimer(ths, electMS);
    ASSERT(ret == 0);
M
Minghao Li 已提交
2344

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

M
Minghao Li 已提交
2349
  if (ths->pFsm->FpLeaderTransferCb != NULL) {
S
Shengliang Guan 已提交
2350
    SFsmCbMeta cbMeta = {
S
Shengliang Guan 已提交
2351 2352 2353 2354 2355 2356 2357 2358 2359
        .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 已提交
2360 2361
    };
    ths->pFsm->FpLeaderTransferCb(ths->pFsm, pRpcMsg, &cbMeta);
2362 2363
  }

M
Minghao Li 已提交
2364
  syncLeaderTransferDestroy(pSyncLeaderTransfer);
2365 2366 2367
  return 0;
}

2368
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
S
Shengliang Guan 已提交
2369
  for (int32_t i = 0; i < pNewCfg->replicaNum; ++i) {
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
    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;
}

2383 2384 2385 2386
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
}

M
Minghao Li 已提交
2387
int32_t syncNodeDoCommit(SSyncNode* ths, SyncIndex beginIndex, SyncIndex endIndex, uint64_t flag) {
2388 2389 2390 2391
  if (beginIndex > endIndex) {
    return 0;
  }

M
Minghao Li 已提交
2392 2393 2394 2395 2396 2397 2398 2399 2400
  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 已提交
2401
      sNTrace(ths, "commit by snapshot from index:%" PRId64 " to index:%" PRId64, beginIndex, snapshot.lastApplyIndex);
2402

M
Minghao Li 已提交
2403 2404 2405
      // update begin index
      beginIndex = snapshot.lastApplyIndex + 1;
    }
2406 2407
  }

2408 2409
  int32_t    code = 0;
  ESyncState state = flag;
M
Minghao Li 已提交
2410

S
Shengliang Guan 已提交
2411
  sNTrace(ths, "commit by wal from index:%" PRId64 " to index:%" PRId64, beginIndex, endIndex);
2412 2413 2414 2415 2416 2417

  // execute fsm
  if (ths->pFsm != NULL) {
    for (SyncIndex i = beginIndex; i <= endIndex; ++i) {
      if (i != SYNC_INDEX_INVALID) {
        SSyncRaftEntry* pEntry;
2418 2419 2420 2421 2422 2423
        SLRUCache*      pCache = ths->pLogStore->pCache;
        LRUHandle*      h = taosLRUCacheLookup(pCache, &i, sizeof(i));
        if (h) {
          pEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
        } else {
          code = ths->pLogStore->syncLogGetEntry(ths->pLogStore, i, &pEntry);
M
Minghao Li 已提交
2424 2425 2426
          // ASSERT(code == 0);
          // ASSERT(pEntry != NULL);
          if (code != 0 || pEntry == NULL) {
S
Shengliang Guan 已提交
2427
            sNError(ths, "get log entry error");
2428
            sFatal("vgId:%d, get log entry %" PRId64 " error when commit since %s", ths->vgId, i, terrstr());
M
Minghao Li 已提交
2429 2430
            continue;
          }
2431
        }
2432

2433
        SRpcMsg rpcMsg = {0};
2434 2435
        syncEntry2OriginalRpc(pEntry, &rpcMsg);

2436
        // user commit
2437 2438
        if ((ths->pFsm->FpCommitCb != NULL) && syncUtilUserCommit(pEntry->originalRpcType)) {
          bool internalExecute = true;
S
Shengliang Guan 已提交
2439
          if ((ths->replicaNum == 1) && ths->restoreFinish && ths->vgId != 1) {
2440 2441 2442
            internalExecute = false;
          }

S
Shengliang Guan 已提交
2443
          sNTrace(ths, "commit index:%" PRId64 ", internal:%d", i, internalExecute);
2444

2445 2446
          // execute fsm in apply thread, or execute outside syncPropose
          if (internalExecute) {
S
Shengliang Guan 已提交
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
            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 已提交
2459
            syncRespMgrGetAndDel(ths->pSyncRespMgr, cbMeta.seqNum, &rpcMsg.info);
S
Shengliang Guan 已提交
2460
            ths->pFsm->FpCommitCb(ths->pFsm, &rpcMsg, &cbMeta);
2461
          }
2462 2463
        }

2464 2465
#if 0
        // execute in pre-commit
M
Minghao Li 已提交
2466
        // leader transfer
2467 2468 2469
        if (pEntry->originalRpcType == TDMT_SYNC_LEADER_TRANSFER) {
          code = syncDoLeaderTransfer(ths, &rpcMsg, pEntry);
          ASSERT(code == 0);
2470
        }
2471
#endif
2472 2473

        // restore finish
2474
        // if only snapshot, a noop entry will be append, so syncLogLastIndex is always ok
2475 2476 2477 2478 2479 2480
        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 已提交
2481

2482
            int64_t restoreDelay = taosGetTimestampMs() - ths->leaderTime;
S
Shengliang Guan 已提交
2483
            sNTrace(ths, "restore finish, index:%" PRId64 ", elapsed:%" PRId64 " ms", pEntry->index, restoreDelay);
2484 2485 2486 2487
          }
        }

        rpcFreeCont(rpcMsg.pCont);
2488 2489 2490 2491 2492
        if (h) {
          taosLRUCacheRelease(pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }
2493 2494 2495 2496
      }
    }
  }
  return 0;
2497 2498 2499
}

bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
S
Shengliang Guan 已提交
2500
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
2501 2502 2503 2504 2505
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
      return true;
    }
  }
  return false;
M
Minghao Li 已提交
2506 2507 2508 2509
}

SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
  SSyncSnapshotSender* pSender = NULL;
S
Shengliang Guan 已提交
2510
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
2511 2512 2513 2514 2515
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pSender = (ths->senders)[i];
    }
  }
  return pSender;
M
Minghao Li 已提交
2516
}
M
Minghao Li 已提交
2517

2518 2519
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
  SSyncTimer* pTimer = NULL;
S
Shengliang Guan 已提交
2520
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
2521 2522 2523 2524 2525 2526 2527
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
    }
  }
  return pTimer;
}

M
Minghao Li 已提交
2528 2529
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
  SPeerState* pState = NULL;
S
Shengliang Guan 已提交
2530
  for (int32_t i = 0; i < ths->replicaNum; ++i) {
M
Minghao Li 已提交
2531 2532 2533 2534 2535 2536 2537 2538 2539
    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 已提交
2540
  if (pState == NULL) {
2541
    sError("vgId:%d, replica maybe dropped", ths->vgId);
M
Minghao Li 已提交
2542 2543
    return false;
  }
M
Minghao Li 已提交
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554

  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 已提交
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568
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 已提交
2569
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
M
Minghao Li 已提交
2570
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
M
Minghao Li 已提交
2571
    if (pSender != NULL && pSender->start) {
M
Minghao Li 已提交
2572 2573 2574 2575 2576 2577
      sError("sync cannot change3");
      return false;
    }
  }

  return true;
M
Minghao Li 已提交
2578 2579
}

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
const char* syncTimerTypeStr(enum ESyncTimeoutType timerType) {
  if (timerType == SYNC_TIMEOUT_PING) {
    return "ping";
  } else if (timerType == SYNC_TIMEOUT_ELECTION) {
    return "elect";
  } else if (timerType == SYNC_TIMEOUT_HEARTBEAT) {
    return "heartbeat";
  } else {
    return "unknown";
  }
}

void syncLogRecvTimer(SSyncNode* pSyncNode, const SyncTimeout* pMsg, const char* s) {
2593
  sNTrace(pSyncNode, "recv sync-timer {type:%s, lc:%" PRId64 ", ms:%d, data:%p}, %s",
S
Shengliang Guan 已提交
2594
          syncTimerTypeStr(pMsg->timeoutType), pMsg->logicClock, pMsg->timerMS, pMsg->data, s);
2595 2596
}

wafwerar's avatar
wafwerar 已提交
2597
void syncLogSendRequestVote(SSyncNode* pSyncNode, const SyncRequestVote* pMsg, const char* s) {
M
Minghao Li 已提交
2598 2599 2600
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
2601
  sNTrace(pSyncNode, "send sync-request-vote to %s:%d {term:%" PRId64 ", lindex:%" PRId64 ", lterm:%" PRId64 "}, %s",
S
Shengliang Guan 已提交
2602
          host, port, pMsg->term, pMsg->lastLogIndex, pMsg->lastLogTerm, s);
M
Minghao Li 已提交
2603 2604
}

wafwerar's avatar
wafwerar 已提交
2605
void syncLogRecvRequestVote(SSyncNode* pSyncNode, const SyncRequestVote* pMsg, const char* s) {
M
Minghao Li 已提交
2606 2607 2608 2609
  char     logBuf[256];
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
2610
  sNTrace(pSyncNode, "recv sync-request-vote from %s:%d, {term:%" PRId64 ", lindex:%" PRId64 ", lterm:%" PRId64 "}, %s",
S
Shengliang Guan 已提交
2611
          host, port, pMsg->term, pMsg->lastLogIndex, pMsg->lastLogTerm, s);
M
Minghao Li 已提交
2612 2613
}

wafwerar's avatar
wafwerar 已提交
2614
void syncLogSendRequestVoteReply(SSyncNode* pSyncNode, const SyncRequestVoteReply* pMsg, const char* s) {
M
Minghao Li 已提交
2615 2616 2617
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
2618
  sNTrace(pSyncNode, "send sync-request-vote-reply to %s:%d {term:%" PRId64 ", grant:%d}, %s", host, port, pMsg->term,
S
Shengliang Guan 已提交
2619
          pMsg->voteGranted, s);
M
Minghao Li 已提交
2620 2621
}

wafwerar's avatar
wafwerar 已提交
2622
void syncLogRecvRequestVoteReply(SSyncNode* pSyncNode, const SyncRequestVoteReply* pMsg, const char* s) {
M
Minghao Li 已提交
2623 2624 2625
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
2626
  sNTrace(pSyncNode, "recv sync-request-vote-reply from %s:%d {term:%" PRId64 ", grant:%d}, %s", host, port, pMsg->term,
S
Shengliang Guan 已提交
2627
          pMsg->voteGranted, s);
M
Minghao Li 已提交
2628 2629
}

wafwerar's avatar
wafwerar 已提交
2630
void syncLogSendAppendEntries(SSyncNode* pSyncNode, const SyncAppendEntries* pMsg, const char* s) {
M
Minghao Li 已提交
2631 2632 2633
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2634
  sNTrace(pSyncNode,
2635 2636
          "send sync-append-entries to %s:%d, {term:%" PRId64 ", pre-index:%" PRId64 ", pre-term:%" PRId64
          ", pterm:%" PRId64 ", cmt:%" PRId64 ", datalen:%d}, %s",
S
Shengliang Guan 已提交
2637 2638
          host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->privateTerm, pMsg->commitIndex,
          pMsg->dataLen, s);
M
Minghao Li 已提交
2639 2640
}

wafwerar's avatar
wafwerar 已提交
2641
void syncLogRecvAppendEntries(SSyncNode* pSyncNode, const SyncAppendEntries* pMsg, const char* s) {
M
Minghao Li 已提交
2642 2643 2644
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2645 2646

  sNTrace(pSyncNode,
2647 2648
          "recv sync-append-entries from %s:%d {term:%" PRId64 ", pre-index:%" PRId64 ", pre-term:%" PRId64
          ", cmt:%" PRId64 ", pterm:%" PRId64 ", datalen:%d}, %s",
S
Shengliang Guan 已提交
2649 2650
          host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
          pMsg->dataLen, s);
M
Minghao Li 已提交
2651 2652
}

wafwerar's avatar
wafwerar 已提交
2653
void syncLogSendAppendEntriesBatch(SSyncNode* pSyncNode, const SyncAppendEntriesBatch* pMsg, const char* s) {
M
Minghao Li 已提交
2654 2655 2656
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2657 2658

  sNTrace(pSyncNode,
2659 2660
          "send sync-append-entries-batch to %s:%d, {term:%" PRId64 ", pre-index:%" PRId64 ", pre-term:%" PRId64
          ", pterm:%" PRId64 ", cmt:%" PRId64 ", datalen:%d, count:%d}, %s",
S
Shengliang Guan 已提交
2661 2662
          host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->privateTerm, pMsg->commitIndex,
          pMsg->dataLen, pMsg->dataCount, s);
M
Minghao Li 已提交
2663 2664
}

wafwerar's avatar
wafwerar 已提交
2665
void syncLogRecvAppendEntriesBatch(SSyncNode* pSyncNode, const SyncAppendEntriesBatch* pMsg, const char* s) {
M
Minghao Li 已提交
2666 2667 2668
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2669 2670

  sNTrace(pSyncNode,
2671 2672
          "recv sync-append-entries-batch from %s:%d, {term:%" PRId64 ", pre-index:%" PRId64 ", pre-term:%" PRId64
          ", pterm:%" PRId64 ", cmt:%" PRId64 ", datalen:%d, count:%d}, %s",
S
Shengliang Guan 已提交
2673 2674
          host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->privateTerm, pMsg->commitIndex,
          pMsg->dataLen, pMsg->dataCount, s);
M
Minghao Li 已提交
2675 2676
}

2677
void syncLogSendAppendEntriesReply(SSyncNode* pSyncNode, const SyncAppendEntriesReply* pMsg, const char* s) {
M
Minghao Li 已提交
2678 2679 2680
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2681 2682

  sNTrace(pSyncNode,
2683
          "send sync-append-entries-reply to %s:%d, {term:%" PRId64 ", pterm:%" PRId64 ", success:%d, match:%" PRId64
S
Shengliang Guan 已提交
2684 2685
          "}, %s",
          host, port, pMsg->term, pMsg->privateTerm, pMsg->success, pMsg->matchIndex, s);
M
Minghao Li 已提交
2686 2687
}

wafwerar's avatar
wafwerar 已提交
2688
void syncLogRecvAppendEntriesReply(SSyncNode* pSyncNode, const SyncAppendEntriesReply* pMsg, const char* s) {
M
Minghao Li 已提交
2689 2690 2691
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2692 2693

  sNTrace(pSyncNode,
2694
          "recv sync-append-entries-reply from %s:%d {term:%" PRId64 ", pterm:%" PRId64 ", success:%d, match:%" PRId64
S
Shengliang Guan 已提交
2695 2696
          "}, %s",
          host, port, pMsg->term, pMsg->privateTerm, pMsg->success, pMsg->matchIndex, s);
M
Minghao Li 已提交
2697
}
2698 2699 2700 2701 2702

void syncLogSendHeartbeat(SSyncNode* pSyncNode, const SyncHeartbeat* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2703 2704

  sNTrace(pSyncNode,
2705
          "send sync-heartbeat to %s:%d {term:%" PRId64 ", cmt:%" PRId64 ", min-match:%" PRId64 ", pterm:%" PRId64
S
Shengliang Guan 已提交
2706 2707
          "}, %s",
          host, port, pMsg->term, pMsg->commitIndex, pMsg->minMatchIndex, pMsg->privateTerm, s);
2708 2709 2710 2711 2712 2713
}

void syncLogRecvHeartbeat(SSyncNode* pSyncNode, const SyncHeartbeat* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2714 2715

  sNTrace(pSyncNode,
2716
          "recv sync-heartbeat from %s:%d {term:%" PRId64 ", cmt:%" PRId64 ", min-match:%" PRId64 ", pterm:%" PRId64
S
Shengliang Guan 已提交
2717 2718
          "}, %s",
          host, port, pMsg->term, pMsg->commitIndex, pMsg->minMatchIndex, pMsg->privateTerm, s);
2719 2720 2721 2722 2723 2724
}

void syncLogSendHeartbeatReply(SSyncNode* pSyncNode, const SyncHeartbeatReply* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
S
Shengliang Guan 已提交
2725

2726
  sNTrace(pSyncNode, "send sync-heartbeat-reply from %s:%d {term:%" PRId64 ", pterm:%" PRId64 "}, %s", host, port,
S
Shengliang Guan 已提交
2727
          pMsg->term, pMsg->privateTerm, s);
2728 2729 2730 2731 2732 2733
}

void syncLogRecvHeartbeatReply(SSyncNode* pSyncNode, const SyncHeartbeatReply* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
2734
  sNTrace(pSyncNode, "recv sync-heartbeat-reply from %s:%d {term:%" PRId64 ", pterm:%" PRId64 "}, %s", host, port,
S
Shengliang Guan 已提交
2735
          pMsg->term, pMsg->privateTerm, s);
M
Minghao Li 已提交
2736
}
2737 2738

void syncLogRecvLocalCmd(SSyncNode* pSyncNode, const SyncLocalCmd* pMsg, const char* s) {
2739 2740
  sNTrace(pSyncNode, "recv sync-local-cmd {cmd:%d-%s, sd-new-term:%" PRId64 ", fc-index:%" PRId64 "}, %s", pMsg->cmd,
          syncLocalCmdGetStr(pMsg->cmd), pMsg->sdNewTerm, pMsg->fcIndex, s);
M
Minghao Li 已提交
2741 2742 2743 2744 2745 2746
}

void syncLogSendSyncPreSnapshot(SSyncNode* pSyncNode, const SyncPreSnapshot* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
2747
  sNTrace(pSyncNode, "send sync-pre-snapshot to %s:%d {term:%" PRId64 "}, %s", host, port, pMsg->term, s);
M
Minghao Li 已提交
2748 2749 2750 2751 2752 2753
}

void syncLogRecvSyncPreSnapshot(SSyncNode* pSyncNode, const SyncPreSnapshot* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
2754
  sNTrace(pSyncNode, "recv sync-pre-snapshot from %s:%d {term:%" PRId64 "}, %s", host, port, pMsg->term, s);
M
Minghao Li 已提交
2755 2756 2757 2758 2759 2760
}

void syncLogSendSyncPreSnapshotReply(SSyncNode* pSyncNode, const SyncPreSnapshotReply* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
2761
  sNTrace(pSyncNode, "send sync-pre-snapshot-reply to %s:%d {term:%" PRId64 ", snap-start:%" PRId64 "}, %s", host, port,
S
Shengliang Guan 已提交
2762
          pMsg->term, pMsg->snapStart, s);
M
Minghao Li 已提交
2763 2764 2765 2766 2767 2768
}

void syncLogRecvSyncPreSnapshotReply(SSyncNode* pSyncNode, const SyncPreSnapshotReply* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
2769
  sNTrace(pSyncNode, "recv sync-pre-snapshot-reply from %s:%d {term:%" PRId64 ", snap-start:%" PRId64 "}, %s", host,
S
Shengliang Guan 已提交
2770
          port, pMsg->term, pMsg->snapStart, s);
M
Minghao Li 已提交
2771
}
M
Minghao Li 已提交
2772 2773 2774 2775 2776 2777 2778 2779

void syncLogSendSyncSnapshotSend(SSyncNode* pSyncNode, const SyncSnapshotSend* pMsg, const char* s) {}

void syncLogRecvSyncSnapshotSend(SSyncNode* pSyncNode, const SyncSnapshotSend* pMsg, const char* s) {}

void syncLogSendSyncSnapshotRsp(SSyncNode* pSyncNode, const SyncSnapshotRsp* pMsg, const char* s) {}

void syncLogRecvSyncSnapshotRsp(SSyncNode* pSyncNode, const SyncSnapshotRsp* pMsg, const char* s) {}