• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #4488

12 Jul 2025 07:47AM UTC coverage: 62.207% (-0.7%) from 62.948%
#4488

push

travis-ci

web-flow
docs: update stream docs (#31822)

157961 of 324087 branches covered (48.74%)

Branch coverage included in aggregate %.

244465 of 322830 relevant lines covered (75.73%)

6561668.76 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

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

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

42
static void    syncNodeEqPingTimer(void* param, void* tmrId);
43
static void    syncNodeEqElectTimer(void* param, void* tmrId);
44
static void    syncNodeEqHeartbeatTimer(void* param, void* tmrId);
45
static int32_t syncNodeAppendNoop(SSyncNode* ths);
46
static void    syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId);
47
static bool    syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg);
48
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId);
49
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
50
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
51
static int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg);
52
static bool    syncNodeInConfig(SSyncNode* pSyncNode, const SSyncCfg* config);
53
static int32_t syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* newConfig, SyncIndex lastConfigChangeIndex);
54
static bool    syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg);
55

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

61
static ESyncStrategy syncNodeStrategy(SSyncNode* pSyncNode);
62

63
int64_t syncOpen(SSyncInfo* pSyncInfo, int32_t vnodeVersion) {
16,995✔
64
  sInfo("vgId:%d, start to open sync", pSyncInfo->vgId);
16,995✔
65
  SSyncNode* pSyncNode = syncNodeOpen(pSyncInfo, vnodeVersion);
16,995✔
66
  if (pSyncNode == NULL) {
17,000!
67
    sError("vgId:%d, failed to open sync node", pSyncInfo->vgId);
×
68
    return -1;
×
69
  }
70

71
  pSyncNode->rid = syncNodeAdd(pSyncNode);
17,000✔
72
  if (pSyncNode->rid < 0) {
17,000!
73
    syncNodeClose(pSyncNode);
×
74
    return -1;
×
75
  }
76

77
  pSyncNode->pingBaseLine = pSyncInfo->pingMs;
17,000✔
78
  pSyncNode->pingTimerMS = pSyncInfo->pingMs;
17,000✔
79
  pSyncNode->electBaseLine = pSyncInfo->electMs;
17,000✔
80
  pSyncNode->hbBaseLine = pSyncInfo->heartbeatMs;
17,000✔
81
  pSyncNode->heartbeatTimerMS = pSyncInfo->heartbeatMs;
17,000✔
82
  pSyncNode->msgcb = pSyncInfo->msgcb;
17,000✔
83
  sInfo("vgId:%d, sync opened", pSyncInfo->vgId);
17,000✔
84
  return pSyncNode->rid;
17,000✔
85
}
86

87
int32_t syncStart(int64_t rid) {
16,999✔
88
  int32_t    code = 0;
16,999✔
89
  int32_t    vgId = 0;
16,999✔
90
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
16,999✔
91
  if (pSyncNode == NULL) {
16,999!
92
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
93
    if (terrno != 0) code = terrno;
×
94
    sError("failed to acquire rid:%" PRId64 " of tsNodeReftId for pSyncNode", rid);
×
95
    TAOS_RETURN(code);
×
96
  }
97
  vgId = pSyncNode->vgId;
16,999✔
98
  sInfo("vgId:%d, begin to start sync", pSyncNode->vgId);
16,999✔
99

100
  if ((code = syncNodeRestore(pSyncNode)) < 0) {
16,999!
101
    sError("vgId:%d, failed to restore sync log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
102
    goto _err;
×
103
  }
104
  sInfo("vgId:%d, sync node restore is executed", pSyncNode->vgId);
16,999✔
105

106
  if ((code = syncNodeStart(pSyncNode)) < 0) {
16,999!
107
    sError("vgId:%d, failed to start sync node since %s", pSyncNode->vgId, tstrerror(code));
×
108
    goto _err;
×
109
  }
110
  sInfo("vgId:%d, sync node start is executed", pSyncNode->vgId);
16,999✔
111

112
  syncNodeRelease(pSyncNode);
16,999✔
113

114
  sInfo("vgId:%d, sync started", vgId);
16,999✔
115

116
  TAOS_RETURN(code);
16,999✔
117

118
_err:
×
119
  syncNodeRelease(pSyncNode);
×
120
  TAOS_RETURN(code);
×
121
}
122

123
int32_t syncNodeGetConfig(int64_t rid, SSyncCfg* cfg) {
23,669✔
124
  int32_t    code = 0;
23,669✔
125
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
23,669✔
126

127
  if (pSyncNode == NULL) {
23,670!
128
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
129
    if (terrno != 0) code = terrno;
×
130
    sError("failed to acquire rid:%" PRId64 " of tsNodeReftId for pSyncNode", rid);
×
131
    TAOS_RETURN(code);
×
132
  }
133

134
  *cfg = pSyncNode->raftCfg.cfg;
23,670✔
135

136
  syncNodeRelease(pSyncNode);
23,670✔
137

138
  return 0;
23,669✔
139
}
140

141
void syncStop(int64_t rid) {
16,999✔
142
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
16,999✔
143
  if (pSyncNode != NULL) {
16,999!
144
    pSyncNode->isStart = false;
16,999✔
145
    syncNodeRelease(pSyncNode);
16,999✔
146
    syncNodeRemove(rid);
16,999✔
147
  }
148
}
16,993✔
149

150
void syncPreStop(int64_t rid) {
16,999✔
151
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
16,999✔
152
  if (pSyncNode != NULL) {
16,999!
153
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
16,999!
154
      sInfo("vgId:%d, stop snapshot receiver", pSyncNode->vgId);
×
155
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
156
    }
157
    syncNodePreClose(pSyncNode);
16,999✔
158
    syncNodeRelease(pSyncNode);
16,999✔
159
  }
160
}
16,999✔
161

162
void syncPostStop(int64_t rid) {
14,532✔
163
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
14,532✔
164
  if (pSyncNode != NULL) {
14,532!
165
    syncNodePostClose(pSyncNode);
14,532✔
166
    syncNodeRelease(pSyncNode);
14,531✔
167
  }
168
}
14,532✔
169

170
static bool syncNodeCheckNewConfig(SSyncNode* pSyncNode, const SSyncCfg* pCfg) {
2,339✔
171
  if (!syncNodeInConfig(pSyncNode, pCfg)) return false;
2,339!
172
  return abs(pCfg->replicaNum - pSyncNode->replicaNum) <= 1;
2,339!
173
}
174

175
int32_t syncReconfig(int64_t rid, SSyncCfg* pNewCfg) {
2,490✔
176
  int32_t    code = 0;
2,490✔
177
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
2,490✔
178
  if (pSyncNode == NULL) {
2,490!
179
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
180
    if (terrno != 0) code = terrno;
×
181
    TAOS_RETURN(code);
×
182
  }
183

184
  if (pSyncNode->raftCfg.lastConfigIndex >= pNewCfg->lastIndex) {
2,490✔
185
    syncNodeRelease(pSyncNode);
151✔
186
    sInfo("vgId:%d, no need Reconfig, current index:%" PRId64 ", new index:%" PRId64, pSyncNode->vgId,
151!
187
          pSyncNode->raftCfg.lastConfigIndex, pNewCfg->lastIndex);
188
    return 0;
151✔
189
  }
190

191
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
2,339!
192
    syncNodeRelease(pSyncNode);
×
193
    code = TSDB_CODE_SYN_NEW_CONFIG_ERROR;
×
194
    sError("vgId:%d, failed to reconfig since invalid new config", pSyncNode->vgId);
×
195
    TAOS_RETURN(code);
×
196
  }
197

198
  TAOS_CHECK_RETURN(syncNodeUpdateNewConfigIndex(pSyncNode, pNewCfg));
2,339!
199

200
  if (syncNodeDoConfigChange(pSyncNode, pNewCfg, pNewCfg->lastIndex) != 0) {
2,339!
201
    code = TSDB_CODE_SYN_NEW_CONFIG_ERROR;
×
202
    sError("vgId:%d, failed to reconfig since do change error", pSyncNode->vgId);
×
203
    TAOS_RETURN(code);
×
204
  }
205

206
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER || pSyncNode->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,339!
207
    // TODO check return value
208
    TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
2,102!
209

210
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
33,632✔
211
      TAOS_CHECK_RETURN(syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]));
31,530!
212
    }
213

214
    TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
2,102!
215
    // syncNodeReplicate(pSyncNode);
216
  }
217

218
  syncNodeRelease(pSyncNode);
2,339✔
219
  TAOS_RETURN(code);
2,339✔
220
}
221

222
int32_t syncProcessMsg(int64_t rid, SRpcMsg* pMsg) {
1,411,296✔
223
  int32_t code = -1;
1,411,296✔
224
  if (!syncIsInit()) {
1,411,296!
225
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
226
    if (terrno != 0) code = terrno;
×
227
    TAOS_RETURN(code);
×
228
  }
229

230
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,411,296✔
231
  if (pSyncNode == NULL) {
1,411,451✔
232
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
120✔
233
    if (terrno != 0) code = terrno;
120!
234
    TAOS_RETURN(code);
×
235
  }
236

237
  switch (pMsg->msgType) {
1,411,331!
238
    case TDMT_SYNC_HEARTBEAT:
52,787✔
239
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
52,787✔
240
      break;
52,788✔
241
    case TDMT_SYNC_HEARTBEAT_REPLY:
50,866✔
242
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
50,866✔
243
      break;
50,867✔
244
    case TDMT_SYNC_TIMEOUT:
65,552✔
245
      code = syncNodeOnTimeout(pSyncNode, pMsg);
65,552✔
246
      break;
65,573✔
247
    case TDMT_SYNC_TIMEOUT_ELECTION:
1,967✔
248
      code = syncNodeOnTimeout(pSyncNode, pMsg);
1,967✔
249
      break;
1,967✔
250
    case TDMT_SYNC_CLIENT_REQUEST:
288,875✔
251
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
288,875✔
252
      break;
288,884✔
253
    case TDMT_SYNC_REQUEST_VOTE:
3,098✔
254
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
3,098✔
255
      break;
3,098✔
256
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
2,791✔
257
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
2,791✔
258
      break;
2,791✔
259
    case TDMT_SYNC_APPEND_ENTRIES:
446,536✔
260
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
446,536✔
261
      break;
446,540✔
262
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
444,643✔
263
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
444,643✔
264
      break;
444,642✔
265
    case TDMT_SYNC_SNAPSHOT_SEND:
966✔
266
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
966✔
267
      break;
966✔
268
    case TDMT_SYNC_SNAPSHOT_RSP:
998✔
269
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
998✔
270
      break;
998✔
271
    case TDMT_SYNC_LOCAL_CMD:
52,238✔
272
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
52,238✔
273
      break;
52,235✔
274
    case TDMT_SYNC_FORCE_FOLLOWER:
14✔
275
      code = syncForceBecomeFollower(pSyncNode, pMsg);
14✔
276
      break;
14✔
277
    case TDMT_SYNC_SET_ASSIGNED_LEADER:
×
278
      code = syncBecomeAssignedLeader(pSyncNode, pMsg);
×
279
      break;
×
280
    default:
×
281
      code = TSDB_CODE_MSG_NOT_PROCESSED;
×
282
  }
283

284
  syncNodeRelease(pSyncNode);
1,411,363✔
285
  if (code != 0) {
1,411,355✔
286
    sDebug("vgId:%d, failed to process sync msg:%p type:%s since %s", pSyncNode->vgId, pMsg, TMSG_INFO(pMsg->msgType),
46!
287
           tstrerror(code));
288
  }
289
  TAOS_RETURN(code);
1,411,355✔
290
}
291

292
int32_t syncLeaderTransfer(int64_t rid) {
16,997✔
293
  int32_t    code = 0;
16,997✔
294
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
16,997✔
295
  if (pSyncNode == NULL) {
16,999!
296
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
297
    if (terrno != 0) code = terrno;
×
298
    TAOS_RETURN(code);
×
299
  }
300

301
  int32_t ret = syncNodeLeaderTransfer(pSyncNode);
16,999✔
302
  syncNodeRelease(pSyncNode);
16,999✔
303
  return ret;
16,999✔
304
}
305

306
int32_t syncForceBecomeFollower(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
14✔
307
  SRaftId id = {0};
14✔
308
  syncNodeBecomeFollower(ths, id, "force election");
14✔
309

310
  SRpcMsg rsp = {
14✔
311
      .code = 0,
312
      .pCont = pRpcMsg->info.rsp,
14✔
313
      .contLen = pRpcMsg->info.rspLen,
14✔
314
      .info = pRpcMsg->info,
315
  };
316
  tmsgSendRsp(&rsp);
14✔
317

318
  return 0;
14✔
319
}
320

321
int32_t syncBecomeAssignedLeader(SSyncNode* ths, SRpcMsg* pRpcMsg) {
×
322
  int32_t code = TSDB_CODE_MND_ARB_TOKEN_MISMATCH;
×
323
  void*   pHead = NULL;
×
324
  int32_t contLen = 0;
×
325

326
  SVArbSetAssignedLeaderReq req = {0};
×
327
  if (tDeserializeSVArbSetAssignedLeaderReq((char*)pRpcMsg->pCont + sizeof(SMsgHead), pRpcMsg->contLen, &req) != 0) {
×
328
    sError("vgId:%d, failed to deserialize SVArbSetAssignedLeaderReq", ths->vgId);
×
329
    code = TSDB_CODE_INVALID_MSG;
×
330
    goto _OVER;
×
331
  }
332

333
  if (ths->arbTerm > req.arbTerm) {
×
334
    sInfo("vgId:%d, skip to set assigned leader, msg with lower term, local:%" PRId64 "msg:%" PRId64, ths->vgId,
×
335
          ths->arbTerm, req.arbTerm);
336
    goto _OVER;
×
337
  }
338

339
  ths->arbTerm = TMAX(req.arbTerm, ths->arbTerm);
×
340

341
  if (!req.force) {
×
342
    if (strncmp(req.memberToken, ths->arbToken, TSDB_ARB_TOKEN_SIZE) != 0) {
×
343
      sInfo("vgId:%d, skip to set assigned leader, token mismatch, local:%s, msg:%s", ths->vgId, ths->arbToken,
×
344
            req.memberToken);
345
      goto _OVER;
×
346
    }
347
  }
348

349
  if (ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
×
350
    code = TSDB_CODE_SUCCESS;
×
351
    raftStoreNextTerm(ths);
×
352
    if (terrno != TSDB_CODE_SUCCESS) {
×
353
      code = terrno;
×
354
      sError("vgId:%d, failed to set next term since:%s", ths->vgId, tstrerror(code));
×
355
      goto _OVER;
×
356
    }
357
    syncNodeBecomeAssignedLeader(ths);
×
358

359
    if ((code = syncNodeAppendNoop(ths)) < 0) {
×
360
      sError("vgId:%d, assigned leader failed to append noop entry since %s", ths->vgId, tstrerror(code));
×
361
    }
362
  }
363

364
  SVArbSetAssignedLeaderRsp rsp = {0};
×
365
  rsp.arbToken = req.arbToken;
×
366
  rsp.memberToken = req.memberToken;
×
367
  rsp.vgId = ths->vgId;
×
368

369
  contLen = tSerializeSVArbSetAssignedLeaderRsp(NULL, 0, &rsp);
×
370
  if (contLen <= 0) {
×
371
    code = TSDB_CODE_OUT_OF_MEMORY;
×
372
    sError("vgId:%d, failed to serialize SVArbSetAssignedLeaderRsp", ths->vgId);
×
373
    goto _OVER;
×
374
  }
375
  pHead = rpcMallocCont(contLen);
×
376
  if (!pHead) {
×
377
    code = terrno;
×
378
    sError("vgId:%d, failed to malloc memory for SVArbSetAssignedLeaderRsp", ths->vgId);
×
379
    goto _OVER;
×
380
  }
381
  if (tSerializeSVArbSetAssignedLeaderRsp(pHead, contLen, &rsp) <= 0) {
×
382
    code = TSDB_CODE_OUT_OF_MEMORY;
×
383
    sError("vgId:%d, failed to serialize SVArbSetAssignedLeaderRsp", ths->vgId);
×
384
    rpcFreeCont(pHead);
×
385
    goto _OVER;
×
386
  }
387

388
  code = TSDB_CODE_SUCCESS;
×
389

390
_OVER:;
×
391
  SRpcMsg rspMsg = {
×
392
      .code = code,
393
      .pCont = pHead,
394
      .contLen = contLen,
395
      .info = pRpcMsg->info,
396
  };
397

398
  tmsgSendRsp(&rspMsg);
×
399

400
  tFreeSVArbSetAssignedLeaderReq(&req);
×
401
  TAOS_RETURN(code);
×
402
}
403

404
int32_t syncSendTimeoutRsp(int64_t rid, int64_t seq) {
×
405
  int32_t    code = 0;
×
406
  SSyncNode* pNode = syncNodeAcquire(rid);
×
407
  if (pNode == NULL) {
×
408
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
409
    if (terrno != 0) code = terrno;
×
410
    TAOS_RETURN(code);
×
411
  }
412

413
  SRpcMsg rpcMsg = {0, .info.notFreeAhandle = 1};
×
414
  int32_t ret = syncRespMgrGetAndDel(pNode->pSyncRespMgr, seq, &rpcMsg.info);
×
415
  rpcMsg.code = TSDB_CODE_SYN_TIMEOUT;
×
416

417
  syncNodeRelease(pNode);
×
418
  if (ret == 1) {
×
419
    sInfo("send timeout response, seq:%" PRId64 " handle:%p ahandle:%p", seq, rpcMsg.info.handle, rpcMsg.info.ahandle);
×
420
    code = rpcSendResponse(&rpcMsg);
×
421
    return code;
×
422
  } else {
423
    sError("no message handle to send timeout response, seq:%" PRId64, seq);
×
424
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
425
  }
426
}
427

428
SyncIndex syncMinMatchIndex(SSyncNode* pSyncNode) {
61,145✔
429
  SyncIndex minMatchIndex = SYNC_INDEX_INVALID;
61,145✔
430

431
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
183,612✔
432
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
122,467✔
433
    if (minMatchIndex == SYNC_INDEX_INVALID) {
122,467✔
434
      minMatchIndex = matchIndex;
67,147✔
435
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
55,320✔
436
      minMatchIndex = matchIndex;
1,835✔
437
    }
438
  }
439
  return minMatchIndex;
61,145✔
440
}
441

442
static SyncIndex syncLogRetentionIndex(SSyncNode* pSyncNode, int64_t bytes) {
967✔
443
  return pSyncNode->pLogStore->syncLogIndexRetention(pSyncNode->pLogStore, bytes);
967✔
444
}
445

446
int32_t syncBeginSnapshot(int64_t rid, int64_t lastApplyIndex) {
28,190✔
447
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
28,190✔
448
  int32_t    code = 0;
28,190✔
449
  if (pSyncNode == NULL) {
28,190✔
450
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
9✔
451
    if (terrno != 0) code = terrno;
9!
452
    sError("sync begin snapshot error");
9!
453
    TAOS_RETURN(code);
9✔
454
  }
455

456
  SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
28,181✔
457
  SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore);
28,181✔
458
  bool      isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore);
28,180✔
459

460
  if (isEmpty || !(lastApplyIndex >= beginIndex && lastApplyIndex <= endIndex)) {
28,180!
461
    sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", empty:%d, do not delete wal", lastApplyIndex, isEmpty);
53!
462
    syncNodeRelease(pSyncNode);
53✔
463
    return 0;
53✔
464
  }
465

466
  int64_t logRetention = 0;
28,127✔
467

468
  if (syncNodeIsMnode(pSyncNode)) {
28,127✔
469
    // mnode
470
    logRetention = tsMndLogRetention;
4,511✔
471
  } else {
472
    // vnode
473
    if (pSyncNode->replicaNum > 1) {
23,616✔
474
      logRetention = SYNC_VNODE_LOG_RETENTION;
442✔
475
    }
476
  }
477

478
  if (pSyncNode->totalReplicaNum > 1) {
28,127✔
479
    if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER &&
975✔
480
        pSyncNode->state != TAOS_SYNC_STATE_LEARNER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
176!
481
      sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " candidate or unknown state, do not delete wal",
8!
482
              lastApplyIndex);
483
      syncNodeRelease(pSyncNode);
8✔
484
      return 0;
8✔
485
    }
486
    SyncIndex retentionIndex =
967✔
487
        TMAX(pSyncNode->minMatchIndex, syncLogRetentionIndex(pSyncNode, SYNC_WAL_LOG_RETENTION_SIZE));
967✔
488
    logRetention += TMAX(0, lastApplyIndex - retentionIndex);
967✔
489
  }
490

491
_DEL_WAL:
27,152✔
492

493
  do {
494
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
28,119✔
495
    SyncIndex          snapshotVer = walGetSnapshotVer(pData->pWal);
28,119✔
496
    SyncIndex          walCommitVer = walGetCommittedVer(pData->pWal);
28,119✔
497
    SyncIndex          wallastVer = walGetLastVer(pData->pWal);
28,119✔
498
    if (lastApplyIndex <= walCommitVer) {
28,119!
499
      SyncIndex snapshottingIndex = atomic_load_64(&pSyncNode->snapshottingIndex);
28,119✔
500

501
      if (snapshottingIndex == SYNC_INDEX_INVALID) {
28,119!
502
        atomic_store_64(&pSyncNode->snapshottingIndex, lastApplyIndex);
28,119✔
503
        pSyncNode->snapshottingTime = taosGetTimestampMs();
28,120✔
504

505
        code = walBeginSnapshot(pData->pWal, lastApplyIndex, logRetention);
28,120✔
506
        if (code == 0) {
28,120!
507
          sNTrace(pSyncNode, "wal snapshot begin, index:%" PRId64 ", last apply index:%" PRId64,
28,120✔
508
                  pSyncNode->snapshottingIndex, lastApplyIndex);
509
        } else {
510
          sNError(pSyncNode, "wal snapshot begin error since:%s, index:%" PRId64 ", last apply index:%" PRId64,
×
511
                  terrstr(), pSyncNode->snapshottingIndex, lastApplyIndex);
512
          atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
×
513
        }
514

515
      } else {
516
        sNTrace(pSyncNode, "snapshotting for %" PRId64 ", do not delete wal for new-snapshot-index:%" PRId64,
×
517
                snapshottingIndex, lastApplyIndex);
518
      }
519
    }
520
  } while (0);
