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

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

38
bool gRaftDetailLog = false;
39

M
Minghao Li 已提交
40 41 42
static int32_t tsNodeRefId = -1;

// ------ local funciton ---------
M
Minghao Li 已提交
43
// enqueue message ----
M
Minghao Li 已提交
44 45 46 47 48
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);
M
Minghao Li 已提交
49

M
Minghao Li 已提交
50
// process message ----
M
Minghao Li 已提交
51 52
int32_t syncNodeOnPingCb(SSyncNode* ths, SyncPing* pMsg);
int32_t syncNodeOnPingReplyCb(SSyncNode* ths, SyncPingReply* pMsg);
M
Minghao Li 已提交
53

M
Minghao Li 已提交
54
// ---------------------------------
H
Hongze Cheng 已提交
55 56 57
static void syncNodeFreeCb(void* param) {
  syncNodeClose(param);
  param = NULL;
58
}
M
Minghao Li 已提交
59 60

int32_t syncInit() {
M
Minghao Li 已提交
61 62 63
  int32_t ret = 0;

  if (!syncEnvIsStart()) {
64
    tsNodeRefId = taosOpenRef(200, syncNodeFreeCb);
M
Minghao Li 已提交
65 66 67 68 69
    if (tsNodeRefId < 0) {
      sError("failed to init node ref");
      syncCleanUp();
      ret = -1;
    } else {
S
Shengliang Guan 已提交
70
      sDebug("sync rsetId:%" PRId64 " is open", tsNodeRefId);
M
Minghao Li 已提交
71 72
      ret = syncEnvStart();
    }
M
Minghao Li 已提交
73 74
  }

M
Minghao Li 已提交
75
  return ret;
M
Minghao Li 已提交
76
}
M
Minghao Li 已提交
77

M
Minghao Li 已提交
78 79
void syncCleanUp() {
  int32_t ret = syncEnvStop();
M
Minghao Li 已提交
80
  ASSERT(ret == 0);
M
Minghao Li 已提交
81 82

  if (tsNodeRefId != -1) {
S
Shengliang Guan 已提交
83
    sDebug("sync rsetId:%" PRId64 " is closed", tsNodeRefId);
M
Minghao Li 已提交
84 85 86
    taosCloseRef(tsNodeRefId);
    tsNodeRefId = -1;
  }
M
Minghao Li 已提交
87
}
M
Minghao Li 已提交
88

89
int64_t syncOpen(SSyncInfo* pSyncInfo) {
M
Minghao Li 已提交
90
  SSyncNode* pSyncNode = syncNodeOpen(pSyncInfo);
91
  if (pSyncNode == NULL) {
92
    sError("vgId:%d, failed to open sync node since %s", pSyncInfo->vgId, terrstr());
93 94
    return -1;
  }
M
Minghao Li 已提交
95

M
Minghao Li 已提交
96 97
  pSyncNode->rid = taosAddRef(tsNodeRefId, pSyncNode);
  if (pSyncNode->rid < 0) {
98 99
    syncNodeClose(pSyncNode);
    pSyncNode = NULL;
M
Minghao Li 已提交
100 101 102
    return -1;
  }

S
Shengliang Guan 已提交
103
  sDebug("vgId:%d, sync rid:%" PRId64 " is added to rsetId:%" PRId64, pSyncInfo->vgId, pSyncNode->rid, tsNodeRefId);
M
Minghao Li 已提交
104
  return pSyncNode->rid;
M
Minghao Li 已提交
105
}
M
Minghao Li 已提交
106

M
Minghao Li 已提交
107 108 109 110 111
void syncStart(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return;
  }
M
Minghao Li 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

  if (pSyncNode->pRaftCfg->isStandBy) {
    syncNodeStartStandBy(pSyncNode);
  } else {
    syncNodeStart(pSyncNode);
  }

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

void syncStartNormal(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return;
  }
M
Minghao Li 已提交
127 128 129 130 131
  syncNodeStart(pSyncNode);

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

M
Minghao Li 已提交
132 133 134 135 136 137 138 139 140 141
void syncStartStandBy(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return;
  }
  syncNodeStartStandBy(pSyncNode);

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

M
Minghao Li 已提交
142
void syncStop(int64_t rid) {
M
Minghao Li 已提交
143
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
S
Shengliang Guan 已提交
144 145
  if (pSyncNode == NULL) return;
  int32_t vgId = pSyncNode->vgId;
M
Minghao Li 已提交
146
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
147

M
Minghao Li 已提交
148
  taosRemoveRef(tsNodeRefId, rid);
S
Shengliang Guan 已提交
149
  sDebug("vgId:%d, sync rid:%" PRId64 " is removed from rsetId:%" PRId64, vgId, rid, tsNodeRefId);
M
Minghao Li 已提交
150
}
M
Minghao Li 已提交
151

M
Minghao Li 已提交
152 153 154
int32_t syncSetStandby(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
M
Minghao Li 已提交
155
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
S
Shengliang Guan 已提交
156
    sError("failed to set standby since accquire ref error, rid:%" PRId64, rid);
M
Minghao Li 已提交
157
    return -1;
M
Minghao Li 已提交
158 159
  }

160
  if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
161 162 163 164 165 166
    if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
      terrno = TSDB_CODE_SYN_IS_LEADER;
    } else {
      terrno = TSDB_CODE_SYN_STANDBY_NOT_READY;
    }
    sError("failed to set standby since it is not follower, state:%s rid:%" PRId64, syncStr(pSyncNode->state), rid);
M
Minghao Li 已提交
167
    taosReleaseRef(tsNodeRefId, pSyncNode->rid);
M
Minghao Li 已提交
168
    return -1;
M
Minghao Li 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  }

  // 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);

  pSyncNode->pRaftCfg->isStandBy = 1;
  raftCfgPersist(pSyncNode->pRaftCfg);

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
184
  sInfo("vgId:%d, set to standby", pSyncNode->vgId);
M
Minghao Li 已提交
185 186 187
  return 0;
}

M
Minghao Li 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
bool syncNodeCheckNewConfig(SSyncNode* pSyncNode, const SSyncCfg* pNewCfg) {
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewCfg);
  if (!IamInNew) {
    return false;
  }

  if (pNewCfg->replicaNum > pSyncNode->replicaNum + 1) {
    return false;
  }

  if (pNewCfg->replicaNum < pSyncNode->replicaNum - 1) {
    return false;
  }

  return true;
}

M
Minghao Li 已提交
205 206 207
int32_t syncReconfigBuild(int64_t rid, const SSyncCfg* pNewCfg, SRpcMsg* pRpcMsg) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
M
Minghao Li 已提交
208 209
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
    return -1;
M
Minghao Li 已提交
210 211
  }
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
212
  int32_t ret = 0;
213

M
Minghao Li 已提交
214
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
M
Minghao Li 已提交
215
    taosReleaseRef(tsNodeRefId, pSyncNode->rid);
M
Minghao Li 已提交
216
    terrno = TSDB_CODE_SYN_NEW_CONFIG_ERROR;
217
    sError("invalid new config. vgId:%d", pSyncNode->vgId);
M
Minghao Li 已提交
218
    return -1;
M
Minghao Li 已提交
219 220 221 222 223 224 225 226 227
  }

  char* newconfig = syncCfg2Str((SSyncCfg*)pNewCfg);
  pRpcMsg->msgType = TDMT_SYNC_CONFIG_CHANGE;
  pRpcMsg->info.noResp = 1;
  pRpcMsg->contLen = strlen(newconfig) + 1;
  pRpcMsg->pCont = rpcMallocCont(pRpcMsg->contLen);
  snprintf(pRpcMsg->pCont, pRpcMsg->contLen, "%s", newconfig);
  taosMemoryFree(newconfig);
228

M
Minghao Li 已提交
229 230 231 232
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return ret;
}

233
int32_t syncReconfig(int64_t rid, SSyncCfg* pNewCfg) {
M
Minghao Li 已提交
234 235
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
M
Minghao Li 已提交
236 237
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
    return -1;
M
Minghao Li 已提交
238 239 240
  }
  ASSERT(rid == pSyncNode->rid);

241
#if 0
M
Minghao Li 已提交
242
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
M
Minghao Li 已提交
243
    taosReleaseRef(tsNodeRefId, pSyncNode->rid);
M
Minghao Li 已提交
244
    terrno = TSDB_CODE_SYN_NEW_CONFIG_ERROR;
245
    sError("invalid new config. vgId:%d", pSyncNode->vgId);
M
Minghao Li 已提交
246
    return -1;
M
Minghao Li 已提交
247
  }
248

M
Minghao Li 已提交
249
  char*   newconfig = syncCfg2Str((SSyncCfg*)pNewCfg);
M
Minghao Li 已提交
250 251
  int32_t ret = 0;

M
Minghao Li 已提交
252
  SRpcMsg rpcMsg = {0};
253
  rpcMsg.msgType = TDMT_SYNC_CONFIG_CHANGE;
S
Shengliang Guan 已提交
254
  rpcMsg.info.noResp = 1;
255
  rpcMsg.contLen = strlen(newconfig) + 1;
M
Minghao Li 已提交
256
  rpcMsg.pCont = rpcMallocCont(rpcMsg.contLen);
257 258
  snprintf(rpcMsg.pCont, rpcMsg.contLen, "%s", newconfig);
  taosMemoryFree(newconfig);
M
Minghao Li 已提交
259 260 261
  ret = syncNodePropose(pSyncNode, &rpcMsg, false);

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
M
Minghao Li 已提交
262
  return ret;
263 264
#else
  syncNodeUpdateNewConfigIndex(pSyncNode, pNewCfg);
265
  syncNodeDoConfigChange(pSyncNode, pNewCfg, SYNC_INDEX_INVALID);
266 267 268
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return 0;
#endif
M
Minghao Li 已提交
269
}
M
Minghao Li 已提交
270

271
int32_t syncLeaderTransfer(int64_t rid) {
M
Minghao Li 已提交
272 273
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
M
Minghao Li 已提交
274 275
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
    return -1;
M
Minghao Li 已提交
276 277 278
  }
  ASSERT(rid == pSyncNode->rid);

M
Minghao Li 已提交
279
  int32_t ret = syncNodeLeaderTransfer(pSyncNode);
M
Minghao Li 已提交
280
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
281 282 283 284 285 286
  return ret;
}

int32_t syncLeaderTransferTo(int64_t rid, SNodeInfo newLeader) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
M
Minghao Li 已提交
287 288
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
    return -1;
289
  }
M
Minghao Li 已提交
290
  ASSERT(rid == pSyncNode->rid);
291

M
Minghao Li 已提交
292
  int32_t ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
293 294 295 296
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return ret;
}

M
Minghao Li 已提交
297 298
int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode) {
  if (pSyncNode->peersNum == 0) {
299
    sDebug("only one replica, cannot leader transfer");
M
Minghao Li 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
  }

  SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
  int32_t   ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
  return ret;
}

int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader) {
  int32_t ret = 0;

  if (pSyncNode->replicaNum == 1) {
313
    sDebug("only one replica, cannot leader transfer");
M
Minghao Li 已提交
314 315 316 317
    terrno = TSDB_CODE_SYN_ONE_REPLICA;
    return -1;
  }

M
Minghao Li 已提交
318 319 320 321 322 323
  do {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "begin leader transfer to %s:%u", newLeader.nodeFqdn, newLeader.nodePort);
    syncNodeEventLog(pSyncNode, logBuf);
  } while (0);

M
Minghao Li 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336
  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);

  ret = syncNodePropose(pSyncNode, &rpcMsg, false);
  return ret;
}

337 338 339 340 341
bool syncCanLeaderTransfer(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return false;
  }
M
Minghao Li 已提交
342
  ASSERT(rid == pSyncNode->rid);
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

  if (pSyncNode->replicaNum == 1) {
    taosReleaseRef(tsNodeRefId, pSyncNode->rid);
    return false;
  }

  if (pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER) {
    taosReleaseRef(tsNodeRefId, pSyncNode->rid);
    return true;
  }

  bool matchOK = true;
  if (pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE || pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    SyncIndex myCommitIndex = pSyncNode->commitIndex;
    for (int i = 0; i < pSyncNode->peersNum; ++i) {
      SyncIndex peerMatchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId)[i]);
      if (peerMatchIndex < myCommitIndex) {
        matchOK = false;
      }
    }
  }

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return matchOK;
}

369
int32_t syncForwardToPeer(int64_t rid, SRpcMsg* pMsg, bool isWeak) {
M
Minghao Li 已提交
370 371 372
  int32_t ret = syncPropose(rid, pMsg, isWeak);
  return ret;
}
M
Minghao Li 已提交
373

M
Minghao Li 已提交
374 375 376 377 378
ESyncState syncGetMyRole(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return TAOS_SYNC_STATE_ERROR;
  }
M
Minghao Li 已提交
379
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
380 381 382 383
  ESyncState state = pSyncNode->state;

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return state;
M
Minghao Li 已提交
384 385
}

M
Minghao Li 已提交
386 387 388 389 390
bool syncIsReady(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return false;
  }
M
Minghao Li 已提交
391
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
392 393
  bool b = (pSyncNode->state == TAOS_SYNC_STATE_LEADER) && pSyncNode->restoreFinish;
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
394 395 396 397 398 399 400 401 402

  // if false, set error code
  if (false == b) {
    if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
      terrno = TSDB_CODE_SYN_NOT_LEADER;
    } else {
      terrno = TSDB_CODE_APP_NOT_READY;
    }
  }
M
Minghao Li 已提交
403 404 405
  return b;
}

M
Minghao Li 已提交
406 407 408 409 410
bool syncIsRestoreFinish(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return false;
  }
M
Minghao Li 已提交
411
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
412 413 414 415 416 417
  bool b = pSyncNode->restoreFinish;

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return b;
}

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
int32_t syncGetSnapshotByIndex(int64_t rid, SyncIndex index, SSnapshot* pSnapshot) {
  if (index < SYNC_INDEX_BEGIN) {
    return -1;
  }

  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  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);
    }
    taosReleaseRef(tsNodeRefId, pSyncNode->rid);
    return -1;
  }
  ASSERT(pEntry != NULL);

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

  syncEntryDestory(pEntry);
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return 0;
}

450 451 452 453 454
int32_t syncGetSnapshotMeta(int64_t rid, struct SSnapshotMeta* sMeta) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return -1;
  }
M
Minghao Li 已提交
455
  ASSERT(rid == pSyncNode->rid);
456 457
  sMeta->lastConfigIndex = pSyncNode->pRaftCfg->lastConfigIndex;

S
Shengliang Guan 已提交
458
  sTrace("vgId:%d, get snapshot meta, lastConfigIndex:%" PRId64, pSyncNode->vgId, pSyncNode->pRaftCfg->lastConfigIndex);
459 460 461 462 463

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return 0;
}

464 465 466 467 468
int32_t syncGetSnapshotMetaByIndex(int64_t rid, SyncIndex snapshotIndex, struct SSnapshotMeta* sMeta) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return -1;
  }
M
Minghao Li 已提交
469
  ASSERT(rid == pSyncNode->rid);
470 471 472 473 474 475 476 477 478 479 480

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

  for (int i = 0; i < pSyncNode->pRaftCfg->configIndexCount; ++i) {
    if ((pSyncNode->pRaftCfg->configIndexArr)[i] > lastIndex &&
        (pSyncNode->pRaftCfg->configIndexArr)[i] <= snapshotIndex) {
      lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[i];
    }
  }
  sMeta->lastConfigIndex = lastIndex;
481
  sTrace("vgId:%d, get snapshot meta by index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId, snapshotIndex,
S
Shengliang Guan 已提交
482
         sMeta->lastConfigIndex);
483 484 485 486 487

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return 0;
}

488 489 490 491 492 493 494 495 496 497
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
  ASSERT(pSyncNode->pRaftCfg->configIndexCount >= 1);
  SyncIndex lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[0];

  for (int i = 0; i < pSyncNode->pRaftCfg->configIndexCount; ++i) {
    if ((pSyncNode->pRaftCfg->configIndexArr)[i] > lastIndex &&
        (pSyncNode->pRaftCfg->configIndexArr)[i] <= snapshotLastApplyIndex) {
      lastIndex = (pSyncNode->pRaftCfg->configIndexArr)[i];
    }
  }
S
Shengliang Guan 已提交
498
  sTrace("vgId:%d, sync get last config index, index:%" PRId64 " lcindex:%" PRId64, pSyncNode->vgId,
S
Shengliang Guan 已提交
499
         snapshotLastApplyIndex, lastIndex);
500 501 502 503

  return lastIndex;
}

M
Minghao Li 已提交
504 505 506 507 508
const char* syncGetMyRoleStr(int64_t rid) {
  const char* s = syncUtilState2String(syncGetMyRole(rid));
  return s;
}

M
Minghao Li 已提交
509 510 511 512 513 514 515 516 517 518 519 520
bool syncRestoreFinish(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return false;
  }
  ASSERT(rid == pSyncNode->rid);
  bool restoreFinish = pSyncNode->restoreFinish;

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return restoreFinish;
}

M
Minghao Li 已提交
521
SyncTerm syncGetMyTerm(int64_t rid) {
M
Minghao Li 已提交
522 523 524 525
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return TAOS_SYNC_STATE_ERROR;
  }
M
Minghao Li 已提交
526
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
527
  SyncTerm term = pSyncNode->pRaftStore->currentTerm;
M
Minghao Li 已提交
528 529

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
M
Minghao Li 已提交
530
  return term;
M
Minghao Li 已提交
531 532
}

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
SyncIndex syncGetLastIndex(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return SYNC_INDEX_INVALID;
  }
  ASSERT(rid == pSyncNode->rid);
  SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return lastIndex;
}

SyncIndex syncGetCommitIndex(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return SYNC_INDEX_INVALID;
  }
  ASSERT(rid == pSyncNode->rid);
  SyncIndex cmtIndex = pSyncNode->commitIndex;

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return cmtIndex;
}

M
Minghao Li 已提交
557
SyncGroupId syncGetVgId(int64_t rid) {
M
Minghao Li 已提交
558 559
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
M
Minghao Li 已提交
560 561
    return TAOS_SYNC_STATE_ERROR;
  }
M
Minghao Li 已提交
562
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
563
  SyncGroupId vgId = pSyncNode->vgId;
M
Minghao Li 已提交
564 565

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
M
Minghao Li 已提交
566
  return vgId;
M
Minghao Li 已提交
567 568
}

M
Minghao Li 已提交
569 570 571 572 573 574
void syncGetEpSet(int64_t rid, SEpSet* pEpSet) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    memset(pEpSet, 0, sizeof(*pEpSet));
    return;
  }