521

522
  syncNodeRelease(pSyncNode);
28,120✔
523
  TAOS_RETURN(code);
28,120✔
524
}
525

526
int32_t syncEndSnapshot(int64_t rid) {
28,181✔
527
  int32_t    code = 0;
28,181✔
528
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
28,181✔
529
  if (pSyncNode == NULL) {
28,181!
530
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
531
    if (terrno != 0) code = terrno;
×
532
    sError("sync end snapshot error");
×
533
    TAOS_RETURN(code);
×
534
  }
535

536
  if (atomic_load_64(&pSyncNode->snapshottingIndex) != SYNC_INDEX_INVALID) {
28,181✔
537
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
28,120✔
538
    code = walEndSnapshot(pData->pWal);
28,120✔
539
    if (code != 0) {
28,120!
540
      sNError(pSyncNode, "wal snapshot end error since:%s", tstrerror(code));
×
541
      syncNodeRelease(pSyncNode);
×
542
      TAOS_RETURN(code);
×
543
    } else {
544
      sNTrace(pSyncNode, "wal snapshot end, index:%" PRId64, atomic_load_64(&pSyncNode->snapshottingIndex));
28,120✔
545
      atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
28,120✔
546
    }
547
  }
548

549
  syncNodeRelease(pSyncNode);
28,181✔
550
  TAOS_RETURN(code);
28,181✔
551
}
552

553
bool syncNodeIsReadyForRead(SSyncNode* pSyncNode) {
3,444,075✔
554
  if (pSyncNode == NULL) {
3,444,075!
555
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
556
    sError("sync ready for read error");
×
557
    return false;
×
558
  }
559

560
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
3,444,075!
561
    terrno = TSDB_CODE_SYN_NOT_LEADER;
93,442✔
562
    return false;
93,441✔
563
  }
564

565
  if (!pSyncNode->restoreFinish) {
3,350,633✔
566
    terrno = TSDB_CODE_SYN_RESTORING;
23,091✔
567
    return false;
23,091✔
568
  }
569

570
  return true;
3,327,542✔
571
}
572

573
bool syncIsReadyForRead(int64_t rid) {
3,066,847✔
574
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
3,066,847✔
575
  if (pSyncNode == NULL) {
3,068,474!
576
    sError("sync ready for read error");
×
577
    return false;
×
578
  }
579

580
  bool ready = syncNodeIsReadyForRead(pSyncNode);
3,068,474✔
581

582
  syncNodeRelease(pSyncNode);
3,068,360✔
583
  return ready;
3,068,188✔
584
}
585

586
#ifdef BUILD_NO_CALL
587
bool syncSnapshotSending(int64_t rid) {
588
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
589
  if (pSyncNode == NULL) {
590
    return false;
591
  }
592

593
  bool b = syncNodeSnapshotSending(pSyncNode);
594
  syncNodeRelease(pSyncNode);
595
  return b;
596
}
597

598
bool syncSnapshotRecving(int64_t rid) {
599
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
600
  if (pSyncNode == NULL) {
601
    return false;
602
  }
603

604
  bool b = syncNodeSnapshotRecving(pSyncNode);
605
  syncNodeRelease(pSyncNode);
606
  return b;
607
}
608
#endif
609

610
int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode) {
16,998✔
611
  if (pSyncNode->peersNum == 0) {
16,998✔
612
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
12,417✔
613
    return 0;
12,417✔
614
  }
615

616
  int32_t ret = 0;
4,581✔
617
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && pSyncNode->replicaNum > 1) {
4,581✔
618
    SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
1,429✔
619
    if (pSyncNode->peersNum == 2) {
1,429✔
620
      SyncIndex matchIndex0 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[0]));
959✔
621
      SyncIndex matchIndex1 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[1]));
959✔
622
      if (matchIndex1 > matchIndex0) {
959✔
623
        newLeader = (pSyncNode->peersNodeInfo)[1];
88✔
624
      }
625
    }
626
    ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
1,429✔
627
  }
628

629
  return ret;
4,581✔
630
}
631

632
int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader) {
1,429✔
633
  if (pSyncNode->replicaNum == 1) {
1,429!
634
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
×
635
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
636
  }
637

638
  sNTrace(pSyncNode, "begin leader transfer to %s:%u", newLeader.nodeFqdn, newLeader.nodePort);
1,429!
639

640
  SRpcMsg rpcMsg = {0};
1,429✔
641
  TAOS_CHECK_RETURN(syncBuildLeaderTransfer(&rpcMsg, pSyncNode->vgId));
1,429!
642

643
  SyncLeaderTransfer* pMsg = rpcMsg.pCont;
1,429✔
644
  pMsg->newLeaderId.addr = SYNC_ADDR(&newLeader);
1,429✔
645
  pMsg->newLeaderId.vgId = pSyncNode->vgId;
1,429✔
646
  pMsg->newNodeInfo = newLeader;
1,429✔
647

648
  int32_t ret = syncNodePropose(pSyncNode, &rpcMsg, false, NULL);
1,429✔
649
  rpcFreeCont(rpcMsg.pCont);
1,429✔
650
  return ret;
1,429✔
651
}
652

653
SSyncState syncGetState(int64_t rid) {
1,499,369✔
654
  SSyncState state = {.state = TAOS_SYNC_STATE_ERROR};
1,499,369✔
655

656
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,499,369✔
657
  if (pSyncNode != NULL) {
1,500,100✔
658
    state.state = pSyncNode->state;
1,500,090✔
659
    state.roleTimeMs = pSyncNode->roleTimeMs;
1,500,090✔
660
    state.startTimeMs = pSyncNode->startTime;
1,500,090✔
661
    state.restored = pSyncNode->restoreFinish;
1,500,090✔
662
    if (pSyncNode->vgId != 1) {
1,500,090✔
663
      state.canRead = syncNodeIsReadyForRead(pSyncNode);
377,312✔
664
    } else {
665
      state.canRead = state.restored;
1,122,778✔
666
    }
667
    /*
668
    double progress = 0;
669
    if(pSyncNode->pLogBuf->totalIndex > 0 && pSyncNode->pLogBuf->commitIndex > 0){
670
      progress = (double)pSyncNode->pLogBuf->commitIndex/(double)pSyncNode->pLogBuf->totalIndex;
671
      state.progress = (int32_t)(progress * 100);
672
    }
673
    else{
674
      state.progress = -1;
675
    }
676
    sDebug("vgId:%d, learner progress state, commitIndex:%" PRId64 " totalIndex:%" PRId64 ", "
677
            "progress:%lf, progress:%d",
678
          pSyncNode->vgId,
679
         pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->totalIndex, progress, state.progress);
680
    */
681
    state.term = raftStoreGetTerm(pSyncNode);
1,500,080✔
682
    syncNodeRelease(pSyncNode);
1,500,119✔
683
  }
684

685
  return state;
1,500,111✔
686
}
687

688
SSyncMetrics syncGetMetrics(int64_t rid) {
×
689
  SSyncMetrics metrics = {0};
×
690

691
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
×
692
  if (pSyncNode != NULL) {
×
693
    sDebug("vgId:%d, sync get metrics, wal_write_bytes:%" PRId64 ", wal_write_time:%" PRId64, pSyncNode->vgId,
×
694
           pSyncNode->wal_write_bytes, pSyncNode->wal_write_time);
695
    metrics.wal_write_bytes = atomic_load_64(&pSyncNode->wal_write_bytes);
×
696
    metrics.wal_write_time = atomic_load_64(&pSyncNode->wal_write_time);
×
697
    syncNodeRelease(pSyncNode);
×
698
  }
699
  return metrics;
×
700
}
701

702
void syncResetMetrics(int64_t rid, const SSyncMetrics* pOldMetrics) {
×
703
  if (pOldMetrics == NULL) return;
×
704

705
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
×
706
  if (pSyncNode != NULL) {
×
707
    // Atomically subtract the old metrics values from current metrics
708
    (void)atomic_sub_fetch_64(&pSyncNode->wal_write_bytes, pOldMetrics->wal_write_bytes);
×
709
    (void)atomic_sub_fetch_64(&pSyncNode->wal_write_time, pOldMetrics->wal_write_time);
×
710
    syncNodeRelease(pSyncNode);
×
711
  }
712
}
713

714
void syncGetCommitIndex(int64_t rid, int64_t* syncCommitIndex) {
259,033✔
715
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
259,033✔
716
  if (pSyncNode != NULL) {
259,033!
717
    *syncCommitIndex = pSyncNode->commitIndex;
259,033✔
718
    syncNodeRelease(pSyncNode);
259,033✔
719
  }
720
}
259,033✔
721

722
int32_t syncGetArbToken(int64_t rid, char* outToken) {
49,047✔
723
  int32_t    code = 0;
49,047✔
724
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
49,047✔
725
  if (pSyncNode == NULL) {
49,047!
726
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
727
    if (terrno != 0) code = terrno;
×
728
    TAOS_RETURN(code);
×
729
  }
730

731
  memset(outToken, 0, TSDB_ARB_TOKEN_SIZE);
49,047✔
732
  (void)taosThreadMutexLock(&pSyncNode->arbTokenMutex);
49,047✔
733
  tstrncpy(outToken, pSyncNode->arbToken, TSDB_ARB_TOKEN_SIZE);
49,047✔
734
  (void)taosThreadMutexUnlock(&pSyncNode->arbTokenMutex);
49,047✔
735

736
  syncNodeRelease(pSyncNode);
49,047✔
737
  TAOS_RETURN(code);
49,047✔
738
}
739

740
int32_t syncCheckSynced(int64_t rid) {
5✔
741
  int32_t    code = 0;
5✔
742
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
5✔
743
  if (pSyncNode == NULL) {
5!
744
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
745
    if (terrno != 0) code = terrno;
×
746
    TAOS_RETURN(code);
×
747
  }
748

749
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
5!
750
    code = TSDB_CODE_VND_ARB_NOT_SYNCED;
×
751
    syncNodeRelease(pSyncNode);
×
752
    TAOS_RETURN(code);
×
753
  }
754

755
  bool isSync = pSyncNode->commitIndex >= pSyncNode->assignedCommitIndex;
5✔
756
  code = (isSync ? TSDB_CODE_SUCCESS : TSDB_CODE_VND_ARB_NOT_SYNCED);
5!
757

758
  syncNodeRelease(pSyncNode);
5✔
759
  TAOS_RETURN(code);
5✔
760
}
761

762
int32_t syncUpdateArbTerm(int64_t rid, SyncTerm arbTerm) {
148✔
763
  int32_t    code = 0;
148✔
764
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
148✔
765
  if (pSyncNode == NULL) {
148!
766
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
767
    if (terrno != 0) code = terrno;
×
768
    TAOS_RETURN(code);
×
769
  }
770

771
  pSyncNode->arbTerm = TMAX(arbTerm, pSyncNode->arbTerm);
148✔
772
  syncNodeRelease(pSyncNode);
148✔
773
  TAOS_RETURN(code);
148✔
774
}
775

776
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
1,169,389✔
777
  if (pSyncNode->raftCfg.configIndexCount < 1) {
1,169,389!
778
    sError("vgId:%d, failed get snapshot config index, configIndexCount:%d", pSyncNode->vgId,
×
779
           pSyncNode->raftCfg.configIndexCount);
780
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
781
    return -2;
×
782
  }
783
  SyncIndex lastIndex = (pSyncNode->raftCfg.configIndexArr)[0];
1,169,389✔
784

785
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
2,392,781✔
786
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
1,223,392✔
787
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
53,996✔
788
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
53,908✔
789
    }
790
  }
791
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
1,169,389✔
792
         lastIndex);
793

794
  return lastIndex;
1,169,394✔
795
}
796

797
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
288,104✔
798
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
507,340✔
799
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
359,227✔
800
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
359,200✔
801
      return pSyncNode->peersId[i];
139,991✔
802
    }
803
  }
804
  return EMPTY_RAFT_ID;
148,113✔
805
}
806

807
static void epsetToString(const SEpSet* pEpSet, char* buffer, size_t bufferSize) {
148,248✔
808
  if (pEpSet == NULL || buffer == NULL) {
148,248!
809
    snprintf(buffer, bufferSize, "EpSet is NULL");
×
810
    return;
×
811
  }
812

813
  size_t offset = 0;
148,256✔
814
  offset += snprintf(buffer + offset, bufferSize - offset, "EpSet: [");
148,256✔
815

816
  for (int i = 0; i < pEpSet->numOfEps; ++i) {
436,363✔
817
    if (offset >= bufferSize) break;
288,107!
818
    offset += snprintf(buffer + offset, bufferSize - offset, "%s:%d%s", pEpSet->eps[i].fqdn, pEpSet->eps[i].port,
288,107✔
819
                       (i + 1 < pEpSet->numOfEps) ? ", " : "");
288,107✔
820
  }
821

822
  if (offset < bufferSize) {
148,256!
823
    snprintf(buffer + offset, bufferSize - offset, "]");
148,257✔
824
  }
825
}
826

827
void syncGetRetryEpSet(int64_t rid, SEpSet* pEpSet) {
148,241✔
828
  pEpSet->numOfEps = 0;
148,241✔
829

830
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
148,241✔
831
  if (pSyncNode == NULL) return;
148,260!
832

833
  int index = -1;
148,260✔
834

835
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
148,260✔
836
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
837
  int j = 0;
148,258✔
838
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
438,160✔
839
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
289,894✔
840
    SEp* pEp = &pEpSet->eps[j];
288,120✔
841
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
288,120✔
842
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
288,120✔
843
    pEpSet->numOfEps++;
288,120✔
844
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
288,120✔
845
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
288,125✔
846
           pEp->port);
847
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
288,128✔
848
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
110,154✔
849
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
850
      index = j;
110,149✔
851
    }
852
    j++;
288,128✔
853
  }
854
  if (pEpSet->numOfEps > 0) {
148,266✔
855
    if (index != -1) {
148,252✔
856
      pEpSet->inUse = index;
110,154✔
857
    } else {
858
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
38,098!
859
          pSyncNode->myRaftId.vgId == pSyncNode->leaderCache.vgId) {
×
860
        pEpSet->inUse = pSyncNode->raftCfg.cfg.myIndex;
×
861
      } else {
862
        pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
38,098✔
863
      }
864
    }
865
    // pEpSet->inUse = 0;
866
  }
867
  epsetSort(pEpSet);
148,266✔
868

869
  char buffer[1024];
870
  epsetToString(pEpSet, buffer, sizeof(buffer));
148,257✔
871
  sDebug("vgId:%d, sync get retry epset numOfEps:%d %s inUse:%d", pSyncNode->vgId, pEpSet->numOfEps, buffer,
148,252✔
872
         pEpSet->inUse);
873
  syncNodeRelease(pSyncNode);
148,252✔
874
}
875

876
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
2,652,112✔
877
  int32_t    code = 0;
2,652,112✔
878
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
2,652,112✔
879
  if (pSyncNode == NULL) {
2,652,327✔
880
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
1✔
881
    if (terrno != 0) code = terrno;
1!
882
    sError("sync propose error");
1!
883
    TAOS_RETURN(code);
1✔
884
  }
885

886
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak, seq);
2,652,326✔
887
  syncNodeRelease(pSyncNode);
2,651,781✔
888
  return ret;
2,652,138✔
889
}
890

891
int32_t syncCheckMember(int64_t rid) {
×
892
  int32_t    code = 0;
×
893
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
×
894
  if (pSyncNode == NULL) {
×
895
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
896
    if (terrno != 0) code = terrno;
×
897
    sError("sync propose error");
×
898
    TAOS_RETURN(code);
×
899
  }
900

901
  if (pSyncNode->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
902
    syncNodeRelease(pSyncNode);
×
903
    return TSDB_CODE_SYN_WRONG_ROLE;
×
904
  }
905

906
  syncNodeRelease(pSyncNode);
×
907
  return 0;
×
908
}
909

910
int32_t syncIsCatchUp(int64_t rid) {
5,867✔
911
  int32_t    code = 0;
5,867✔
912
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
5,867✔
913
  if (pSyncNode == NULL) {
5,867!
914
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
915
    if (terrno != 0) code = terrno;
×
916
    sError("sync Node Acquire error since %d", ERRNO);
×
917
    TAOS_RETURN(code);
×
918
  }
919

920
  int32_t isCatchUp = 0;
5,867✔
921
  if (pSyncNode->pLogBuf->totalIndex < 0 || pSyncNode->pLogBuf->commitIndex < 0 ||
5,867!
922
      pSyncNode->pLogBuf->totalIndex < pSyncNode->pLogBuf->commitIndex ||
1,007!
923
      pSyncNode->pLogBuf->totalIndex - pSyncNode->pLogBuf->commitIndex > SYNC_LEARNER_CATCHUP) {
1,007✔
924
    sInfo("vgId:%d, Not catch up, wait one second, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64,
5,506!
925
          pSyncNode->vgId, pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex,
926
          pSyncNode->pLogBuf->matchIndex);
927
    isCatchUp = 0;
5,506✔
928
  } else {
929
    sInfo("vgId:%d, Catch up, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64, pSyncNode->vgId,
361!
930
          pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->matchIndex);
931
    isCatchUp = 1;
361✔
932
  }
933

934
  syncNodeRelease(pSyncNode);
5,867✔
935
  return isCatchUp;
5,867✔
936
}
937

938
ESyncRole syncGetRole(int64_t rid) {
5,867✔
939
  int32_t    code = 0;
5,867✔
940
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
5,867✔
941
  if (pSyncNode == NULL) {
5,867!
942
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
943
    if (terrno != 0) code = terrno;
×
944
    sError("sync Node Acquire error since %d", ERRNO);
×
945
    TAOS_RETURN(code);
×
946
  }
947

948
  ESyncRole role = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole;
5,867✔
949

950
  syncNodeRelease(pSyncNode);
5,867✔
951
  return role;
5,867✔
952
}
953

954
int64_t syncGetTerm(int64_t rid) {
19,411✔
955
  int32_t    code = 0;
19,411✔
956
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
19,411✔
957
  if (pSyncNode == NULL) {
19,411!
958
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
959
    if (terrno != 0) code = terrno;
×
960
    sError("sync Node Acquire error since %d", ERRNO);
×
961
    TAOS_RETURN(code);
×
962
  }
963

964
  int64_t term = raftStoreGetTerm(pSyncNode);
19,411✔
965

966
  syncNodeRelease(pSyncNode);
19,411✔
967
  return term;
19,411✔
968
}
969

970
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
2,653,566✔
971
  int32_t code = 0;
2,653,566✔
972
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,653,566!
973
    code = TSDB_CODE_SYN_NOT_LEADER;
9,691✔
974
    sNWarn(pSyncNode, "sync propose not leader, type:%s", TMSG_INFO(pMsg->msgType));
9,691!
975
    TAOS_RETURN(code);
9,691✔
976
  }
977

978
  if (!pSyncNode->restoreFinish) {
2,643,875✔
979
    code = TSDB_CODE_SYN_PROPOSE_NOT_READY;
119✔
980
    sNWarn(pSyncNode, "failed to sync propose since not ready, type:%s, last:%" PRId64 ", cmt:%" PRId64,
119!
981
           TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
982
    TAOS_RETURN(code);
119✔
983
  }
984

985
  // heartbeat timeout
986
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER && syncNodeHeartbeatReplyTimeout(pSyncNode)) {
2,643,756✔
987
    code = TSDB_CODE_SYN_PROPOSE_NOT_READY;
4✔
988
    sNError(pSyncNode, "failed to sync propose since heartbeat timeout, type:%s, last:%" PRId64 ", cmt:%" PRId64,
4!
989
            TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
990
    TAOS_RETURN(code);
4✔
991
  }
992

993
  // optimized one replica
994
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
2,643,788✔
995
    SyncIndex retIndex;
996
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
2,353,045✔
997
    if (code >= 0) {
2,352,579!
998
      pMsg->info.conn.applyIndex = retIndex;
2,352,710✔
999
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
2,352,710✔
1000

1001
      // after raft member change, need to handle 1->2 switching point
1002
      // at this point, need to switch entry handling thread
1003
      if (pSyncNode->replicaNum == 1) {
2,352,881!
1004
        sGDebug(&pMsg->info.traceId, "vgId:%d, index:%" PRId64 ", propose optimized msg type:%s", pSyncNode->vgId,
2,352,943!
1005
                retIndex, TMSG_INFO(pMsg->msgType));
1006
        return 1;
2,352,792✔
1007
      } else {
1008
        sGDebug(&pMsg->info.traceId,
×
1009
                "vgId:%d, index:%" PRId64 ", propose optimized msg, return to normal, type:%s, handle:%p",
1010
                pSyncNode->vgId, retIndex, TMSG_INFO(pMsg->msgType), pMsg->info.handle);
1011
        return 0;
×
1012
      }
1013
    } else {
1014
      code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1015
      sError("vgId:%d, failed to propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
×
1016
             TMSG_INFO(pMsg->msgType));
1017
      TAOS_RETURN(code);
×
1018
    }
1019
  } else {
1020
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
290,850✔
1021
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
290,857✔
1022
    SRpcMsg   rpcMsg = {.info.traceId = pMsg->info.traceId};
290,858✔
1023
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
290,858✔
1024
    if (code != 0) {
290,859!
1025
      sError("vgId:%d, failed to propose msg while serialize since %s", pSyncNode->vgId, terrstr());
×
1026
      code = syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum);
×
1027
      TAOS_RETURN(code);
×
1028
    }
1029

1030
    sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, propose msg, type:%s", pSyncNode->vgId, pMsg,