M
Minghao Li 已提交
575
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
576 577
  pEpSet->numOfEps = 0;
  for (int i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
M
Minghao Li 已提交
578 579
    snprintf(pEpSet->eps[i].fqdn, sizeof(pEpSet->eps[i].fqdn), "%s", (pSyncNode->pRaftCfg->cfg.nodeInfo)[i].nodeFqdn);
    pEpSet->eps[i].port = (pSyncNode->pRaftCfg->cfg.nodeInfo)[i].nodePort;
M
Minghao Li 已提交
580
    (pEpSet->numOfEps)++;
S
Shengliang Guan 已提交
581
    sInfo("vgId:%d, sync get epset: index:%d %s:%d", pSyncNode->vgId, i, pEpSet->eps[i].fqdn, pEpSet->eps[i].port);
M
Minghao Li 已提交
582 583
  }
  pEpSet->inUse = pSyncNode->pRaftCfg->cfg.myIndex;
S
Shengliang Guan 已提交
584
  sInfo("vgId:%d, sync get epset in-use:%d", pSyncNode->vgId, pEpSet->inUse);
585 586 587

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}
M
Minghao Li 已提交
588

589 590 591 592 593 594 595 596 597 598 599 600
void syncGetRetryEpSet(int64_t rid, SEpSet* pEpSet) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    memset(pEpSet, 0, sizeof(*pEpSet));
    return;
  }
  ASSERT(rid == pSyncNode->rid);
  pEpSet->numOfEps = 0;
  for (int i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
    snprintf(pEpSet->eps[i].fqdn, sizeof(pEpSet->eps[i].fqdn), "%s", (pSyncNode->pRaftCfg->cfg.nodeInfo)[i].nodeFqdn);
    pEpSet->eps[i].port = (pSyncNode->pRaftCfg->cfg.nodeInfo)[i].nodePort;
    (pEpSet->numOfEps)++;
M
Minghao Li 已提交
601 602
    sInfo("vgId:%d, sync get retry epset: index:%d %s:%d", pSyncNode->vgId, i, pEpSet->eps[i].fqdn,
          pEpSet->eps[i].port);
603 604
  }
  pEpSet->inUse = (pSyncNode->pRaftCfg->cfg.myIndex + 1) % pEpSet->numOfEps;
M
Minghao Li 已提交
605
  sInfo("vgId:%d, sync get retry epset in-use:%d", pSyncNode->vgId, pEpSet->inUse);
M
Minghao Li 已提交
606 607 608 609

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

M
Minghao Li 已提交
610 611 612 613 614
int32_t syncGetRespRpc(int64_t rid, uint64_t index, SRpcMsg* msg) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return TAOS_SYNC_STATE_ERROR;
  }
M
Minghao Li 已提交
615
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
616 617 618 619 620 621 622 623 624 625 626

  SRespStub stub;
  int32_t   ret = syncRespMgrGet(pSyncNode->pSyncRespMgr, index, &stub);
  if (ret == 1) {
    memcpy(msg, &(stub.rpcMsg), sizeof(SRpcMsg));
  }

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return ret;
}

S
Shengliang Guan 已提交
627
int32_t syncGetAndDelRespRpc(int64_t rid, uint64_t index, SRpcHandleInfo* pInfo) {
M
Minghao Li 已提交
628 629 630 631
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return TAOS_SYNC_STATE_ERROR;
  }
M
Minghao Li 已提交
632
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
633 634 635 636

  SRespStub stub;
  int32_t   ret = syncRespMgrGetAndDel(pSyncNode->pSyncRespMgr, index, &stub);
  if (ret == 1) {
S
Shengliang Guan 已提交
637
    *pInfo = stub.rpcMsg.info;
M
Minghao Li 已提交
638 639
  }

S
Shengliang Guan 已提交
640
  sTrace("vgId:%d, get seq:%" PRIu64 " rpc handle:%p", pSyncNode->vgId, index, pInfo->handle);
M
Minghao Li 已提交
641 642 643 644
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return ret;
}

645
void syncSetMsgCb(int64_t rid, const SMsgCb* msgcb) {
M
Minghao Li 已提交
646 647
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
S
Shengliang Guan 已提交
648
    sTrace("syncSetQ get pSyncNode is NULL, rid:%" PRId64, rid);
M
Minghao Li 已提交
649 650
    return;
  }
M
Minghao Li 已提交
651
  ASSERT(rid == pSyncNode->rid);
S
Shengliang Guan 已提交
652
  pSyncNode->msgcb = msgcb;
M
Minghao Li 已提交
653 654 655 656 657 658 659

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

char* sync2SimpleStr(int64_t rid) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
S
Shengliang Guan 已提交
660
    sTrace("syncSetRpc get pSyncNode is NULL, rid:%" PRId64, rid);
M
Minghao Li 已提交
661 662
    return NULL;
  }
M
Minghao Li 已提交
663
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
664 665 666 667 668 669 670 671 672 673 674
  char* s = syncNode2SimpleStr(pSyncNode);
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);

  return s;
}

void setPingTimerMS(int64_t rid, int32_t pingTimerMS) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return;
  }
M
Minghao Li 已提交
675
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
676 677 678 679 680 681 682 683 684 685 686
  pSyncNode->pingBaseLine = pingTimerMS;
  pSyncNode->pingTimerMS = pingTimerMS;

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

void setElectTimerMS(int64_t rid, int32_t electTimerMS) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return;
  }
M
Minghao Li 已提交
687
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
688 689 690 691 692 693 694 695 696 697
  pSyncNode->electBaseLine = electTimerMS;

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

void setHeartbeatTimerMS(int64_t rid, int32_t hbTimerMS) {
  SSyncNode* pSyncNode = (SSyncNode*)taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    return;
  }
M
Minghao Li 已提交
698
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
699 700 701 702 703 704
  pSyncNode->hbBaseLine = hbTimerMS;
  pSyncNode->heartbeatTimerMS = hbTimerMS;

  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
}

M
Minghao Li 已提交
705
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak) {
706
  SSyncNode* pSyncNode = taosAcquireRef(tsNodeRefId, rid);
707
  if (pSyncNode == NULL) {
M
Minghao Li 已提交
708
    taosReleaseRef(tsNodeRefId, rid);
M
Minghao Li 已提交
709 710
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
    return -1;
711
  }
M
Minghao Li 已提交
712
  ASSERT(rid == pSyncNode->rid);
M
Minghao Li 已提交
713

714
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak);
M
Minghao Li 已提交
715 716 717 718
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return ret;
}

719
int32_t syncProposeBatch(int64_t rid, SRpcMsg** pMsgPArr, bool* pIsWeakArr, int32_t arrSize) {
M
Minghao Li 已提交
720 721 722 723 724 725 726 727 728 729 730 731
  if (arrSize < 0) {
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
    return -1;
  }

  SSyncNode* pSyncNode = taosAcquireRef(tsNodeRefId, rid);
  if (pSyncNode == NULL) {
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
    return -1;
  }
  ASSERT(rid == pSyncNode->rid);

732
  int32_t ret = syncNodeProposeBatch(pSyncNode, pMsgPArr, pIsWeakArr, arrSize);
M
Minghao Li 已提交
733 734 735 736
  taosReleaseRef(tsNodeRefId, pSyncNode->rid);
  return ret;
}

737
static bool syncNodeBatchOK(SRpcMsg** pMsgPArr, int32_t arrSize) {
M
Minghao Li 已提交
738
  for (int32_t i = 0; i < arrSize; ++i) {
739
    if (pMsgPArr[i]->msgType == TDMT_SYNC_CONFIG_CHANGE) {
M
Minghao Li 已提交
740 741 742
      return false;
    }

743
    if (pMsgPArr[i]->msgType == TDMT_SYNC_CONFIG_CHANGE_FINISH) {
M
Minghao Li 已提交
744 745 746 747 748 749 750
      return false;
    }
  }

  return true;
}

751 752
int32_t syncNodeProposeBatch(SSyncNode* pSyncNode, SRpcMsg** pMsgPArr, bool* pIsWeakArr, int32_t arrSize) {
  if (!syncNodeBatchOK(pMsgPArr, arrSize)) {
M
Minghao Li 已提交
753 754 755 756 757 758
    syncNodeErrorLog(pSyncNode, "sync propose batch error");
    terrno = TSDB_CODE_SYN_BATCH_ERROR;
    return -1;
  }

  if (arrSize > SYNC_MAX_BATCH_SIZE) {
M
Minghao Li 已提交
759
    syncNodeErrorLog(pSyncNode, "sync propose batch error");
M
Minghao Li 已提交
760 761 762 763
    terrno = TSDB_CODE_SYN_BATCH_ERROR;
    return -1;
  }

M
Minghao Li 已提交
764
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
M
Minghao Li 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777
    syncNodeErrorLog(pSyncNode, "sync propose not leader");
    terrno = TSDB_CODE_SYN_NOT_LEADER;
    return -1;
  }

  if (pSyncNode->changing) {
    syncNodeErrorLog(pSyncNode, "sync propose not ready");
    terrno = TSDB_CODE_SYN_PROPOSE_NOT_READY;
    return -1;
  }

  SRaftMeta raftArr[SYNC_MAX_BATCH_SIZE];
  for (int i = 0; i < arrSize; ++i) {
M
Minghao Li 已提交
778 779
    do {
      char eventLog[128];
780 781
      snprintf(eventLog, sizeof(eventLog), "propose message, type:%s batch:%d", TMSG_INFO(pMsgPArr[i]->msgType),
               arrSize);
M
Minghao Li 已提交
782 783 784
      syncNodeEventLog(pSyncNode, eventLog);
    } while (0);

M
Minghao Li 已提交
785 786
    SRespStub stub;
    stub.createTime = taosGetTimestampMs();
787
    stub.rpcMsg = *(pMsgPArr[i]);
M
Minghao Li 已提交
788 789 790 791 792 793
    uint64_t seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);

    raftArr[i].isWeak = pIsWeakArr[i];
    raftArr[i].seqNum = seqNum;
  }

794
  SyncClientRequestBatch* pSyncMsg = syncClientRequestBatchBuild(pMsgPArr, raftArr, arrSize, pSyncNode->vgId);
M
Minghao Li 已提交
795 796 797 798 799 800
  ASSERT(pSyncMsg != NULL);

  SRpcMsg rpcMsg;
  syncClientRequestBatch2RpcMsg(pSyncMsg, &rpcMsg);
  taosMemoryFree(pSyncMsg);  // only free msg body, do not free rpc msg content

M
Minghao Li 已提交
801 802 803 804 805 806 807
  if (pSyncNode->replicaNum == 1 && pSyncNode->vgId != 1) {
    int32_t code = syncNodeOnClientRequestBatchCb(pSyncNode, pSyncMsg);
    if (code == 0) {
      // update rpc msg applyIndex
      SRpcMsg* msgArr = syncClientRequestBatchRpcMsgArr(pSyncMsg);
      ASSERT(arrSize == pSyncMsg->dataCount);
      for (int i = 0; i < arrSize; ++i) {
808
        pMsgPArr[i]->info.conn.applyIndex = msgArr[i].info.conn.applyIndex;
M
Minghao Li 已提交
809 810 811 812 813 814 815 816 817 818 819
        syncRespMgrDel(pSyncNode->pSyncRespMgr, raftArr[i].seqNum);
      }

      rpcFreeCont(rpcMsg.pCont);
      terrno = 0;
      return 1;

    } else {
      terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
      return -1;
    }
M
Minghao Li 已提交
820 821

  } else {
M
Minghao Li 已提交
822 823 824 825 826 827 828 829 830
    if (pSyncNode->FpEqMsg != NULL && (*pSyncNode->FpEqMsg)(pSyncNode->msgcb, &rpcMsg) == 0) {
      // enqueue msg ok
      return 0;

    } else {
      sError("vgId:%d, enqueue msg error, FpEqMsg is NULL", pSyncNode->vgId);
      terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
      return -1;
    }
M
Minghao Li 已提交
831 832 833 834
  }

  return 0;
}
835

836
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak) {
M
Minghao Li 已提交
837
  int32_t ret = 0;
M
Minghao Li 已提交
838

M
Minghao Li 已提交
839 840
  do {
    char eventLog[128];
S
Shengliang Guan 已提交
841
    snprintf(eventLog, sizeof(eventLog), "propose message, type:%s", TMSG_INFO(pMsg->msgType));
M
Minghao Li 已提交
842 843
    syncNodeEventLog(pSyncNode, eventLog);
  } while (0);
M
Minghao Li 已提交
844

M
Minghao Li 已提交
845
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
M
Minghao Li 已提交
846 847 848
    if (pSyncNode->changing && pMsg->msgType != TDMT_SYNC_CONFIG_CHANGE_FINISH) {
      ret = -1;
      terrno = TSDB_CODE_SYN_PROPOSE_NOT_READY;
S
Shengliang Guan 已提交
849
      sError("vgId:%d, failed to sync propose since not ready, type:%s", pSyncNode->vgId, TMSG_INFO(pMsg->msgType));
M
Minghao Li 已提交
850 851 852 853 854 855 856 857
      goto _END;
    }

    // config change
    if (pMsg->msgType == TDMT_SYNC_CONFIG_CHANGE) {
      if (!syncNodeCanChange(pSyncNode)) {
        ret = -1;
        terrno = TSDB_CODE_SYN_RECONFIG_NOT_READY;
S
Shengliang Guan 已提交
858
        sError("vgId:%d, failed to sync reconfig since not ready, type:%s", pSyncNode->vgId, TMSG_INFO(pMsg->msgType));
M
Minghao Li 已提交
859 860 861 862 863 864 865
        goto _END;
      }

      ASSERT(!pSyncNode->changing);
      pSyncNode->changing = true;
    }

866 867
    // not restored, vnode enable
    if (!pSyncNode->restoreFinish && pSyncNode->vgId != 1) {
868 869 870 871 872 873 874
      ret = -1;
      terrno = TSDB_CODE_SYN_PROPOSE_NOT_READY;
      sError("vgId:%d, failed to sync propose since not ready, type:%s, last:%ld, cmt:%ld", pSyncNode->vgId,
             TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
      goto _END;
    }

M
Minghao Li 已提交
875 876 877 878 879 880
    SRespStub stub;
    stub.createTime = taosGetTimestampMs();
    stub.rpcMsg = *pMsg;
    uint64_t seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);

    SyncClientRequest* pSyncMsg = syncClientRequestBuild2(pMsg, seqNum, isWeak, pSyncNode->vgId);
M
Minghao Li 已提交
881 882
    SRpcMsg            rpcMsg;
    syncClientRequest2RpcMsg(pSyncMsg, &rpcMsg);
883

884 885 886 887 888 889
    // optimized one replica
    if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
      SyncIndex retIndex;
      int32_t   code = syncNodeOnClientRequestCb(pSyncNode, pSyncMsg, &retIndex);
      if (code == 0) {
        pMsg->info.conn.applyIndex = retIndex;
M
Minghao Li 已提交
890
        pMsg->info.conn.applyTerm = pSyncNode->pRaftStore->currentTerm;
891 892 893
        rpcFreeCont(rpcMsg.pCont);
        syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum);
        ret = 1;
894 895
        sDebug("vgId:%d, sync optimize index:%" PRId64 ", type:%s", pSyncNode->vgId, retIndex,
               TMSG_INFO(pMsg->msgType));
896 897 898
      } else {
        ret = -1;
        terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
S
Shengliang Guan 已提交
899 900
        sError("vgId:%d, failed to sync optimize index:%" PRId64 ", type:%s", pSyncNode->vgId, retIndex,
               TMSG_INFO(pMsg->msgType));
901 902
      }

M
Minghao Li 已提交
903
    } else {
904 905 906 907 908
      if (pSyncNode->FpEqMsg != NULL && (*pSyncNode->FpEqMsg)(pSyncNode->msgcb, &rpcMsg) == 0) {
        ret = 0;
      } else {
        ret = -1;
        terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
S
Shengliang Guan 已提交
909
        sError("vgId:%d, failed to enqueue msg since its null", pSyncNode->vgId);
910
      }
M
Minghao Li 已提交
911
    }
912

M
Minghao Li 已提交
913
    syncClientRequestDestroy(pSyncMsg);
M
Minghao Li 已提交
914 915
    goto _END;

M
Minghao Li 已提交
916
  } else {
M
Minghao Li 已提交
917 918
    ret = -1;
    terrno = TSDB_CODE_SYN_NOT_LEADER;
S
Shengliang Guan 已提交
919 920
    sError("vgId:%d, sync propose not leader, %s, type:%s", pSyncNode->vgId, syncUtilState2String(pSyncNode->state),
           TMSG_INFO(pMsg->msgType));
M
Minghao Li 已提交
921
    goto _END;
M
Minghao Li 已提交
922
  }
M
Minghao Li 已提交
923

M
Minghao Li 已提交
924
_END:
M
Minghao Li 已提交
925 926 927
  return ret;
}

M
Minghao Li 已提交
928
// open/close --------------
929
SSyncNode* syncNodeOpen(SSyncInfo* pSyncInfo) {
930 931 932 933 934
  SSyncNode* pSyncNode = (SSyncNode*)taosMemoryCalloc(1, sizeof(SSyncNode));
  if (pSyncNode == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }
M
Minghao Li 已提交
935

M
Minghao Li 已提交
936 937 938 939 940
  int32_t ret = 0;
  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());
941
      goto _error;
M
Minghao Li 已提交
942
    }
943
  }
M
Minghao Li 已提交
944

S
Shengliang Guan 已提交
945
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
946
  if (!taosCheckExistFile(pSyncNode->configPath)) {
M
Minghao Li 已提交
947 948 949
    // create a new raft config file
    SRaftCfgMeta meta;
    meta.isStandBy = pSyncInfo->isStandBy;
M
Minghao Li 已提交
950
    meta.snapshotStrategy = pSyncInfo->snapshotStrategy;
951
    meta.lastConfigIndex = SYNC_INDEX_INVALID;
M
Minghao Li 已提交
952
    meta.batchSize = pSyncInfo->batchSize;
M
Minghao Li 已提交
953
    ret = raftCfgCreateFile((SSyncCfg*)&(pSyncInfo->syncCfg), meta, pSyncNode->configPath);
954
    if (ret != 0) {
H
Hongze Cheng 已提交
955 956
      sError("failed to create raft cfg file. configPath: %s", pSyncNode->configPath);
      goto _error;
957
    }
958 959 960
  } else {
    // update syncCfg by raft_config.json
    pSyncNode->pRaftCfg = raftCfgOpen(pSyncNode->configPath);
961
    if (pSyncNode->pRaftCfg == NULL) {
H
Hongze Cheng 已提交
962 963
      sError("failed to open raft cfg file. path:%s", pSyncNode->configPath);
      goto _error;
964
    }
965 966 967
    if (pSyncInfo->syncCfg.replicaNum == 0) {
      pSyncInfo->syncCfg = pSyncNode->pRaftCfg->cfg;
    }
968 969

    raftCfgClose(pSyncNode->pRaftCfg);
970
    pSyncNode->pRaftCfg = NULL;
M
Minghao Li 已提交
971 972
  }