290,859!
1031
            TMSG_INFO(pMsg->msgType));
1032
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
290,859✔
1033
    if (code != 0) {
290,856✔
1034
      sWarn("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
1,973!
1035
      TAOS_CHECK_RETURN(syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum));
1,975✔
1036
    }
1037

1038
    if (seq != NULL) *seq = seqNum;
290,812✔
1039
    TAOS_RETURN(code);
290,812✔
1040
  }
1041
}
1042

1043
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId) {
286,528✔
1044
  pSyncTimer->pTimer = NULL;
286,528✔
1045
  pSyncTimer->counter = 0;
286,528✔
1046
  pSyncTimer->timerMS = pSyncNode->hbBaseLine;
286,528✔
1047
  pSyncTimer->timerCb = syncNodeEqPeerHeartbeatTimer;
286,528✔
1048
  pSyncTimer->destId = destId;
286,528✔
1049
  pSyncTimer->timeStamp = taosGetTimestampMs();
286,527✔
1050
  atomic_store_64(&pSyncTimer->logicClock, 0);
286,527✔
1051
  return 0;
286,526✔
1052
}
1053

1054
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
3,480✔
1055
  int32_t code = 0;
3,480✔
1056
  int64_t tsNow = taosGetTimestampMs();
3,480✔
1057
  if (syncIsInit()) {
3,480!
1058
    SSyncHbTimerData* pData = syncHbTimerDataAcquire(pSyncTimer->hbDataRid);
3,480✔
1059
    if (pData == NULL) {
3,480!
1060
      pData = taosMemoryMalloc(sizeof(SSyncHbTimerData));
3,480!
1061
      pData->rid = syncHbTimerDataAdd(pData);
3,480✔
1062
    }
1063
    pSyncTimer->hbDataRid = pData->rid;
3,480✔
1064
    pSyncTimer->timeStamp = tsNow;
3,480✔
1065

1066
    pData->syncNodeRid = pSyncNode->rid;
3,480✔
1067
    pData->pTimer = pSyncTimer;
3,480✔
1068
    pData->destId = pSyncTimer->destId;
3,480✔
1069
    pData->logicClock = pSyncTimer->logicClock;
3,480✔
1070
    pData->execTime = tsNow + pSyncTimer->timerMS;
3,480✔
1071

1072
    sTrace("vgId:%d, start hb timer, rid:%" PRId64 " addr:0x%" PRIx64 " at %d", pSyncNode->vgId, pData->rid,
3,480!
1073
           pData->destId.addr, pSyncTimer->timerMS);
1074

1075
    bool stopped = taosTmrResetPriority(pSyncTimer->timerCb, pSyncTimer->timerMS, (void*)(pData->rid),
3,480✔
1076
                                        syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
3,480✔
1077
    if (stopped) {
3,480!
1078
      sError("vgId:%d, failed to reset hb timer success", pSyncNode->vgId);
×
1079
      return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1080
    }
1081
  } else {
1082
    code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1083
    sError("vgId:%d, start ctrl hb timer error, sync env is stop", pSyncNode->vgId);
×
1084
  }
1085
  return code;
3,480✔
1086
}
1087

1088
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
35,229✔
1089
  int32_t ret = 0;
35,229✔
1090
  (void)atomic_add_fetch_64(&pSyncTimer->logicClock, 1);
35,229✔
1091
  bool stop = taosTmrStop(pSyncTimer->pTimer);
35,230✔
1092
  sDebug("vgId:%d, stop hb timer stop:%d", pSyncNode->vgId, stop);
35,230✔
1093
  pSyncTimer->pTimer = NULL;
35,230✔
1094
  syncHbTimerDataRemove(pSyncTimer->hbDataRid);
35,230✔
1095
  pSyncTimer->hbDataRid = -1;
35,231✔
1096
  return ret;
35,231✔
1097
}
1098

1099
int32_t syncNodeLogStoreRestoreOnNeed(SSyncNode* pNode) {
17,000✔
1100
  int32_t code = 0;
17,000✔
1101
  if (pNode->pLogStore == NULL) {
17,000!
1102
    sError("vgId:%d, log store not created", pNode->vgId);
×
1103
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1104
  }
1105
  if (pNode->pFsm == NULL) {
17,000!
1106
    sError("vgId:%d, pFsm not registered", pNode->vgId);
×
1107
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1108
  }
1109
  if (pNode->pFsm->FpGetSnapshotInfo == NULL) {
17,000!
1110
    sError("vgId:%d, FpGetSnapshotInfo not registered", pNode->vgId);
×
1111
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1112
  }
1113
  SSnapshot snapshot = {0};
17,000✔
1114
  // TODO check return value
1115
  (void)pNode->pFsm->FpGetSnapshotInfo(pNode->pFsm, &snapshot);
17,000✔
1116

1117
  SyncIndex commitIndex = snapshot.lastApplyIndex;
17,000✔
1118
  SyncIndex firstVer = pNode->pLogStore->syncLogBeginIndex(pNode->pLogStore);
17,000✔
1119
  SyncIndex lastVer = pNode->pLogStore->syncLogLastIndex(pNode->pLogStore);
17,000✔
1120
  if ((lastVer < commitIndex || firstVer > commitIndex + 1) || pNode->fsmState == SYNC_FSM_STATE_INCOMPLETE) {
17,000!
1121
    if ((code = pNode->pLogStore->syncLogRestoreFromSnapshot(pNode->pLogStore, commitIndex)) != 0) {
×
1122
      sError("vgId:%d, failed to restore log store from snapshot since %s. lastVer:%" PRId64 ", snapshotVer:%" PRId64,
×
1123
             pNode->vgId, terrstr(), lastVer, commitIndex);
1124
      TAOS_RETURN(code);
×
1125
    }
1126
  }
1127
  TAOS_RETURN(code);
17,000✔
1128
}
1129

1130
// open/close --------------
1131
SSyncNode* syncNodeOpen(SSyncInfo* pSyncInfo, int32_t vnodeVersion) {
16,999✔
1132
  int32_t    code = 0;
16,999✔
1133
  SSyncNode* pSyncNode = taosMemoryCalloc(1, sizeof(SSyncNode));
16,999!
1134
  if (pSyncNode == NULL) {
17,000!
1135
    terrno = TSDB_CODE_OUT_OF_MEMORY;
×
1136
    goto _error;
×
1137
  }
1138

1139
  if (!taosDirExist((char*)(pSyncInfo->path))) {
17,000✔
1140
    if (taosMkDir(pSyncInfo->path) != 0) {
13,225!
1141
      terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
1142
      sError("vgId:%d, failed to create dir:%s since %s", pSyncInfo->vgId, pSyncInfo->path, terrstr());
×
1143
      goto _error;
×
1144
    }
1145
  }
1146

1147
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
16,999✔
1148
  snprintf(pSyncNode->raftStorePath, sizeof(pSyncNode->raftStorePath), "%s%sraft_store.json", pSyncInfo->path,
16,999✔
1149
           TD_DIRSEP);
1150
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
16,999✔
1151

1152
  if (!taosCheckExistFile(pSyncNode->configPath)) {
16,999✔
1153
    // create a new raft config file
1154
    sInfo("vgId:%d, create a new raft config file", pSyncInfo->vgId);
13,224✔
1155
    pSyncNode->vgId = pSyncInfo->vgId;
13,225✔
1156
    pSyncNode->mountVgId = pSyncInfo->mountVgId;
13,225✔
1157
    pSyncNode->raftCfg.isStandBy = pSyncInfo->isStandBy;
13,225✔
1158
    pSyncNode->raftCfg.snapshotStrategy = pSyncInfo->snapshotStrategy;
13,225✔
1159
    pSyncNode->raftCfg.lastConfigIndex = pSyncInfo->syncCfg.lastIndex;
13,225✔
1160
    pSyncNode->raftCfg.batchSize = pSyncInfo->batchSize;
13,225✔
1161
    pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
13,225✔
1162
    pSyncNode->raftCfg.configIndexCount = 1;
13,225✔
1163
    pSyncNode->raftCfg.configIndexArr[0] = -1;
13,225✔
1164

1165
    if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
13,225!
1166
      terrno = code;
×
1167
      sError("vgId:%d, failed to create sync cfg file", pSyncNode->vgId);
×
1168
      goto _error;
×
1169
    }
1170
  } else {
1171
    // update syncCfg by raft_config.json
1172
    if ((code = syncReadCfgFile(pSyncNode)) != 0) {
3,776!
1173
      terrno = code;
×
1174
      sError("vgId:%d, failed to read sync cfg file", pSyncNode->vgId);
×
1175
      goto _error;
×
1176
    }
1177

1178
    if (vnodeVersion > pSyncNode->raftCfg.cfg.changeVersion) {
3,774✔
1179
      if (pSyncInfo->syncCfg.totalReplicaNum > 0 && syncIsConfigChanged(&pSyncNode->raftCfg.cfg, &pSyncInfo->syncCfg)) {
2,538!
1180
        sInfo("vgId:%d, use sync config from input options and write to cfg file", pSyncNode->vgId);
2,162!
1181
        pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
2,162✔
1182
        if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
2,162!
1183
          terrno = code;
×
1184
          sError("vgId:%d, failed to write sync cfg file", pSyncNode->vgId);
×
1185
          goto _error;
×
1186
        }
1187
      } else {
1188
        sInfo("vgId:%d, use sync config from sync cfg file", pSyncNode->vgId);
376!
1189
        pSyncInfo->syncCfg = pSyncNode->raftCfg.cfg;
376✔
1190
      }
1191
    } else {
1192
      sInfo("vgId:%d, skip save sync cfg file since request ver:%d <= file ver:%d", pSyncNode->vgId, vnodeVersion,
1,236!
1193
            pSyncInfo->syncCfg.changeVersion);
1194
    }
1195
  }
1196

1197
  // init by SSyncInfo
1198
  pSyncNode->vgId = pSyncInfo->vgId;
17,000✔
1199
  pSyncNode->mountVgId = pSyncInfo->mountVgId;
17,000✔
1200
  SSyncCfg* pCfg = &pSyncNode->raftCfg.cfg;
17,000✔
1201
  bool      updated = false;
17,000✔
1202
  sInfo("vgId:%d, start to open sync node, totalReplicaNum:%d replicaNum:%d selfIndex:%d", pSyncNode->vgId,
17,000✔
1203
        pCfg->totalReplicaNum, pCfg->replicaNum, pCfg->myIndex);
1204
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
43,534✔
1205
    SNodeInfo* pNode = &pCfg->nodeInfo[i];
26,534✔
1206
    if (tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort)) {
26,534!
1207
      updated = true;
×
1208
    }
1209
    sInfo("vgId:%d, index:%d ep:%s:%u dnode:%d cluster:%" PRId64, pSyncNode->vgId, i, pNode->nodeFqdn, pNode->nodePort,
26,534✔
1210
          pNode->nodeId, pNode->clusterId);
1211
  }
1212

1213
  if (vnodeVersion > pSyncInfo->syncCfg.changeVersion) {
17,000✔
1214
    if (updated) {
2,468!
1215
      sInfo("vgId:%d, save config info since dnode info changed", pSyncNode->vgId);
×
1216
      if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
×
1217
        terrno = code;
×
1218
        sError("vgId:%d, failed to write sync cfg file on dnode info updated", pSyncNode->vgId);
×
1219
        goto _error;
×
1220
      }
1221
    }
1222
  }
1223

1224
  pSyncNode->pWal = pSyncInfo->pWal;
17,000✔
1225
  pSyncNode->msgcb = pSyncInfo->msgcb;
17,000✔
1226
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
17,000✔
1227
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
17,000✔
1228
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
17,000✔
1229

1230
  // create raft log ring buffer
1231
  code = syncLogBufferCreate(&pSyncNode->pLogBuf);
17,000✔
1232
  if (pSyncNode->pLogBuf == NULL) {
17,000!
1233
    sError("failed to init sync log buffer since %s. vgId:%d", tstrerror(code), pSyncNode->vgId);
×
1234
    goto _error;
×
1235
  }
1236

1237
  // init replicaNum, replicasId
1238
  pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
17,000✔
1239
  pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
17,000✔
1240
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
43,534✔
1241
    if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
26,534!
1242
        false) {
1243
      sError("vgId:%d, failed to determine raft member id, replica:%d", pSyncNode->vgId, i);
×
1244
      goto _error;
×
1245
    }
1246
  }
1247

1248
  // init internal
1249
  pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
17,000✔
1250
  pSyncNode->myRaftId = pSyncNode->replicasId[pSyncNode->raftCfg.cfg.myIndex];
17,000✔
1251

1252
  // init peersNum, peers, peersId
1253
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
17,000✔
1254
  int32_t j = 0;
17,000✔
1255
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
43,534✔
1256
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
26,534✔
1257
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
9,534✔
1258
      pSyncNode->peersId[j] = pSyncNode->replicasId[i];
9,534✔
1259
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
9,534✔
1260
      j++;
9,534✔
1261
    }
1262
  }
1263

1264
  pSyncNode->arbTerm = -1;
17,000✔
1265
  (void)taosThreadMutexInit(&pSyncNode->arbTokenMutex, NULL);
17,000✔
1266
  syncUtilGenerateArbToken(pSyncNode->myNodeInfo.nodeId, pSyncInfo->vgId, pSyncNode->arbToken);
17,000✔
1267
  sInfo("vgId:%d, generate arb token:%s", pSyncNode->vgId, pSyncNode->arbToken);
17,000✔
1268

1269
  // init raft algorithm
1270
  pSyncNode->pFsm = pSyncInfo->pFsm;
17,000✔
1271
  pSyncInfo->pFsm = NULL;
17,000✔
1272
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
17,000✔
1273
  pSyncNode->leaderCache = EMPTY_RAFT_ID;
17,000✔
1274
  pSyncNode->leaderCacheEp.port = 0;
17,000✔
1275
  pSyncNode->leaderCacheEp.fqdn[0] = '\0';
17,000✔
1276

1277
  // init life cycle outside
1278

1279
  // TLA+ Spec
1280
  // InitHistoryVars == /\ elections = {}
1281
  //                    /\ allLogs   = {}
1282
  //                    /\ voterLog  = [i \in Server |-> [j \in {} |-> <<>>]]
1283
  // InitServerVars == /\ currentTerm = [i \in Server |-> 1]
1284
  //                   /\ state       = [i \in Server |-> Follower]
1285
  //                   /\ votedFor    = [i \in Server |-> Nil]
1286
  // InitCandidateVars == /\ votesResponded = [i \in Server |-> {}]
1287
  //                      /\ votesGranted   = [i \in Server |-> {}]
1288
  // \* The values nextIndex[i][i] and matchIndex[i][i] are never read, since the
1289
  // \* leader does not send itself messages. It's still easier to include these
1290
  // \* in the functions.
1291
  // InitLeaderVars == /\ nextIndex  = [i \in Server |-> [j \in Server |-> 1]]
1292
  //                   /\ matchIndex = [i \in Server |-> [j \in Server |-> 0]]
1293
  // InitLogVars == /\ log          = [i \in Server |-> << >>]
1294
  //                /\ commitIndex  = [i \in Server |-> 0]
1295
  // Init == /\ messages = [m \in {} |-> 0]
1296
  //         /\ InitHistoryVars
1297
  //         /\ InitServerVars
1298
  //         /\ InitCandidateVars
1299
  //         /\ InitLeaderVars
1300
  //         /\ InitLogVars
1301
  //
1302

1303
  // init TLA+ server vars
1304
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
17,000✔
1305
  pSyncNode->roleTimeMs = taosGetTimestampMs();
17,000✔
1306
  if ((code = raftStoreOpen(pSyncNode)) != 0) {
17,000!
1307
    terrno = code;
×
1308
    sError("vgId:%d, failed to open raft store at path %s", pSyncNode->vgId, pSyncNode->raftStorePath);
×
1309
    goto _error;
×
1310
  }
1311

1312
  // init TLA+ candidate vars
1313
  pSyncNode->pVotesGranted = voteGrantedCreate(pSyncNode);
17,000✔
1314
  if (pSyncNode->pVotesGranted == NULL) {
17,000!
1315
    sError("vgId:%d, failed to create VotesGranted", pSyncNode->vgId);
×
1316
    goto _error;
×
1317
  }
1318
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
17,000✔
1319
  if (pSyncNode->pVotesRespond == NULL) {
17,000!
1320
    sError("vgId:%d, failed to create VotesRespond", pSyncNode->vgId);
×
1321
    goto _error;
×
1322
  }
1323

1324
  // init TLA+ leader vars
1325
  pSyncNode->pNextIndex = syncIndexMgrCreate(pSyncNode);
17,000✔
1326
  if (pSyncNode->pNextIndex == NULL) {
17,000!
1327
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
×
1328
    goto _error;
×
1329
  }
1330
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
17,000✔
1331
  if (pSyncNode->pMatchIndex == NULL) {
17,000!
1332
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
×
1333
    goto _error;
×
1334
  }
1335

1336
  // init TLA+ log vars
1337
  pSyncNode->pLogStore = logStoreCreate(pSyncNode);
17,000✔
1338
  if (pSyncNode->pLogStore == NULL) {
17,000!
1339
    sError("vgId:%d, failed to create SyncLogStore", pSyncNode->vgId);
×
1340
    goto _error;
×
1341
  }
1342

1343
  SyncIndex commitIndex = SYNC_INDEX_INVALID;
17,000✔
1344
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
17,000✔
1345
    SSnapshot snapshot = {0};
16,998✔
1346
    // TODO check return value
1347
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
16,998✔
1348
    if (snapshot.lastApplyIndex > commitIndex) {
16,999✔
1349
      commitIndex = snapshot.lastApplyIndex;
1,586✔
1350
      sNTrace(pSyncNode, "reset commit index by snapshot");
1,586!
1351
    }
1352
    pSyncNode->fsmState = snapshot.state;
16,999✔
1353
    if (pSyncNode->fsmState == SYNC_FSM_STATE_INCOMPLETE) {
16,999!
1354
      sError("vgId:%d, fsm state is incomplete.", pSyncNode->vgId);
×
1355
      if (pSyncNode->replicaNum == 1) {
×
1356
        terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1357
        goto _error;
×
1358
      }
1359
    }
1360
  }
1361
  pSyncNode->commitIndex = commitIndex;
17,001✔
1362
  sInfo("vgId:%d, sync node commitIndex initialized as %" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
17,001✔
1363

1364
  // restore log store on need
1365
  if ((code = syncNodeLogStoreRestoreOnNeed(pSyncNode)) < 0) {
17,002!
1366
    terrno = code;
×
1367
    sError("vgId:%d, failed to restore log store since %s.", pSyncNode->vgId, terrstr());
×
1368
    goto _error;
×
1369
  }
1370

1371
  // timer ms init
1372
  pSyncNode->pingBaseLine = PING_TIMER_MS;
17,000✔
1373
  pSyncNode->electBaseLine = tsElectInterval;
17,000✔
1374
  pSyncNode->hbBaseLine = tsHeartbeatInterval;
17,000✔
1375

1376
  // init ping timer
1377
  pSyncNode->pPingTimer = NULL;
17,000✔
1378
  pSyncNode->pingTimerMS = pSyncNode->pingBaseLine;
17,000✔
1379
  atomic_store_64(&pSyncNode->pingTimerLogicClock, 0);
17,000✔
1380
  atomic_store_64(&pSyncNode->pingTimerLogicClockUser, 0);
17,000✔
1381
  pSyncNode->FpPingTimerCB = syncNodeEqPingTimer;
17,000✔
1382
  pSyncNode->pingTimerCounter = 0;
17,000✔
1383

1384
  // init elect timer
1385
  pSyncNode->pElectTimer = NULL;
17,000✔
1386
  pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
17,000✔
1387
  atomic_store_64(&pSyncNode->electTimerLogicClock, 0);
17,000✔
1388
  pSyncNode->FpElectTimerCB = syncNodeEqElectTimer;
17,000✔
1389
  pSyncNode->electTimerCounter = 0;
17,000✔
1390

1391
  // init heartbeat timer
1392
  pSyncNode->pHeartbeatTimer = NULL;
17,000✔
1393
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
17,000✔
1394
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, 0);
17,000✔
1395
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClockUser, 0);
17,000✔
1396
#ifdef BUILD_NO_CALL
1397
  pSyncNode->FpHeartbeatTimerCB = syncNodeEqHeartbeatTimer;
1398
#endif
1399
  pSyncNode->heartbeatTimerCounter = 0;
17,000✔
1400

1401
  // init peer heartbeat timer
1402
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
271,998✔
1403
    if ((code = syncHbTimerInit(pSyncNode, &(pSyncNode->peerHeartbeatTimerArr[i]), (pSyncNode->replicasId)[i])) != 0) {
254,998!
1404
      terrno = code;
×
1405
      goto _error;
×
1406
    }
1407
  }
1408

1409
  // tools
1410
  if ((code = syncRespMgrCreate(pSyncNode, SYNC_RESP_TTL_MS, &pSyncNode->pSyncRespMgr)) != 0) {
17,000!
1411
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
×
1412
    goto _error;
×
1413
  }
1414
  if (pSyncNode->pSyncRespMgr == NULL) {
17,000!
1415
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
×
1416
    goto _error;
×
1417
  }
1418

1419
  // restore state
1420
  pSyncNode->restoreFinish = false;
17,000✔
1421

1422
  // snapshot senders
1423
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
271,931✔
1424
    SSyncSnapshotSender* pSender = NULL;
254,932✔
1425
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
254,932✔
1426
    if (pSender == NULL) return NULL;
254,908!
1427

1428
    pSyncNode->senders[i] = pSender;
254,908✔
1429
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
254,908✔
1430
  }
1431

1432
  // snapshot receivers
1433
  code = snapshotReceiverCreate(pSyncNode, EMPTY_RAFT_ID, &pSyncNode->pNewNodeReceiver);
16,999✔
1434
  if (pSyncNode->pNewNodeReceiver == NULL) return NULL;