M
Minghao Li 已提交
973
  // init by SSyncInfo
M
Minghao Li 已提交
974 975
  pSyncNode->vgId = pSyncInfo->vgId;
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
S
Shengliang Guan 已提交
976 977 978
  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 已提交
979

M
Minghao Li 已提交
980
  pSyncNode->pWal = pSyncInfo->pWal;
S
Shengliang Guan 已提交
981
  pSyncNode->msgcb = pSyncInfo->msgcb;
M
Minghao Li 已提交
982
  pSyncNode->FpSendMsg = pSyncInfo->FpSendMsg;
M
Minghao Li 已提交
983
  pSyncNode->FpEqMsg = pSyncInfo->FpEqMsg;
M
Minghao Li 已提交
984

M
Minghao Li 已提交
985 986
  // init raft config
  pSyncNode->pRaftCfg = raftCfgOpen(pSyncNode->configPath);
987 988 989 990
  if (pSyncNode->pRaftCfg == NULL) {
    sError("failed to open raft cfg file. path:%s", pSyncNode->configPath);
    goto _error;
  }
M
Minghao Li 已提交
991

M
Minghao Li 已提交
992
  // init internal
M
Minghao Li 已提交
993
  pSyncNode->myNodeInfo = pSyncNode->pRaftCfg->cfg.nodeInfo[pSyncNode->pRaftCfg->cfg.myIndex];
994
  if (!syncUtilnodeInfo2raftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId)) {
H
Hongze Cheng 已提交
995 996
    sError("failed to determine my raft member id. vgId:%d", pSyncNode->vgId);
    goto _error;
997
  }
M
Minghao Li 已提交
998

M
Minghao Li 已提交
999
  // init peersNum, peers, peersId
M
Minghao Li 已提交
1000
  pSyncNode->peersNum = pSyncNode->pRaftCfg->cfg.replicaNum - 1;
M
Minghao Li 已提交
1001
  int j = 0;
M
Minghao Li 已提交
1002 1003 1004
  for (int i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
    if (i != pSyncNode->pRaftCfg->cfg.myIndex) {
      pSyncNode->peersNodeInfo[j] = pSyncNode->pRaftCfg->cfg.nodeInfo[i];
M
Minghao Li 已提交
1005 1006 1007
      j++;
    }
  }
M
Minghao Li 已提交
1008
  for (int i = 0; i < pSyncNode->peersNum; ++i) {
1009
    if (!syncUtilnodeInfo2raftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i])) {
H
Hongze Cheng 已提交
1010 1011
      sError("failed to determine raft member id. vgId:%d, peer:%d", pSyncNode->vgId, i);
      goto _error;
1012
    }
M
Minghao Li 已提交
1013
  }
M
Minghao Li 已提交
1014

M
Minghao Li 已提交
1015
  // init replicaNum, replicasId
M
Minghao Li 已提交
1016 1017
  pSyncNode->replicaNum = pSyncNode->pRaftCfg->cfg.replicaNum;
  for (int i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
H
Hongze Cheng 已提交
1018 1019 1020
    if (!syncUtilnodeInfo2raftId(&pSyncNode->pRaftCfg->cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i])) {
      sError("failed to determine raft member id. vgId:%d, replica:%d", pSyncNode->vgId, i);
      goto _error;
1021
    }
M
Minghao Li 已提交
1022 1023
  }

M
Minghao Li 已提交
1024
  // init raft algorithm
M
Minghao Li 已提交
1025
  pSyncNode->pFsm = pSyncInfo->pFsm;
1026
  pSyncInfo->pFsm = NULL;
M
Minghao Li 已提交
1027
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->pRaftCfg->cfg.replicaNum);
M
Minghao Li 已提交
1028 1029
  pSyncNode->leaderCache = EMPTY_RAFT_ID;

M
Minghao Li 已提交
1030
  // init life cycle outside
M
Minghao Li 已提交
1031

M
Minghao Li 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  // 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 已提交
1056
  // init TLA+ server vars
M
syncInt  
Minghao Li 已提交
1057
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
M
Minghao Li 已提交
1058
  pSyncNode->pRaftStore = raftStoreOpen(pSyncNode->raftStorePath);
1059 1060 1061 1062
  if (pSyncNode->pRaftStore == NULL) {
    sError("failed to open raft store. path: %s", pSyncNode->raftStorePath);
    goto _error;
  }
M
Minghao Li 已提交
1063

M
Minghao Li 已提交
1064
  // init TLA+ candidate vars
M
Minghao Li 已提交
1065
  pSyncNode->pVotesGranted = voteGrantedCreate(pSyncNode);
1066 1067 1068 1069
  if (pSyncNode->pVotesGranted == NULL) {
    sError("failed to create VotesGranted. vgId:%d", pSyncNode->vgId);
    goto _error;
  }
M
Minghao Li 已提交
1070
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
1071 1072 1073 1074
  if (pSyncNode->pVotesRespond == NULL) {
    sError("failed to create VotesRespond. vgId:%d", pSyncNode->vgId);
    goto _error;
  }
M
Minghao Li 已提交
1075

M
Minghao Li 已提交
1076 1077
  // init TLA+ leader vars
  pSyncNode->pNextIndex = syncIndexMgrCreate(pSyncNode);
1078 1079 1080 1081
  if (pSyncNode->pNextIndex == NULL) {
    sError("failed to create SyncIndexMgr. vgId:%d", pSyncNode->vgId);
    goto _error;
  }
M
Minghao Li 已提交
1082
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
1083 1084 1085 1086
  if (pSyncNode->pMatchIndex == NULL) {
    sError("failed to create SyncIndexMgr. vgId:%d", pSyncNode->vgId);
    goto _error;
  }
M
Minghao Li 已提交
1087 1088 1089

  // init TLA+ log vars
  pSyncNode->pLogStore = logStoreCreate(pSyncNode);
1090 1091 1092 1093
  if (pSyncNode->pLogStore == NULL) {
    sError("failed to create SyncLogStore. vgId:%d", pSyncNode->vgId);
    goto _error;
  }
1094 1095 1096 1097 1098

  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);
1099
    if (code != 0) {
H
Hongze Cheng 已提交
1100 1101
      sError("failed to get snapshot info. vgId:%d, code:%d", pSyncNode->vgId, code);
      goto _error;
1102
    }
1103 1104 1105 1106 1107 1108
    if (snapshot.lastApplyIndex > commitIndex) {
      commitIndex = snapshot.lastApplyIndex;
      syncNodeEventLog(pSyncNode, "reset commit index by snapshot");
    }
  }
  pSyncNode->commitIndex = commitIndex;
M
Minghao Li 已提交
1109

M
Minghao Li 已提交
1110 1111 1112 1113 1114
  // timer ms init
  pSyncNode->pingBaseLine = PING_TIMER_MS;
  pSyncNode->electBaseLine = ELECT_TIMER_MS_MIN;
  pSyncNode->hbBaseLine = HEARTBEAT_TIMER_MS;

M
Minghao Li 已提交
1115
  // init ping timer
M
Minghao Li 已提交
1116
  pSyncNode->pPingTimer = NULL;
M
Minghao Li 已提交
1117
  pSyncNode->pingTimerMS = pSyncNode->pingBaseLine;
M
Minghao Li 已提交
1118 1119
  atomic_store_64(&pSyncNode->pingTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->pingTimerLogicClockUser, 0);
M
Minghao Li 已提交
1120
  pSyncNode->FpPingTimerCB = syncNodeEqPingTimer;
M
Minghao Li 已提交
1121
  pSyncNode->pingTimerCounter = 0;
M
Minghao Li 已提交
1122

M
Minghao Li 已提交
1123 1124
  // init elect timer
  pSyncNode->pElectTimer = NULL;
M
Minghao Li 已提交
1125
  pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
M
Minghao Li 已提交
1126 1127
  atomic_store_64(&pSyncNode->electTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->electTimerLogicClockUser, 0);
M
Minghao Li 已提交
1128
  pSyncNode->FpElectTimerCB = syncNodeEqElectTimer;
M
Minghao Li 已提交
1129 1130 1131 1132
  pSyncNode->electTimerCounter = 0;

  // init heartbeat timer
  pSyncNode->pHeartbeatTimer = NULL;
M
Minghao Li 已提交
1133
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
M
Minghao Li 已提交
1134 1135
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, 0);
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClockUser, 0);
M
Minghao Li 已提交
1136
  pSyncNode->FpHeartbeatTimerCB = syncNodeEqHeartbeatTimer;
M
Minghao Li 已提交
1137 1138
  pSyncNode->heartbeatTimerCounter = 0;

M
Minghao Li 已提交
1139
  // init callback
M
Minghao Li 已提交
1140 1141
  pSyncNode->FpOnPing = syncNodeOnPingCb;
  pSyncNode->FpOnPingReply = syncNodeOnPingReplyCb;
M
Minghao Li 已提交
1142
  pSyncNode->FpOnClientRequest = syncNodeOnClientRequestCb;
M
Minghao Li 已提交
1143
  pSyncNode->FpOnTimeout = syncNodeOnTimeoutCb;
M
Minghao Li 已提交
1144

M
Minghao Li 已提交
1145 1146 1147
  pSyncNode->FpOnSnapshotSend = syncNodeOnSnapshotSendCb;
  pSyncNode->FpOnSnapshotRsp = syncNodeOnSnapshotRspCb;

M
Minghao Li 已提交
1148
  if (pSyncNode->pRaftCfg->snapshotStrategy) {
S
Shengliang Guan 已提交
1149
    sInfo("vgId:%d, sync node use snapshot", pSyncNode->vgId);
M
Minghao Li 已提交
1150 1151 1152 1153
    pSyncNode->FpOnRequestVote = syncNodeOnRequestVoteSnapshotCb;
    pSyncNode->FpOnRequestVoteReply = syncNodeOnRequestVoteReplySnapshotCb;
    pSyncNode->FpOnAppendEntries = syncNodeOnAppendEntriesSnapshotCb;
    pSyncNode->FpOnAppendEntriesReply = syncNodeOnAppendEntriesReplySnapshotCb;
M
Minghao Li 已提交
1154 1155

  } else {
S
Shengliang Guan 已提交
1156
    sInfo("vgId:%d, sync node do not use snapshot", pSyncNode->vgId);
M
Minghao Li 已提交
1157 1158 1159 1160
    pSyncNode->FpOnRequestVote = syncNodeOnRequestVoteCb;
    pSyncNode->FpOnRequestVoteReply = syncNodeOnRequestVoteReplyCb;
    pSyncNode->FpOnAppendEntries = syncNodeOnAppendEntriesCb;
    pSyncNode->FpOnAppendEntriesReply = syncNodeOnAppendEntriesReplyCb;
M
Minghao Li 已提交
1161 1162
  }

M
Minghao Li 已提交
1163
  // tools
M
Minghao Li 已提交
1164
  pSyncNode->pSyncRespMgr = syncRespMgrCreate(pSyncNode, SYNC_RESP_TTL_MS);
1165 1166 1167 1168
  if (pSyncNode->pSyncRespMgr == NULL) {
    sError("failed to create SyncRespMgr. vgId:%d", pSyncNode->vgId);
    goto _error;
  }
M
Minghao Li 已提交
1169

1170 1171
  // restore state
  pSyncNode->restoreFinish = false;
1172

M
Minghao Li 已提交
1173 1174 1175 1176 1177 1178 1179 1180
  // snapshot senders
  for (int i = 0; i < TSDB_MAX_REPLICA; ++i) {
    SSyncSnapshotSender* pSender = snapshotSenderCreate(pSyncNode, i);
    // ASSERT(pSender != NULL);
    (pSyncNode->senders)[i] = pSender;
  }

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

M
Minghao Li 已提交
1183 1184 1185
  // is config changing
  pSyncNode->changing = false;

M
Minghao Li 已提交
1186
  // start in syncNodeStart
M
Minghao Li 已提交
1187
  // start raft
M
Minghao Li 已提交
1188
  // syncNodeBecomeFollower(pSyncNode);
M
Minghao Li 已提交
1189

M
Minghao Li 已提交
1190 1191
  int64_t timeNow = taosGetTimestampMs();
  pSyncNode->startTime = timeNow;
1192
  pSyncNode->leaderTime = timeNow;
M
Minghao Li 已提交
1193 1194
  pSyncNode->lastReplicateTime = timeNow;

M
Minghao Li 已提交
1195
  syncNodeEventLog(pSyncNode, "sync open");
1196

M
Minghao Li 已提交
1197
  return pSyncNode;
1198 1199 1200

_error:
  if (pSyncInfo->pFsm) {
H
Hongze Cheng 已提交
1201 1202
    taosMemoryFree(pSyncInfo->pFsm);
    pSyncInfo->pFsm = NULL;
1203 1204 1205 1206
  }
  syncNodeClose(pSyncNode);
  pSyncNode = NULL;
  return NULL;
M
Minghao Li 已提交
1207 1208
}

M
Minghao Li 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
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 已提交
1220 1221
void syncNodeStart(SSyncNode* pSyncNode) {
  // start raft
1222
  if (pSyncNode->replicaNum == 1) {
M
Minghao Li 已提交
1223
    raftStoreNextTerm(pSyncNode->pRaftStore);
1224
    syncNodeBecomeLeader(pSyncNode, "one replica start");
M
format  
Minghao Li 已提交
1225

1226
    // Raft 3.6.2 Committing entries from previous terms
1227 1228
    syncNodeAppendNoop(pSyncNode);
    syncMaybeAdvanceCommitIndex(pSyncNode);
M
Minghao Li 已提交
1229 1230
  } else {
    syncNodeBecomeFollower(pSyncNode, "first start");
1231 1232
  }

1233 1234 1235 1236 1237
  if (pSyncNode->vgId == 1) {
    int32_t ret = 0;
    ret = syncNodeStartPingTimer(pSyncNode);
    ASSERT(ret == 0);
  }
M
Minghao Li 已提交
1238 1239
}

M
Minghao Li 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248
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);
1249 1250 1251 1252 1253 1254

  if (pSyncNode->vgId == 1) {
    int32_t ret = 0;
    ret = syncNodeStartPingTimer(pSyncNode);
    ASSERT(ret == 0);
  }
M
Minghao Li 已提交
1255 1256
}

M
Minghao Li 已提交
1257
void syncNodeClose(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1258
  syncNodeEventLog(pSyncNode, "sync close");
1259 1260 1261
  if (pSyncNode == NULL) {
    return;
  }
M
Minghao Li 已提交
1262 1263 1264
  int32_t ret;

  ret = raftStoreClose(pSyncNode->pRaftStore);
M
Minghao Li 已提交
1265
  ASSERT(ret == 0);
M
Minghao Li 已提交
1266

M
Minghao Li 已提交
1267
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
1268
  pSyncNode->pSyncRespMgr = NULL;
M
Minghao Li 已提交
1269
  voteGrantedDestroy(pSyncNode->pVotesGranted);
1270
  pSyncNode->pVotesGranted = NULL;
M
Minghao Li 已提交
1271
  votesRespondDestory(pSyncNode->pVotesRespond);
1272
  pSyncNode->pVotesRespond = NULL;
M
Minghao Li 已提交
1273
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
1274
  pSyncNode->pNextIndex = NULL;
M
Minghao Li 已提交
1275
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
1276
  pSyncNode->pMatchIndex = NULL;
M
Minghao Li 已提交
1277
  logStoreDestory(pSyncNode->pLogStore);
1278
  pSyncNode->pLogStore = NULL;
M
Minghao Li 已提交
1279
  raftCfgClose(pSyncNode->pRaftCfg);
1280
  pSyncNode->pRaftCfg = NULL;
M
Minghao Li 已提交
1281 1282 1283 1284 1285

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

M
Minghao Li 已提交
1286 1287 1288 1289
  if (pSyncNode->pFsm != NULL) {
    taosMemoryFree(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
1290 1291 1292 1293 1294 1295 1296
  for (int i = 0; i < TSDB_MAX_REPLICA; ++i) {
    if ((pSyncNode->senders)[i] != NULL) {
      snapshotSenderDestroy((pSyncNode->senders)[i]);
      (pSyncNode->senders)[i] = NULL;
    }
  }

M
Minghao Li 已提交
1297 1298 1299 1300 1301
  if (pSyncNode->pNewNodeReceiver != NULL) {
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
    pSyncNode->pNewNodeReceiver = NULL;
  }

1302
  taosMemoryFree(pSyncNode);
M
Minghao Li 已提交
1303 1304
}

M
Minghao Li 已提交
1305
// option
M
Minghao Li 已提交
1306 1307
// bool syncNodeSnapshotEnable(SSyncNode* pSyncNode) { return pSyncNode->pRaftCfg->snapshotEnable; }

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

M
Minghao Li 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
// ping --------------
int32_t syncNodePing(SSyncNode* pSyncNode, const SRaftId* destRaftId, SyncPing* pMsg) {
  syncPingLog2((char*)"==syncNodePing==", pMsg);
  int32_t ret = 0;

  SRpcMsg rpcMsg;
  syncPing2RpcMsg(pMsg, &rpcMsg);
  syncRpcMsgLog2((char*)"==syncNodePing==", &rpcMsg);

  ret = syncNodeSendMsgById(destRaftId, pSyncNode, &rpcMsg);
  return ret;
}

int32_t syncNodePingSelf(SSyncNode* pSyncNode) {
  int32_t   ret = 0;
M
Minghao Li 已提交
1325
  SyncPing* pMsg = syncPingBuild3(&pSyncNode->myRaftId, &pSyncNode->myRaftId, pSyncNode->vgId);
M
Minghao Li 已提交
1326
  ret = syncNodePing(pSyncNode, &pMsg->destId, pMsg);
M
Minghao Li 已提交
1327
  ASSERT(ret == 0);
M
Minghao Li 已提交
1328 1329 1330 1331 1332 1333 1334 1335

  syncPingDestroy(pMsg);
  return ret;
}

int32_t syncNodePingPeers(SSyncNode* pSyncNode) {
  int32_t ret = 0;
  for (int i = 0; i < pSyncNode->peersNum; ++i) {
M
Minghao Li 已提交
1336 1337 1338
    SRaftId*  destId = &(pSyncNode->peersId[i]);
    SyncPing* pMsg = syncPingBuild3(&pSyncNode->myRaftId, destId, pSyncNode->vgId);
    ret = syncNodePing(pSyncNode, destId, pMsg);
M
Minghao Li 已提交
1339
    ASSERT(ret == 0);
M
Minghao Li 已提交
1340 1341 1342 1343 1344 1345 1346
    syncPingDestroy(pMsg);
  }
  return ret;
}

int32_t syncNodePingAll(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1347 1348 1349 1350
  for (int i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
    SRaftId*  destId = &(pSyncNode->replicasId[i]);
    SyncPing* pMsg = syncPingBuild3(&pSyncNode->myRaftId, destId, pSyncNode->vgId);
    ret = syncNodePing(pSyncNode, destId, pMsg);
M
Minghao Li 已提交
1351
    ASSERT(ret == 0);
M
Minghao Li 已提交
1352 1353 1354 1355 1356 1357 1358 1359
    syncPingDestroy(pMsg);
  }
  return ret;
}

// timer control --------------
int32_t syncNodeStartPingTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
1360 1361 1362 1363 1364
  if (syncEnvIsStart()) {
    taosTmrReset(pSyncNode->FpPingTimerCB, pSyncNode->pingTimerMS, pSyncNode, gSyncEnv->pTimerManager,
                 &pSyncNode->pPingTimer);
    atomic_store_64(&pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1365
    sError("vgId:%d, start ping timer error, sync env is stop", pSyncNode->vgId);
1366
  }
M
Minghao Li 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
  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;
1380 1381 1382 1383 1384
  if (syncEnvIsStart()) {
    pSyncNode->electTimerMS = ms;
    taosTmrReset(pSyncNode->FpElectTimerCB, pSyncNode->electTimerMS, pSyncNode, gSyncEnv->pTimerManager,
                 &pSyncNode->pElectTimer);
    atomic_store_64(&pSyncNode->electTimerLogicClock, pSyncNode->electTimerLogicClockUser);
1385 1386 1387 1388 1389 1390 1391

    do {
      char logBuf[128];
      snprintf(logBuf, sizeof(logBuf), "elect timer reset, ms:%d", ms);
      syncNodeEventLog(pSyncNode, logBuf);
    } while (0);

1392
  } else {
M
Minghao Li 已提交
1393
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
1394
  }
M
Minghao Li 已提交
1395 1396 1397 1398 1399 1400 1401 1402
  return ret;
}

int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
  atomic_add_fetch_64(&pSyncNode->electTimerLogicClockUser, 1);
  taosTmrStop(pSyncNode->pElectTimer);
  pSyncNode->pElectTimer = NULL;
1403 1404

  sTrace("vgId:%d, sync %s stop elect timer", pSyncNode->vgId, syncUtilState2String(pSyncNode->state));
M
Minghao Li 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
  return ret;
}

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

M
Minghao Li 已提交
1415 1416
int32_t syncNodeResetElectTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
M
Minghao Li 已提交
1417 1418 1419 1420 1421 1422 1423
  int32_t electMS;

  if (pSyncNode->pRaftCfg->isStandBy) {
    electMS = TIMER_MAX_MS;
  } else {
    electMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
  }
M
Minghao Li 已提交
1424
  ret = syncNodeRestartElectTimer(pSyncNode, electMS);
1425 1426 1427 1428 1429 1430 1431 1432

  do {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine,
             2 * pSyncNode->electBaseLine, electMS);
    syncNodeEventLog(pSyncNode, logBuf);
  } while (0);

M
Minghao Li 已提交
1433 1434 1435
  return ret;
}

M
Minghao Li 已提交
1436
static int32_t syncNodeDoStartHeartbeatTimer(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1437
  int32_t ret = 0;
1438 1439 1440 1441 1442
  if (syncEnvIsStart()) {
    taosTmrReset(pSyncNode->FpHeartbeatTimerCB, pSyncNode->heartbeatTimerMS, pSyncNode, gSyncEnv->pTimerManager,
                 &pSyncNode->pHeartbeatTimer);
    atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
  } else {
M
Minghao Li 已提交
1443
    sError("vgId:%d, start heartbeat timer error, sync env is stop", pSyncNode->vgId);
1444
  }
1445 1446 1447 1448 1449 1450 1451

  do {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
    syncNodeEventLog(pSyncNode, logBuf);
  } while (0);

M
Minghao Li 已提交
1452 1453 1454
  return ret;
}

M
Minghao Li 已提交
1455 1456 1457 1458 1459
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
  int32_t ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
  return ret;
}
1460

M
Minghao Li 已提交
1461 1462 1463
int32_t syncNodeStartHeartbeatTimerMS(SSyncNode* pSyncNode, int32_t ms) {
  pSyncNode->heartbeatTimerMS = ms;
  int32_t ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
1464 1465 1466
  return ret;
}

M
Minghao Li 已提交
1467 1468 1469
int32_t syncNodeStartHeartbeatTimerNow(SSyncNode* pSyncNode) {
  pSyncNode->heartbeatTimerMS = 1;
  int32_t ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
M
Minghao Li 已提交
1470 1471 1472
  return ret;
}

M
Minghao Li 已提交
1473 1474 1475 1476 1477
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
  int32_t ret = 0;
  atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1);
  taosTmrStop(pSyncNode->pHeartbeatTimer);
  pSyncNode->pHeartbeatTimer = NULL;
1478 1479

  sTrace("vgId:%d, sync %s stop heartbeat timer", pSyncNode->vgId, syncUtilState2String(pSyncNode->state));
1480

M
Minghao Li 已提交
1481 1482 1483
  return ret;
}

1484 1485 1486 1487 1488 1489
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode) {
  syncNodeStopHeartbeatTimer(pSyncNode);
  syncNodeStartHeartbeatTimer(pSyncNode);
  return 0;
}

M
Minghao Li 已提交
1490
int32_t syncNodeRestartHeartbeatTimerNow(SSyncNode* pSyncNode) {
1491
  syncNodeStopHeartbeatTimer(pSyncNode);
M
Minghao Li 已提交
1492
  syncNodeStartHeartbeatTimerNow(pSyncNode);
1493 1494 1495
  return 0;
}

M
Minghao Li 已提交
1496 1497 1498 1499 1500 1501
int32_t syncNodeRestartNowHeartbeatTimerMS(SSyncNode* pSyncNode, int32_t ms) {
  syncNodeStopHeartbeatTimer(pSyncNode);
  syncNodeStartHeartbeatTimerMS(pSyncNode, ms);
  return 0;
}

M
Minghao Li 已提交
1502 1503 1504 1505
// utils --------------
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
  syncUtilraftId2EpSet(destRaftId, &epSet);
M
Minghao Li 已提交
1506 1507 1508 1509
  if (pSyncNode->FpSendMsg != NULL) {
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

1510
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1511
    pSyncNode->FpSendMsg(&epSet, pMsg);
M
Minghao Li 已提交
1512
  } else {
M
Minghao Li 已提交
1513 1514
    sError("vgId:%d, sync send msg by id error, fp-send-msg is null", pSyncNode->vgId);
    return -1;
M
Minghao Li 已提交
1515
  }
M
Minghao Li 已提交
1516

M
Minghao Li 已提交
1517 1518 1519 1520 1521 1522
  return 0;
}

int32_t syncNodeSendMsgByInfo(const SNodeInfo* nodeInfo, SSyncNode* pSyncNode, SRpcMsg* pMsg) {
  SEpSet epSet;
  syncUtilnodeInfo2EpSet(nodeInfo, &epSet);
M
Minghao Li 已提交
1523 1524 1525 1526
  if (pSyncNode->FpSendMsg != NULL) {
    // htonl
    syncUtilMsgHtoN(pMsg->pCont);

1527
    pMsg->info.noResp = 1;
S
Shengliang Guan 已提交
1528
    pSyncNode->FpSendMsg(&epSet, pMsg);
M
Minghao Li 已提交
1529
  } else {
M
Minghao Li 已提交
1530
    sError("vgId:%d, sync send msg by info error, fp-send-msg is null", pSyncNode->vgId);
M
Minghao Li 已提交
1531
  }
M
Minghao Li 已提交
1532 1533 1534
  return 0;
}

M
Minghao Li 已提交
1535
cJSON* syncNode2Json(const SSyncNode* pSyncNode) {
C
Cary Xu 已提交
1536
  char   u64buf[128] = {0};
M
Minghao Li 已提交
1537 1538
  cJSON* pRoot = cJSON_CreateObject();

M
Minghao Li 已提交
1539 1540 1541
  if (pSyncNode != NULL) {
    // init by SSyncInfo
    cJSON_AddNumberToObject(pRoot, "vgId", pSyncNode->vgId);
M
Minghao Li 已提交
1542
    cJSON_AddItemToObject(pRoot, "SRaftCfg", raftCfg2Json(pSyncNode->pRaftCfg));
M
Minghao Li 已提交
1543
    cJSON_AddStringToObject(pRoot, "path", pSyncNode->path);
M
Minghao Li 已提交
1544 1545 1546
    cJSON_AddStringToObject(pRoot, "raftStorePath", pSyncNode->raftStorePath);
    cJSON_AddStringToObject(pRoot, "configPath", pSyncNode->configPath);

M
Minghao Li 已提交
1547 1548 1549
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->pWal);
    cJSON_AddStringToObject(pRoot, "pWal", u64buf);

S
Shengliang Guan 已提交
1550
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->msgcb);
M
Minghao Li 已提交
1551 1552 1553 1554
    cJSON_AddStringToObject(pRoot, "rpcClient", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpSendMsg);
    cJSON_AddStringToObject(pRoot, "FpSendMsg", u64buf);

S
Shengliang Guan 已提交
1555
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->msgcb);
M
Minghao Li 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    cJSON_AddStringToObject(pRoot, "queue", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpEqMsg);
    cJSON_AddStringToObject(pRoot, "FpEqMsg", u64buf);

    // init internal
    cJSON* pMe = syncUtilNodeInfo2Json(&pSyncNode->myNodeInfo);
    cJSON_AddItemToObject(pRoot, "myNodeInfo", pMe);
    cJSON* pRaftId = syncUtilRaftId2Json(&pSyncNode->myRaftId);
    cJSON_AddItemToObject(pRoot, "myRaftId", pRaftId);

    cJSON_AddNumberToObject(pRoot, "peersNum", pSyncNode->peersNum);
    cJSON* pPeers = cJSON_CreateArray();
    cJSON_AddItemToObject(pRoot, "peersNodeInfo", pPeers);
    for (int i = 0; i < pSyncNode->peersNum; ++i) {
      cJSON_AddItemToArray(pPeers, syncUtilNodeInfo2Json(&pSyncNode->peersNodeInfo[i]));
    }
    cJSON* pPeersId = cJSON_CreateArray();
    cJSON_AddItemToObject(pRoot, "peersId", pPeersId);
    for (int i = 0; i < pSyncNode->peersNum; ++i) {
      cJSON_AddItemToArray(pPeersId, syncUtilRaftId2Json(&pSyncNode->peersId[i]));
    }
M
Minghao Li 已提交
1577

M
Minghao Li 已提交
1578 1579 1580 1581 1582 1583
    cJSON_AddNumberToObject(pRoot, "replicaNum", pSyncNode->replicaNum);
    cJSON* pReplicasId = cJSON_CreateArray();
    cJSON_AddItemToObject(pRoot, "replicasId", pReplicasId);
    for (int i = 0; i < pSyncNode->replicaNum; ++i) {
      cJSON_AddItemToArray(pReplicasId, syncUtilRaftId2Json(&pSyncNode->replicasId[i]));
    }
M
Minghao Li 已提交
1584

M
Minghao Li 已提交
1585 1586 1587 1588 1589 1590 1591
    // raft algorithm
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->pFsm);
    cJSON_AddStringToObject(pRoot, "pFsm", u64buf);
    cJSON_AddNumberToObject(pRoot, "quorum", pSyncNode->quorum);
    cJSON* pLaderCache = syncUtilRaftId2Json(&pSyncNode->leaderCache);
    cJSON_AddItemToObject(pRoot, "leaderCache", pLaderCache);

M
Minghao Li 已提交
1592
    // life cycle
S
Shengliang Guan 已提交
1593
    snprintf(u64buf, sizeof(u64buf), "%" PRId64, pSyncNode->rid);
M
Minghao Li 已提交
1594 1595
    cJSON_AddStringToObject(pRoot, "rid", u64buf);

M
Minghao Li 已提交
1596 1597 1598
    // tla+ server vars
    cJSON_AddNumberToObject(pRoot, "state", pSyncNode->state);
    cJSON_AddStringToObject(pRoot, "state_str", syncUtilState2String(pSyncNode->state));
M
Minghao Li 已提交
1599
    cJSON_AddItemToObject(pRoot, "pRaftStore", raftStore2Json(pSyncNode->pRaftStore));
M
Minghao Li 已提交
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

    // tla+ candidate vars
    cJSON_AddItemToObject(pRoot, "pVotesGranted", voteGranted2Json(pSyncNode->pVotesGranted));
    cJSON_AddItemToObject(pRoot, "pVotesRespond", votesRespond2Json(pSyncNode->pVotesRespond));

    // tla+ leader vars
    cJSON_AddItemToObject(pRoot, "pNextIndex", syncIndexMgr2Json(pSyncNode->pNextIndex));
    cJSON_AddItemToObject(pRoot, "pMatchIndex", syncIndexMgr2Json(pSyncNode->pMatchIndex));

    // tla+ log vars
    cJSON_AddItemToObject(pRoot, "pLogStore", logStore2Json(pSyncNode->pLogStore));
S
Shengliang Guan 已提交
1611
    snprintf(u64buf, sizeof(u64buf), "%" PRId64, pSyncNode->commitIndex);
M
Minghao Li 已提交
1612 1613
    cJSON_AddStringToObject(pRoot, "commitIndex", u64buf);

M
Minghao Li 已提交
1614 1615 1616 1617 1618
    // timer ms init
    cJSON_AddNumberToObject(pRoot, "pingBaseLine", pSyncNode->pingBaseLine);
    cJSON_AddNumberToObject(pRoot, "electBaseLine", pSyncNode->electBaseLine);
    cJSON_AddNumberToObject(pRoot, "hbBaseLine", pSyncNode->hbBaseLine);

M
Minghao Li 已提交
1619 1620 1621 1622
    // ping timer
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->pPingTimer);
    cJSON_AddStringToObject(pRoot, "pPingTimer", u64buf);
    cJSON_AddNumberToObject(pRoot, "pingTimerMS", pSyncNode->pingTimerMS);
S
Shengliang Guan 已提交
1623
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->pingTimerLogicClock);
M
Minghao Li 已提交
1624
    cJSON_AddStringToObject(pRoot, "pingTimerLogicClock", u64buf);
S
Shengliang Guan 已提交
1625
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->pingTimerLogicClockUser);
M
Minghao Li 已提交
1626 1627 1628
    cJSON_AddStringToObject(pRoot, "pingTimerLogicClockUser", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpPingTimerCB);
    cJSON_AddStringToObject(pRoot, "FpPingTimerCB", u64buf);
S
Shengliang Guan 已提交
1629
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->pingTimerCounter);
M
Minghao Li 已提交
1630 1631 1632 1633 1634 1635
    cJSON_AddStringToObject(pRoot, "pingTimerCounter", u64buf);

    // elect timer
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->pElectTimer);
    cJSON_AddStringToObject(pRoot, "pElectTimer", u64buf);
    cJSON_AddNumberToObject(pRoot, "electTimerMS", pSyncNode->electTimerMS);
S
Shengliang Guan 已提交
1636
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->electTimerLogicClock);
M
Minghao Li 已提交
1637
    cJSON_AddStringToObject(pRoot, "electTimerLogicClock", u64buf);
S
Shengliang Guan 已提交
1638
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->electTimerLogicClockUser);
M
Minghao Li 已提交
1639 1640 1641
    cJSON_AddStringToObject(pRoot, "electTimerLogicClockUser", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpElectTimerCB);
    cJSON_AddStringToObject(pRoot, "FpElectTimerCB", u64buf);
S
Shengliang Guan 已提交
1642
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->electTimerCounter);
M
Minghao Li 已提交
1643 1644 1645 1646 1647 1648
    cJSON_AddStringToObject(pRoot, "electTimerCounter", u64buf);

    // heartbeat timer
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->pHeartbeatTimer);
    cJSON_AddStringToObject(pRoot, "pHeartbeatTimer", u64buf);
    cJSON_AddNumberToObject(pRoot, "heartbeatTimerMS", pSyncNode->heartbeatTimerMS);
S
Shengliang Guan 已提交
1649
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->heartbeatTimerLogicClock);
M
Minghao Li 已提交
1650
    cJSON_AddStringToObject(pRoot, "heartbeatTimerLogicClock", u64buf);
S
Shengliang Guan 已提交
1651
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->heartbeatTimerLogicClockUser);
M
Minghao Li 已提交
1652 1653 1654
    cJSON_AddStringToObject(pRoot, "heartbeatTimerLogicClockUser", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpHeartbeatTimerCB);
    cJSON_AddStringToObject(pRoot, "FpHeartbeatTimerCB", u64buf);
S
Shengliang Guan 已提交
1655
    snprintf(u64buf, sizeof(u64buf), "%" PRIu64, pSyncNode->heartbeatTimerCounter);
M
Minghao Li 已提交
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
    cJSON_AddStringToObject(pRoot, "heartbeatTimerCounter", u64buf);

    // callback
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpOnPing);
    cJSON_AddStringToObject(pRoot, "FpOnPing", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpOnPingReply);
    cJSON_AddStringToObject(pRoot, "FpOnPingReply", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpOnRequestVote);
    cJSON_AddStringToObject(pRoot, "FpOnRequestVote", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpOnRequestVoteReply);
    cJSON_AddStringToObject(pRoot, "FpOnRequestVoteReply", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpOnAppendEntries);
    cJSON_AddStringToObject(pRoot, "FpOnAppendEntries", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpOnAppendEntriesReply);
    cJSON_AddStringToObject(pRoot, "FpOnAppendEntriesReply", u64buf);
    snprintf(u64buf, sizeof(u64buf), "%p", pSyncNode->FpOnTimeout);
    cJSON_AddStringToObject(pRoot, "FpOnTimeout", u64buf);
M
Minghao Li 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685

    // restoreFinish
    cJSON_AddNumberToObject(pRoot, "restoreFinish", pSyncNode->restoreFinish);

    // snapshot senders
    cJSON* pSenders = cJSON_CreateArray();
    cJSON_AddItemToObject(pRoot, "senders", pSenders);
    for (int i = 0; i < TSDB_MAX_REPLICA; ++i) {
      cJSON_AddItemToArray(pSenders, snapshotSender2Json((pSyncNode->senders)[i]));
    }

    // snapshot receivers
    cJSON* pReceivers = cJSON_CreateArray();
1686
    cJSON_AddItemToObject(pRoot, "receiver", snapshotReceiver2Json(pSyncNode->pNewNodeReceiver));
M
Minghao Li 已提交
1687 1688 1689

    // changing
    cJSON_AddNumberToObject(pRoot, "changing", pSyncNode->changing);
M
Minghao Li 已提交
1690 1691 1692 1693 1694 1695 1696
  }

  cJSON* pJson = cJSON_CreateObject();
  cJSON_AddItemToObject(pJson, "SSyncNode", pRoot);
  return pJson;
}

M
Minghao Li 已提交
1697 1698 1699 1700 1701 1702 1703
char* syncNode2Str(const SSyncNode* pSyncNode) {
  cJSON* pJson = syncNode2Json(pSyncNode);
  char*  serialized = cJSON_Print(pJson);
  cJSON_Delete(pJson);
  return serialized;
}