16,999!
1435
  sRDebug(pSyncNode->pNewNodeReceiver, "snapshot receiver create while open sync node, data:%p",
16,999✔
1436
          pSyncNode->pNewNodeReceiver);
1437

1438
  // is config changing
1439
  pSyncNode->changing = false;
16,999✔
1440

1441
  // replication mgr
1442
  if ((code = syncNodeLogReplInit(pSyncNode)) < 0) {
16,999!
1443
    terrno = code;
×
1444
    sError("vgId:%d, failed to init repl mgr since %s.", pSyncNode->vgId, terrstr());
×
1445
    goto _error;
×
1446
  }
1447

1448
  // peer state
1449
  if ((code = syncNodePeerStateInit(pSyncNode)) < 0) {
17,000!
1450
    terrno = code;
×
1451
    sError("vgId:%d, failed to init peer stat since %s.", pSyncNode->vgId, terrstr());
×
1452
    goto _error;
×
1453
  }
1454

1455
  //
1456
  // min match index
1457
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
16,999✔
1458

1459
  // start in syncNodeStart
1460
  // start raft
1461

1462
  int64_t timeNow = taosGetTimestampMs();
16,999✔
1463
  pSyncNode->startTime = timeNow;
16,999✔
1464
  pSyncNode->lastReplicateTime = timeNow;
16,999✔
1465

1466
  // snapshotting
1467
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
16,999✔
1468

1469
  // init log buffer
1470
  if ((code = syncLogBufferInit(pSyncNode->pLogBuf, pSyncNode)) < 0) {
17,000!
1471
    terrno = code;
×
1472
    sError("vgId:%d, failed to init sync log buffer since %s", pSyncNode->vgId, terrstr());
×
1473
    goto _error;
×
1474
  }
1475

1476
  pSyncNode->isStart = true;
17,000✔
1477
  pSyncNode->electNum = 0;
17,000✔
1478
  pSyncNode->becomeLeaderNum = 0;
17,000✔
1479
  pSyncNode->becomeAssignedLeaderNum = 0;
17,000✔
1480
  pSyncNode->configChangeNum = 0;
17,000✔
1481
  pSyncNode->hbSlowNum = 0;
17,000✔
1482
  pSyncNode->hbrSlowNum = 0;
17,000✔
1483
  pSyncNode->tmrRoutineNum = 0;
17,000✔
1484

1485
  sNInfo(pSyncNode, "sync node opened, node:%p electInterval:%d heartbeatInterval:%d heartbeatTimeout:%d", pSyncNode,
17,000✔
1486
         tsElectInterval, tsHeartbeatInterval, tsHeartbeatTimeout);
1487
  return pSyncNode;
17,000✔
1488

1489
_error:
×
1490
  if (pSyncInfo->pFsm) {
×
1491
    taosMemoryFree(pSyncInfo->pFsm);
×
1492
    pSyncInfo->pFsm = NULL;
×
1493
  }
1494
  syncNodeClose(pSyncNode);
×
1495
  pSyncNode = NULL;
×
1496
  return NULL;
×
1497
}
1498

1499
#ifdef BUILD_NO_CALL
1500
void syncNodeMaybeUpdateCommitBySnapshot(SSyncNode* pSyncNode) {
1501
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
1502
    SSnapshot snapshot = {0};
1503
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
1504
    if (snapshot.lastApplyIndex > pSyncNode->commitIndex) {
1505
      pSyncNode->commitIndex = snapshot.lastApplyIndex;
1506
    }
1507
  }
1508
}
1509
#endif
1510

1511
int32_t syncNodeRestore(SSyncNode* pSyncNode) {
16,999✔
1512
  int32_t code = 0;
16,999✔
1513
  if (pSyncNode->pLogStore == NULL) {
16,999!
1514
    sError("vgId:%d, log store not created", pSyncNode->vgId);
×
1515
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1516
  }
1517
  if (pSyncNode->pLogBuf == NULL) {
16,999!
1518
    sError("vgId:%d, ring log buffer not created", pSyncNode->vgId);
×
1519
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1520
  }
1521

1522
  (void)taosThreadMutexLock(&pSyncNode->pLogBuf->mutex);
16,999✔
1523
  SyncIndex lastVer = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
16,999✔
1524
  SyncIndex commitIndex = pSyncNode->pLogStore->syncLogCommitIndex(pSyncNode->pLogStore);
16,999✔
1525
  SyncIndex endIndex = pSyncNode->pLogBuf->endIndex;
16,999✔
1526
  (void)taosThreadMutexUnlock(&pSyncNode->pLogBuf->mutex);
16,999✔
1527

1528
  if (lastVer != -1 && endIndex != lastVer + 1) {
16,999!
1529
    code = TSDB_CODE_WAL_LOG_INCOMPLETE;
×
1530
    sWarn("vgId:%d, failed to restore sync node since %s. expected lastLogIndex:%" PRId64 ", lastVer:%" PRId64,
×
1531
          pSyncNode->vgId, terrstr(), endIndex - 1, lastVer);
1532
    // TAOS_RETURN(code);
1533
  }
1534

1535
  // if (endIndex != lastVer + 1) return TSDB_CODE_SYN_INTERNAL_ERROR;
1536
  pSyncNode->commitIndex = TMAX(pSyncNode->commitIndex, commitIndex);
16,999✔
1537
  sInfo("vgId:%d, restore began, and keep syncing until commitIndex:%" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
16,999✔
1538

1539
  if (pSyncNode->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
33,998!
1540
      (code = syncLogBufferCommit(pSyncNode->pLogBuf, pSyncNode, pSyncNode->commitIndex, NULL, "restore")) < 0) {
16,999✔
1541
    TAOS_RETURN(code);
×
1542
  }
1543

1544
  TAOS_RETURN(code);
16,999✔
1545
}
1546

1547
int32_t syncNodeStart(SSyncNode* pSyncNode) {
16,999✔
1548
  // start raft
1549
  sInfo("vgId:%d, begin to start sync node", pSyncNode->vgId);
16,999✔
1550
  if (pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
16,999✔
1551
    syncNodeBecomeLearner(pSyncNode, "first start");
364✔
1552
  } else {
1553
    if (pSyncNode->replicaNum == 1) {
16,635✔
1554
      raftStoreNextTerm(pSyncNode);
12,571✔
1555
      syncNodeBecomeLeader(pSyncNode, "one replica start");
12,571✔
1556

1557
      // Raft 3.6.2 Committing entries from previous terms
1558
      TAOS_CHECK_RETURN(syncNodeAppendNoop(pSyncNode));
12,571!
1559
    } else {
1560
      SRaftId id = {0};
4,064✔
1561
      syncNodeBecomeFollower(pSyncNode, id, "first start");
4,064✔
1562
    }
1563
  }
1564

1565
  int32_t ret = 0;
16,999✔
1566
  ret = syncNodeStartPingTimer(pSyncNode);
16,999✔
1567
  if (ret != 0) {
16,999!
1568
    sError("vgId:%d, failed to start ping timer since %s", pSyncNode->vgId, tstrerror(ret));
×
1569
  }
1570
  sInfo("vgId:%d, sync node started", pSyncNode->vgId);
16,999✔
1571
  return ret;
16,999✔
1572
}
1573

1574
#ifdef BUILD_NO_CALL
1575
int32_t syncNodeStartStandBy(SSyncNode* pSyncNode) {
1576
  // state change
1577
  int32_t code = 0;
1578
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
1579
  pSyncNode->roleTimeMs = taosGetTimestampMs();
1580
  // TODO check return value
1581
  TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1582

1583
  // reset elect timer, long enough
1584
  int32_t electMS = TIMER_MAX_MS;
1585
  code = syncNodeRestartElectTimer(pSyncNode, electMS);
1586
  if (code < 0) {
1587
    sError("vgId:%d, failed to restart elect timer since %s", pSyncNode->vgId, terrstr());
1588
    return -1;
1589
  }
1590

1591
  code = syncNodeStartPingTimer(pSyncNode);
1592
  if (code < 0) {
1593
    sError("vgId:%d, failed to start ping timer since %s", pSyncNode->vgId, terrstr());
1594
    return -1;
1595
  }
1596
  return code;
1597
}
1598
#endif
1599

1600
void syncNodePreClose(SSyncNode* pSyncNode) {
16,999✔
1601
  int32_t code = 0;
16,999✔
1602
  if (pSyncNode == NULL) {
16,999!
1603
    sError("failed to pre close sync node since sync node is null");
×
1604
    return;
×
1605
  }
1606
  if (pSyncNode->pFsm == NULL) {
16,999!
1607
    sError("failed to pre close sync node since fsm is null");
×
1608
    return;
×
1609
  }
1610
  if (pSyncNode->pFsm->FpApplyQueueItems == NULL) {
16,999!
1611
    sError("failed to pre close sync node since FpApplyQueueItems is null");
×
1612
    return;
×
1613
  }
1614

1615
  // stop elect timer
1616
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
16,999!
1617
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1618
    return;
×
1619
  }
1620

1621
  // stop heartbeat timer
1622
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
16,999!
1623
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
1624
    return;
×
1625
  }
1626

1627
  // stop ping timer
1628
  if ((code = syncNodeStopPingTimer(pSyncNode)) != 0) {
16,999!
1629
    sError("vgId:%d, failed to stop ping timer since %s", pSyncNode->vgId, tstrerror(code));
×
1630
    return;
×
1631
  }
1632

1633
  // clean rsp
1634
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
16,999✔
1635
}
1636

1637
void syncNodePostClose(SSyncNode* pSyncNode) {
14,532✔
1638
  if (pSyncNode->pNewNodeReceiver != NULL) {
14,532!
1639
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
14,532!
1640
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1641
    }
1642

1643
    sDebug("vgId:%d, snapshot receiver destroy while preclose sync node, data:%p", pSyncNode->vgId,
14,532✔
1644
           pSyncNode->pNewNodeReceiver);
1645
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
14,532✔
1646
    pSyncNode->pNewNodeReceiver = NULL;
14,531✔
1647
  }
1648
}
14,531✔
1649

1650
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }
3,472!
1651

1652
void syncNodeClose(SSyncNode* pSyncNode) {
16,999✔
1653
  int32_t code = 0;
16,999✔
1654
  if (pSyncNode == NULL) return;
16,999!
1655
  sNInfo(pSyncNode, "sync close, node:%p", pSyncNode);
16,999✔
1656

1657
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
16,999✔
1658

1659
  if ((code = syncNodeStopPingTimer(pSyncNode)) != 0) {
16,999!
1660
    sError("vgId:%d, failed to stop ping timer since %s", pSyncNode->vgId, tstrerror(code));
×
1661
    return;
×
1662
  }
1663
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
16,999!
1664
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1665
    return;
×
1666
  }
1667
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
16,999!
1668
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
1669
    return;
×
1670
  }
1671
  syncNodeLogReplDestroy(pSyncNode);
16,999✔
1672

1673
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
16,999✔
1674
  pSyncNode->pSyncRespMgr = NULL;
16,998✔
1675
  voteGrantedDestroy(pSyncNode->pVotesGranted);
16,998✔
1676
  pSyncNode->pVotesGranted = NULL;
16,996✔
1677
  votesRespondDestory(pSyncNode->pVotesRespond);
16,996✔
1678
  pSyncNode->pVotesRespond = NULL;
16,997✔
1679
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
16,997✔
1680
  pSyncNode->pNextIndex = NULL;
16,996✔
1681
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
16,996✔
1682
  pSyncNode->pMatchIndex = NULL;
16,998✔
1683
  logStoreDestory(pSyncNode->pLogStore);
16,998✔
1684
  pSyncNode->pLogStore = NULL;
16,997✔
1685
  syncLogBufferDestroy(pSyncNode->pLogBuf);
16,997✔
1686
  pSyncNode->pLogBuf = NULL;
16,999✔
1687

1688
  (void)taosThreadMutexDestroy(&pSyncNode->arbTokenMutex);
16,999✔
1689

1690
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
271,928✔
1691
    if (pSyncNode->senders[i] != NULL) {
254,929!
1692
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", pSyncNode->vgId, pSyncNode->senders[i]);
254,931✔
1693

1694
      if (snapshotSenderIsStart(pSyncNode->senders[i])) {
254,938!
1695
        snapshotSenderStop(pSyncNode->senders[i], false);
×
1696
      }
1697

1698
      snapshotSenderDestroy(pSyncNode->senders[i]);
254,926✔
1699
      pSyncNode->senders[i] = NULL;
254,954✔
1700
    }
1701
  }
1702

1703
  if (pSyncNode->pNewNodeReceiver != NULL) {
16,999✔
1704
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
2,467!
1705
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1706
    }
1707

1708
    sDebug("vgId:%d, snapshot receiver destroy while close, data:%p", pSyncNode->vgId, pSyncNode->pNewNodeReceiver);
2,467✔
1709
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
2,467✔
1710
    pSyncNode->pNewNodeReceiver = NULL;
2,467✔
1711
  }
1712

1713
  if (pSyncNode->pFsm != NULL) {
16,999!
1714
    taosMemoryFree(pSyncNode->pFsm);
16,999!
1715
  }
1716

1717
  raftStoreClose(pSyncNode);
16,997✔
1718

1719
  taosMemoryFree(pSyncNode);
16,997!
1720
}
1721

1722
ESyncStrategy syncNodeStrategy(SSyncNode* pSyncNode) { return pSyncNode->raftCfg.snapshotStrategy; }
×
1723

1724
// timer control --------------
1725
int32_t syncNodeStartPingTimer(SSyncNode* pSyncNode) {
16,999✔
1726
  int32_t code = 0;
16,999✔
1727
  if (syncIsInit()) {
16,999!
1728
    bool stopped = taosTmrResetPriority(pSyncNode->FpPingTimerCB, pSyncNode->pingTimerMS, (void*)pSyncNode->rid,
16,999✔
1729
                                        syncEnv()->pTimerManager, &pSyncNode->pPingTimer, 2);
16,999✔
1730
    if (stopped) {
16,999!
1731
      sError("vgId:%d, failed to reset ping timer, ms:%d", pSyncNode->vgId, pSyncNode->pingTimerMS);
×
1732
      return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1733
    }
1734
    atomic_store_64(&pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
16,999✔
1735
  } else {
1736
    sError("vgId:%d, start ping timer error, sync env is stop", pSyncNode->vgId);
×
1737
  }
1738
  return code;
16,999✔
1739
}
1740

1741
int32_t syncNodeStopPingTimer(SSyncNode* pSyncNode) {
33,998✔
1742
  int32_t code = 0;
33,998✔
1743
  (void)atomic_add_fetch_64(&pSyncNode->pingTimerLogicClockUser, 1);
33,998✔
1744
  bool stop = taosTmrStop(pSyncNode->pPingTimer);
33,998✔
1745
  sDebug("vgId:%d, stop ping timer, stop:%d", pSyncNode->vgId, stop);
33,998✔
1746
  pSyncNode->pPingTimer = NULL;
33,998✔
1747
  return code;
33,998✔
1748
}
1749

1750
int32_t syncNodeStartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
473,416✔
1751
  int32_t code = 0;
473,416✔
1752
  if (syncIsInit()) {
473,416!
1753
    pSyncNode->electTimerMS = ms;
473,416✔
1754

1755
    int64_t execTime = taosGetTimestampMs() + ms;
473,416✔
1756
    atomic_store_64(&(pSyncNode->electTimerParam.executeTime), execTime);
473,416✔
1757
    atomic_store_64(&(pSyncNode->electTimerParam.logicClock), pSyncNode->electTimerLogicClock);
473,417✔
1758
    pSyncNode->electTimerParam.pSyncNode = pSyncNode;
473,416✔
1759
    pSyncNode->electTimerParam.pData = NULL;
473,416✔
1760

1761
    bool stopped = taosTmrReset(pSyncNode->FpElectTimerCB, pSyncNode->electTimerMS, (void*)(pSyncNode->rid),
473,416✔
1762
                                syncEnv()->pTimerManager, &pSyncNode->pElectTimer);
473,416✔
1763
    if (stopped) sWarn("vgId:%d, failed to reset elect timer, ms:%d", pSyncNode->vgId, ms);
473,417!
1764
  } else {
1765
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
×
1766
  }
1767
  return code;
473,417✔
1768
}
1769

1770
int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
521,437✔
1771
  int32_t code = 0;
521,437✔
1772
  (void)atomic_add_fetch_64(&pSyncNode->electTimerLogicClock, 1);
521,437✔
1773
  bool stop = taosTmrStop(pSyncNode->pElectTimer);
521,437✔
1774
  sTrace("vgId:%d, stop elect timer, stop:%d", pSyncNode->vgId, stop);
521,436✔
1775
  pSyncNode->pElectTimer = NULL;
521,436✔
1776

1777
  return code;
521,436✔
1778
}
1779

1780
int32_t syncNodeRestartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
473,417✔
1781
  int32_t ret = 0;
473,417✔
1782
  TAOS_CHECK_RETURN(syncNodeStopElectTimer(pSyncNode));
473,417!
1783
  TAOS_CHECK_RETURN(syncNodeStartElectTimer(pSyncNode, ms));
473,416!
1784
  return ret;
473,417✔
1785
}
1786

1787
void syncNodeResetElectTimer(SSyncNode* pSyncNode) {
473,416✔
1788
  int32_t code = 0;
473,416✔
1789
  int32_t electMS;
1790

1791
  if (pSyncNode->raftCfg.isStandBy) {
473,416!
1792
    electMS = TIMER_MAX_MS;
×
1793
  } else {
1794
    electMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
473,416✔
1795
  }
1796

1797
  if ((code = syncNodeRestartElectTimer(pSyncNode, electMS)) != 0) {
473,417!
1798
    sWarn("vgId:%d, failed to restart elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1799
    return;
×
1800
  };
1801

1802
  sNTrace(pSyncNode, "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine,
473,417!
1803
          electMS);
1804
}
1805

1806
#ifdef BUILD_NO_CALL
1807
static int32_t syncNodeDoStartHeartbeatTimer(SSyncNode* pSyncNode) {
1808
  int32_t code = 0;
1809
  if (syncIsInit()) {
1810
    TAOS_CHECK_RETURN(taosTmrReset(pSyncNode->FpHeartbeatTimerCB, pSyncNode->heartbeatTimerMS, (void*)pSyncNode->rid,
1811
                                   syncEnv()->pTimerManager, &pSyncNode->pHeartbeatTimer));
1812
    atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
1813
  } else {
1814
    sError("vgId:%d, start heartbeat timer error, sync env is stop", pSyncNode->vgId);
1815
  }
1816

1817
  sNTrace(pSyncNode, "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
1818
  return code;
1819
}
1820
#endif
1821

1822
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
16,125✔
1823
  int32_t ret = 0;
16,125✔
1824

1825
#if 0
1826
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
1827
  ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
1828
#endif
1829

1830
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
19,605✔
1831
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
3,480✔
1832
    if (pSyncTimer != NULL) {
3,480!
1833
      TAOS_CHECK_RETURN(syncHbTimerStart(pSyncNode, pSyncTimer));
3,480!
1834
    }
1835
  }
1836

1837
  return ret;
16,125✔
1838
}
1839

1840
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
43,293✔
1841
  int32_t code = 0;
43,293✔
1842

1843
#if 0
1844
  TAOS_CHECK_RETURN(atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1));
1845
  bool stop = taosTmrStop(pSyncNode->pHeartbeatTimer);
1846
  sDebug("vgId:%d, stop heartbeat timer, stop:%d", pSyncNode->vgId, stop);
1847
  pSyncNode->pHeartbeatTimer = NULL;
1848
#endif
1849

1850
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
78,524✔
1851
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
35,228✔
1852
    if (pSyncTimer != NULL) {
35,230!
1853
      TAOS_CHECK_RETURN(syncHbTimerStop(pSyncNode, pSyncTimer));
35,230!
1854
    }
1855
  }
1856

1857
  return code;
43,296✔
1858
}
1859

1860
#ifdef BUILD_NO_CALL
1861
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode) {
1862
  // TODO check return value
1863
  int32_t code = 0;
1864
  TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1865
  TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
1866
  return 0;
1867
}
1868
#endif
1869

1870
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pNode, SRpcMsg* pMsg) {
1,035,923✔
1871
  SEpSet* epSet = NULL;
1,035,923✔
1872
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
1,526,969✔
1873
    if (destRaftId->addr == pNode->peersId[i].addr) {
1,526,907✔
1874
      epSet = &pNode->peersEpset[i];
1,035,861✔
1875
      break;
1,035,861✔
1876
    }
1877
  }
1878

1879
  int32_t code = -1;
1,035,923✔
1880
  if (pNode->syncSendMSg != NULL && epSet != NULL) {
1,035,923!
1881
    syncUtilMsgHtoN(pMsg->pCont);
1,035,869✔
1882
    pMsg->info.noResp = 1;
1,035,838✔
1883
    code = pNode->syncSendMSg(epSet, pMsg);
1,035,838✔
1884
  }
1885

1886
  if (code < 0) {
1,035,962✔
1887
    sError("vgId:%d, failed to send sync msg since %s. epset:%p dnode:%d addr:0x%" PRIx64, pNode->vgId, tstrerror(code),
90!
1888
           epSet, DID(destRaftId), destRaftId->addr);
1889
    rpcFreeCont(pMsg->pCont);
90✔
1890
  }
1891

1892
  TAOS_RETURN(code);
1,035,962✔
1893
}
1894

1895
inline bool syncNodeInConfig(SSyncNode* pNode, const SSyncCfg* pCfg) {
3,065✔
1896
  bool b1 = false;
3,065✔
1897
  bool b2 = false;
3,065✔
1898

1899
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
3,661!
1900
    if (strcmp(pCfg->nodeInfo[i].nodeFqdn, pNode->myNodeInfo.nodeFqdn) == 0 &&
3,661!
1901
        pCfg->nodeInfo[i].nodePort == pNode->myNodeInfo.nodePort) {
3,661✔
1902
      b1 = true;
3,065✔
1903
      break;
3,065✔
1904
    }
1905
  }