1704
inline void syncNodeEventLog(const SSyncNode* pSyncNode, char* str) {
M
Minghao Li 已提交
1705
  int32_t userStrLen = strlen(str);
M
Minghao Li 已提交
1706 1707

  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0};
M
Minghao Li 已提交
1708
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
M
Minghao Li 已提交
1709 1710
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
  }
M
Minghao Li 已提交
1711 1712 1713 1714 1715 1716 1717

  SyncIndex logLastIndex = SYNC_INDEX_INVALID;
  SyncIndex logBeginIndex = SYNC_INDEX_INVALID;
  if (pSyncNode->pLogStore != NULL) {
    logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
    logBeginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
  }
M
Minghao Li 已提交
1718

M
Minghao Li 已提交
1719
  char* pCfgStr = syncCfg2SimpleStr(&(pSyncNode->pRaftCfg->cfg));
1720 1721 1722 1723
  char* printStr = "";
  if (pCfgStr != NULL) {
    printStr = pCfgStr;
  }
M
Minghao Li 已提交
1724

M
Minghao Li 已提交
1725
  if (userStrLen < 256) {
M
Minghao Li 已提交
1726
    char logBuf[256 + 256];
1727 1728
    if (pSyncNode != NULL && pSyncNode->pRaftCfg != NULL && pSyncNode->pRaftStore != NULL) {
      snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
1729 1730 1731 1732 1733
               "vgId:%d, sync %s %s, tm:%" PRIu64 ", cmt:%" PRId64 ", fst:%" PRId64 ", lst:%" PRId64 ", snap:%" PRId64
               ", snap-tm:%" PRIu64
               ", sby:%d, "
               "stgy:%d, bch:%d, "
               "r-num:%d, "
1734
               "lcfg:%" PRId64 ", chging:%d, rsto:%d, dquorum:%d, elt:%" PRId64 ", hb:%" PRId64 ", %s",
1735
               pSyncNode->vgId, syncUtilState2String(pSyncNode->state), str, pSyncNode->pRaftStore->currentTerm,
M
Minghao Li 已提交
1736
               pSyncNode->commitIndex, logBeginIndex, logLastIndex, snapshot.lastApplyIndex, snapshot.lastApplyTerm,
1737 1738
               pSyncNode->pRaftCfg->isStandBy, pSyncNode->pRaftCfg->snapshotStrategy, pSyncNode->pRaftCfg->batchSize,
               pSyncNode->replicaNum, pSyncNode->pRaftCfg->lastConfigIndex, pSyncNode->changing,
1739 1740
               pSyncNode->restoreFinish, syncNodeDynamicQuorum(pSyncNode), pSyncNode->electTimerLogicClockUser,
               pSyncNode->heartbeatTimerLogicClockUser, printStr);
1741 1742 1743
    } else {
      snprintf(logBuf, sizeof(logBuf), "%s", str);
    }
1744
    // sDebug("%s", logBuf);
M
Minghao Li 已提交
1745 1746
    // sInfo("%s", logBuf);
    sTrace("%s", logBuf);
M
Minghao Li 已提交
1747

M
Minghao Li 已提交
1748
  } else {
M
Minghao Li 已提交
1749
    int   len = 256 + userStrLen;
M
Minghao Li 已提交
1750
    char* s = (char*)taosMemoryMalloc(len);
1751 1752
    if (pSyncNode != NULL && pSyncNode->pRaftCfg != NULL && pSyncNode->pRaftStore != NULL) {
      snprintf(s, len,
M
Minghao Li 已提交
1753 1754 1755 1756 1757
               "vgId:%d, sync %s %s, tm:%" PRIu64 ", cmt:%" PRId64 ", fst:%" PRId64 ", lst:%" PRId64 ", snap:%" PRId64
               ", snap-tm:%" PRIu64
               ", sby:%d, "
               "stgy:%d, bch:%d, "
               "r-num:%d, "
1758
               "lcfg:%" PRId64 ", chging:%d, rsto:%d, dquorum:%d, elt:%" PRId64 ", hb:%" PRId64 ", %s",
1759
               pSyncNode->vgId, syncUtilState2String(pSyncNode->state), str, pSyncNode->pRaftStore->currentTerm,
M
Minghao Li 已提交
1760
               pSyncNode->commitIndex, logBeginIndex, logLastIndex, snapshot.lastApplyIndex, snapshot.lastApplyTerm,
1761 1762
               pSyncNode->pRaftCfg->isStandBy, pSyncNode->pRaftCfg->snapshotStrategy, pSyncNode->pRaftCfg->batchSize,
               pSyncNode->replicaNum, pSyncNode->pRaftCfg->lastConfigIndex, pSyncNode->changing,
1763 1764
               pSyncNode->restoreFinish, syncNodeDynamicQuorum(pSyncNode), pSyncNode->electTimerLogicClockUser,
               pSyncNode->heartbeatTimerLogicClockUser, printStr);
1765 1766 1767
    } else {
      snprintf(s, len, "%s", str);
    }
1768
    // sDebug("%s", s);
M
Minghao Li 已提交
1769 1770
    // sInfo("%s", s);
    sTrace("%s", s);
M
Minghao Li 已提交
1771 1772
    taosMemoryFree(s);
  }
M
Minghao Li 已提交
1773 1774

  taosMemoryFree(pCfgStr);
M
Minghao Li 已提交
1775 1776
}

1777
inline void syncNodeErrorLog(const SSyncNode* pSyncNode, char* str) {
M
Minghao Li 已提交
1778 1779 1780
  int32_t userStrLen = strlen(str);

  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0};
M
Minghao Li 已提交
1781
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
M
Minghao Li 已提交
1782 1783
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
  }
M
Minghao Li 已提交
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796

  SyncIndex logLastIndex = SYNC_INDEX_INVALID;
  SyncIndex logBeginIndex = SYNC_INDEX_INVALID;
  if (pSyncNode->pLogStore != NULL) {
    logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
    logBeginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
  }

  char* pCfgStr = syncCfg2SimpleStr(&(pSyncNode->pRaftCfg->cfg));
  char* printStr = "";
  if (pCfgStr != NULL) {
    printStr = pCfgStr;
  }
M
Minghao Li 已提交
1797 1798

  if (userStrLen < 256) {
M
Minghao Li 已提交
1799
    char logBuf[256 + 256];
1800 1801
    if (pSyncNode != NULL && pSyncNode->pRaftCfg != NULL && pSyncNode->pRaftStore != NULL) {
      snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
1802 1803 1804 1805 1806 1807
               "vgId:%d, sync %s %s, tm:%" PRIu64 ", cmt:%" PRId64 ", fst:%" PRId64 ", lst:%" PRId64 ", snap:%" PRId64
               ", snap-tm:%" PRIu64
               ", sby:%d, "
               "stgy:%d, bch:%d, "
               "r-num:%d, "
               "lcfg:%" PRId64 ", chging:%d, rsto:%d, %s",
1808
               pSyncNode->vgId, syncUtilState2String(pSyncNode->state), str, pSyncNode->pRaftStore->currentTerm,
M
Minghao Li 已提交
1809 1810 1811 1812
               pSyncNode->commitIndex, logBeginIndex, logLastIndex, snapshot.lastApplyIndex, snapshot.lastApplyTerm,
               pSyncNode->pRaftCfg->isStandBy, pSyncNode->pRaftCfg->snapshotStrategy, pSyncNode->pRaftCfg->batchSize,
               pSyncNode->replicaNum, pSyncNode->pRaftCfg->lastConfigIndex, pSyncNode->changing,
               pSyncNode->restoreFinish, printStr);
1813 1814 1815
    } else {
      snprintf(logBuf, sizeof(logBuf), "%s", str);
    }
M
Minghao Li 已提交
1816 1817 1818
    sError("%s", logBuf);

  } else {
M
Minghao Li 已提交
1819
    int   len = 256 + userStrLen;
M
Minghao Li 已提交
1820
    char* s = (char*)taosMemoryMalloc(len);
1821 1822
    if (pSyncNode != NULL && pSyncNode->pRaftCfg != NULL && pSyncNode->pRaftStore != NULL) {
      snprintf(s, len,
M
Minghao Li 已提交
1823 1824 1825 1826 1827 1828
               "vgId:%d, sync %s %s, tm:%" PRIu64 ", cmt:%" PRId64 ", fst:%" PRId64 ", lst:%" PRId64 ", snap:%" PRId64
               ", snap-tm:%" PRIu64
               ", sby:%d, "
               "stgy:%d, bch:%d, "
               "r-num:%d, "
               "lcfg:%" PRId64 ", chging:%d, rsto:%d, %s",
1829
               pSyncNode->vgId, syncUtilState2String(pSyncNode->state), str, pSyncNode->pRaftStore->currentTerm,
M
Minghao Li 已提交
1830 1831 1832 1833
               pSyncNode->commitIndex, logBeginIndex, logLastIndex, snapshot.lastApplyIndex, snapshot.lastApplyTerm,
               pSyncNode->pRaftCfg->isStandBy, pSyncNode->pRaftCfg->snapshotStrategy, pSyncNode->pRaftCfg->batchSize,
               pSyncNode->replicaNum, pSyncNode->pRaftCfg->lastConfigIndex, pSyncNode->changing,
               pSyncNode->restoreFinish, printStr);
1834 1835 1836
    } else {
      snprintf(s, len, "%s", str);
    }
M
Minghao Li 已提交
1837 1838 1839
    sError("%s", s);
    taosMemoryFree(s);
  }
M
Minghao Li 已提交
1840 1841

  taosMemoryFree(pCfgStr);
M
Minghao Li 已提交
1842 1843
}

1844
inline char* syncNode2SimpleStr(const SSyncNode* pSyncNode) {
M
Minghao Li 已提交
1845 1846
  int   len = 256;
  char* s = (char*)taosMemoryMalloc(len);
M
Minghao Li 已提交
1847 1848 1849 1850 1851 1852 1853 1854

  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0};
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
  }
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
  SyncIndex logBeginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);

M
Minghao Li 已提交
1855
  snprintf(s, len,
M
Minghao Li 已提交
1856 1857 1858 1859
           "vgId:%d, sync %s, tm:%" PRIu64 ", cmt:%" PRId64 ", fst:%" PRId64 ", lst:%" PRId64 ", snap:%" PRId64
           ", sby:%d, "
           "r-num:%d, "
           "lcfg:%" PRId64 ", chging:%d, rsto:%d",
M
Minghao Li 已提交
1860 1861 1862 1863
           pSyncNode->vgId, syncUtilState2String(pSyncNode->state), pSyncNode->pRaftStore->currentTerm,
           pSyncNode->commitIndex, logBeginIndex, logLastIndex, snapshot.lastApplyIndex, pSyncNode->pRaftCfg->isStandBy,
           pSyncNode->replicaNum, pSyncNode->pRaftCfg->lastConfigIndex, pSyncNode->changing, pSyncNode->restoreFinish);

M
Minghao Li 已提交
1864 1865 1866
  return s;
}

1867
inline bool syncNodeInConfig(SSyncNode* pSyncNode, const SSyncCfg* config) {
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
  bool b1 = false;
  bool b2 = false;

  for (int i = 0; i < config->replicaNum; ++i) {
    if (strcmp((config->nodeInfo)[i].nodeFqdn, pSyncNode->myNodeInfo.nodeFqdn) == 0 &&
        (config->nodeInfo)[i].nodePort == pSyncNode->myNodeInfo.nodePort) {
      b1 = true;
      break;
    }
  }

  for (int i = 0; i < config->replicaNum; ++i) {
    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;
}

1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
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 已提交
1907
void syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncIndex lastConfigChangeIndex) {
1908
  SSyncCfg oldConfig = pSyncNode->pRaftCfg->cfg;
1909 1910 1911 1912 1913
  if (!syncIsConfigChanged(&oldConfig, pNewConfig)) {
    sInfo("vgId:1, sync not reconfig since not changed");
    return;
  }

1914
  pSyncNode->pRaftCfg->cfg = *pNewConfig;
1915 1916
  pSyncNode->pRaftCfg->lastConfigIndex = lastConfigChangeIndex;

M
Minghao Li 已提交
1917 1918
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
M
Minghao Li 已提交
1919

M
Minghao Li 已提交
1920 1921
  bool isDrop = false;
  bool isAdd = false;
M
Minghao Li 已提交
1922

M
Minghao Li 已提交
1923 1924 1925 1926
  if (IamInOld && !IamInNew) {
    isDrop = true;
  } else {
    isDrop = false;
1927
  }
1928

M
Minghao Li 已提交
1929 1930 1931 1932 1933
  if (!IamInOld && IamInNew) {
    isAdd = true;
  } else {
    isAdd = false;
  }
M
Minghao Li 已提交
1934

M
Minghao Li 已提交
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
  // log begin config change
  do {
    char  eventLog[256];
    char* pOldCfgStr = syncCfg2SimpleStr(&oldConfig);
    char* pNewCfgStr = syncCfg2SimpleStr(pNewConfig);
    snprintf(eventLog, sizeof(eventLog), "begin do config change, from %s to %s", pOldCfgStr, pNewCfgStr);
    syncNodeEventLog(pSyncNode, eventLog);
    taosMemoryFree(pOldCfgStr);
    taosMemoryFree(pNewCfgStr);
  } while (0);

M
Minghao Li 已提交
1946 1947
  if (IamInNew) {
    pSyncNode->pRaftCfg->isStandBy = 0;  // change isStandBy to normal
M
Minghao Li 已提交
1948
  }
M
Minghao Li 已提交
1949 1950
  if (isDrop) {
    pSyncNode->pRaftCfg->isStandBy = 1;  // set standby
M
Minghao Li 已提交
1951 1952
  }

M
Minghao Li 已提交
1953
  // add last config index
M
Minghao Li 已提交
1954
  raftCfgAddConfigIndex(pSyncNode->pRaftCfg, lastConfigChangeIndex);
M
Minghao Li 已提交
1955

M
Minghao Li 已提交
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
  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];
    for (int i = 0; i < TSDB_MAX_REPLICA; ++i) {
      oldSenders[i] = (pSyncNode->senders)[i];
M
Minghao Li 已提交
1967

M
Minghao Li 已提交
1968 1969 1970 1971
      char* eventLog = snapshotSender2SimpleStr(oldSenders[i], "snapshot sender save old");
      syncNodeEventLog(pSyncNode, eventLog);
      taosMemoryFree(eventLog);
    }
1972

M
Minghao Li 已提交
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    // init internal
    pSyncNode->myNodeInfo = pSyncNode->pRaftCfg->cfg.nodeInfo[pSyncNode->pRaftCfg->cfg.myIndex];
    syncUtilnodeInfo2raftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId);

    // init peersNum, peers, peersId
    pSyncNode->peersNum = pSyncNode->pRaftCfg->cfg.replicaNum - 1;
    int j = 0;
    for (int i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
      if (i != pSyncNode->pRaftCfg->cfg.myIndex) {
        pSyncNode->peersNodeInfo[j] = pSyncNode->pRaftCfg->cfg.nodeInfo[i];
        j++;
      }
    }
    for (int i = 0; i < pSyncNode->peersNum; ++i) {
      syncUtilnodeInfo2raftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]);
    }
1989

M
Minghao Li 已提交
1990 1991 1992 1993 1994
    // init replicaNum, replicasId
    pSyncNode->replicaNum = pSyncNode->pRaftCfg->cfg.replicaNum;
    for (int i = 0; i < pSyncNode->pRaftCfg->cfg.replicaNum; ++i) {
      syncUtilnodeInfo2raftId(&pSyncNode->pRaftCfg->cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]);
    }
1995

M
Minghao Li 已提交
1996 1997 1998 1999
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
M
Minghao Li 已提交
2000

M
Minghao Li 已提交
2001
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->pRaftCfg->cfg.replicaNum);
M
Minghao Li 已提交
2002

M
Minghao Li 已提交
2003
    // reset snapshot senders
2004

M
Minghao Li 已提交
2005 2006 2007 2008
    // clear new
    for (int i = 0; i < TSDB_MAX_REPLICA; ++i) {
      (pSyncNode->senders)[i] = NULL;
    }
M
Minghao Li 已提交
2009

M
Minghao Li 已提交
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
    // reset new
    for (int i = 0; i < pSyncNode->replicaNum; ++i) {
      // reset sender
      bool reset = false;
      for (int j = 0; j < TSDB_MAX_REPLICA; ++j) {
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j])) {
          char     host[128];
          uint16_t port;
          syncUtilU642Addr((pSyncNode->replicasId)[i].addr, host, sizeof(host), &port);

          do {
            char eventLog[256];
S
Shengliang Guan 已提交
2022
            snprintf(eventLog, sizeof(eventLog), "snapshot sender reset for: %" PRIu64 ", newIndex:%d, %s:%d, %p",
M
Minghao Li 已提交
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
                     (pSyncNode->replicasId)[i].addr, i, host, port, oldSenders[j]);
            syncNodeEventLog(pSyncNode, eventLog);
          } while (0);

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

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

          do {
            char eventLog[256];
            snprintf(eventLog, sizeof(eventLog),
                     "snapshot sender udpate replicaIndex from %d to %d, %s:%d, %p, reset:%d", oldreplicaIndex, i, host,
                     port, (pSyncNode->senders)[i], reset);
            syncNodeEventLog(pSyncNode, eventLog);
          } while (0);
        }
2043 2044
      }
    }
2045

M
Minghao Li 已提交
2046 2047 2048 2049
    // create new
    for (int i = 0; i < TSDB_MAX_REPLICA; ++i) {
      if ((pSyncNode->senders)[i] == NULL) {
        (pSyncNode->senders)[i] = snapshotSenderCreate(pSyncNode, i);
M
Minghao Li 已提交
2050

M
Minghao Li 已提交
2051 2052 2053 2054
        char* eventLog = snapshotSender2SimpleStr((pSyncNode->senders)[i], "snapshot sender create new");
        syncNodeEventLog(pSyncNode, eventLog);
        taosMemoryFree(eventLog);
      }
2055 2056
    }

M
Minghao Li 已提交
2057 2058 2059 2060
    // free old
    for (int i = 0; i < TSDB_MAX_REPLICA; ++i) {
      if (oldSenders[i] != NULL) {
        snapshotSenderDestroy(oldSenders[i]);
M
Minghao Li 已提交
2061

M
Minghao Li 已提交
2062 2063 2064 2065 2066
        do {
          char eventLog[128];
          snprintf(eventLog, sizeof(eventLog), "snapshot sender delete old %p replica-index:%d", oldSenders[i], i);
          syncNodeEventLog(pSyncNode, eventLog);
        } while (0);
M
Minghao Li 已提交
2067

M
Minghao Li 已提交
2068 2069
        oldSenders[i] = NULL;
      }
2070 2071
    }

2072
    // persist cfg
M
Minghao Li 已提交
2073
    raftCfgPersist(pSyncNode->pRaftCfg);
2074

M
Minghao Li 已提交
2075 2076 2077
    char  tmpbuf[512];
    char* oldStr = syncCfg2SimpleStr(&oldConfig);
    char* newStr = syncCfg2SimpleStr(pNewConfig);
2078 2079
    snprintf(tmpbuf, sizeof(tmpbuf), "config change from %d to %d, index:%" PRId64 ", %s  -->  %s",
             oldConfig.replicaNum, pNewConfig->replicaNum, lastConfigChangeIndex, oldStr, newStr);
M
Minghao Li 已提交
2080 2081
    taosMemoryFree(oldStr);
    taosMemoryFree(newStr);
M
Minghao Li 已提交
2082

M
Minghao Li 已提交
2083 2084 2085
    // change isStandBy to normal (election timeout)
    if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
      syncNodeBecomeLeader(pSyncNode, tmpbuf);
2086 2087 2088 2089 2090

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

M
Minghao Li 已提交
2091 2092 2093 2094
    } else {
      syncNodeBecomeFollower(pSyncNode, tmpbuf);
    }
  } else {
2095
    // persist cfg
M
Minghao Li 已提交
2096
    raftCfgPersist(pSyncNode->pRaftCfg);
2097

M
Minghao Li 已提交
2098 2099 2100
    char  tmpbuf[512];
    char* oldStr = syncCfg2SimpleStr(&oldConfig);
    char* newStr = syncCfg2SimpleStr(pNewConfig);
2101 2102
    snprintf(tmpbuf, sizeof(tmpbuf), "do not config change from %d to %d, index:%" PRId64 ", %s  -->  %s",
             oldConfig.replicaNum, pNewConfig->replicaNum, lastConfigChangeIndex, oldStr, newStr);
M
Minghao Li 已提交
2103 2104 2105
    taosMemoryFree(oldStr);
    taosMemoryFree(newStr);
    syncNodeEventLog(pSyncNode, tmpbuf);
2106
  }
2107

M
Minghao Li 已提交
2108
_END:
M
Minghao Li 已提交
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119

  // log end config change
  do {
    char  eventLog[256];
    char* pOldCfgStr = syncCfg2SimpleStr(&oldConfig);
    char* pNewCfgStr = syncCfg2SimpleStr(pNewConfig);
    snprintf(eventLog, sizeof(eventLog), "end do config change, from %s to %s", pOldCfgStr, pNewCfgStr);
    syncNodeEventLog(pSyncNode, eventLog);
    taosMemoryFree(pOldCfgStr);
    taosMemoryFree(pNewCfgStr);
  } while (0);
M
Minghao Li 已提交
2120
  return;
M
Minghao Li 已提交
2121 2122
}

M
Minghao Li 已提交
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
SSyncNode* syncNodeAcquire(int64_t rid) {
  SSyncNode* pNode = taosAcquireRef(tsNodeRefId, rid);
  if (pNode == NULL) {
    sTrace("failed to acquire node from refId:%" PRId64, rid);
  }

  return pNode;
}

void syncNodeRelease(SSyncNode* pNode) { taosReleaseRef(tsNodeRefId, pNode->rid); }

M
Minghao Li 已提交
2134 2135 2136 2137
// raft state change --------------
void syncNodeUpdateTerm(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
2138
    char tmpBuf[64];
S
Shengliang Guan 已提交
2139
    snprintf(tmpBuf, sizeof(tmpBuf), "update term to %" PRIu64, term);
2140
    syncNodeBecomeFollower(pSyncNode, tmpBuf);
M
Minghao Li 已提交
2141 2142 2143 2144
    raftStoreClearVote(pSyncNode->pRaftStore);
  }
}

2145 2146 2147 2148 2149 2150
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
  if (term > pSyncNode->pRaftStore->currentTerm) {
    raftStoreSetTerm(pSyncNode->pRaftStore, term);
  }
}

2151 2152
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }

2153
void syncNodeBecomeFollower(SSyncNode* pSyncNode, const char* debugStr) {
M
Minghao Li 已提交
2154
  // maybe clear leader cache
M
Minghao Li 已提交
2155 2156 2157 2158
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
  }

M
Minghao Li 已提交
2159
  // state change
M
Minghao Li 已提交
2160 2161 2162
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
  syncNodeStopHeartbeatTimer(pSyncNode);

M
Minghao Li 已提交
2163 2164
  // reset elect timer
  syncNodeResetElectTimer(pSyncNode);
M
Minghao Li 已提交
2165

2166 2167 2168
  // send rsp to client
  syncNodeLeaderChangeRsp(pSyncNode);

2169 2170 2171 2172 2173
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
  // trace log
  do {
    int32_t debugStrLen = strlen(debugStr);
    if (debugStrLen < 256) {
      char eventLog[256 + 64];
      snprintf(eventLog, sizeof(eventLog), "become follower %s", debugStr);
      syncNodeEventLog(pSyncNode, eventLog);
    } else {
      char* eventLog = taosMemoryMalloc(debugStrLen + 64);
      snprintf(eventLog, debugStrLen, "become follower %s", debugStr);
      syncNodeEventLog(pSyncNode, eventLog);
      taosMemoryFree(eventLog);
    }
  } while (0);
M
Minghao Li 已提交
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
}

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

2211 2212 2213
  // reset restoreFinish
  pSyncNode->restoreFinish = false;

M
Minghao Li 已提交
2214
  // state change
M
Minghao Li 已提交
2215
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
M
Minghao Li 已提交
2216 2217

  // set leader cache
M
Minghao Li 已提交
2218 2219 2220
  pSyncNode->leaderCache = pSyncNode->myRaftId;

  for (int i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
M
Minghao Li 已提交
2221 2222
    // maybe overwrite myself, no harm
    // just do it!
2223 2224 2225 2226 2227 2228 2229 2230 2231

    // 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 已提交
2232 2233 2234
  }

  for (int i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
M
Minghao Li 已提交
2235 2236
    // maybe overwrite myself, no harm
    // just do it!
M
Minghao Li 已提交
2237 2238 2239
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
  }

2240 2241
  // update sender private term
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
2242 2243 2244 2245 2246
  if (pMySender != NULL) {
    for (int i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
      if ((pSyncNode->senders)[i]->privateTerm > pMySender->privateTerm) {
        pMySender->privateTerm = (pSyncNode->senders)[i]->privateTerm;
      }
2247
    }
2248
    (pMySender->privateTerm) += 100;
2249 2250
  }

2251 2252 2253 2254 2255
  // close receiver
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
    snapshotReceiverForceStop(pSyncNode->pNewNodeReceiver);
  }

M
Minghao Li 已提交
2256
  // stop elect timer
M
Minghao Li 已提交
2257
  syncNodeStopElectTimer(pSyncNode);
M
Minghao Li 已提交
2258

M
Minghao Li 已提交
2259 2260
  // start heartbeat timer
  syncNodeStartHeartbeatTimer(pSyncNode);
M
Minghao Li 已提交
2261

2262 2263 2264 2265 2266
  // call back
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
  }

M
Minghao Li 已提交
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
  // trace log
  do {
    int32_t debugStrLen = strlen(debugStr);
    if (debugStrLen < 256) {
      char eventLog[256 + 64];
      snprintf(eventLog, sizeof(eventLog), "become leader %s", debugStr);
      syncNodeEventLog(pSyncNode, eventLog);
    } else {
      char* eventLog = taosMemoryMalloc(debugStrLen + 64);
      snprintf(eventLog, debugStrLen, "become leader %s", debugStr);
      syncNodeEventLog(pSyncNode, eventLog);
      taosMemoryFree(eventLog);
    }
  } while (0);
M
Minghao Li 已提交
2281 2282 2283
}

void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
2284
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
2285
  // ASSERT(voteGrantedMajority(pSyncNode->pVotesGranted));
2286
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");
M
Minghao Li 已提交
2287

M
Minghao Li 已提交
2288 2289
  syncNodeLog2("==state change syncNodeCandidate2Leader==", pSyncNode);

M
Minghao Li 已提交
2290
  // Raft 3.6.2 Committing entries from previous terms
2291 2292
  syncNodeAppendNoop(pSyncNode);
  syncMaybeAdvanceCommitIndex(pSyncNode);
M
Minghao Li 已提交
2293 2294 2295
}

void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
2296
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_FOLLOWER);
M
Minghao Li 已提交
2297
  pSyncNode->state = TAOS_SYNC_STATE_CANDIDATE;
M
Minghao Li 已提交
2298

M
Minghao Li 已提交
2299
  syncNodeEventLog(pSyncNode, "follower to candidate");
M
Minghao Li 已提交
2300 2301 2302
}

void syncNodeLeader2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
2303
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_LEADER);
2304
  syncNodeBecomeFollower(pSyncNode, "leader to follower");
M
Minghao Li 已提交
2305

M
Minghao Li 已提交
2306
  syncNodeEventLog(pSyncNode, "leader to follower");
M
Minghao Li 已提交
2307 2308 2309
}

void syncNodeCandidate2Follower(SSyncNode* pSyncNode) {
M
Minghao Li 已提交
2310
  ASSERT(pSyncNode->state == TAOS_SYNC_STATE_CANDIDATE);
2311
  syncNodeBecomeFollower(pSyncNode, "candidate to follower");
M
Minghao Li 已提交
2312

M
Minghao Li 已提交
2313
  syncNodeEventLog(pSyncNode, "candidate to follower");
M
Minghao Li 已提交
2314 2315 2316
}

// raft vote --------------
M
Minghao Li 已提交
2317 2318 2319

// just called by syncNodeVoteForSelf
// need assert
M
Minghao Li 已提交
2320
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
M
Minghao Li 已提交
2321 2322
  ASSERT(term == pSyncNode->pRaftStore->currentTerm);
  ASSERT(!raftStoreHasVoted(pSyncNode->pRaftStore));
M
Minghao Li 已提交
2323 2324 2325 2326

  raftStoreVote(pSyncNode->pRaftStore, pRaftId);
}

M
Minghao Li 已提交
2327
// simulate get vote from outside
M
Minghao Li 已提交
2328 2329 2330
void syncNodeVoteForSelf(SSyncNode* pSyncNode) {
  syncNodeVoteForTerm(pSyncNode, pSyncNode->pRaftStore->currentTerm, &(pSyncNode->myRaftId));

M
Minghao Li 已提交
2331
  SyncRequestVoteReply* pMsg = syncRequestVoteReplyBuild(pSyncNode->vgId);
M
Minghao Li 已提交
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
  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 已提交
2342
// snapshot --------------
M
Minghao Li 已提交
2343 2344

// return if has a snapshot
M
Minghao Li 已提交
2345 2346
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
  bool      ret = false;
2347
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2348 2349
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
2350 2351 2352 2353 2354 2355 2356
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
      ret = true;
    }
  }
  return ret;
}

M
Minghao Li 已提交
2357 2358
// return max(logLastIndex, snapshotLastIndex)
// if no snapshot and log, return -1
2359
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
M
Minghao Li 已提交
2360
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2361 2362
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
    pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
2363 2364 2365 2366 2367 2368 2369
  }
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);

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

M
Minghao Li 已提交
2370 2371
// return the last term of snapshot and log
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
M
Minghao Li 已提交
2372 2373
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
  SyncTerm lastTerm = 0;
M
Minghao Li 已提交
2374 2375
  if (syncNodeHasSnapshot(pSyncNode)) {
    // has snapshot
2376
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2377 2378
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
M
Minghao Li 已提交
2379 2380
    }

M
Minghao Li 已提交
2381 2382 2383
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
    if (logLastIndex > snapshot.lastApplyIndex) {
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
M
Minghao Li 已提交
2384 2385 2386 2387
    } else {
      lastTerm = snapshot.lastApplyTerm;
    }

M
Minghao Li 已提交
2388
  } else {
M
Minghao Li 已提交
2389 2390
    // no snapshot
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
2391
  }
M
Minghao Li 已提交
2392

M
Minghao Li 已提交
2393 2394 2395 2396 2397 2398 2399
  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);
2400 2401
  return 0;
}
M
Minghao Li 已提交
2402

M
Minghao Li 已提交
2403
// return append-entries first try index
M
Minghao Li 已提交
2404 2405 2406 2407 2408
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
  return syncStartIndex;
}

M
Minghao Li 已提交
2409 2410
// if index > 0, return index - 1
// else, return -1
2411 2412 2413 2414 2415 2416 2417 2418 2419
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
  SyncIndex preIndex = index - 1;
  if (preIndex < SYNC_INDEX_INVALID) {
    preIndex = SYNC_INDEX_INVALID;
  }

  return preIndex;
}

M
Minghao Li 已提交
2420 2421 2422 2423
// if index < 0, return SYNC_TERM_INVALID
// if index == 0, return 0
// if index > 0, return preTerm
// if error, return SYNC_TERM_INVALID
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
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 已提交
2437 2438 2439 2440 2441 2442

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

2443 2444 2445 2446 2447 2448
  if (code == 0) {
    ASSERT(pPreEntry != NULL);
    preTerm = pPreEntry->term;
    taosMemoryFree(pPreEntry);
    return preTerm;
  } else {
2449 2450 2451 2452
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
      pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
      if (snapshot.lastApplyIndex == preIndex) {
        return snapshot.lastApplyTerm;
2453 2454 2455 2456
      }
    }
  }

2457 2458
  do {
    char logBuf[128];
S
Shengliang Guan 已提交
2459 2460
    snprintf(logBuf, sizeof(logBuf),
             "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRIu64, index,
M
Minghao Li 已提交
2461
             snapshot.lastApplyIndex, snapshot.lastApplyTerm);
2462 2463 2464
    syncNodeErrorLog(pSyncNode, logBuf);
  } while (0);

2465 2466
  return SYNC_TERM_INVALID;
}
M
Minghao Li 已提交
2467 2468 2469 2470

// 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 已提交
2471
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
M
Minghao Li 已提交
2472 2473 2474
  return 0;
}

M
Minghao Li 已提交
2475 2476 2477
// for debug --------------
void syncNodePrint(SSyncNode* pObj) {
  char* serialized = syncNode2Str(pObj);
S
Shengliang Guan 已提交
2478
  printf("syncNodePrint | len:%" PRIu64 " | %s \n", strlen(serialized), serialized);
M
Minghao Li 已提交
2479
  fflush(NULL);
wafwerar's avatar
wafwerar 已提交
2480
  taosMemoryFree(serialized);
M
Minghao Li 已提交
2481 2482 2483 2484
}

void syncNodePrint2(char* s, SSyncNode* pObj) {
  char* serialized = syncNode2Str(pObj);
S
Shengliang Guan 已提交
2485
  printf("syncNodePrint2 | len:%" PRIu64 " | %s | %s \n", strlen(serialized), s, serialized);
M
Minghao Li 已提交
2486
  fflush(NULL);
wafwerar's avatar
wafwerar 已提交
2487
  taosMemoryFree(serialized);
M
Minghao Li 已提交
2488 2489 2490 2491
}

void syncNodeLog(SSyncNode* pObj) {
  char* serialized = syncNode2Str(pObj);
S
Shengliang Guan 已提交
2492
  sTraceLong("syncNodeLog | len:%" PRIu64 " | %s", strlen(serialized), serialized);
wafwerar's avatar
wafwerar 已提交
2493
  taosMemoryFree(serialized);
M
Minghao Li 已提交
2494 2495 2496
}

void syncNodeLog2(char* s, SSyncNode* pObj) {
2497 2498
  if (gRaftDetailLog) {
    char* serialized = syncNode2Str(pObj);
S
Shengliang Guan 已提交
2499
    sTraceLong("syncNodeLog2 | len:%" PRIu64 " | %s | %s", strlen(serialized), s, serialized);
2500 2501
    taosMemoryFree(serialized);
  }
M
Minghao Li 已提交
2502 2503
}

M
Minghao Li 已提交
2504 2505
void syncNodeLog3(char* s, SSyncNode* pObj) {
  char* serialized = syncNode2Str(pObj);
S
Shengliang Guan 已提交
2506
  sTraceLong("syncNodeLog3 | len:%" PRIu64 " | %s | %s", strlen(serialized), s, serialized);
M
Minghao Li 已提交
2507 2508 2509
  taosMemoryFree(serialized);
}