1906

1907
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
3,661!
1908
    SRaftId raftId = {
3,661✔
1909
        .addr = SYNC_ADDR(&pCfg->nodeInfo[i]),
3,661✔
1910
        .vgId = pNode->vgId,
3,661✔
1911
    };
1912

1913
    if (syncUtilSameId(&raftId, &pNode->myRaftId)) {
3,661✔
1914
      b2 = true;
3,065✔
1915
      break;
3,065✔
1916
    }
1917
  }
1918

1919
  if (b1 != b2) {
3,065!
1920
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1921
    return false;
×
1922
  }
1923
  return b1;
3,065✔
1924
}
1925

1926
static bool syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg) {
4,501✔
1927
  if (pOldCfg->totalReplicaNum != pNewCfg->totalReplicaNum) return true;
4,501✔
1928
  if (pOldCfg->myIndex != pNewCfg->myIndex) return true;
2,993✔
1929
  for (int32_t i = 0; i < pOldCfg->totalReplicaNum; ++i) {
7,286✔
1930
    const SNodeInfo* pOldInfo = &pOldCfg->nodeInfo[i];
5,310✔
1931
    const SNodeInfo* pNewInfo = &pNewCfg->nodeInfo[i];
5,310✔
1932
    if (strcmp(pOldInfo->nodeFqdn, pNewInfo->nodeFqdn) != 0) return true;
5,310!
1933
    if (pOldInfo->nodePort != pNewInfo->nodePort) return true;
5,310✔
1934
    if (pOldInfo->nodeRole != pNewInfo->nodeRole) return true;
5,306✔
1935
  }
1936

1937
  return false;
1,976✔
1938
}
1939

1940
int32_t syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncIndex lastConfigChangeIndex) {
2,339✔
1941
  int32_t  code = 0;
2,339✔
1942
  SSyncCfg oldConfig = pSyncNode->raftCfg.cfg;
2,339✔
1943
  if (!syncIsConfigChanged(&oldConfig, pNewConfig)) {
2,339✔
1944
    sInfo("vgId:1, sync not reconfig since not changed");
1,976✔
1945
    return 0;
1,976✔
1946
  }
1947

1948
  pSyncNode->raftCfg.cfg = *pNewConfig;
363✔
1949
  pSyncNode->raftCfg.lastConfigIndex = lastConfigChangeIndex;
363✔
1950

1951
  pSyncNode->configChangeNum++;
363✔
1952

1953
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
363✔
1954
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
363✔
1955

1956
  bool isDrop = false;
363✔
1957
  bool isAdd = false;
363✔
1958

1959
  if (IamInOld && !IamInNew) {
363!
1960
    isDrop = true;
×
1961
  } else {
1962
    isDrop = false;
363✔
1963
  }
1964

1965
  if (!IamInOld && IamInNew) {
363!
1966
    isAdd = true;
×
1967
  } else {
1968
    isAdd = false;
363✔
1969
  }
1970

1971
  // log begin config change
1972
  sNInfo(pSyncNode, "begin do config change, from %d to %d, from %" PRId64 " to %" PRId64 ", replicas:%d",
363!
1973
         pSyncNode->vgId, oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum, oldConfig.lastIndex,
1974
         pNewConfig->lastIndex);
1975

1976
  if (IamInNew) {
363!
1977
    pSyncNode->raftCfg.isStandBy = 0;  // change isStandBy to normal
363✔
1978
  }
1979
  if (isDrop) {
363!
1980
    pSyncNode->raftCfg.isStandBy = 1;  // set standby
×
1981
  }
1982

1983
  // add last config index
1984
  SRaftCfg* pCfg = &pSyncNode->raftCfg;
363✔
1985
  if (pCfg->configIndexCount >= MAX_CONFIG_INDEX_COUNT) {
363!
1986
    sNError(pSyncNode, "failed to add cfg index:%d since out of range", pCfg->configIndexCount);
×
1987
    terrno = TSDB_CODE_OUT_OF_RANGE;
×
1988
    return -1;
×
1989
  }
1990

1991
  pCfg->configIndexArr[pCfg->configIndexCount] = lastConfigChangeIndex;
363✔
1992
  pCfg->configIndexCount++;
363✔
1993

1994
  if (IamInNew) {
363!
1995
    //-----------------------------------------
1996
    int32_t ret = 0;
363✔
1997

1998
    // save snapshot senders
1999
    SRaftId oldReplicasId[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
2000
    memcpy(oldReplicasId, pSyncNode->replicasId, sizeof(oldReplicasId));
363✔
2001
    SSyncSnapshotSender* oldSenders[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
2002
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
5,808✔
2003
      oldSenders[i] = pSyncNode->senders[i];
5,445✔
2004
      sSTrace(oldSenders[i], "snapshot sender save old");
5,445!
2005
    }
2006

2007
    // init internal
2008
    pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
363✔
2009
    if (syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId) == false) return terrno;
363!
2010

2011
    // init peersNum, peers, peersId
2012
    pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
363✔
2013
    int32_t j = 0;
363✔
2014
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
1,310✔
2015
      if (i != pSyncNode->raftCfg.cfg.myIndex) {
947✔
2016
        pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
584✔
2017
        syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
584✔
2018
        j++;
584✔
2019
      }
2020
    }
2021
    for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
947✔
2022
      if (syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]) == false)
584!
2023
        return terrno;
×
2024
    }
2025

2026
    // init replicaNum, replicasId
2027
    pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
363✔
2028
    pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
363✔
2029
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
1,310✔
2030
      if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
947!
2031
          false)
2032
        return terrno;
×
2033
    }
2034

2035
    // update quorum first
2036
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
363✔
2037

2038
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
363✔
2039
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
363✔
2040
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
363✔
2041
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
363✔
2042

2043
    // reset snapshot senders
2044

2045
    // clear new
2046
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
5,808✔
2047
      pSyncNode->senders[i] = NULL;
5,445✔
2048
    }
2049

2050
    // reset new
2051
    for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
1,310✔
2052
      // reset sender
2053
      bool reset = false;
947✔
2054
      for (int32_t j = 0; j < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++j) {
3,989✔
2055
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
3,823!
2056
          sNTrace(pSyncNode, "snapshot sender reset for:%" PRId64 ", newIndex:%d, dnode:%d, %p",
781!
2057
                  (pSyncNode->replicasId)[i].addr, i, DID(&pSyncNode->replicasId[i]), oldSenders[j]);
2058

2059
          pSyncNode->senders[i] = oldSenders[j];
781✔
2060
          oldSenders[j] = NULL;
781✔
2061
          reset = true;
781✔
2062

2063
          // reset replicaIndex
2064
          int32_t oldreplicaIndex = pSyncNode->senders[i]->replicaIndex;
781✔
2065
          pSyncNode->senders[i]->replicaIndex = i;
781✔
2066

2067
          sNTrace(pSyncNode, "snapshot sender udpate replicaIndex from %d to %d, dnode:%d, %p, reset:%d",
781!
2068
                  oldreplicaIndex, i, DID(&pSyncNode->replicasId[i]), pSyncNode->senders[i], reset);
2069

2070
          break;
781✔
2071
        }
2072
      }
2073
    }
2074

2075
    // create new
2076
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
5,808✔
2077
      if (pSyncNode->senders[i] == NULL) {
5,445✔
2078
        TAOS_CHECK_RETURN(snapshotSenderCreate(pSyncNode, i, &pSyncNode->senders[i]));
4,664!
2079
        if (pSyncNode->senders[i] == NULL) {
4,664!
2080
          // will be created later while send snapshot
2081
          sSError(pSyncNode->senders[i], "snapshot sender create failed while reconfig");
×
2082
        } else {
2083
          sSDebug(pSyncNode->senders[i], "snapshot sender create while reconfig, data:%p", pSyncNode->senders[i]);
4,664✔
2084
        }
2085
      } else {
2086
        sSDebug(pSyncNode->senders[i], "snapshot sender already exist, data:%p", pSyncNode->senders[i]);
781✔
2087
      }
2088
    }
2089

2090
    // free old
2091
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
5,808✔
2092
      if (oldSenders[i] != NULL) {
5,445✔
2093
        sSDebug(oldSenders[i], "snapshot sender destroy old, data:%p replica-index:%d", oldSenders[i], i);
4,664✔
2094
        snapshotSenderDestroy(oldSenders[i]);
4,664✔
2095
        oldSenders[i] = NULL;
4,664✔
2096
      }
2097
    }
2098

2099
    // persist cfg
2100
    TAOS_CHECK_RETURN(syncWriteCfgFile(pSyncNode));
363!
2101
  } else {
2102
    // persist cfg
2103
    TAOS_CHECK_RETURN(syncWriteCfgFile(pSyncNode));
×
2104
    sNInfo(pSyncNode, "do not config change from %d to %d", oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum);
×
2105
  }
2106

2107
_END:
×
2108
  // log end config change
2109
  sNInfo(pSyncNode, "end do config change, from %d to %d", oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum);
363!
2110
  return 0;
363✔
2111
}
2112

2113
// raft state change --------------
2114
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
507✔
2115
  if (term > raftStoreGetTerm(pSyncNode)) {
507!
2116
    raftStoreSetTerm(pSyncNode, term);
×
2117
  }
2118
}
507✔
2119

2120
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm, SRaftId id) {
413,974✔
2121
  SyncTerm currentTerm = raftStoreGetTerm(pSyncNode);
413,974✔
2122
  if (currentTerm > newTerm) {
413,977!
2123
    sNTrace(pSyncNode, "step down, ignore, new-term:%" PRId64 ", current-term:%" PRId64, newTerm, currentTerm);
×
2124
    return;
×
2125
  }
2126

2127
  do {
2128
    sNTrace(pSyncNode, "step down, new-term:%" PRId64 ", current-term:%" PRId64, newTerm, currentTerm);
413,977!
2129
  } while (0);
2130

2131
  if (pSyncNode->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
413,977!
2132
    (void)taosThreadMutexLock(&pSyncNode->arbTokenMutex);
×
2133
    syncUtilGenerateArbToken(pSyncNode->myNodeInfo.nodeId, pSyncNode->vgId, pSyncNode->arbToken);
×
2134
    sInfo("vgId:%d, step down as assigned leader, new arbToken:%s", pSyncNode->vgId, pSyncNode->arbToken);
×
2135
    (void)taosThreadMutexUnlock(&pSyncNode->arbTokenMutex);
×
2136
  }
2137

2138
  if (currentTerm < newTerm) {
413,974✔
2139
    raftStoreSetTerm(pSyncNode, newTerm);
3,106✔
2140
    char tmpBuf[64];
2141
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
3,106✔
2142
    syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
3,106✔
2143
    raftStoreClearVote(pSyncNode);
3,106✔
2144
  } else {
2145
    if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
410,868✔
2146
      syncNodeBecomeFollower(pSyncNode, id, "step down");
9✔
2147
    }
2148
  }
2149
}
2150

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

2153
void syncNodeBecomeFollower(SSyncNode* pSyncNode, SRaftId leaderId, const char* debugStr) {
7,193✔
2154
  int32_t code = 0;  // maybe clear leader cache
7,193✔
2155
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
7,193✔
2156
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
78✔
2157
    pSyncNode->leaderCacheEp.port = 0;
78✔
2158
    pSyncNode->leaderCacheEp.fqdn[0] = '\0';
78✔
2159
  }
2160

2161
  pSyncNode->hbSlowNum = 0;
7,193✔
2162

2163
  pSyncNode->leaderCache = leaderId;  // state change
7,193✔
2164

2165
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
23,002✔
2166
    if (syncUtilSameId(&pSyncNode->replicasId[i], &leaderId)) {
18,924✔
2167
      pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[i].nodePort;
3,115✔
2168
      strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
3,115✔
2169
      break;
3,115✔
2170
    }
2171
  }
2172
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
7,193✔
2173
  pSyncNode->roleTimeMs = taosGetTimestampMs();
7,193✔
2174
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
7,193!
2175
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2176
    return;
×
2177
  }
2178

2179
  // trace log
2180
  sNTrace(pSyncNode, "become follower %s", debugStr);
7,193!
2181

2182
  // send rsp to client
2183
  syncNodeLeaderChangeRsp(pSyncNode);
7,193✔
2184

2185
  // call back
2186
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
7,193!
2187
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
7,193✔
2188
  }
2189

2190
  // min match index
2191
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
7,193✔
2192

2193
  // reset log buffer
2194
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
7,193!
2195
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2196
    return;
×
2197
  }
2198

2199
  // reset elect timer
2200
  syncNodeResetElectTimer(pSyncNode);
7,193✔
2201

2202
  sInfo("vgId:%d, become follower. %s", pSyncNode->vgId, debugStr);
7,193!
2203
}
2204

2205
void syncNodeBecomeLearner(SSyncNode* pSyncNode, const char* debugStr) {
364✔
2206
  pSyncNode->hbSlowNum = 0;
364✔
2207

2208
  // state change
2209
  pSyncNode->state = TAOS_SYNC_STATE_LEARNER;
364✔
2210
  pSyncNode->roleTimeMs = taosGetTimestampMs();
364✔
2211

2212
  // trace log
2213
  sNTrace(pSyncNode, "become learner %s", debugStr);
364!
2214

2215
  // call back
2216
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLearnerCb != NULL) {
364!
2217
    pSyncNode->pFsm->FpBecomeLearnerCb(pSyncNode->pFsm);
364✔
2218
  }
2219

2220
  // min match index
2221
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
364✔
2222

2223
  // reset log buffer
2224
  int32_t code = 0;
364✔
2225
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
364!
2226
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2227
    return;
×
2228
  };
2229
}
2230

2231
// TLA+ Spec
2232
// \* Candidate i transitions to leader.
2233
// BecomeLeader(i) ==
2234
//     /\ state[i] = Candidate
2235
//     /\ votesGranted[i] \in Quorum
2236
//     /\ state'      = [state EXCEPT ![i] = Leader]
2237
//     /\ nextIndex'  = [nextIndex EXCEPT ![i] =
2238
//                          [j \in Server |-> Len(log[i]) + 1]]
2239
//     /\ matchIndex' = [matchIndex EXCEPT ![i] =
2240
//                          [j \in Server |-> 0]]
2241
//     /\ elections'  = elections \cup
2242
//                          {[eterm     |-> currentTerm[i],
2243
//                            eleader   |-> i,
2244
//                            elog      |-> log[i],
2245
//                            evotes    |-> votesGranted[i],
2246
//                            evoterLog |-> voterLog[i]]}
2247
//     /\ UNCHANGED <<messages, currentTerm, votedFor, candidateVars, logVars>>
2248
//
2249
void syncNodeBecomeLeader(SSyncNode* pSyncNode, const char* debugStr) {
14,023✔
2250
  int32_t code = 0;
14,023✔
2251
  pSyncNode->becomeLeaderNum++;
14,023✔
2252
  pSyncNode->hbrSlowNum = 0;
14,023✔
2253

2254
  // reset restoreFinish
2255
  pSyncNode->restoreFinish = false;
14,023✔
2256

2257
  // state change
2258
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
14,023✔
2259
  pSyncNode->roleTimeMs = taosGetTimestampMs();
14,023✔
2260

2261
  // set leader cache
2262
  pSyncNode->leaderCache = pSyncNode->myRaftId;
14,023✔
2263
  strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeFqdn,
14,023✔
2264
          TSDB_FQDN_LEN);
2265
  pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodePort;
14,023✔
2266

2267
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
30,955✔
2268
    SyncIndex lastIndex;
2269
    SyncTerm  lastTerm;
2270
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
16,932✔
2271
    if (code != 0) {
16,932!
2272
      sError("vgId:%d, failed to become leader since %s", pSyncNode->vgId, tstrerror(code));
×
2273
      return;
×
2274
    }
2275
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
16,932✔
2276
  }
2277

2278
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
30,955✔
2279
    // maybe overwrite myself, no harm
2280
    // just do it!
2281
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
16,932✔
2282
  }
2283

2284
  // init peer mgr
2285
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
14,023!
2286
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2287
    return;
×
2288
  }
2289

2290
#if 0
2291
  // update sender private term
2292
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
2293
  if (pMySender != NULL) {
2294
    for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
2295
      if (pSyncNode->senders[i]->privateTerm > pMySender->privateTerm) {
2296
        pMySender->privateTerm = pSyncNode->senders[i]->privateTerm;
2297
      }
2298
    }
2299
    (pMySender->privateTerm) += 100;
2300
  }
2301
#endif
2302

2303
  // close receiver
2304
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
14,023!
2305
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2306
  }
2307

2308
  // stop elect timer
2309
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
14,023!
2310
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
2311
    return;
×
2312
  }
2313

2314
  // start heartbeat timer
2315
  if ((code = syncNodeStartHeartbeatTimer(pSyncNode)) != 0) {
14,023!
2316
    sError("vgId:%d, failed to start heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2317
    return;
×
2318
  }
2319

2320
  // send heartbeat right now
2321
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
14,023!
2322
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2323
    return;
×
2324
  }
2325

2326
  // call back
2327
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
14,023!
2328
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
14,023✔
2329
  }
2330

2331
  // min match index
2332
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
14,023✔
2333

2334
  // reset log buffer
2335
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
14,023!
2336
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2337
    return;
×
2338
  }
2339

2340
  // trace log
2341
  sNInfo(pSyncNode, "become leader %s", debugStr);
14,023✔
2342
}
2343

2344
void syncNodeBecomeAssignedLeader(SSyncNode* pSyncNode) {
×
2345
  int32_t code = 0;
×
2346
  pSyncNode->becomeAssignedLeaderNum++;
×
2347
  pSyncNode->hbrSlowNum = 0;
×
2348

2349
  // reset restoreFinish
2350
  // pSyncNode->restoreFinish = false;
2351

2352
  // state change
2353
  pSyncNode->state = TAOS_SYNC_STATE_ASSIGNED_LEADER;
×
2354
  pSyncNode->roleTimeMs = taosGetTimestampMs();
×
2355

2356
  // set leader cache
2357
  pSyncNode->leaderCache = pSyncNode->myRaftId;
×
2358

2359
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
×
2360
    SyncIndex lastIndex;
2361
    SyncTerm  lastTerm;
2362
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
×
2363
    if (code != 0) {
×
2364
      sError("vgId:%d, failed to become assigned leader since %s", pSyncNode->vgId, tstrerror(code));
×
2365
      return;
×
2366
    }
2367
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
×
2368
  }
2369

2370
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
×
2371
    // maybe overwrite myself, no harm
2372
    // just do it!
2373
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
×
2374
  }
2375

2376
  // init peer mgr
2377
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
×
2378
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2379
    return;
×
2380
  }
2381

2382
  // close receiver
2383
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
×
2384
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2385
  }
2386

2387
  // stop elect timer
2388
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
×
2389
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
2390
    return;
×
2391
  }
2392

2393
  // start heartbeat timer
2394
  if ((code = syncNodeStartHeartbeatTimer(pSyncNode)) != 0) {
×
2395
    sError("vgId:%d, failed to start heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2396
    return;
×
2397
  }
2398

2399
  // send heartbeat right now
2400
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
×
2401
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2402
    return;
×
2403
  }
2404

2405
  // call back
2406
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeAssignedLeaderCb != NULL) {
×
2407
    pSyncNode->pFsm->FpBecomeAssignedLeaderCb(pSyncNode->pFsm);
×
2408
  }
2409

2410
  // min match index
2411
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
×
2412

2413
  // reset log buffer
2414
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
×
2415
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2416
    return;
×
2417
  }
2418

2419
  // trace log
2420
  sNInfo(pSyncNode, "become assigned leader");
×
2421
}
2422

2423
void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
1,452✔
2424
  if (pSyncNode->state != TAOS_SYNC_STATE_CANDIDATE) {
1,452!
2425
    sError("vgId:%d, failed leader from candidate since node state is wrong:%d", pSyncNode->vgId, pSyncNode->state);
×
2426
    return;
×
2427
  }
2428
  bool granted = voteGrantedMajority(pSyncNode->pVotesGranted);
1,452✔
2429
  if (!granted) {
1,452!
2430
    sError("vgId:%d, not granted by majority.", pSyncNode->vgId);
×
2431
    return;
×
2432
  }
2433
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");
1,452✔
2434

2435
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
1,452!
2436

2437
  int32_t ret = syncNodeAppendNoop(pSyncNode);
1,452✔
2438
  if (ret < 0) {
1,452!
2439
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, terrstr());
×
2440
  }
2441

2442
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,452✔
2443

2444
  sInfo("vgId:%d, become leader. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64, pSyncNode->vgId,
1,452!
2445
        raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2446
}
2447

2448
bool syncNodeIsMnode(SSyncNode* pSyncNode) { return (pSyncNode->vgId == 1); }
159,368✔
2449

2450
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
31,021✔
2451
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
496,357✔
2452
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
465,336✔
2453
    pSyncNode->peerStates[i].lastSendTime = 0;
465,336✔
2454
  }
2455

2456
  return 0;
31,021✔
2457
}
2458

2459
void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
1,843✔
2460
  if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
1,843!
2461
    sError("vgId:%d, failed candidate from follower since node state is wrong:%d", pSyncNode->vgId, pSyncNode->state);
×
2462
    return;
×
2463
  }
2464
  pSyncNode->state = TAOS_SYNC_STATE_CANDIDATE;
1,843✔
2465
  pSyncNode->roleTimeMs = taosGetTimestampMs();
1,843✔
2466
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,843✔
2467
  sInfo("vgId:%d, become candidate from follower. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64,
1,843!
2468
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2469

2470
  sNTrace(pSyncNode, "follower to candidate");
1,843!
2471
}
2472

2473
int32_t syncNodeAssignedLeader2Leader(SSyncNode* pSyncNode) {
×
2474
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) return TSDB_CODE_SYN_INTERNAL_ERROR;
×
2475
  syncNodeBecomeLeader(pSyncNode, "assigned leader to leader");
×
2476

2477
  sNTrace(pSyncNode, "assigned leader to leader");
×
2478

2479
  int32_t ret = syncNodeAppendNoop(pSyncNode);
×
2480
  if (ret < 0) {
×
2481
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, tstrerror(ret));
×
2482
  }
2483

2484
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
×
2485
  sInfo("vgId:%d, become leader from assigned leader. term:%" PRId64 ", commit index:%" PRId64
×
2486
        "assigned commit index:%" PRId64 ", last index:%" PRId64,
2487
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, pSyncNode->assignedCommitIndex,
2488
        lastIndex);
2489
  return 0;
×
2490
}
2491

2492
// just called by syncNodeVoteForSelf
2493
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
1,967✔
2494
  SyncTerm storeTerm = raftStoreGetTerm(pSyncNode);
1,967✔
2495
  if (term != storeTerm) {
1,967!
2496
    sError("vgId:%d, failed to vote for term, term:%" PRId64 ", storeTerm:%" PRId64, pSyncNode->vgId, term, storeTerm);
×
2497
    return;
×
2498
  }
2499
  sTrace("vgId:%d, begin hasVoted", pSyncNode->vgId);
1,967!
2500
  bool voted = raftStoreHasVoted(pSyncNode);
1,967✔
2501
  if (voted) {
1,967!
2502
    sError("vgId:%d, failed to vote for term since not voted", pSyncNode->vgId);
×
2503
    return;
×
2504
  }
2505

2506
  raftStoreVote(pSyncNode, pRaftId);
1,967✔
2507
}
2508

2509
// simulate get vote from outside
2510
void syncNodeVoteForSelf(SSyncNode* pSyncNode, SyncTerm currentTerm) {
1,967✔
2511
  syncNodeVoteForTerm(pSyncNode, currentTerm, &pSyncNode->myRaftId);
1,967✔
2512

2513
  SRpcMsg rpcMsg = {0};
1,967✔
2514
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
1,967✔
2515
  if (ret != 0) return;
1,967!
2516

2517
  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
1,967✔
2518
  pMsg->srcId = pSyncNode->myRaftId;
1,967✔
2519
  pMsg->destId = pSyncNode->myRaftId;
1,967✔
2520
  pMsg->term = currentTerm;
1,967✔
2521
  pMsg->voteGranted = true;
1,967✔
2522

2523
  voteGrantedVote(pSyncNode->pVotesGranted, pMsg);
1,967✔
2524
  votesRespondAdd(pSyncNode->pVotesRespond, pMsg);
1,967✔
2525
  rpcFreeCont(rpcMsg.pCont);
1,967✔
2526
}
2527

2528
// return if has a snapshot
2529
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
23,880✔
2530
  bool      ret = false;
23,880✔
2531
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
23,880✔
2532
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
23,880!
2533
    // TODO check return value
2534
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
23,880✔
2535
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
23,880✔
2536
      ret = true;
2,528✔
2537
    }
2538
  }
2539
  return ret;
23,880✔
2540
}
2541

2542
// return max(logLastIndex, snapshotLastIndex)
2543
// if no snapshot and log, return -1
2544
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
24,003✔
2545
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
24,003✔
2546
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
24,003!
2547
    // TODO check return value
2548
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
24,003✔
2549
  }
2550
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
24,003✔
2551

2552
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
24,003✔
2553
  return lastIndex;
24,003✔
2554
}
2555

2556
// return the last term of snapshot and log
2557
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
2558
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
23,880✔
2559
  SyncTerm lastTerm = 0;
23,880✔
2560
  if (syncNodeHasSnapshot(pSyncNode)) {
23,880✔
2561
    // has snapshot
2562
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2,528✔
2563
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2,528!
2564
      // TODO check return value
2565
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2,528✔
2566
    }
2567

2568
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
2,528✔
2569
    if (logLastIndex > snapshot.lastApplyIndex) {
2,528✔
2570
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1,455✔
2571
    } else {
2572
      lastTerm = snapshot.lastApplyTerm;
1,073✔
2573
    }
2574

2575
  } else {
2576
    // no snapshot
2577
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
21,352✔
2578
  }
2579

2580
  return lastTerm;
23,880✔
2581
}
2582

2583
// get last index and term along with snapshot
2584
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
20,782✔
2585
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
20,782✔
2586
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
20,782✔
2587
  return 0;
20,782✔
2588
}
2589

2590
#ifdef BUILD_NO_CALL
2591
// return append-entries first try index
2592
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
2593
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
2594
  return syncStartIndex;
2595
}
2596

2597
// if index > 0, return index - 1
2598
// else, return -1
2599
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
2600
  SyncIndex preIndex = index - 1;
2601
  if (preIndex < SYNC_INDEX_INVALID) {
2602
    preIndex = SYNC_INDEX_INVALID;
2603
  }
2604

2605
  return preIndex;
2606
}
2607

2608
// if index < 0, return SYNC_TERM_INVALID
2609
// if index == 0, return 0
2610
// if index > 0, return preTerm
2611
// if error, return SYNC_TERM_INVALID
2612
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
2613
  if (index < SYNC_INDEX_BEGIN) {
2614
    return SYNC_TERM_INVALID;
2615
  }
2616

2617
  if (index == SYNC_INDEX_BEGIN) {
2618
    return 0;
2619
  }
2620

2621
  SyncTerm  preTerm = 0;
2622
  SyncIndex preIndex = index - 1;
2623

2624
  SSyncRaftEntry* pPreEntry = NULL;
2625
  SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
2626
  LRUHandle*      h = taosLRUCacheLookup(pCache, &preIndex, sizeof(preIndex));
2627
  int32_t         code = 0;
2628
  if (h) {
2629
    pPreEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2630
    code = 0;
2631

2632
    pSyncNode->pLogStore->cacheHit++;
2633
    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);
2634

2635
  } else {
2636
    pSyncNode->pLogStore->cacheMiss++;
2637
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);
2638

2639
    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
2640
  }
2641

2642
  SSnapshot snapshot = {.data = NULL,
2643
                        .lastApplyIndex = SYNC_INDEX_INVALID,
2644
                        .lastApplyTerm = SYNC_TERM_INVALID,
2645
                        .lastConfigIndex = SYNC_INDEX_INVALID};
2646

2647
  if (code == 0) {
2648
    if (pPreEntry == NULL) return -1;
2649
    preTerm = pPreEntry->term;
2650

2651
    if (h) {
2652
      taosLRUCacheRelease(pCache, h, false);
2653
    } else {
2654
      syncEntryDestroy(pPreEntry);
2655
    }
2656

2657
    return preTerm;
2658
  } else {
2659
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2660
      // TODO check return value
2661
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2662
      if (snapshot.lastApplyIndex == preIndex) {
2663
        return snapshot.lastApplyTerm;
2664
      }
2665
    }
2666
  }
2667

2668
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
2669
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
2670
  return SYNC_TERM_INVALID;
2671
}
2672

2673
// get pre index and term of "index"
2674
int32_t syncNodeGetPreIndexTerm(SSyncNode* pSyncNode, SyncIndex index, SyncIndex* pPreIndex, SyncTerm* pPreTerm) {
2675
  *pPreIndex = syncNodeGetPreIndex(pSyncNode, index);
2676
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
2677
  return 0;
2678
}
2679
#endif
2680

2681
static void syncNodeEqPingTimer(void* param, void* tmrId) {
65,772✔
2682
  if (!syncIsInit()) return;
65,772!
2683

2684
  int64_t    rid = (int64_t)param;
65,772✔
2685
  SSyncNode* pNode = syncNodeAcquire(rid);
65,772✔
2686

2687
  if (pNode == NULL) return;
65,772!
2688

2689
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
65,772!
2690
    SRpcMsg rpcMsg = {0};
65,772✔
2691
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
65,772✔
2692
                                    pNode->pingTimerMS, pNode);
2693
    if (code != 0) {
65,772!
2694
      sError("failed to build ping msg");
×
2695
      rpcFreeCont(rpcMsg.pCont);
×
2696
      goto _out;
×
2697
    }
2698

2699
    // sTrace("enqueue ping msg");
2700
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
65,772✔
2701
    if (code != 0) {
65,772!
2702
      sError("failed to sync enqueue ping msg since %s", terrstr());
×
2703
      rpcFreeCont(rpcMsg.pCont);
×
2704
      goto _out;
×
2705
    }
2706

2707
  _out:
65,772✔
2708
    if (taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
65,772!
2709
                     &pNode->pPingTimer))
2710
      sError("failed to reset ping timer");
×
2711
  }
2712
  syncNodeRelease(pNode);
65,772✔
2713
}
2714

2715
static void syncNodeEqElectTimer(void* param, void* tmrId) {
1,978✔
2716
  if (!syncIsInit()) return;
1,989!
2717

2718
  int64_t    rid = (int64_t)param;
1,978✔
2719
  SSyncNode* pNode = syncNodeAcquire(rid);
1,978✔
2720

2721
  if (pNode == NULL) return;
1,978✔
2722

2723
  if (pNode->syncEqMsg == NULL) {
1,973!
2724
    syncNodeRelease(pNode);
×
2725
    return;
×
2726
  }
2727

2728
  int64_t tsNow = taosGetTimestampMs();
1,973✔
2729
  if (tsNow < pNode->electTimerParam.executeTime) {
1,973✔
2730
    syncNodeRelease(pNode);
6✔
2731
    return;
6✔
2732
  }
2733

2734
  SRpcMsg rpcMsg = {0};
1,967✔
2735
  int32_t code =
2736
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
1,967✔
2737

2738
  if (code != 0) {
1,967!
2739
    sError("failed to build elect msg");
×
2740
    syncNodeRelease(pNode);
×
2741
    return;
×
2742
  }
2743

2744
  SyncTimeout* pTimeout = rpcMsg.pCont;
1,967✔
2745
  sNTrace(pNode, "enqueue elect msg lc:%" PRId64, pTimeout->logicClock);
1,967!
2746

2747
  code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
1,967✔
2748
  if (code != 0) {
1,967!
2749
    sError("failed to sync enqueue elect msg since %s", terrstr());
×
2750
    rpcFreeCont(rpcMsg.pCont);
×
2751
    syncNodeRelease(pNode);
×
2752
    return;
×
2753
  }
2754

2755
  syncNodeRelease(pNode);
1,967✔
2756
}
2757

2758
#ifdef BUILD_NO_CALL
2759
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
2760
  if (!syncIsInit()) return;
2761

2762
  int64_t    rid = (int64_t)param;
2763
  SSyncNode* pNode = syncNodeAcquire(rid);
2764

2765
  if (pNode == NULL) return;
2766

2767
  if (pNode->totalReplicaNum > 1) {
2768
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
2769
      SRpcMsg rpcMsg = {0};
2770
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
2771
                                      pNode->heartbeatTimerMS, pNode);
2772

2773
      if (code != 0) {
2774
        sError("failed to build heartbeat msg");
2775
        goto _out;
2776
      }
2777

2778
      sTrace("vgId:%d, enqueue heartbeat timer", pNode->vgId);
2779
      code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
2780
      if (code != 0) {
2781
        sError("failed to enqueue heartbeat msg since %s", terrstr());
2782
        rpcFreeCont(rpcMsg.pCont);
2783
        goto _out;
2784
      }
2785

2786
    _out:
2787
      if (taosTmrReset(syncNodeEqHeartbeatTimer, pNode->heartbeatTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
2788
                       &pNode->pHeartbeatTimer) != 0)
2789
        return;
2790

2791
    } else {
2792
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
2793
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
2794
    }
2795
  }
2796
}
2797
#endif
2798

2799
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
58,087✔
2800
  int32_t code = 0;
58,087✔
2801
  int64_t hbDataRid = (int64_t)param;
58,087✔
2802
  int64_t tsNow = taosGetTimestampMs();
58,087✔
2803

2804
  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
58,087✔
2805
  if (pData == NULL) {
58,087!
2806
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
×
2807
    return;
×
2808
  }
2809

2810
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
58,087✔
2811
  if (pSyncNode == NULL) {
58,087✔
2812
    syncHbTimerDataRelease(pData);
6✔
2813
    sError("hb timer get pSyncNode NULL");
6!
2814
    return;
6✔
2815
  }
2816

2817
  SSyncTimer* pSyncTimer = pData->pTimer;
58,081✔
2818

2819
  if (!pSyncNode->isStart) {
58,081!
2820
    syncNodeRelease(pSyncNode);
×
2821
    syncHbTimerDataRelease(pData);
×
2822
    sError("vgId:%d, hb timer sync node already stop", pSyncNode->vgId);
×
2823
    return;
×
2824
  }
2825

2826
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
58,081!
2827
    syncNodeRelease(pSyncNode);
×
2828
    syncHbTimerDataRelease(pData);
×
2829
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
×
2830
    return;
×
2831
  }
2832

2833
  sTrace("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
58,081!
2834
         pData->destId.addr);
2835

2836
  if (pSyncNode->totalReplicaNum > 1) {
58,081✔
2837
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
58,077✔
2838
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
58,077✔
2839

2840
    if (timerLogicClock == msgLogicClock) {
58,077✔
2841
      if (tsNow > pData->execTime) {
58,070✔
2842
        pData->execTime += pSyncTimer->timerMS;
58,011✔
2843

2844
        SRpcMsg rpcMsg = {0};
58,011✔
2845
        if ((code = syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId)) != 0) {
58,011!
2846
          sError("vgId:%d, failed to build heartbeat msg since %s", pSyncNode->vgId, tstrerror(code));
×
2847
          syncNodeRelease(pSyncNode);
×
2848
          syncHbTimerDataRelease(pData);
×
2849
          return;
×
2850
        }
2851

2852
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);
58,011✔
2853

2854
        SyncHeartbeat* pSyncMsg = rpcMsg.pCont;
58,011✔
2855
        pSyncMsg->srcId = pSyncNode->myRaftId;
58,011✔
2856
        pSyncMsg->destId = pData->destId;
58,011✔
2857
        pSyncMsg->term = raftStoreGetTerm(pSyncNode);
58,011✔
2858
        pSyncMsg->commitIndex = pSyncNode->commitIndex;
58,011✔
2859
        pSyncMsg->minMatchIndex = pSyncNode->minMatchIndex;
58,011✔
2860
        pSyncMsg->privateTerm = 0;
58,011✔
2861
        pSyncMsg->timeStamp = tsNow;
58,011✔
2862

2863
        // update reset time
2864
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
58,011✔
2865
        pSyncTimer->timeStamp = tsNow;
58,011✔
2866

2867
        // send msg
2868
        TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
58,011✔
2869
        TRACE_SET_ROOTID(&(rpcMsg.info.traceId), tGenIdPI64());
58,011✔
2870
        sGTrace(&rpcMsg.info.traceId, "vgId:%d, send sync-heartbeat to dnode:%d", pSyncNode->vgId,
58,011!
2871
                DID(&(pSyncMsg->destId)));
2872
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime);
58,011✔
2873
        int ret = syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
58,011✔
2874
        if (ret != 0) {
58,011✔
2875
          sError("vgId:%d, failed to send heartbeat since %s", pSyncNode->vgId, tstrerror(ret));
90!
2876
        }
2877
      }
2878

2879
      if (syncIsInit()) {
58,070!
2880
        sTrace("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
58,070!
2881
        bool stopped = taosTmrResetPriority(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS, (void*)hbDataRid,
58,070✔
2882
                                            syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
58,070✔
2883
        if (stopped) sError("vgId:%d, reset peer hb timer error, %s", pSyncNode->vgId, tstrerror(code));
58,070!
2884

2885
      } else {
2886
        sError("sync env is stop, reset peer hb timer error");
×
2887
      }
2888

2889
    } else {
2890
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64, pSyncNode->vgId,
7!
2891
             timerLogicClock, msgLogicClock);
2892
    }
2893
  }
2894

2895
  syncHbTimerDataRelease(pData);
58,081✔
2896
  syncNodeRelease(pSyncNode);
58,081✔
2897
}
2898

2899
#ifdef BUILD_NO_CALL
2900
static void deleteCacheEntry(const void* key, size_t keyLen, void* value, void* ud) {
2901
  (void)ud;
2902
  taosMemoryFree(value);
2903
}
2904

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

2909
  int32_t   code = 0;
2910
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2911
  LRUStatus status = taosLRUCacheInsert(pLogStore->pCache, &pEntry->index, sizeof(pEntry->index), pEntry, entryLen,
2912
                                        deleteCacheEntry, h, TAOS_LRU_PRIORITY_LOW, NULL);
2913
  if (status != TAOS_LRU_STATUS_OK) {
2914
    code = -1;
2915
  }
2916

2917
  return code;
2918
}
2919
#endif
2920

2921
void syncBuildConfigFromReq(SAlterVnodeReplicaReq* pReq, SSyncCfg* cfg) {  // TODO SAlterVnodeReplicaReq name is proper?
×
2922
  cfg->replicaNum = 0;
×
2923
  cfg->totalReplicaNum = 0;
×
2924
  int32_t code = 0;
×
2925

2926
  for (int i = 0; i < pReq->replica; ++i) {
×
2927
    SNodeInfo* pNode = &cfg->nodeInfo[i];
×
2928
    pNode->nodeId = pReq->replicas[i].id;
×
2929
    pNode->nodePort = pReq->replicas[i].port;
×
2930
    tstrncpy(pNode->nodeFqdn, pReq->replicas[i].fqdn, sizeof(pNode->nodeFqdn));
×
2931
    pNode->nodeRole = TAOS_SYNC_ROLE_VOTER;
×
2932
    bool update = tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort);
×
2933
    sInfo("vgId:%d, replica:%d ep:%s:%u dnode:%d nodeRole:%d, update:%d", pReq->vgId, i, pNode->nodeFqdn,
×
2934
          pNode->nodePort, pNode->nodeId, pNode->nodeRole, update);
2935
    cfg->replicaNum++;
×
2936
  }
2937
  if (pReq->selfIndex != -1) {
×
2938
    cfg->myIndex = pReq->selfIndex;
×
2939
  }
2940
  for (int i = cfg->replicaNum; i < pReq->replica + pReq->learnerReplica; ++i) {
×
2941
    SNodeInfo* pNode = &cfg->nodeInfo[i];
×
2942
    pNode->nodeId = pReq->learnerReplicas[cfg->totalReplicaNum].id;
×
2943
    pNode->nodePort = pReq->learnerReplicas[cfg->totalReplicaNum].port;
×
2944
    pNode->nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
2945
    tstrncpy(pNode->nodeFqdn, pReq->learnerReplicas[cfg->totalReplicaNum].fqdn, sizeof(pNode->nodeFqdn));
×
2946
    bool update = tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort);
×
2947
    sInfo("vgId:%d, replica:%d ep:%s:%u dnode:%d nodeRole:%d, update:%d", pReq->vgId, i, pNode->nodeFqdn,
×
2948
          pNode->nodePort, pNode->nodeId, pNode->nodeRole, update);
2949
    cfg->totalReplicaNum++;
×
2950
  }
2951
  cfg->totalReplicaNum += pReq->replica;
×
2952
  if (pReq->learnerSelfIndex != -1) {
×
2953
    cfg->myIndex = pReq->replica + pReq->learnerSelfIndex;
×
2954
  }
2955
  cfg->changeVersion = pReq->changeVersion;
×
2956
}
×
2957

2958
int32_t syncNodeCheckChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry) {
×
2959
  int32_t code = 0;
×
2960
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
2961
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
2962
  }
2963

2964
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
2965
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
2966

2967
  SAlterVnodeTypeReq req = {0};
×
2968
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
2969
    code = TSDB_CODE_INVALID_MSG;
×
2970
    TAOS_RETURN(code);
×
2971
  }
2972

2973
  SSyncCfg cfg = {0};
×
2974
  syncBuildConfigFromReq(&req, &cfg);
×
2975

2976
  if (cfg.totalReplicaNum >= 1 &&
×
2977
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
×
2978
    bool incfg = false;
×
2979
    for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
2980
      if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
2981
          ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
2982
        incfg = true;
×
2983
        break;
×
2984
      }
2985
    }
2986

2987
    if (!incfg) {
×
2988
      SyncTerm currentTerm = raftStoreGetTerm(ths);
×
2989
      SRaftId  id = EMPTY_RAFT_ID;
×
2990
      syncNodeStepDown(ths, currentTerm, id);
×
2991
      return 1;
×
2992
    }
2993
  }
2994
  return 0;
×
2995
}
2996

2997
void syncNodeLogConfigInfo(SSyncNode* ths, SSyncCfg* cfg, char* str) {
×
2998
  sInfo("vgId:%d, %s. SyncNode, replicaNum:%d, peersNum:%d, lastConfigIndex:%" PRId64
×
2999
        ", changeVersion:%d, "
3000
        "restoreFinish:%d",
3001
        ths->vgId, str, ths->replicaNum, ths->peersNum, ths->raftCfg.lastConfigIndex, ths->raftCfg.cfg.changeVersion,
3002
        ths->restoreFinish);
3003

3004
  sInfo("vgId:%d, %s, myNodeInfo, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3005
        ths->myNodeInfo.clusterId, ths->myNodeInfo.nodeId, ths->myNodeInfo.nodeFqdn, ths->myNodeInfo.nodePort,
3006
        ths->myNodeInfo.nodeRole);
3007

3008
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3009
    sInfo("vgId:%d, %s, peersNodeInfo%d, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3010
          i, ths->peersNodeInfo[i].clusterId, ths->peersNodeInfo[i].nodeId, ths->peersNodeInfo[i].nodeFqdn,
3011
          ths->peersNodeInfo[i].nodePort, ths->peersNodeInfo[i].nodeRole);
3012
  }
3013

3014
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3015
    char    buf[256];
3016
    int32_t len = 256;
×
3017
    int32_t n = 0;
×
3018
    n += tsnprintf(buf + n, len - n, "%s", "{");