M
Minghao Li 已提交
2510
// ------ local funciton ---------
M
Minghao Li 已提交
2511
// enqueue message ----
M
Minghao Li 已提交
2512 2513
static void syncNodeEqPingTimer(void* param, void* tmrId) {
  SSyncNode* pSyncNode = (SSyncNode*)param;
M
Minghao Li 已提交
2514
  if (atomic_load_64(&pSyncNode->pingTimerLogicClockUser) <= atomic_load_64(&pSyncNode->pingTimerLogicClock)) {
M
Minghao Li 已提交
2515
    SyncTimeout* pSyncMsg = syncTimeoutBuild2(SYNC_TIMEOUT_PING, atomic_load_64(&pSyncNode->pingTimerLogicClock),
M
Minghao Li 已提交
2516
                                              pSyncNode->pingTimerMS, pSyncNode->vgId, pSyncNode);
M
Minghao Li 已提交
2517 2518
    SRpcMsg      rpcMsg;
    syncTimeout2RpcMsg(pSyncMsg, &rpcMsg);
M
Minghao Li 已提交
2519
    syncRpcMsgLog2((char*)"==syncNodeEqPingTimer==", &rpcMsg);
M
Minghao Li 已提交
2520
    if (pSyncNode->FpEqMsg != NULL) {
2521 2522
      int32_t code = pSyncNode->FpEqMsg(pSyncNode->msgcb, &rpcMsg);
      if (code != 0) {
S
Shengliang Guan 已提交
2523
        sError("vgId:%d, sync enqueue ping msg error, code:%d", pSyncNode->vgId, code);
2524 2525 2526 2527
        rpcFreeCont(rpcMsg.pCont);
        syncTimeoutDestroy(pSyncMsg);
        return;
      }
M
Minghao Li 已提交
2528 2529 2530
    } else {
      sTrace("syncNodeEqPingTimer pSyncNode->FpEqMsg is NULL");
    }
M
Minghao Li 已提交
2531 2532
    syncTimeoutDestroy(pSyncMsg);

2533 2534 2535 2536 2537 2538 2539
    if (syncEnvIsStart()) {
      taosTmrReset(syncNodeEqPingTimer, pSyncNode->pingTimerMS, pSyncNode, gSyncEnv->pTimerManager,
                   &pSyncNode->pPingTimer);
    } else {
      sError("sync env is stop, syncNodeEqPingTimer");
    }

M
Minghao Li 已提交
2540
  } else {
S
Shengliang Guan 已提交
2541
    sTrace("==syncNodeEqPingTimer== pingTimerLogicClock:%" PRIu64 ", pingTimerLogicClockUser:%" PRIu64,
M
Minghao Li 已提交
2542
           pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
M
Minghao Li 已提交
2543 2544 2545 2546 2547 2548 2549
  }
}

static void syncNodeEqElectTimer(void* param, void* tmrId) {
  SSyncNode* pSyncNode = (SSyncNode*)param;
  if (atomic_load_64(&pSyncNode->electTimerLogicClockUser) <= atomic_load_64(&pSyncNode->electTimerLogicClock)) {
    SyncTimeout* pSyncMsg = syncTimeoutBuild2(SYNC_TIMEOUT_ELECTION, atomic_load_64(&pSyncNode->electTimerLogicClock),
M
Minghao Li 已提交
2550
                                              pSyncNode->electTimerMS, pSyncNode->vgId, pSyncNode);
M
Minghao Li 已提交
2551
    SRpcMsg      rpcMsg;
M
Minghao Li 已提交
2552
    syncTimeout2RpcMsg(pSyncMsg, &rpcMsg);
M
Minghao Li 已提交
2553
    syncRpcMsgLog2((char*)"==syncNodeEqElectTimer==", &rpcMsg);
M
Minghao Li 已提交
2554
    if (pSyncNode->FpEqMsg != NULL) {
2555 2556
      int32_t code = pSyncNode->FpEqMsg(pSyncNode->msgcb, &rpcMsg);
      if (code != 0) {
S
Shengliang Guan 已提交
2557
        sError("vgId:%d, sync enqueue elect msg error, code:%d", pSyncNode->vgId, code);
2558 2559 2560 2561
        rpcFreeCont(rpcMsg.pCont);
        syncTimeoutDestroy(pSyncMsg);
        return;
      }
M
Minghao Li 已提交
2562
    } else {
2563
      sTrace("syncNodeEqElectTimer FpEqMsg is NULL");
M
Minghao Li 已提交
2564
    }
M
Minghao Li 已提交
2565 2566
    syncTimeoutDestroy(pSyncMsg);

M
Minghao Li 已提交
2567
    // reset timer ms
2568
    if (syncEnvIsStart()) {
2569 2570 2571 2572
      pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
      taosTmrReset(syncNodeEqElectTimer, pSyncNode->electTimerMS, pSyncNode, gSyncEnv->pTimerManager,
                   &pSyncNode->pElectTimer);
    } else {
2573
      sError("sync env is stop, syncNodeEqElectTimer");
2574
    }
M
Minghao Li 已提交
2575
  } else {
S
Shengliang Guan 已提交
2576
    sTrace("==syncNodeEqElectTimer== electTimerLogicClock:%" PRIu64 ", electTimerLogicClockUser:%" PRIu64,
M
Minghao Li 已提交
2577
           pSyncNode->electTimerLogicClock, pSyncNode->electTimerLogicClockUser);
M
Minghao Li 已提交
2578 2579 2580
  }
}

M
Minghao Li 已提交
2581 2582
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
  SSyncNode* pSyncNode = (SSyncNode*)param;
2583 2584 2585

  syncNodeEventLog(pSyncNode, "eq hb timer");

2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
  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);
      syncRpcMsgLog2((char*)"==syncNodeEqHeartbeatTimer==", &rpcMsg);
      if (pSyncNode->FpEqMsg != NULL) {
        int32_t code = pSyncNode->FpEqMsg(pSyncNode->msgcb, &rpcMsg);
        if (code != 0) {
S
Shengliang Guan 已提交
2598
          sError("vgId:%d, sync enqueue timer msg error, code:%d", pSyncNode->vgId, code);
2599 2600 2601 2602 2603
          rpcFreeCont(rpcMsg.pCont);
          syncTimeoutDestroy(pSyncMsg);
          return;
        }
      } else {
2604
        sError("vgId:%d, enqueue msg cb ptr (i.e. FpEqMsg) not set.", pSyncNode->vgId);
2605
      }
2606
      syncTimeoutDestroy(pSyncMsg);
M
Minghao Li 已提交
2607

2608 2609 2610 2611 2612 2613
      if (syncEnvIsStart()) {
        taosTmrReset(syncNodeEqHeartbeatTimer, pSyncNode->heartbeatTimerMS, pSyncNode, gSyncEnv->pTimerManager,
                     &pSyncNode->pHeartbeatTimer);
      } else {
        sError("sync env is stop, syncNodeEqHeartbeatTimer");
      }
2614
    } else {
2615 2616 2617
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRIu64 ", heartbeatTimerLogicClockUser:%" PRIu64
             "",
             pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
2618
    }
M
Minghao Li 已提交
2619 2620 2621
  }
}

M
Minghao Li 已提交
2622 2623
static int32_t syncNodeEqNoop(SSyncNode* ths) {
  int32_t ret = 0;
M
Minghao Li 已提交
2624
  ASSERT(ths->state == TAOS_SYNC_STATE_LEADER);
M
Minghao Li 已提交
2625

2626
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2627
  SyncTerm        term = ths->pRaftStore->currentTerm;
M
Minghao Li 已提交
2628
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
M
Minghao Li 已提交
2629
  ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2630 2631 2632 2633

  uint32_t           entryLen;
  char*              serialized = syncEntrySerialize(pEntry, &entryLen);
  SyncClientRequest* pSyncMsg = syncClientRequestBuild(entryLen);
M
Minghao Li 已提交
2634
  ASSERT(pSyncMsg->dataLen == entryLen);
M
Minghao Li 已提交
2635 2636
  memcpy(pSyncMsg->data, serialized, entryLen);

S
Shengliang Guan 已提交
2637
  SRpcMsg rpcMsg = {0};
M
Minghao Li 已提交
2638
  syncClientRequest2RpcMsg(pSyncMsg, &rpcMsg);
M
Minghao Li 已提交
2639
  if (ths->FpEqMsg != NULL) {
S
Shengliang Guan 已提交
2640
    ths->FpEqMsg(ths->msgcb, &rpcMsg);
M
Minghao Li 已提交
2641 2642 2643
  } else {
    sTrace("syncNodeEqNoop pSyncNode->FpEqMsg is NULL");
  }
M
Minghao Li 已提交
2644

wafwerar's avatar
wafwerar 已提交
2645
  taosMemoryFree(serialized);
M
Minghao Li 已提交
2646 2647 2648 2649 2650
  syncClientRequestDestroy(pSyncMsg);

  return ret;
}

2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664
static void deleteCacheEntry(const void* key, size_t keyLen, void* value) { taosMemoryFree(value); }

static int32_t syncCacheEntry(SSyncLogStore* pLogStore, SSyncRaftEntry* pEntry, LRUHandle** h) {
  int       code = 0;
  int       entryLen = sizeof(*pEntry) + pEntry->dataLen;
  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 已提交
2665 2666 2667
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
  int32_t ret = 0;

2668
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2669
  SyncTerm        term = ths->pRaftStore->currentTerm;
M
Minghao Li 已提交
2670
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
M
Minghao Li 已提交
2671
  ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2672

2673 2674 2675
  LRUHandle* h = NULL;
  syncCacheEntry(ths->pLogStore, pEntry, &h);

M
Minghao Li 已提交
2676
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2677
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
2678
    if (code != 0) {
2679
      sError("vgId:%d, failed to append log entry since %s", ths->vgId, tstrerror(terrno));
2680 2681
      return -1;
    }
M
Minghao Li 已提交
2682
    syncNodeReplicate(ths, false);
M
Minghao Li 已提交
2683 2684
  }

2685 2686 2687 2688 2689 2690
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2691 2692 2693
  return ret;
}

M
Minghao Li 已提交
2694
// on message ----
M
Minghao Li 已提交
2695 2696
int32_t syncNodeOnPingCb(SSyncNode* ths, SyncPing* pMsg) {
  // log state
2697
  char logBuf[1024] = {0};
M
Minghao Li 已提交
2698
  snprintf(logBuf, sizeof(logBuf),
2699 2700
           "==syncNodeOnPingCb== vgId:%d, state: %d, %s, term:%" PRIu64 " electTimerLogicClock:%" PRIu64
           ", "
S
Shengliang Guan 已提交
2701
           "electTimerLogicClockUser:%" PRIu64 ", electTimerMS:%d",
M
Minghao Li 已提交
2702 2703 2704
           ths->vgId, ths->state, syncUtilState2String(ths->state), ths->pRaftStore->currentTerm,
           ths->electTimerLogicClock, ths->electTimerLogicClockUser, ths->electTimerMS);

M
Minghao Li 已提交
2705
  int32_t ret = 0;
M
Minghao Li 已提交
2706 2707
  syncPingLog2(logBuf, pMsg);
  SyncPingReply* pMsgReply = syncPingReplyBuild3(&ths->myRaftId, &pMsg->srcId, ths->vgId);
M
Minghao Li 已提交
2708 2709
  SRpcMsg        rpcMsg;
  syncPingReply2RpcMsg(pMsgReply, &rpcMsg);
M
Minghao Li 已提交
2710 2711 2712 2713 2714 2715 2716 2717

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

M
Minghao Li 已提交
2718 2719 2720 2721 2722
  syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg);

  return ret;
}

M
Minghao Li 已提交
2723
int32_t syncNodeOnPingReplyCb(SSyncNode* ths, SyncPingReply* pMsg) {
M
Minghao Li 已提交
2724 2725 2726 2727
  int32_t ret = 0;
  syncPingReplyLog2("==syncNodeOnPingReplyCb==", pMsg);
  return ret;
}
M
Minghao Li 已提交
2728

2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777
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);

  if (pMsg->term >= ths->pRaftStore->currentTerm && ths->state != TAOS_SYNC_STATE_FOLLOWER) {
    syncNodeBecomeFollower(ths, "become follower by hb");
  }

  if (pMsg->term == ths->pRaftStore->currentTerm) {
    // sInfo("vgId:%d, heartbeat reset timer", ths->vgId);
    syncNodeResetElectTimer(ths);

#if 0
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER) {
      syncNodeFollowerCommit(ths, pMsg->commitIndex);
    }
#endif
  }

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

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

  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 已提交
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
// 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>>
//
2788
int32_t syncNodeOnClientRequestCb(SSyncNode* ths, SyncClientRequest* pMsg, SyncIndex* pRetIndex) {
M
Minghao Li 已提交
2789
  int32_t ret = 0;
2790
  int32_t code = 0;
M
Minghao Li 已提交
2791 2792
  syncClientRequestLog2("==syncNodeOnClientRequestCb==", pMsg);

M
Minghao Li 已提交
2793
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
M
Minghao Li 已提交
2794 2795
  SyncTerm        term = ths->pRaftStore->currentTerm;
  SSyncRaftEntry* pEntry = syncEntryBuild2((SyncClientRequest*)pMsg, term, index);
M
Minghao Li 已提交
2796
  ASSERT(pEntry != NULL);
M
Minghao Li 已提交
2797

2798 2799 2800
  LRUHandle* h = NULL;
  syncCacheEntry(ths->pLogStore, pEntry, &h);

M
Minghao Li 已提交
2801
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
2802 2803 2804 2805
    // append entry
    code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
    if (code != 0) {
      // del resp mgr, call FpCommitCb
2806
      sError("vgId:%d, failed to append log entry since %s", ths->vgId, tstrerror(terrno));
2807 2808
      return -1;
    }
M
Minghao Li 已提交
2809

2810 2811
    // if mulit replica, start replicate right now
    if (ths->replicaNum > 1) {
M
Minghao Li 已提交
2812
      syncNodeReplicate(ths, false);
M
Minghao Li 已提交
2813

2814 2815 2816
      // pre commit
      syncNodePreCommit(ths, pEntry, 0);
    }
2817

2818 2819 2820 2821
    // if only myself, maybe commit right now
    if (ths->replicaNum == 1) {
      syncMaybeAdvanceCommitIndex(ths);
    }
M
Minghao Li 已提交
2822 2823
  }

2824 2825 2826 2827 2828 2829 2830 2831
  if (pRetIndex != NULL) {
    if (ret == 0 && pEntry != NULL) {
      *pRetIndex = pEntry->index;
    } else {
      *pRetIndex = SYNC_INDEX_INVALID;
    }
  }

2832 2833 2834 2835 2836 2837
  if (h) {
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
  } else {
    syncEntryDestory(pEntry);
  }

M
Minghao Li 已提交
2838
  return ret;
2839
}
M
Minghao Li 已提交
2840

M
Minghao Li 已提交
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
int32_t syncNodeOnClientRequestBatchCb(SSyncNode* ths, SyncClientRequestBatch* pMsg) {
  int32_t code = 0;

  if (ths->state != TAOS_SYNC_STATE_LEADER) {
    // call FpCommitCb, delete resp mgr
    return -1;
  }

  SyncIndex index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
  SyncTerm  term = ths->pRaftStore->currentTerm;

  int32_t    raftMetaArrayLen = sizeof(SRaftMeta) * pMsg->dataCount;
  int32_t    rpcArrayLen = sizeof(SRpcMsg) * pMsg->dataCount;
  SRaftMeta* raftMetaArr = (SRaftMeta*)(pMsg->data);
  SRpcMsg*   msgArr = (SRpcMsg*)((char*)(pMsg->data) + raftMetaArrayLen);
  for (int32_t i = 0; i < pMsg->dataCount; ++i) {
    SSyncRaftEntry* pEntry = syncEntryBuild(msgArr[i].contLen);
    ASSERT(pEntry != NULL);

    pEntry->originalRpcType = msgArr[i].msgType;
    pEntry->seqNum = raftMetaArr[i].seqNum;
    pEntry->isWeak = raftMetaArr[i].isWeak;
    pEntry->term = term;
    pEntry->index = index;
    memcpy(pEntry->data, msgArr[i].pCont, msgArr[i].contLen);
    ASSERT(msgArr[i].contLen == pEntry->dataLen);

    code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry);
    if (code != 0) {
2870
      sError("vgId:%d, failed to append log entry since %s", ths->vgId, tstrerror(terrno));
M
Minghao Li 已提交
2871 2872 2873
      // del resp mgr, call FpCommitCb
      return -1;
    }
M
Minghao Li 已提交
2874 2875 2876

    // update rpc msg conn apply.index
    msgArr[i].info.conn.applyIndex = pEntry->index;
M
Minghao Li 已提交
2877 2878 2879 2880 2881
  }

  // fsync once
  SSyncLogStoreData* pData = ths->pLogStore->data;
  SWal*              pWal = pData->pWal;
2882
  walFsync(pWal, false);
M
Minghao Li 已提交
2883

M
Minghao Li 已提交
2884
  if (ths->replicaNum > 1) {
M
Minghao Li 已提交
2885
    // if multi replica, start replicate right now
M
Minghao Li 已提交
2886
    syncNodeReplicate(ths, false);
M
Minghao Li 已提交
2887 2888 2889 2890 2891 2892

  } else if (ths->replicaNum == 1) {
    // one replica
    syncMaybeAdvanceCommitIndex(ths);
  }

M
Minghao Li 已提交
2893 2894 2895
  return 0;
}

S
Shengliang Guan 已提交
2896 2897 2898
const char* syncStr(ESyncState state) {
  switch (state) {
    case TAOS_SYNC_STATE_FOLLOWER:
2899
      return "follower";
S
Shengliang Guan 已提交
2900
    case TAOS_SYNC_STATE_CANDIDATE:
2901
      return "candidate";
S
Shengliang Guan 已提交
2902
    case TAOS_SYNC_STATE_LEADER:
2903
      return "leader";
S
Shengliang Guan 已提交
2904
    default:
2905
      return "error";
S
Shengliang Guan 已提交
2906
  }
M
Minghao Li 已提交
2907
}
2908

2909
int32_t syncDoLeaderTransfer(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry) {
2910 2911 2912 2913
  if (ths->state != TAOS_SYNC_STATE_FOLLOWER) {
    syncNodeEventLog(ths, "I am not follower, can not do leader transfer");
    return 0;
  }
2914 2915 2916 2917 2918 2919

  if (!ths->restoreFinish) {
    syncNodeEventLog(ths, "restore not finish, can not do leader transfer");
    return 0;
  }

2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
  if (pEntry->term < ths->pRaftStore->currentTerm) {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "little term:%lu, can not do leader transfer", pEntry->term);
    syncNodeEventLog(ths, logBuf);
    return 0;
  }

  if (pEntry->index < syncNodeGetLastIndex(ths)) {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "little index:%ld, can not do leader transfer", pEntry->index);
    syncNodeEventLog(ths, logBuf);
2931 2932 2933
    return 0;
  }

2934 2935 2936 2937 2938 2939 2940
  /*
    if (ths->vgId > 1) {
      syncNodeEventLog(ths, "I am vnode, can not do leader transfer");
      return 0;
    }
  */

M
Minghao Li 已提交
2941 2942
  SyncLeaderTransfer* pSyncLeaderTransfer = syncLeaderTransferFromRpcMsg2(pRpcMsg);

2943 2944 2945 2946 2947
  do {
    char logBuf[128];
    snprintf(logBuf, sizeof(logBuf), "do leader transfer, index:%ld", pEntry->index);
    syncNodeEventLog(ths, logBuf);
  } while (0);
M
Minghao Li 已提交
2948

M
Minghao Li 已提交
2949 2950 2951
  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 已提交
2952

M
Minghao Li 已提交
2953 2954
  bool same = sameId || sameNodeInfo;
  if (same) {
M
Minghao Li 已提交
2955 2956 2957 2958
    // reset elect timer now!
    int32_t electMS = 1;
    int32_t ret = syncNodeRestartElectTimer(ths, electMS);
    ASSERT(ret == 0);
M
Minghao Li 已提交
2959 2960

    char eventLog[256];
S
Shengliang Guan 已提交
2961
    snprintf(eventLog, sizeof(eventLog), "maybe leader transfer to %s:%d %" PRIu64,
M
Minghao Li 已提交
2962 2963 2964
             pSyncLeaderTransfer->newNodeInfo.nodeFqdn, pSyncLeaderTransfer->newNodeInfo.nodePort,
             pSyncLeaderTransfer->newLeaderId.addr);
    syncNodeEventLog(ths, eventLog);
2965 2966
  }

M
Minghao Li 已提交
2967
  if (ths->pFsm->FpLeaderTransferCb != NULL) {
2968
    SFsmCbMeta cbMeta = {0};
M
Minghao Li 已提交
2969 2970 2971 2972
    cbMeta.code = 0;
    cbMeta.currentTerm = ths->pRaftStore->currentTerm;
    cbMeta.flag = 0;
    cbMeta.index = pEntry->index;
2973
    cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
M
Minghao Li 已提交
2974 2975 2976 2977 2978
    cbMeta.isWeak = pEntry->isWeak;
    cbMeta.seqNum = pEntry->seqNum;
    cbMeta.state = ths->state;
    cbMeta.term = pEntry->term;
    ths->pFsm->FpLeaderTransferCb(ths->pFsm, pRpcMsg, cbMeta);
2979 2980
  }

M
Minghao Li 已提交
2981
  syncLeaderTransferDestroy(pSyncLeaderTransfer);
2982 2983 2984
  return 0;
}

2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
  for (int i = 0; i < pNewCfg->replicaNum; ++i) {
    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;
}

M
Minghao Li 已提交
3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
static int32_t syncNodeConfigChangeFinish(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry) {
  SyncReconfigFinish* pFinish = syncReconfigFinishFromRpcMsg2(pRpcMsg);
  ASSERT(pFinish);

  if (ths->pFsm->FpReConfigCb != NULL) {
    SReConfigCbMeta cbMeta = {0};
    cbMeta.code = 0;
    cbMeta.index = pEntry->index;
    cbMeta.term = pEntry->term;
    cbMeta.seqNum = pEntry->seqNum;
    cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, pEntry->index);
    cbMeta.state = ths->state;
    cbMeta.currentTerm = ths->pRaftStore->currentTerm;
    cbMeta.isWeak = pEntry->isWeak;
    cbMeta.flag = 0;

    cbMeta.oldCfg = pFinish->oldCfg;
    cbMeta.newCfg = pFinish->newCfg;
    cbMeta.newCfgIndex = pFinish->newCfgIndex;
    cbMeta.newCfgTerm = pFinish->newCfgTerm;
    cbMeta.newCfgSeqNum = pFinish->newCfgSeqNum;

S
Shengliang Guan 已提交
3022
    ths->pFsm->FpReConfigCb(ths->pFsm, pRpcMsg, &cbMeta);
M
Minghao Li 已提交
3023 3024
  }

3025
  // clear changing
M
Minghao Li 已提交
3026 3027 3028 3029 3030
  ths->changing = false;

  char  tmpbuf[512];
  char* oldStr = syncCfg2SimpleStr(&(pFinish->oldCfg));
  char* newStr = syncCfg2SimpleStr(&(pFinish->newCfg));
S
Shengliang Guan 已提交
3031
  snprintf(tmpbuf, sizeof(tmpbuf), "config change finish from %d to %d, index:%" PRId64 ", %s  -->  %s",
M
Minghao Li 已提交
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
           pFinish->oldCfg.replicaNum, pFinish->newCfg.replicaNum, pFinish->newCfgIndex, oldStr, newStr);
  taosMemoryFree(oldStr);
  taosMemoryFree(newStr);
  syncNodeEventLog(ths, tmpbuf);

  syncReconfigFinishDestroy(pFinish);

  return 0;
}

static int32_t syncNodeConfigChange(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry,
                                    SyncReconfigFinish* pFinish) {
3044 3045 3046
  // set changing
  ths->changing = true;

M
Minghao Li 已提交
3047
  // old config
3048 3049
  SSyncCfg oldSyncCfg = ths->pRaftCfg->cfg;

M
Minghao Li 已提交
3050
  // new config
3051 3052 3053 3054 3055
  SSyncCfg newSyncCfg;
  int32_t  ret = syncCfgFromStr(pRpcMsg->pCont, &newSyncCfg);
  ASSERT(ret == 0);

  // update new config myIndex
3056 3057
  syncNodeUpdateNewConfigIndex(ths, &newSyncCfg);

M
Minghao Li 已提交
3058 3059
  // do config change
  syncNodeDoConfigChange(ths, &newSyncCfg, pEntry->index);
3060

M
Minghao Li 已提交
3061 3062 3063 3064 3065 3066
  // set pFinish
  pFinish->oldCfg = oldSyncCfg;
  pFinish->newCfg = newSyncCfg;
  pFinish->newCfgIndex = pEntry->index;
  pFinish->newCfgTerm = pEntry->term;
  pFinish->newCfgSeqNum = pEntry->seqNum;
3067

M
Minghao Li 已提交
3068 3069
  return 0;
}
3070

M
Minghao Li 已提交
3071 3072 3073 3074 3075 3076 3077 3078 3079
static int32_t syncNodeProposeConfigChangeFinish(SSyncNode* ths, SyncReconfigFinish* pFinish) {
  SRpcMsg rpcMsg;
  syncReconfigFinish2RpcMsg(pFinish, &rpcMsg);

  int32_t code = syncNodePropose(ths, &rpcMsg, false);
  if (code != 0) {
    sError("syncNodeProposeConfigChangeFinish error");
    ths->changing = false;
  }
3080 3081 3082
  return 0;
}

3083
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
3084 3085
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType));
  // return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
3086 3087
}

3088
int32_t syncNodeCommit(SSyncNode* ths, SyncIndex beginIndex, SyncIndex endIndex, uint64_t flag) {
3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
  if (beginIndex > endIndex) {
    return 0;
  }

  // advance commit index to sanpshot first
  SSnapshot snapshot = {0};
  ths->pFsm->FpGetSnapshotInfo(ths->pFsm, &snapshot);
  if (snapshot.lastApplyIndex >= 0 && snapshot.lastApplyIndex >= beginIndex) {
    char eventLog[128];
    snprintf(eventLog, sizeof(eventLog), "commit by snapshot from index:%" PRId64 " to index:%" PRId64, beginIndex,
             snapshot.lastApplyIndex);
    syncNodeEventLog(ths, eventLog);

    // update begin index
    beginIndex = snapshot.lastApplyIndex + 1;
  }

3106 3107
  int32_t    code = 0;
  ESyncState state = flag;
M
Minghao Li 已提交
3108 3109

  char eventLog[128];
3110
  snprintf(eventLog, sizeof(eventLog), "commit by wal from index:%" PRId64 " to index:%" PRId64, beginIndex, endIndex);
M
Minghao Li 已提交
3111
  syncNodeEventLog(ths, eventLog);
3112 3113 3114 3115 3116 3117

  // execute fsm
  if (ths->pFsm != NULL) {
    for (SyncIndex i = beginIndex; i <= endIndex; ++i) {
      if (i != SYNC_INDEX_INVALID) {
        SSyncRaftEntry* pEntry;
3118 3119 3120 3121 3122 3123
        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);
3124
          if (code != 0) {
3125 3126 3127
            sError("vgId:%d, failed to get log entry since %s. index:%lld", ths->vgId, tstrerror(terrno), i);
            return -1;
          }
3128 3129
          ASSERT(pEntry != NULL);
        }
3130 3131 3132 3133

        SRpcMsg rpcMsg;
        syncEntry2OriginalRpc(pEntry, &rpcMsg);

3134
        // user commit
3135 3136
        if ((ths->pFsm->FpCommitCb != NULL) && syncUtilUserCommit(pEntry->originalRpcType)) {
          bool internalExecute = true;
3137 3138
          if ((ths->replicaNum == 1) && ths->restoreFinish) {
            // if ((ths->replicaNum == 1) && ths->restoreFinish && ths->vgId != 1) {
3139 3140 3141 3142 3143
            internalExecute = false;
          }

          do {
            char logBuf[128];
S
Shengliang Guan 已提交
3144
            snprintf(logBuf, sizeof(logBuf), "commit index:%" PRId64 ", internal:%d", i, internalExecute);
3145 3146
            syncNodeEventLog(ths, logBuf);
          } while (0);
3147

3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
          // execute fsm in apply thread, or execute outside syncPropose
          if (internalExecute) {
            SFsmCbMeta cbMeta = {0};
            cbMeta.index = pEntry->index;
            cbMeta.lastConfigIndex = syncNodeGetSnapshotConfigIndex(ths, cbMeta.index);
            cbMeta.isWeak = pEntry->isWeak;
            cbMeta.code = 0;
            cbMeta.state = ths->state;
            cbMeta.seqNum = pEntry->seqNum;
            cbMeta.term = pEntry->term;
            cbMeta.currentTerm = ths->pRaftStore->currentTerm;
            cbMeta.flag = flag;

            ths->pFsm->FpCommitCb(ths->pFsm, &rpcMsg, cbMeta);
          }
3163 3164 3165
        }

        // config change
3166
        if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE) {
M
Minghao Li 已提交
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
          SyncReconfigFinish* pFinish = syncReconfigFinishBuild(ths->vgId);
          ASSERT(pFinish != NULL);

          code = syncNodeConfigChange(ths, &rpcMsg, pEntry, pFinish);
          ASSERT(code == 0);

          if (ths->state == TAOS_SYNC_STATE_LEADER) {
            syncNodeProposeConfigChangeFinish(ths, pFinish);
          }
          syncReconfigFinishDestroy(pFinish);
        }

        // config change finish
        if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE_FINISH) {
          code = syncNodeConfigChangeFinish(ths, &rpcMsg, pEntry);
3182 3183
          ASSERT(code == 0);
        }
3184

3185 3186
#if 0
        // execute in pre-commit
M
Minghao Li 已提交
3187
        // leader transfer
3188 3189 3190
        if (pEntry->originalRpcType == TDMT_SYNC_LEADER_TRANSFER) {
          code = syncDoLeaderTransfer(ths, &rpcMsg, pEntry);
          ASSERT(code == 0);
3191
        }
3192
#endif
3193 3194

        // restore finish
3195
        // if only snapshot, a noop entry will be append, so syncLogLastIndex is always ok
3196 3197 3198 3199 3200 3201
        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 已提交
3202

3203 3204
            int64_t restoreDelay = taosGetTimestampMs() - ths->leaderTime;

M
Minghao Li 已提交
3205
            char eventLog[128];
3206 3207
            snprintf(eventLog, sizeof(eventLog), "restore finish, index:%ld, elapsed:%ld ms, ", pEntry->index,
                     restoreDelay);
M
Minghao Li 已提交
3208
            syncNodeEventLog(ths, eventLog);
3209 3210 3211 3212
          }
        }

        rpcFreeCont(rpcMsg.pCont);
3213 3214 3215 3216 3217
        if (h) {
          taosLRUCacheRelease(pCache, h, false);
        } else {
          syncEntryDestory(pEntry);
        }
3218 3219 3220 3221
      }
    }
  }
  return 0;
3222 3223 3224 3225 3226 3227 3228 3229 3230
}

bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
  for (int i = 0; i < ths->replicaNum; ++i) {
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
      return true;
    }
  }
  return false;
M
Minghao Li 已提交
3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
}

SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
  SSyncSnapshotSender* pSender = NULL;
  for (int i = 0; i < ths->replicaNum; ++i) {
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
      pSender = (ths->senders)[i];
    }
  }
  return pSender;
M
Minghao Li 已提交
3241
}
M
Minghao Li 已提交
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265

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;
    }
  }

  for (int i = 0; i < pSyncNode->peersNum; ++i) {
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
    if (pSender->start) {
      sError("sync cannot change3");
      return false;
    }
  }

  return true;
M
Minghao Li 已提交
3266 3267
}

wafwerar's avatar
wafwerar 已提交
3268
void syncLogSendRequestVote(SSyncNode* pSyncNode, const SyncRequestVote* pMsg, const char* s) {
M
Minghao Li 已提交
3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
           "send sync-request-vote to %s:%d {term:%" PRIu64 ", lindex:%" PRId64 ", lterm:%" PRIu64 "}, %s", host, port,
           pMsg->term, pMsg->lastLogIndex, pMsg->lastLogTerm, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

wafwerar's avatar
wafwerar 已提交
3279
void syncLogRecvRequestVote(SSyncNode* pSyncNode, const SyncRequestVote* pMsg, const char* s) {
M
Minghao Li 已提交
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
  char     logBuf[256];
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
  snprintf(logBuf, sizeof(logBuf),
           "recv sync-request-vote from %s:%d, {term:%" PRIu64 ", lindex:%" PRId64 ", lterm:%" PRIu64 "}, %s", host,
           port, pMsg->term, pMsg->lastLogIndex, pMsg->lastLogTerm, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

wafwerar's avatar
wafwerar 已提交
3290
void syncLogSendRequestVoteReply(SSyncNode* pSyncNode, const SyncRequestVoteReply* pMsg, const char* s) {
M
Minghao Li 已提交
3291 3292 3293 3294 3295 3296 3297 3298 3299
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf), "send sync-request-vote-reply to %s:%d {term:%" PRIu64 ", grant:%d}, %s", host, port,
           pMsg->term, pMsg->voteGranted, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

wafwerar's avatar
wafwerar 已提交
3300
void syncLogRecvRequestVoteReply(SSyncNode* pSyncNode, const SyncRequestVoteReply* pMsg, const char* s) {
M
Minghao Li 已提交
3301 3302 3303 3304 3305 3306 3307 3308 3309
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf), "recv sync-request-vote-reply from %s:%d {term:%" PRIu64 ", grant:%d}, %s", host,
           port, pMsg->term, pMsg->voteGranted, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

wafwerar's avatar
wafwerar 已提交
3310
void syncLogSendAppendEntries(SSyncNode* pSyncNode, const SyncAppendEntries* pMsg, const char* s) {
M
Minghao Li 已提交
3311 3312 3313 3314 3315 3316
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
           "send sync-append-entries to %s:%d, {term:%" PRIu64 ", pre-index:%" PRId64 ", pre-term:%" PRIu64
M
Minghao Li 已提交
3317
           ", pterm:%" PRIu64 ", cmt:%" PRId64
M
Minghao Li 已提交
3318 3319 3320 3321 3322 3323 3324
           ", "
           "datalen:%d}, %s",
           host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->privateTerm, pMsg->commitIndex,
           pMsg->dataLen, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

wafwerar's avatar
wafwerar 已提交
3325
void syncLogRecvAppendEntries(SSyncNode* pSyncNode, const SyncAppendEntries* pMsg, const char* s) {
M
Minghao Li 已提交
3326 3327 3328 3329 3330
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
3331
           "recv sync-append-entries from %s:%d {term:%" PRIu64 ", pre-index:%" PRIu64 ", pre-term:%" PRIu64
M
Minghao Li 已提交
3332
           ", cmt:%" PRIu64 ", pterm:%" PRIu64
M
Minghao Li 已提交
3333 3334 3335 3336
           ", "
           "datalen:%d}, %s",
           host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->commitIndex, pMsg->privateTerm,
           pMsg->dataLen, s);
M
Minghao Li 已提交
3337
  syncNodeEventLog(pSyncNode, logBuf);
M
Minghao Li 已提交
3338 3339
}

wafwerar's avatar
wafwerar 已提交
3340
void syncLogSendAppendEntriesBatch(SSyncNode* pSyncNode, const SyncAppendEntriesBatch* pMsg, const char* s) {
M
Minghao Li 已提交
3341 3342 3343 3344 3345 3346
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
           "send sync-append-entries-batch to %s:%d, {term:%" PRIu64 ", pre-index:%" PRId64 ", pre-term:%" PRIu64
M
Minghao Li 已提交
3347
           ", pterm:%" PRIu64 ", cmt:%" PRId64 ", datalen:%d, count:%d}, %s",
M
Minghao Li 已提交
3348 3349
           host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->privateTerm, pMsg->commitIndex,
           pMsg->dataLen, pMsg->dataCount, s);
M
Minghao Li 已提交
3350 3351 3352
  syncNodeEventLog(pSyncNode, logBuf);
}

wafwerar's avatar
wafwerar 已提交
3353
void syncLogRecvAppendEntriesBatch(SSyncNode* pSyncNode, const SyncAppendEntriesBatch* pMsg, const char* s) {
M
Minghao Li 已提交
3354 3355 3356 3357 3358 3359
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
           "recv sync-append-entries-batch from %s:%d, {term:%" PRIu64 ", pre-index:%" PRId64 ", pre-term:%" PRIu64
M
Minghao Li 已提交
3360
           ", pterm:%" PRIu64 ", cmt:%" PRId64 ", datalen:%d, count:%d}, %s",
M
Minghao Li 已提交
3361 3362
           host, port, pMsg->term, pMsg->prevLogIndex, pMsg->prevLogTerm, pMsg->privateTerm, pMsg->commitIndex,
           pMsg->dataLen, pMsg->dataCount, s);
M
Minghao Li 已提交
3363
  syncNodeEventLog(pSyncNode, logBuf);
M
Minghao Li 已提交
3364 3365
}

3366
void syncLogSendAppendEntriesReply(SSyncNode* pSyncNode, const SyncAppendEntriesReply* pMsg, const char* s) {
M
Minghao Li 已提交
3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
           "send sync-append-entries-reply to %s:%d, {term:%" PRIu64 ", pterm:%" PRIu64 ", success:%d, match:%" PRId64
           "}, %s",
           host, port, pMsg->term, pMsg->privateTerm, pMsg->success, pMsg->matchIndex, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

wafwerar's avatar
wafwerar 已提交
3378
void syncLogRecvAppendEntriesReply(SSyncNode* pSyncNode, const SyncAppendEntriesReply* pMsg, const char* s) {
M
Minghao Li 已提交
3379 3380 3381 3382 3383
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
M
Minghao Li 已提交
3384
           "recv sync-append-entries-reply from %s:%d {term:%" PRIu64 ", pterm:%" PRIu64 ", success:%d, match:%" PRId64
M
Minghao Li 已提交
3385 3386
           "}, %s",
           host, port, pMsg->term, pMsg->privateTerm, pMsg->success, pMsg->matchIndex, s);
M
Minghao Li 已提交
3387
  syncNodeEventLog(pSyncNode, logBuf);
M
Minghao Li 已提交
3388
}
3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430

void syncLogSendHeartbeat(SSyncNode* pSyncNode, const SyncHeartbeat* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
           "send sync-heartbeat from %s:%d {term:%" PRIu64 ", cmt:%" PRIu64 ", pterm:%" PRIu64 "}, %s", host, port,
           pMsg->term, pMsg->commitIndex, pMsg->privateTerm, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

void syncLogRecvHeartbeat(SSyncNode* pSyncNode, const SyncHeartbeat* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf),
           "recv sync-heartbeat from %s:%d {term:%" PRIu64 ", cmt:%" PRIu64 ", pterm:%" PRIu64 "}, %s", host, port,
           pMsg->term, pMsg->commitIndex, pMsg->privateTerm, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

void syncLogSendHeartbeatReply(SSyncNode* pSyncNode, const SyncHeartbeatReply* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->destId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf), "send sync-heartbeat-reply from %s:%d {term:%" PRIu64 ", pterm:%" PRIu64 "}, %s",
           host, port, pMsg->term, pMsg->privateTerm, s);
  syncNodeEventLog(pSyncNode, logBuf);
}

void syncLogRecvHeartbeatReply(SSyncNode* pSyncNode, const SyncHeartbeatReply* pMsg, const char* s) {
  char     host[64];
  uint16_t port;
  syncUtilU642Addr(pMsg->srcId.addr, host, sizeof(host), &port);
  char logBuf[256];
  snprintf(logBuf, sizeof(logBuf), "recv sync-heartbeat-reply from %s:%d {term:%" PRIu64 ", pterm:%" PRIu64 "}, %s",
           host, port, pMsg->term, pMsg->privateTerm, s);
  syncNodeEventLog(pSyncNode, logBuf);
}