×
3019
    for (int i = 0; i < ths->peersEpset->numOfEps; i++) {
×
3020
      n += tsnprintf(buf + n, len - n, "%s:%d%s", ths->peersEpset->eps[i].fqdn, ths->peersEpset->eps[i].port,
×
3021
                     (i + 1 < ths->peersEpset->numOfEps ? ", " : ""));
×
3022
    }
3023
    n += tsnprintf(buf + n, len - n, "%s", "}");
×
3024

3025
    sInfo("vgId:%d, %s, peersEpset%d, %s, inUse:%d", ths->vgId, str, i, buf, ths->peersEpset->inUse);
×
3026
  }
3027

3028
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3029
    sInfo("vgId:%d, %s, peersId%d, addr:0x%" PRIx64, ths->vgId, str, i, ths->peersId[i].addr);
×
3030
  }
3031

3032
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3033
    sInfo("vgId:%d, %s, nodeInfo%d, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str, i,
×
3034
          ths->raftCfg.cfg.nodeInfo[i].clusterId, ths->raftCfg.cfg.nodeInfo[i].nodeId,
3035
          ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, ths->raftCfg.cfg.nodeInfo[i].nodePort,
3036
          ths->raftCfg.cfg.nodeInfo[i].nodeRole);
3037
  }
3038

3039
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3040
    sInfo("vgId:%d, %s, replicasId%d, addr:0x%" PRIx64, ths->vgId, str, i, ths->replicasId[i].addr);
×
3041
  }
3042
}
×
3043

3044
int32_t syncNodeRebuildPeerAndCfg(SSyncNode* ths, SSyncCfg* cfg) {
×
3045
  int32_t i = 0;
×
3046

3047
  // change peersNodeInfo
3048
  i = 0;
×
3049
  for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3050
    if (!(strcmp(ths->myNodeInfo.nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3051
          ths->myNodeInfo.nodePort == cfg->nodeInfo[j].nodePort)) {
×
3052
      ths->peersNodeInfo[i].nodeRole = cfg->nodeInfo[j].nodeRole;
×
3053
      ths->peersNodeInfo[i].clusterId = cfg->nodeInfo[j].clusterId;
×
3054
      tstrncpy(ths->peersNodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn, TSDB_FQDN_LEN);
×
3055
      ths->peersNodeInfo[i].nodeId = cfg->nodeInfo[j].nodeId;
×
3056
      ths->peersNodeInfo[i].nodePort = cfg->nodeInfo[j].nodePort;
×
3057

3058
      syncUtilNodeInfo2EpSet(&ths->peersNodeInfo[i], &ths->peersEpset[i]);
×
3059

3060
      if (syncUtilNodeInfo2RaftId(&ths->peersNodeInfo[i], ths->vgId, &ths->peersId[i]) == false) {
×
3061
        sError("vgId:%d, failed to determine raft member id, peer:%d", ths->vgId, i);
×
3062
        return terrno;
×
3063
      }
3064

3065
      i++;
×
3066
    }
3067
  }
3068
  ths->peersNum = i;
×
3069

3070
  // change cfg nodeInfo
3071
  ths->raftCfg.cfg.replicaNum = 0;
×
3072
  i = 0;
×
3073
  for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3074
    if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3075
      ths->raftCfg.cfg.replicaNum++;
×
3076
    }
3077
    ths->raftCfg.cfg.nodeInfo[i].nodeRole = cfg->nodeInfo[j].nodeRole;
×
3078
    ths->raftCfg.cfg.nodeInfo[i].clusterId = cfg->nodeInfo[j].clusterId;
×
3079
    tstrncpy(ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn, TSDB_FQDN_LEN);
×
3080
    ths->raftCfg.cfg.nodeInfo[i].nodeId = cfg->nodeInfo[j].nodeId;
×
3081
    ths->raftCfg.cfg.nodeInfo[i].nodePort = cfg->nodeInfo[j].nodePort;
×
3082
    if ((strcmp(ths->myNodeInfo.nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3083
         ths->myNodeInfo.nodePort == cfg->nodeInfo[j].nodePort)) {
×
3084
      ths->raftCfg.cfg.myIndex = i;
×
3085
    }
3086
    i++;
×
3087
  }
3088
  ths->raftCfg.cfg.totalReplicaNum = i;
×
3089

3090
  return 0;
×
3091
}
3092

3093
void syncNodeChangePeerAndCfgToVoter(SSyncNode* ths, SSyncCfg* cfg) {
×
3094
  // change peersNodeInfo
3095
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3096
    for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3097
      if (strcmp(ths->peersNodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3098
          ths->peersNodeInfo[i].nodePort == cfg->nodeInfo[j].nodePort) {
×
3099
        if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3100
          ths->peersNodeInfo[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3101
        }
3102
      }
3103
    }
3104
  }
3105

3106
  // change cfg nodeInfo
3107
  ths->raftCfg.cfg.replicaNum = 0;
×
3108
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3109
    for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3110
      if (strcmp(ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3111
          ths->raftCfg.cfg.nodeInfo[i].nodePort == cfg->nodeInfo[j].nodePort) {
×
3112
        if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3113
          ths->raftCfg.cfg.nodeInfo[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3114
          ths->raftCfg.cfg.replicaNum++;
×
3115
        }
3116
      }
3117
    }
3118
  }
3119
}
×
3120

3121
int32_t syncNodeRebuildAndCopyIfExist(SSyncNode* ths, int32_t oldtotalReplicaNum) {
×
3122
  int32_t code = 0;
×
3123
  // 1.rebuild replicasId, remove deleted one
3124
  SRaftId oldReplicasId[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
3125
  memcpy(oldReplicasId, ths->replicasId, sizeof(oldReplicasId));
×
3126

3127
  ths->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3128
  ths->totalReplicaNum = ths->raftCfg.cfg.totalReplicaNum;
×
3129
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3130
    if (syncUtilNodeInfo2RaftId(&ths->raftCfg.cfg.nodeInfo[i], ths->vgId, &ths->replicasId[i]) == false) return terrno;
×
3131
  }
3132

3133
  // 2.rebuild MatchIndex, remove deleted one
3134
  SSyncIndexMgr* oldIndex = ths->pMatchIndex;
×
3135

3136
  ths->pMatchIndex = syncIndexMgrCreate(ths);
×
3137
  if (ths->pMatchIndex == NULL) {
×
3138
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3139
    if (terrno != 0) code = terrno;
×
3140
    TAOS_RETURN(code);
×
3141
  }
3142

3143
  syncIndexMgrCopyIfExist(ths->pMatchIndex, oldIndex, oldReplicasId);
×
3144

3145
  syncIndexMgrDestroy(oldIndex);
×
3146

3147
  // 3.rebuild NextIndex, remove deleted one
3148
  SSyncIndexMgr* oldNextIndex = ths->pNextIndex;
×
3149

3150
  ths->pNextIndex = syncIndexMgrCreate(ths);
×
3151
  if (ths->pNextIndex == NULL) {
×
3152
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3153
    if (terrno != 0) code = terrno;
×
3154
    TAOS_RETURN(code);
×
3155
  }
3156

3157
  syncIndexMgrCopyIfExist(ths->pNextIndex, oldNextIndex, oldReplicasId);
×
3158

3159
  syncIndexMgrDestroy(oldNextIndex);
×
3160

3161
  // 4.rebuild pVotesGranted, pVotesRespond, no need to keep old vote state, only rebuild
3162
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3163
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3164

3165
  // 5.rebuild logReplMgr
3166
  for (int i = 0; i < oldtotalReplicaNum; ++i) {
×
3167
    sDebug("vgId:%d, old logReplMgrs i:%d, peerId:%d, restoreed:%d, [%" PRId64 " %" PRId64 ", %" PRId64 ")", ths->vgId,
×
3168
           i, ths->logReplMgrs[i]->peerId, ths->logReplMgrs[i]->restored, ths->logReplMgrs[i]->startIndex,
3169
           ths->logReplMgrs[i]->matchIndex, ths->logReplMgrs[i]->endIndex);
3170
  }
3171

3172
  SSyncLogReplMgr* oldLogReplMgrs = NULL;
×
3173
  int64_t          length = sizeof(SSyncLogReplMgr) * (TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA);
×
3174
  oldLogReplMgrs = taosMemoryMalloc(length);
×
3175
  if (NULL == oldLogReplMgrs) return terrno;
×
3176
  memset(oldLogReplMgrs, 0, length);
×
3177

3178
  for (int i = 0; i < oldtotalReplicaNum; i++) {
×
3179
    oldLogReplMgrs[i] = *(ths->logReplMgrs[i]);
×
3180
  }
3181

3182
  syncNodeLogReplDestroy(ths);
×
3183
  if ((code = syncNodeLogReplInit(ths)) != 0) {
×
3184
    taosMemoryFree(oldLogReplMgrs);
×
3185
    TAOS_RETURN(code);
×
3186
  }
3187

3188
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3189
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3190
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3191
        *(ths->logReplMgrs[i]) = oldLogReplMgrs[j];
×
3192
        ths->logReplMgrs[i]->peerId = i;
×
3193
      }
3194
    }
3195
  }
3196

3197
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3198
    sDebug("vgId:%d, new logReplMgrs i:%d, peerId:%d, restoreed:%d, [%" PRId64 " %" PRId64 ", %" PRId64 ")", ths->vgId,
×
3199
           i, ths->logReplMgrs[i]->peerId, ths->logReplMgrs[i]->restored, ths->logReplMgrs[i]->startIndex,
3200
           ths->logReplMgrs[i]->matchIndex, ths->logReplMgrs[i]->endIndex);
3201
  }
3202

3203
  // 6.rebuild sender
3204
  for (int i = 0; i < oldtotalReplicaNum; ++i) {
×
3205
    sDebug("vgId:%d, old sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3206
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3207
  }
3208

3209
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3210
    if (ths->senders[i] != NULL) {
×
3211
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", ths->vgId, ths->senders[i]);
×
3212

3213
      if (snapshotSenderIsStart(ths->senders[i])) {
×
3214
        snapshotSenderStop(ths->senders[i], false);
×
3215
      }
3216

3217
      snapshotSenderDestroy(ths->senders[i]);
×
3218
      ths->senders[i] = NULL;
×
3219
    }
3220
  }
3221

3222
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3223
    SSyncSnapshotSender* pSender = NULL;
×
3224
    int32_t              code = snapshotSenderCreate(ths, i, &pSender);
×
3225
    if (pSender == NULL) return terrno = code;
×
3226

3227
    ths->senders[i] = pSender;
×
3228
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
×
3229
  }
3230

3231
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3232
    sDebug("vgId:%d, new sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3233
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3234
  }
3235

3236
  // 7.rebuild synctimer
3237
  if ((code = syncNodeStopHeartbeatTimer(ths)) != 0) {
×
3238
    taosMemoryFree(oldLogReplMgrs);
×
3239
    TAOS_RETURN(code);
×
3240
  }
3241

3242
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3243
    if ((code = syncHbTimerInit(ths, &ths->peerHeartbeatTimerArr[i], ths->replicasId[i])) != 0) {
×
3244
      taosMemoryFree(oldLogReplMgrs);
×
3245
      TAOS_RETURN(code);
×
3246
    }
3247
  }
3248

3249
  if ((code = syncNodeStartHeartbeatTimer(ths)) != 0) {
×
3250
    taosMemoryFree(oldLogReplMgrs);
×
3251
    TAOS_RETURN(code);
×
3252
  }
3253

3254
  // 8.rebuild peerStates
3255
  SPeerState oldState[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA] = {0};
×
3256
  for (int i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; i++) {
×
3257
    oldState[i] = ths->peerStates[i];
×
3258
  }
3259

3260
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3261
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3262
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3263
        ths->peerStates[i] = oldState[j];
×
3264
      }
3265
    }
3266
  }
3267

3268
  taosMemoryFree(oldLogReplMgrs);
×
3269

3270
  return 0;
×
3271
}
3272

3273
void syncNodeChangeToVoter(SSyncNode* ths) {
×
3274
  // replicasId, only need to change replicaNum when 1->3
3275
  ths->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3276
  sDebug("vgId:%d, totalReplicaNum:%d", ths->vgId, ths->totalReplicaNum);
×
3277
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
×
3278
    sDebug("vgId:%d, i:%d, replicaId.addr:0x%" PRIx64, ths->vgId, i, ths->replicasId[i].addr);
×
3279
  }
3280

3281
  // pMatchIndex, pNextIndex, only need to change replicaNum when 1->3
3282
  ths->pMatchIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3283
  ths->pNextIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3284

3285
  sDebug("vgId:%d, pMatchIndex->totalReplicaNum:%d", ths->vgId, ths->pMatchIndex->totalReplicaNum);
×
3286
  for (int32_t i = 0; i < ths->pMatchIndex->totalReplicaNum; ++i) {
×
3287
    sDebug("vgId:%d, i:%d, match.index:%" PRId64, ths->vgId, i, ths->pMatchIndex->index[i]);
×
3288
  }
3289

3290
  // pVotesGranted, pVotesRespond
3291
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3292
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3293

3294
  // logRepMgrs
3295
  // no need to change logRepMgrs when 1->3
3296
}
×
3297

3298
void syncNodeResetPeerAndCfg(SSyncNode* ths) {
×
3299
  SNodeInfo node = {0};
×
3300
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3301
    memcpy(&ths->peersNodeInfo[i], &node, sizeof(SNodeInfo));
×
3302
  }
3303

3304
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3305
    memcpy(&ths->raftCfg.cfg.nodeInfo[i], &node, sizeof(SNodeInfo));
×
3306
  }
3307
}
×
3308

3309
int32_t syncNodeChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry, char* str) {
×
3310
  int32_t code = 0;
×
3311
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3312
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3313
  }
3314

3315
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3316
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3317

3318
  SAlterVnodeTypeReq req = {0};
×
3319
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3320
    code = TSDB_CODE_INVALID_MSG;
×
3321
    TAOS_RETURN(code);
×
3322
  }
3323

3324
  SSyncCfg cfg = {0};
×
3325
  syncBuildConfigFromReq(&req, &cfg);
×
3326

3327
  if (cfg.changeVersion <= ths->raftCfg.cfg.changeVersion) {
×
3328
    sInfo(
×
3329
        "vgId:%d, skip conf change entry since lower version. "
3330
        "this entry, index:%" PRId64 ", term:%" PRId64
3331
        ", totalReplicaNum:%d, changeVersion:%d; "
3332
        "current node, replicaNum:%d, peersNum:%d, lastConfigIndex:%" PRId64 ", changeVersion:%d",
3333
        ths->vgId, pEntry->index, pEntry->term, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum, ths->peersNum,
3334
        ths->raftCfg.lastConfigIndex, ths->raftCfg.cfg.changeVersion);
3335
    return 0;
×
3336
  }
3337

3338
  if (strcmp(str, "Commit") == 0) {
×
3339
    sInfo(
×
3340
        "vgId:%d, change config from %s. "
3341
        "this, i:%" PRId64
3342
        ", trNum:%d, vers:%d; "
3343
        "node, rNum:%d, pNum:%d, trNum:%d, "
3344
        "buffer: [%" PRId64 " %" PRId64 " %" PRId64 ", %" PRId64
3345
        "), "
3346
        "cond:(next i:%" PRId64 ", t:%" PRId64 " ==%s)",
3347
        ths->vgId, str, pEntry->index - 1, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum, ths->peersNum,
3348
        ths->totalReplicaNum, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex, ths->pLogBuf->matchIndex,
3349
        ths->pLogBuf->endIndex, pEntry->index, pEntry->term, TMSG_INFO(pEntry->originalRpcType));
3350
  } else {
3351
    sInfo(
×
3352
        "vgId:%d, change config from %s. "
3353
        "this, i:%" PRId64 ", t:%" PRId64
3354
        ", trNum:%d, vers:%d; "
3355
        "node, rNum:%d, pNum:%d, trNum:%d, "
3356
        "buffer: [%" PRId64 " %" PRId64 " %" PRId64 ", %" PRId64
3357
        "), "
3358
        "cond:(pre i:%" PRId64 "==ci:%" PRId64 ", bci:%" PRId64 ")",
3359
        ths->vgId, str, pEntry->index, pEntry->term, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum,
3360
        ths->peersNum, ths->totalReplicaNum, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3361
        ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex, pEntry->index - 1, ths->commitIndex,
3362
        ths->pLogBuf->commitIndex);
3363
  }
3364

3365
  syncNodeLogConfigInfo(ths, &cfg, "before config change");
×
3366

3367
  int32_t oldTotalReplicaNum = ths->totalReplicaNum;
×
3368

3369
  if (cfg.totalReplicaNum == 1 || cfg.totalReplicaNum == 2) {  // remove replica
×
3370

3371
    bool incfg = false;
×
3372
    for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3373
      if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3374
          ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3375
        incfg = true;
×
3376
        break;
×
3377
      }
3378
    }
3379

3380
    if (incfg) {  // remove other
×
3381
      syncNodeResetPeerAndCfg(ths);
×
3382

3383
      // no need to change myNodeInfo
3384

3385
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3386
        TAOS_RETURN(code);
×
3387
      };
3388

3389
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3390
        TAOS_RETURN(code);
×
3391
      };
3392
    } else {  // remove myself
3393
      // no need to do anything actually, to change the following to reduce distruptive server chance
3394

3395
      syncNodeResetPeerAndCfg(ths);
×
3396

3397
      // change myNodeInfo
3398
      ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
3399

3400
      // change peer and cfg
3401
      ths->peersNum = 0;
×
3402
      memcpy(&ths->raftCfg.cfg.nodeInfo[0], &ths->myNodeInfo, sizeof(SNodeInfo));
×
3403
      ths->raftCfg.cfg.replicaNum = 0;
×
3404
      ths->raftCfg.cfg.totalReplicaNum = 1;
×
3405

3406
      // change other
3407
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3408
        TAOS_RETURN(code);
×
3409
      }
3410

3411
      // change state
3412
      ths->state = TAOS_SYNC_STATE_LEARNER;
×
3413
    }
3414

3415
    ths->restoreFinish = false;
×
3416
  } else {                            // add replica, or change replica type
3417
    if (ths->totalReplicaNum == 3) {  // change replica type
×
3418
      sInfo("vgId:%d, begin change replica type", ths->vgId);
×
3419

3420
      // change myNodeInfo
3421
      for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3422
        if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3423
            ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3424
          if (cfg.nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3425
            ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3426
          }
3427
        }
3428
      }
3429

3430
      // change peer and cfg
3431
      syncNodeChangePeerAndCfgToVoter(ths, &cfg);
×
3432

3433
      // change other
3434
      syncNodeChangeToVoter(ths);
×
3435

3436
      // change state
3437
      if (ths->state == TAOS_SYNC_STATE_LEARNER) {
×
3438
        if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3439
          ths->state = TAOS_SYNC_STATE_FOLLOWER;
×
3440
        }
3441
      }
3442

3443
      ths->restoreFinish = false;
×
3444
    } else {  // add replica
3445
      sInfo("vgId:%d, begin add replica", ths->vgId);
×
3446

3447
      // no need to change myNodeInfo
3448

3449
      // change peer and cfg
3450
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3451
        TAOS_RETURN(code);
×
3452
      };
3453

3454
      // change other
3455
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3456
        TAOS_RETURN(code);
×
3457
      };
3458

3459
      // no need to change state
3460

3461
      if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
3462
        ths->restoreFinish = false;
×
3463
      }
3464
    }
3465
  }
3466

3467
  ths->quorum = syncUtilQuorum(ths->replicaNum);
×
3468

3469
  ths->raftCfg.lastConfigIndex = pEntry->index;
×
3470
  ths->raftCfg.cfg.lastIndex = pEntry->index;
×
3471
  ths->raftCfg.cfg.changeVersion = cfg.changeVersion;
×
3472

3473
  syncNodeLogConfigInfo(ths, &cfg, "after config change");
×
3474

3475
  if ((code = syncWriteCfgFile(ths)) != 0) {
×
3476
    sError("vgId:%d, failed to create sync cfg file", ths->vgId);
×
3477
    TAOS_RETURN(code);
×
3478
  };
3479

3480
  TAOS_RETURN(code);
×
3481
}
3482

3483
int32_t syncNodeAppend(SSyncNode* ths, SSyncRaftEntry* pEntry, SRpcMsg* pMsg) {
2,655,764✔
3484
  int32_t code = -1;
2,655,764✔
3485
  if (pEntry->dataLen < sizeof(SMsgHead)) {
2,655,764!
3486
    code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
3487
    sError("vgId:%d, msg:%p, cannot append an invalid client request with no msg head, type:%s dataLen:%d", ths->vgId,
×
3488
           pMsg, TMSG_INFO(pEntry->originalRpcType), pEntry->dataLen);
3489
    syncEntryDestroy(pEntry);
×
3490
    pEntry = NULL;
×
3491
    goto _out;
×
3492
  }
3493

3494
  // append to log buffer
3495
  if ((code = syncLogBufferAppend(ths->pLogBuf, ths, pEntry)) < 0) {
2,655,764✔
3496
    sError("vgId:%d, index:%" PRId64 ", failed to enqueue sync log buffer", ths->vgId, pEntry->index);
219!
3497
    int32_t ret = 0;
219✔
3498
    if ((ret = syncFsmExecute(ths, ths->pFsm, ths->state, raftStoreGetTerm(ths), pEntry, terrno, false)) != 0) {
219!
3499
      sError("vgId:%d, index:%" PRId64 ", failed to execute fsm since %s", ths->vgId, pEntry->index, tstrerror(ret));
×
3500
    }
3501
    syncEntryDestroy(pEntry);
×
3502
    pEntry = NULL;
×
3503
    goto _out;
×
3504
  }
3505

3506
  code = 0;
2,655,723✔
3507
_out:;
2,655,723✔
3508
  // proceed match index, with replicating on needed
3509
  SyncIndex       matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL, "Append", pMsg);
2,655,723✔
3510
  const STraceId* trace = pEntry ? &pEntry->originRpcTraceId : NULL;
2,655,607!
3511

3512
  if (pEntry != NULL) {
2,655,607!
3513
    sGDebug(trace,
2,655,864!
3514
            "vgId:%d, index:%" PRId64 ", raft entry appended, msg:%p term:%" PRId64 " buf:[%" PRId64 " %" PRId64
3515
            " %" PRId64 ", %" PRId64 ")",
3516
            ths->vgId, pEntry->index, pMsg, pEntry->term, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3517
            ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex);
3518
  }
3519

3520
  if (code == 0 && ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,655,607!
3521
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
×
3522
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
×
3523

3524
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
×
3525
        syncLogBufferCommit(ths->pLogBuf, ths, ths->assignedCommitIndex, trace, "append-entry") < 0) {
×
3526
      sGError(trace, "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64, ths->vgId, index,
×
3527
              pMsg, ths->commitIndex);
3528
      code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
3529
    }
3530
  }
3531

3532
  // multi replica
3533
  if (ths->replicaNum > 1) {
2,655,529✔
3534
    TAOS_RETURN(code);
190,700✔
3535
  }
3536

3537
  // single replica
3538
  SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, matchIndex);
2,464,829✔
3539
  sGTrace(trace, "vgId:%d, index:%" PRId64 ", raft entry update commit, msg:%p return index:%" PRId64, ths->vgId,
2,465,065!
3540
          matchIndex, pMsg, returnIndex);
3541

3542
  if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
4,930,279!
3543
      (code = syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, trace, "append-entry")) < 0) {
2,464,929✔
3544
    sGError(trace,
×
3545
            "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64 " return index:%" PRId64,
3546
            ths->vgId, matchIndex, pMsg, ths->commitIndex, returnIndex);
3547
  }
3548

3549
  TAOS_RETURN(code);
2,465,350✔
3550
}
3551

3552
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
2,643,685✔
3553
  if (pSyncNode->totalReplicaNum == 1) {
2,643,685✔
3554
    return false;
2,448,998✔
3555
  }
3556

3557
  int32_t toCount = 0;
194,687✔
3558
  int64_t tsNow = taosGetTimestampMs();
194,812✔
3559
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
580,861✔
3560
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
386,054✔
3561
      continue;
4,187✔
3562
    }
3563
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
381,867✔
3564
    if (recvTime == 0 || recvTime == -1) {
381,862!
3565
      continue;
×
3566
    }
3567

3568
    if (tsNow - recvTime > tsHeartbeatTimeout) {
381,862✔
3569
      toCount++;
14,470✔
3570
    }
3571
  }
3572

3573
  bool b = (toCount >= pSyncNode->quorum ? true : false);
194,807✔
3574

3575
  return b;
194,807✔
3576
}
3577

3578
bool syncNodeSnapshotSending(SSyncNode* pSyncNode) {
×
3579
  if (pSyncNode == NULL) return false;
×
3580
  bool b = false;
×
3581
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
×
3582
    if (pSyncNode->senders[i] != NULL && pSyncNode->senders[i]->start) {
×
3583
      b = true;
×
3584
      break;
×
3585
    }
3586
  }
3587
  return b;
×
3588
}
3589

3590
bool syncNodeSnapshotRecving(SSyncNode* pSyncNode) {
×
3591
  if (pSyncNode == NULL) return false;
×
3592
  if (pSyncNode->pNewNodeReceiver == NULL) return false;
×
3593
  if (pSyncNode->pNewNodeReceiver->start) return true;
×
3594
  return false;
×
3595
}
3596

3597
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
14,023✔
3598
  int32_t   code = 0;
14,023✔
3599
  SyncIndex index = syncLogBufferGetEndIndex(ths->pLogBuf);
14,023✔
3600
  SyncTerm  term = raftStoreGetTerm(ths);
14,023✔
3601

3602
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
14,023✔
3603
  if (pEntry == NULL) {
14,023!
3604
    code = TSDB_CODE_OUT_OF_MEMORY;
×
3605
    TAOS_RETURN(code);
×
3606
  }
3607

3608
  code = syncNodeAppend(ths, pEntry, NULL);
14,023✔
3609
  TAOS_RETURN(code);
14,023✔
3610
}
3611

3612
#ifdef BUILD_NO_CALL
3613
static int32_t syncNodeAppendNoopOld(SSyncNode* ths) {
3614
  int32_t ret = 0;
3615

3616
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
3617
  SyncTerm        term = raftStoreGetTerm(ths);
3618
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
3619
  if (pEntry == NULL) return -1;
3620

3621
  LRUHandle* h = NULL;
3622

3623
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
3624
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry, false);
3625
    if (code != 0) {
3626
      sError("append noop error");
3627
      return -1;
3628
    }
3629

3630
    syncCacheEntry(ths->pLogStore, pEntry, &h);
3631
  }
3632

3633
  if (h) {
3634
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
3635
  } else {
3636
    syncEntryDestroy(pEntry);
3637
  }
3638

3639
  return ret;
3640
}
3641
#endif
3642

3643
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
52,787✔
3644
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
52,787✔
3645
  bool           resetElect = false;
52,787✔
3646

3647
  int64_t tsMs = taosGetTimestampMs();
52,787✔
3648

3649
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pNextIndex, &(pMsg->srcId));
52,787✔
3650
  syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);
52,788✔
3651
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
52,788✔
3652

3653
  int64_t netElapsed = tsMs - pMsg->timeStamp;
52,788✔
3654
  int64_t timeDiff = tsMs - lastRecvTime;
52,788✔
3655
  syncLogRecvHeartbeat(ths, pMsg, netElapsed, &pRpcMsg->info.traceId, timeDiff);
52,788✔
3656

3657
  if (!syncNodeInRaftGroup(ths, &pMsg->srcId)) {
52,787✔
3658
    sWarn(
18!
3659
        "vgId:%d, drop heartbeat msg from dnode:%d, because it come from another cluster:%d, differ from current "
3660
        "cluster:%d",
3661
        ths->vgId, DID(&(pMsg->srcId)), CID(&(pMsg->srcId)), CID(&(ths->myRaftId)));
3662
    return 0;
18✔
3663
  }
3664

3665
  SyncTerm currentTerm = raftStoreGetTerm(ths);
52,769✔
3666

3667
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
52,770✔
3668
    raftStoreSetTerm(ths, pMsg->term);
353✔
3669
    currentTerm = pMsg->term;
353✔
3670
  }
3671

3672
  int64_t tsMs2 = taosGetTimestampMs();
52,770✔
3673

3674
  int64_t processTime = tsMs2 - tsMs;
52,770✔
3675
  if (processTime > SYNC_HEARTBEAT_SLOW_MS) {
52,770!
3676
    sGError(&pRpcMsg->info.traceId,
×
3677
            "vgId:%d, process sync-heartbeat msg from dnode:%d, commit-index:%" PRId64 ", cluster:%d msgTerm:%" PRId64
3678
            " currentTerm:%" PRId64 ", processTime:%" PRId64,
3679
            ths->vgId, DID(&(pMsg->srcId)), pMsg->commitIndex, CID(&(pMsg->srcId)), pMsg->term, currentTerm,
3680
            processTime);
3681
  } else {
3682
    sGDebug(&pRpcMsg->info.traceId,
52,770!
3683
            "vgId:%d, process sync-heartbeat msg from dnode:%d, commit-index:%" PRId64 ", cluster:%d msgTerm:%" PRId64
3684
            " currentTerm:%" PRId64 ", processTime:%" PRId64,
3685
            ths->vgId, DID(&(pMsg->srcId)), pMsg->commitIndex, CID(&(pMsg->srcId)), pMsg->term, currentTerm,
3686
            processTime);
3687
  }
3688

3689
  if (pMsg->term == currentTerm &&
52,770✔
3690
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
52,245!
3691
    resetElect = true;
52,245✔
3692

3693
    ths->minMatchIndex = pMsg->minMatchIndex;
52,245✔
3694

3695
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
52,245✔
3696
      SRpcMsg rpcMsgLocalCmd = {0};
52,239✔
3697
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
52,239!
3698
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
52,240✔
3699

3700
      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
52,240✔
3701
      pSyncMsg->cmd =
52,240✔
3702
          (ths->state == TAOS_SYNC_STATE_LEARNER) ? SYNC_LOCAL_CMD_LEARNER_CMT : SYNC_LOCAL_CMD_FOLLOWER_CMT;
52,240✔
3703
      pSyncMsg->commitIndex = pMsg->commitIndex;
52,240✔
3704
      pSyncMsg->currentTerm = pMsg->term;
52,240✔
3705

3706
      if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
52,240!
3707
        int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
52,240✔
3708
        if (code != 0) {
52,240!
3709
          sError("vgId:%d, failed to enqueue commit msg from heartbeat since %s, code:%d", ths->vgId, terrstr(), code);
×
3710
          rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3711
        } else {
3712
          sGTrace(&pRpcMsg->info.traceId,
52,240!
3713
                  "vgId:%d, enqueue commit msg from heartbeat, commit-index:%" PRId64 ", term:%" PRId64, ths->vgId,
3714
                  pMsg->commitIndex, pMsg->term);
3715
        }
3716
      }
3717
    }
3718
  }
3719

3720
  if (pMsg->term >= currentTerm &&
52,771✔
3721
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
52,770!
3722
    SRpcMsg rpcMsgLocalCmd = {0};
×
3723
    TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
×
3724
    rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
×
3725

3726
    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
×
3727
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
×
3728
    pSyncMsg->currentTerm = pMsg->term;
×
3729
    pSyncMsg->commitIndex = pMsg->commitIndex;
×
3730

3731
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
×
3732
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
×
3733
      if (code != 0) {
×
3734
        sError("vgId:%d, sync enqueue step-down msg error, code:%d", ths->vgId, code);
×
3735
        rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3736
      } else {
3737
        sTrace("vgId:%d, sync enqueue step-down msg, new-term:%" PRId64, ths->vgId, pMsg->term);
×
3738
      }
3739
    }
3740
  }
3741

3742
  SRpcMsg rpcMsg = {0};
52,771✔
3743
  TAOS_CHECK_RETURN(syncBuildHeartbeatReply(&rpcMsg, ths->vgId));
52,771!
3744
  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
52,770✔
3745
  pMsgReply->destId = pMsg->srcId;
52,770✔
3746
  pMsgReply->srcId = ths->myRaftId;
52,770✔
3747
  pMsgReply->term = currentTerm;
52,770✔
3748
  pMsgReply->privateTerm = 8864;  // magic number
52,770✔
3749
  pMsgReply->startTime = ths->startTime;
52,770✔
3750
  pMsgReply->timeStamp = tsMs;
52,770✔
3751
  rpcMsg.info.traceId = pRpcMsg->info.traceId;
52,770✔
3752

3753
  // reply
3754
  int64_t tsMs3 = taosGetTimestampMs();
52,770✔
3755

3756
  int64_t processTime2 = tsMs3 - tsMs2;
52,770✔
3757
  TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
52,770✔
3758
  if (processTime2 > SYNC_HEARTBEAT_SLOW_MS) {
52,770✔
3759
    sGError(&rpcMsg.info.traceId,
1!
3760
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3761
            ", processTime:%" PRId64,
3762
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3763
  } else {
3764
    if(tsSyncLogHeartbeat){
52,769!
3765
      sGInfo(&rpcMsg.info.traceId,
×
3766
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3767
            ", processTime:%" PRId64,
3768
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3769
    }
3770
    else{
3771
      sGDebug(&rpcMsg.info.traceId,
52,769!
3772
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3773
            ", processTime:%" PRId64,
3774
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3775
    }
3776
  }
3777

3778
  TAOS_CHECK_RETURN(syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg));
52,770!
3779

3780
  if (resetElect) syncNodeResetElectTimer(ths);
52,770✔
3781
  return 0;
52,770✔
3782
}
3783

3784
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
50,866✔
3785
  int32_t code = 0;
50,866✔
3786

3787
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
50,866✔
3788
  SSyncLogReplMgr*    pMgr = syncNodeGetLogReplMgr(ths, &pMsg->srcId);
50,866✔
3789
  if (pMgr == NULL) {
50,867!
3790
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3791
    if (terrno != 0) code = terrno;
×
3792
    sError("vgId:%d, failed to get log repl mgr for the peer at addr 0x016%" PRIx64, ths->vgId, pMsg->srcId.addr);
×
3793
    TAOS_RETURN(code);
×
3794
  }
3795

3796
  int64_t tsMs = taosGetTimestampMs();
50,867✔
3797
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pMatchIndex, &pMsg->srcId);
50,867✔
3798
  syncLogRecvHeartbeatReply(ths, pMsg, tsMs - pMsg->timeStamp, &pRpcMsg->info.traceId, tsMs - lastRecvTime);
50,867✔
3799

3800
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
50,866✔
3801
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
50,866✔
3802

3803
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
50,866✔
3804
}
3805

3806
#ifdef BUILD_NO_CALL
3807
int32_t syncNodeOnHeartbeatReplyOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
3808
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
3809

3810
  int64_t tsMs = taosGetTimestampMs();
3811
  int64_t timeDiff = tsMs - pMsg->timeStamp;
3812
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff, &pRpcMsg->info.traceId, timeDiff);
3813

3814
  // update last reply time, make decision whether the other node is alive or not
3815
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
3816
  return 0;
3817
}
3818
#endif
3819

3820
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
52,238✔
3821
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
52,238✔
3822
  syncLogRecvLocalCmd(ths, pMsg, &pRpcMsg->info.traceId);
52,238✔
3823

3824
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
52,237!
3825
    SRaftId id = EMPTY_RAFT_ID;
×
3826
    syncNodeStepDown(ths, pMsg->currentTerm, id);
×
3827

3828
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT || pMsg->cmd == SYNC_LOCAL_CMD_LEARNER_CMT) {
104,474!
3829
    if (syncLogBufferIsEmpty(ths->pLogBuf)) {
52,237!
3830
      sError("vgId:%d, sync log buffer is empty", ths->vgId);
×
3831
      return 0;
×
3832
    }
3833
    SyncTerm matchTerm = syncLogBufferGetLastMatchTerm(ths->pLogBuf);
52,238✔
3834
    if (matchTerm < 0) {
52,240!
3835
      return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3836
    }
3837
    if (pMsg->currentTerm == matchTerm) {
52,240✔
3838
      SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, pMsg->commitIndex);
47,894✔
3839
      sTrace("vgId:%d, raft entry update commit, return index:%" PRId64, ths->vgId, returnIndex);
47,893!
3840
    }
3841
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
104,478!
3842
        syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, &pRpcMsg->info.traceId, "heartbeat") < 0) {
52,240✔
3843
      sError("vgId:%d, failed to commit raft log since %s. commit index:%" PRId64, ths->vgId, terrstr(),
×
3844
             ths->commitIndex);
3845
    }
3846
  } else {
3847
    sError("error local cmd");
×
3848
  }
3849

3850
  return 0;
52,239✔
3851
}
3852

3853
// TLA+ Spec
3854
// ClientRequest(i, v) ==
3855
//     /\ state[i] = Leader
3856
//     /\ LET entry == [term  |-> currentTerm[i],
3857
//                      value |-> v]
3858
//            newLog == Append(log[i], entry)
3859
//        IN  log' = [log EXCEPT ![i] = newLog]
3860
//     /\ UNCHANGED <<messages, serverVars, candidateVars,
3861
//                    leaderVars, commitIndex>>
3862
//
3863

3864
int32_t syncNodeOnClientRequest(SSyncNode* ths, SRpcMsg* pMsg, SyncIndex* pRetIndex) {
2,641,785✔
3865
  sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, process client request", ths->vgId, pMsg);
2,641,785!
3866
  int32_t code = 0;
2,641,786✔
3867

3868
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
2,641,786✔
3869
  SyncTerm        term = raftStoreGetTerm(ths);
2,641,946✔
3870
  SSyncRaftEntry* pEntry = NULL;
2,641,925✔
3871
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
2,641,925✔
3872
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
288,883✔
3873
  } else {
3874
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
2,353,042✔
3875
  }
3876

3877
  if (pEntry == NULL) {
2,641,831!
3878
    sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to process client request since %s", ths->vgId, pMsg,
×
3879
            terrstr());
3880
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3881
  }
3882

3883
  // 1->2, config change is add in write thread, and will continue in sync thread
3884
  // need save message for it
3885
  if (pMsg->msgType == TDMT_SYNC_CONFIG_CHANGE) {
2,641,831!
3886
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
×
3887
    uint64_t  seqNum = syncRespMgrAdd(ths->pSyncRespMgr, &stub);
×
3888
    pEntry->seqNum = seqNum;
×
3889
  }
3890

3891
  if (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,641,831!
3892
    if (pRetIndex) {
2,641,831✔
3893
      (*pRetIndex) = index;
2,352,923✔
3894
    }
3895

3896
    if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE) {
2,641,831!
3897
      int32_t code = syncNodeCheckChangeConfig(ths, pEntry);
×
3898
      if (code < 0) {
×
3899
        sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to check change config since %s", ths->vgId, pMsg,
×
3900
                terrstr());
3901
        syncEntryDestroy(pEntry);
×
3902
        pEntry = NULL;
×
3903
        TAOS_RETURN(code);
×
3904
      }
3905

3906
      if (code > 0) {
×
3907
        SRpcMsg rsp = {.code = pMsg->code, .info = pMsg->info};
×
3908
        int32_t num = syncRespMgrGetAndDel(ths->pSyncRespMgr, pEntry->seqNum, &rsp.info);
×
3909
        sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, get response stub for config change, seqNum:%" PRIu64 " num:%d",
×
3910
                ths->vgId, pMsg, pEntry->seqNum, num);
3911
        if (rsp.info.handle != NULL) {
×
3912
          tmsgSendRsp(&rsp);
×
3913
        }
3914
        syncEntryDestroy(pEntry);
×
3915
        pEntry = NULL;
×
3916
        TAOS_RETURN(code);
×
3917
      }
3918
    }
3919

3920
    code = syncNodeAppend(ths, pEntry, pMsg);
2,641,831✔
3921
    return code;
2,641,446✔
3922
  } else {
3923
    syncEntryDestroy(pEntry);
×
3924
    pEntry = NULL;
×
3925
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3926
  }
3927
}
3928

3929
const char* syncStr(ESyncState state) {
1,058,585✔
3930
  switch (state) {
1,058,585!
3931
    case TAOS_SYNC_STATE_FOLLOWER:
702,186✔
3932
      return "follower";
702,186✔
3933
    case TAOS_SYNC_STATE_CANDIDATE:
5,330✔
3934
      return "candidate";
5,330✔
3935
    case TAOS_SYNC_STATE_LEADER:
324,374✔
3936
      return "leader";
324,374✔
3937
    case TAOS_SYNC_STATE_ERROR:
×
3938
      return "error";
×
3939
    case TAOS_SYNC_STATE_OFFLINE:
5,695✔
3940
      return "offline";
5,695✔
3941
    case TAOS_SYNC_STATE_LEARNER:
21,011✔
3942
      return "learner";
21,011✔
3943
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
×
3944
      return "assigned leader";
×
3945
    default:
×
3946
      return "unknown";
×
3947
  }
3948
}
3949

3950
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
2,339✔
3951
  for (int32_t i = 0; i < pNewCfg->totalReplicaNum; ++i) {
2,643!
3952
    SRaftId raftId = {
2,643✔
3953
        .addr = SYNC_ADDR(&pNewCfg->nodeInfo[i]),
2,643✔
3954
        .vgId = ths->vgId,
2,643✔
3955
    };
3956

3957
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
2,643✔
3958
      pNewCfg->myIndex = i;
2,339✔
3959
      return 0;
2,339✔
3960
    }
3961
  }
3962

3963
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3964
}
3965

3966
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
2,643,654✔
3967
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
2,643,654!
3968
}
3969

3970
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
951,821✔
3971
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
1,870,214✔
3972
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
1,870,197✔
3973
      return true;
951,797✔
3974
    }
3975
  }
3976
  return false;
17✔
3977
}
3978

3979
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
38,613✔
3980
  SSyncSnapshotSender* pSender = NULL;
38,613✔
3981
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
156,757✔
3982
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
118,116✔
3983
      pSender = (ths->senders)[i];
38,662✔
3984
    }
3985
  }
3986
  return pSender;
38,641✔
3987
}
3988

3989
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
38,708✔
3990
  SSyncTimer* pTimer = NULL;
38,708✔
3991
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
165,445✔
3992
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
126,736✔
3993
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
38,708✔
3994
    }
3995
  }
3996
  return pTimer;
38,709✔
3997
}
3998

3999
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
130,577✔
4000
  SPeerState* pState = NULL;
130,577✔
4001
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
416,343✔
4002
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
285,769✔
4003
      pState = &((ths->peerStates)[i]);
130,574✔
4004
    }
4005
  }
4006
  return pState;
130,574✔
4007
}
4008

4009
#ifdef BUILD_NO_CALL
4010
bool syncNodeNeedSendAppendEntries(SSyncNode* ths, const SRaftId* pDestId, const SyncAppendEntries* pMsg) {
4011
  SPeerState* pState = syncNodeGetPeerState(ths, pDestId);
4012
  if (pState == NULL) {
4013
    sError("vgId:%d, replica maybe dropped", ths->vgId);
4014
    return false;
4015
  }
4016

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

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

4024
  return true;
4025
}
4026

4027
bool syncNodeCanChange(SSyncNode* pSyncNode) {
4028
  if (pSyncNode->changing) {
4029
    sError("sync cannot change");
4030
    return false;
4031
  }
4032

4033
  if ((pSyncNode->commitIndex >= SYNC_INDEX_BEGIN)) {
4034
    SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);
4035
    if (pSyncNode->commitIndex != lastIndex) {
4036
      sError("sync cannot change2");
4037
      return false;
4038
    }
4039
  }
4040

4041
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
4042
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
4043
    if (pSender != NULL && pSender->start) {
4044
      sError("sync cannot change3");
4045
      return false;
4046
    }
4047
  }
4048

4049
  return true;
4050
}
4051
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc