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

taosdata / TDengine / #4815

17 Oct 2025 06:47AM UTC coverage: 61.177% (-0.03%) from 61.206%
#4815

push

travis-ci

web-flow
Merge pull request #33289 from taosdata/3.0

enh: Code Optimization (#33283)

155629 of 324369 branches covered (47.98%)

Branch coverage included in aggregate %.

207706 of 269535 relevant lines covered (77.06%)

127615938.53 hits per line

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

53.0
/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) {
4,723,328✔
64
  sInfo("vgId:%d, start to open sync", pSyncInfo->vgId);
4,723,328✔
65

66
  SSyncNode* pSyncNode = syncNodeOpen(pSyncInfo, vnodeVersion, pSyncInfo->electMs, pSyncInfo->heartbeatMs);
4,723,328✔
67
  if (pSyncNode == NULL) {
4,724,209!
68
    sError("vgId:%d, failed to open sync node", pSyncInfo->vgId);
×
69
    return -1;
×
70
  }
71

72
  pSyncNode->rid = syncNodeAdd(pSyncNode);
4,724,209✔
73
  if (pSyncNode->rid < 0) {
4,724,209!
74
    syncNodeClose(pSyncNode);
×
75
    return -1;
×
76
  }
77

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

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

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

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

114
  syncNodeRelease(pSyncNode);
4,723,991✔
115

116
  sInfo("vgId:%d, sync started", vgId);
4,723,991✔
117

118
  TAOS_RETURN(code);
4,723,991✔
119

120
_err:
×
121
  syncNodeRelease(pSyncNode);
×
122
  TAOS_RETURN(code);
×
123
}
124

125
int32_t syncNodeGetConfig(int64_t rid, SSyncCfg* cfg) {
6,458,123✔
126
  int32_t    code = 0;
6,458,123✔
127
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
6,458,123✔
128

129
  if (pSyncNode == NULL) {
6,459,734!
130
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
131
    if (terrno != 0) code = terrno;
×
132
    sError("failed to acquire rid:%" PRId64 " of tsNodeReftId for pSyncNode", rid);
×
133
    TAOS_RETURN(code);
×
134
  }
135

136
  *cfg = pSyncNode->raftCfg.cfg;
6,459,734✔
137

138
  syncNodeRelease(pSyncNode);
6,458,997✔
139

140
  return 0;
6,458,123✔
141
}
142

143
void syncStop(int64_t rid) {
4,723,991✔
144
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,723,991✔
145
  if (pSyncNode != NULL) {
4,723,991!
146
    pSyncNode->isStart = false;
4,723,991✔
147
    syncNodeRelease(pSyncNode);
4,723,991✔
148
    syncNodeRemove(rid);
4,723,991✔
149
  }
150
}
4,723,991✔
151

152
void syncPreStop(int64_t rid) {
4,723,969✔
153
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,723,969✔
154
  if (pSyncNode != NULL) {
4,723,991!
155
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
4,723,991!
156
      sInfo("vgId:%d, stop snapshot receiver", pSyncNode->vgId);
×
157
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
158
    }
159
    syncNodePreClose(pSyncNode);
4,723,969✔
160
    syncNodeRelease(pSyncNode);
4,722,647✔
161
  }
162
}
4,723,991✔
163

164
void syncPostStop(int64_t rid) {
4,161,135✔
165
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,161,135✔
166
  if (pSyncNode != NULL) {
4,161,135!
167
    syncNodePostClose(pSyncNode);
4,161,135✔
168
    syncNodeRelease(pSyncNode);
4,161,135✔
169
  }
170
}
4,161,135✔
171

172
static bool syncNodeCheckNewConfig(SSyncNode* pSyncNode, const SSyncCfg* pCfg) {
494,663✔
173
  if (!syncNodeInConfig(pSyncNode, pCfg)) return false;
494,663!
174
  return abs(pCfg->replicaNum - pSyncNode->replicaNum) <= 1;
494,663!
175
}
176

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

186
  if (pSyncNode->raftCfg.lastConfigIndex >= pNewCfg->lastIndex) {
532,304✔
187
    syncNodeRelease(pSyncNode);
37,641✔
188
    sInfo("vgId:%d, no need Reconfig, current index:%" PRId64 ", new index:%" PRId64, pSyncNode->vgId,
37,641!
189
          pSyncNode->raftCfg.lastConfigIndex, pNewCfg->lastIndex);
190
    return 0;
37,641✔
191
  }
192

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

200
  TAOS_CHECK_RETURN(syncNodeUpdateNewConfigIndex(pSyncNode, pNewCfg));
494,663!
201

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

208
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER || pSyncNode->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
494,663!
209
    // TODO check return value
210
    TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
446,581!
211

212
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
7,145,296✔
213
      TAOS_CHECK_RETURN(syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]));
6,698,715!
214
    }
215

216
    TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
446,581!
217
    // syncNodeReplicate(pSyncNode);
218
  }
219

220
  syncNodeRelease(pSyncNode);
494,663✔
221
  TAOS_RETURN(code);
494,663✔
222
}
223

224
int32_t syncProcessMsg(int64_t rid, SRpcMsg* pMsg) {
189,862,117✔
225
  int32_t code = -1;
189,862,117✔
226
  if (!syncIsInit()) {
189,862,117!
227
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
228
    if (terrno != 0) code = terrno;
×
229
    TAOS_RETURN(code);
×
230
  }
231

232
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
189,861,079✔
233
  if (pSyncNode == NULL) {
189,862,300!
234
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
235
    if (terrno != 0) code = terrno;
×
236
    TAOS_RETURN(code);
×
237
  }
238

239
  switch (pMsg->msgType) {
189,862,300!
240
    case TDMT_SYNC_HEARTBEAT:
19,361,652✔
241
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
19,361,652✔
242
      break;
19,361,468✔
243
    case TDMT_SYNC_HEARTBEAT_REPLY:
19,073,835✔
244
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
19,073,835✔
245
      break;
19,073,719✔
246
    case TDMT_SYNC_TIMEOUT:
24,543,887✔
247
      code = syncNodeOnTimeout(pSyncNode, pMsg);
24,543,887✔
248
      break;
24,521,344✔
249
    case TDMT_SYNC_TIMEOUT_ELECTION:
528,169✔
250
      code = syncNodeOnTimeout(pSyncNode, pMsg);
528,169✔
251
      break;
528,169✔
252
    case TDMT_SYNC_CLIENT_REQUEST:
41,354,071✔
253
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
41,354,071✔
254
      break;
41,354,071✔
255
    case TDMT_SYNC_REQUEST_VOTE:
894,521✔
256
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
894,521✔
257
      break;
894,521✔
258
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
865,999✔
259
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
865,999✔
260
      break;
865,999✔
261
    case TDMT_SYNC_APPEND_ENTRIES:
31,831,490✔
262
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
31,831,490✔
263
      break;
31,831,490✔
264
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
31,753,684✔
265
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
31,753,684✔
266
      break;
31,752,848✔
267
    case TDMT_SYNC_SNAPSHOT_SEND:
220,929✔
268
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
220,929✔
269
      break;
220,929✔
270
    case TDMT_SYNC_SNAPSHOT_RSP:
221,227✔
271
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
221,227✔
272
      break;
221,227✔
273
    case TDMT_SYNC_LOCAL_CMD:
19,198,770✔
274
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
19,198,770✔
275
      break;
19,198,770✔
276
    case TDMT_SYNC_FORCE_FOLLOWER:
6,911✔
277
      code = syncForceBecomeFollower(pSyncNode, pMsg);
6,911✔
278
      break;
6,911✔
279
    case TDMT_SYNC_SET_ASSIGNED_LEADER:
7,155✔
280
      code = syncBecomeAssignedLeader(pSyncNode, pMsg);
7,155✔
281
      break;
6,668✔
282
    default:
×
283
      code = TSDB_CODE_MSG_NOT_PROCESSED;
×
284
  }
285

286
  syncNodeRelease(pSyncNode);
189,838,134✔
287
  if (code != 0) {
189,835,878✔
288
    sDebug("vgId:%d, failed to process sync msg:%p type:%s since %s", pSyncNode->vgId, pMsg, TMSG_INFO(pMsg->msgType),
15,830!
289
           tstrerror(code));
290
  }
291
  TAOS_RETURN(code);
189,835,878✔
292
}
293

294
int32_t syncLeaderTransfer(int64_t rid) {
4,723,991✔
295
  int32_t    code = 0;
4,723,991✔
296
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,723,991✔
297
  if (pSyncNode == NULL) {
4,723,991!
298
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
299
    if (terrno != 0) code = terrno;
×
300
    TAOS_RETURN(code);
×
301
  }
302

303
  int32_t ret = syncNodeLeaderTransfer(pSyncNode);
4,723,991✔
304
  syncNodeRelease(pSyncNode);
4,723,991✔
305
  return ret;
4,723,991✔
306
}
307

308
int32_t syncForceBecomeFollower(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
6,911✔
309
  SRaftId id = {0};
6,911✔
310
  syncNodeBecomeFollower(ths, id, "force election");
6,911✔
311

312
  SRpcMsg rsp = {
13,822✔
313
      .code = 0,
314
      .pCont = pRpcMsg->info.rsp,
6,911✔
315
      .contLen = pRpcMsg->info.rspLen,
6,911✔
316
      .info = pRpcMsg->info,
317
  };
318
  tmsgSendRsp(&rsp);
6,911✔
319

320
  return 0;
6,911✔
321
}
322

323
int32_t syncBecomeAssignedLeader(SSyncNode* ths, SRpcMsg* pRpcMsg) {
6,668✔
324
  int32_t code = TSDB_CODE_MND_ARB_TOKEN_MISMATCH;
6,668✔
325
  void*   pHead = NULL;
6,668✔
326
  int32_t contLen = 0;
6,668✔
327

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

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

341
  ths->arbTerm = TMAX(req.arbTerm, ths->arbTerm);
6,668✔
342

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

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

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

366
  SVArbSetAssignedLeaderRsp rsp = {0};
935✔
367
  rsp.arbToken = req.arbToken;
935✔
368
  rsp.memberToken = req.memberToken;
935✔
369
  rsp.vgId = ths->vgId;
935✔
370

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

390
  code = TSDB_CODE_SUCCESS;
935✔
391

392
_OVER:;
6,668✔
393
  SRpcMsg rspMsg = {
6,668✔
394
      .code = code,
395
      .pCont = pHead,
396
      .contLen = contLen,
397
      .info = pRpcMsg->info,
398
  };
399

400
  tmsgSendRsp(&rspMsg);
6,668✔
401

402
  tFreeSVArbSetAssignedLeaderReq(&req);
6,668✔
403
  TAOS_RETURN(code);
6,668✔
404
}
405

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

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

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

430
SyncIndex syncMinMatchIndex(SSyncNode* pSyncNode) {
21,374,007✔
431
  SyncIndex minMatchIndex = SYNC_INDEX_INVALID;
21,374,007✔
432

433
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
64,132,740✔
434
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
42,758,733✔
435
    if (minMatchIndex == SYNC_INDEX_INVALID) {
42,758,733✔
436
      minMatchIndex = matchIndex;
23,241,820✔
437
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
19,516,913✔
438
      minMatchIndex = matchIndex;
399,152✔
439
    }
440
  }
441
  return minMatchIndex;
21,374,007✔
442
}
443

444
static SyncIndex syncLogRetentionIndex(SSyncNode* pSyncNode, int64_t bytes) {
282,044✔
445
  return pSyncNode->pLogStore->syncLogIndexRetention(pSyncNode->pLogStore, bytes);
282,044✔
446
}
447

448
int32_t syncBeginSnapshot(int64_t rid, int64_t lastApplyIndex) {
7,473,941✔
449
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
7,473,941✔
450
  int32_t    code = 0;
7,473,199✔
451
  if (pSyncNode == NULL) {
7,473,199✔
452
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
5,842✔
453
    if (terrno != 0) code = terrno;
5,842!
454
    sError("sync begin snapshot error");
5,842✔
455
    TAOS_RETURN(code);
5,842✔
456
  }
457

458
  SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
7,467,357✔
459
  SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore);
7,467,730✔
460
  bool      isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore);
7,467,328✔
461

462
  if (isEmpty || !(lastApplyIndex >= beginIndex && lastApplyIndex <= endIndex)) {
7,467,730!
463
    sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 ", empty:%d, do not delete wal", lastApplyIndex, isEmpty);
11,682!
464
    syncNodeRelease(pSyncNode);
11,682✔
465
    return 0;
10,947✔
466
  }
467

468
  int64_t logRetention = 0;
7,456,048✔
469

470
  if (syncNodeIsMnode(pSyncNode)) {
7,456,048✔
471
    // mnode
472
    logRetention = tsMndLogRetention;
1,008,365✔
473
  } else {
474
    // vnode
475
    if (pSyncNode->replicaNum > 1) {
6,448,045✔
476
      logRetention = SYNC_VNODE_LOG_RETENTION;
179,492✔
477
    }
478
  }
479

480
  if (pSyncNode->totalReplicaNum > 1) {
7,456,410✔
481
    if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER &&
283,383✔
482
        pSyncNode->state != TAOS_SYNC_STATE_LEARNER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
47,071!
483
      sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " candidate or unknown state, do not delete wal",
1,339!
484
              lastApplyIndex);
485
      syncNodeRelease(pSyncNode);
1,339✔
486
      return 0;
1,339✔
487
    }
488
    SyncIndex retentionIndex =
282,044✔
489
        TMAX(pSyncNode->minMatchIndex, syncLogRetentionIndex(pSyncNode, SYNC_WAL_LOG_RETENTION_SIZE));
282,044✔
490
    logRetention += TMAX(0, lastApplyIndex - retentionIndex);
282,044✔
491
  }
492

493
_DEL_WAL:
7,173,034✔
494

495
  do {
496
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
7,455,078✔
497
    SyncIndex          snapshotVer = walGetSnapshotVer(pData->pWal);
7,453,938✔
498
    SyncIndex          walCommitVer = walGetCommittedVer(pData->pWal);
7,454,333✔
499
    SyncIndex          wallastVer = walGetLastVer(pData->pWal);
7,453,554✔
500
    if (lastApplyIndex <= walCommitVer) {
7,453,916!
501
      SyncIndex snapshottingIndex = atomic_load_64(&pSyncNode->snapshottingIndex);
7,453,916✔
502

503
      if (snapshottingIndex == SYNC_INDEX_INVALID) {
7,454,455!
504
        atomic_store_64(&pSyncNode->snapshottingIndex, lastApplyIndex);
7,454,455✔
505
        pSyncNode->snapshottingTime = taosGetTimestampMs();
7,455,566✔
506

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

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

524
  syncNodeRelease(pSyncNode);
7,455,813✔
525
  TAOS_RETURN(code);
7,455,813✔
526
}
527

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

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

551
  syncNodeRelease(pSyncNode);
7,468,099✔
552
  TAOS_RETURN(code);
7,468,099✔
553
}
554

555
bool syncNodeIsReadyForRead(SSyncNode* pSyncNode) {
629,925,674✔
556
  if (pSyncNode == NULL) {
629,925,674!
557
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
558
    sError("sync ready for read error");
×
559
    return false;
×
560
  }
561

562
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
629,925,674✔
563
    terrno = TSDB_CODE_SYN_NOT_LEADER;
70,892,468✔
564
    return false;
70,892,468✔
565
  }
566

567
  if (!pSyncNode->restoreFinish) {
559,048,428✔
568
    terrno = TSDB_CODE_SYN_RESTORING;
111,789✔
569
    return false;
134,610✔
570
  }
571

572
  return true;
558,948,816✔
573
}
574

575
bool syncIsReadyForRead(int64_t rid) {
521,802,485✔
576
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
521,802,485✔
577
  if (pSyncNode == NULL) {
521,813,117!
578
    sError("sync ready for read error");
×
579
    return false;
×
580
  }
581

582
  bool ready = syncNodeIsReadyForRead(pSyncNode);
521,813,117✔
583

584
  syncNodeRelease(pSyncNode);
521,829,807✔
585
  return ready;
521,799,634✔
586
}
587

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

595
  bool b = syncNodeSnapshotSending(pSyncNode);
596
  syncNodeRelease(pSyncNode);
597
  return b;
598
}
599

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

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

612
int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode) {
4,723,991✔
613
  if (pSyncNode->peersNum == 0) {
4,723,991✔
614
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
3,283,104✔
615
    return 0;
3,283,104✔
616
  }
617

618
  int32_t ret = 0;
1,440,887✔
619
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && pSyncNode->replicaNum > 1) {
1,440,887✔
620
    SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
449,133✔
621
    if (pSyncNode->peersNum == 2) {
449,133✔
622
      SyncIndex matchIndex0 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[0]));
284,154✔
623
      SyncIndex matchIndex1 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[1]));
284,154✔
624
      if (matchIndex1 > matchIndex0) {
284,154✔
625
        newLeader = (pSyncNode->peersNodeInfo)[1];
7,568✔
626
      }
627
    }
628
    ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
449,133✔
629
  }
630

631
  return ret;
1,440,887✔
632
}
633

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

640
  sNTrace(pSyncNode, "begin leader transfer to %s:%u", newLeader.nodeFqdn, newLeader.nodePort);
449,133!
641

642
  SRpcMsg rpcMsg = {0};
449,133✔
643
  TAOS_CHECK_RETURN(syncBuildLeaderTransfer(&rpcMsg, pSyncNode->vgId));
449,133!
644

645
  SyncLeaderTransfer* pMsg = rpcMsg.pCont;
449,133✔
646
  pMsg->newLeaderId.addr = SYNC_ADDR(&newLeader);
449,133✔
647
  pMsg->newLeaderId.vgId = pSyncNode->vgId;
449,133✔
648
  pMsg->newNodeInfo = newLeader;
449,133✔
649

650
  int32_t ret = syncNodePropose(pSyncNode, &rpcMsg, false, NULL);
449,133✔
651
  rpcFreeCont(rpcMsg.pCont);
449,133✔
652
  return ret;
449,133✔
653
}
654

655
int32_t syncResetTimer(int64_t rid, int32_t electInterval, int32_t heartbeatInterval) {
×
656
  int32_t code = 0;
×
657
  sInfo("sync Reset Timer, rid:%" PRId64, rid);
×
658
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
×
659
  if (pSyncNode == NULL) {
×
660
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
661
    if (terrno != 0) code = terrno;
×
662
    sError("failed to acquire rid:%" PRId64 " of tsNodeReftId for pSyncNode", rid);
×
663
    TAOS_RETURN(code);
×
664
  }
665
  pSyncNode->electBaseLine = electInterval;
×
666
  syncNodeResetElectTimer(pSyncNode);
×
667

668
  sInfo("vgId:%d, sync Reset Timer, rid:%" PRId64, pSyncNode->vgId, rid);
×
669
  code = syncNodeRestartHeartbeatTimer(pSyncNode, heartbeatInterval);
×
670

671
  syncNodeRelease(pSyncNode);
×
672
  return code;
×
673
}
674

675
SSyncState syncGetState(int64_t rid) {
724,905,378✔
676
  SSyncState state = {.state = TAOS_SYNC_STATE_ERROR};
724,905,378✔
677

678
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
724,905,378✔
679
  if (pSyncNode != NULL) {
724,915,441!
680
    state.state = pSyncNode->state;
724,915,441✔
681
    state.roleTimeMs = pSyncNode->roleTimeMs;
724,915,441✔
682
    state.startTimeMs = pSyncNode->startTime;
724,908,348✔
683
    state.restored = pSyncNode->restoreFinish;
724,907,401!
684
    if (pSyncNode->vgId != 1) {
724,911,808✔
685
      state.canRead = syncNodeIsReadyForRead(pSyncNode);
108,132,265✔
686
    } else {
687
      state.canRead = state.restored;
616,771,567!
688
    }
689
    /*
690
    double progress = 0;
691
    if(pSyncNode->pLogBuf->totalIndex > 0 && pSyncNode->pLogBuf->commitIndex > 0){
692
      progress = (double)pSyncNode->pLogBuf->commitIndex/(double)pSyncNode->pLogBuf->totalIndex;
693
      state.progress = (int32_t)(progress * 100);
694
    }
695
    else{
696
      state.progress = -1;
697
    }
698
    sDebug("vgId:%d, learner progress state, commitIndex:%" PRId64 " totalIndex:%" PRId64 ", "
699
            "progress:%lf, progress:%d",
700
          pSyncNode->vgId,
701
         pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->totalIndex, progress, state.progress);
702
    */
703
    state.term = raftStoreGetTerm(pSyncNode);
724,900,743✔
704
    syncNodeRelease(pSyncNode);
724,915,800✔
705
  }
706

707
  return state;
724,912,254✔
708
}
709

710
SSyncMetrics syncGetMetrics(int64_t rid) {
×
711
  SSyncMetrics metrics = {0};
×
712

713
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
×
714
  if (pSyncNode != NULL) {
×
715
    sDebug("vgId:%d, sync get metrics, wal_write_bytes:%" PRId64 ", wal_write_time:%" PRId64, pSyncNode->vgId,
×
716
           pSyncNode->wal_write_bytes, pSyncNode->wal_write_time);
717
    metrics.wal_write_bytes = atomic_load_64(&pSyncNode->wal_write_bytes);
×
718
    metrics.wal_write_time = atomic_load_64(&pSyncNode->wal_write_time);
×
719
    syncNodeRelease(pSyncNode);
×
720
  }
721
  return metrics;
×
722
}
723

724
void syncResetMetrics(int64_t rid, const SSyncMetrics* pOldMetrics) {
×
725
  if (pOldMetrics == NULL) return;
×
726

727
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
×
728
  if (pSyncNode != NULL) {
×
729
    // Atomically subtract the old metrics values from current metrics
730
    (void)atomic_sub_fetch_64(&pSyncNode->wal_write_bytes, pOldMetrics->wal_write_bytes);
×
731
    (void)atomic_sub_fetch_64(&pSyncNode->wal_write_time, pOldMetrics->wal_write_time);
×
732
    syncNodeRelease(pSyncNode);
×
733
  }
734
}
735

736
void syncGetCommitIndex(int64_t rid, int64_t* syncCommitIndex) {
103,887,707✔
737
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
103,887,707✔
738
  if (pSyncNode != NULL) {
103,887,707!
739
    *syncCommitIndex = pSyncNode->commitIndex;
103,887,707✔
740
    syncNodeRelease(pSyncNode);
103,887,707✔
741
  }
742
}
103,887,707✔
743

744
int32_t syncGetArbToken(int64_t rid, char* outToken) {
19,363,460✔
745
  int32_t    code = 0;
19,363,460✔
746
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
19,363,460✔
747
  if (pSyncNode == NULL) {
19,363,460!
748
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
749
    if (terrno != 0) code = terrno;
×
750
    TAOS_RETURN(code);
×
751
  }
752

753
  memset(outToken, 0, TSDB_ARB_TOKEN_SIZE);
19,363,460!
754
  (void)taosThreadMutexLock(&pSyncNode->arbTokenMutex);
19,363,460✔
755
  tstrncpy(outToken, pSyncNode->arbToken, TSDB_ARB_TOKEN_SIZE);
19,363,460!
756
  (void)taosThreadMutexUnlock(&pSyncNode->arbTokenMutex);
19,363,460✔
757

758
  syncNodeRelease(pSyncNode);
19,363,460✔
759
  TAOS_RETURN(code);
19,363,460✔
760
}
761

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

771
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER) {
4,046!
772
    code = TSDB_CODE_SYN_NOT_LEADER;
×
773
    syncNodeRelease(pSyncNode);
×
774
    TAOS_RETURN(code);
×
775
  }
776

777
  bool isSync = pSyncNode->commitIndex >= pSyncNode->assignedCommitIndex;
4,046✔
778
  code = (isSync ? TSDB_CODE_SUCCESS : TSDB_CODE_VND_ARB_NOT_SYNCED);
4,046!
779
  if (!isSync) {
4,046!
780
    sInfo("vgId:%d, not synced, assignedCommitIndex:%" PRId64 ", commitIndex:%" PRId64, pSyncNode->vgId,
×
781
          pSyncNode->assignedCommitIndex, pSyncNode->commitIndex);
782
  }
783

784
  syncNodeRelease(pSyncNode);
4,046✔
785
  TAOS_RETURN(code);
4,046✔
786
}
787

788
int32_t syncUpdateArbTerm(int64_t rid, SyncTerm arbTerm) {
142,562✔
789
  int32_t    code = 0;
142,562✔
790
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
142,562✔
791
  if (pSyncNode == NULL) {
142,562!
792
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
793
    if (terrno != 0) code = terrno;
×
794
    TAOS_RETURN(code);
×
795
  }
796

797
  pSyncNode->arbTerm = TMAX(arbTerm, pSyncNode->arbTerm);
142,562✔
798
  syncNodeRelease(pSyncNode);
142,562✔
799
  TAOS_RETURN(code);
142,562✔
800
}
801

802
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
91,372,183✔
803
  if (pSyncNode->raftCfg.configIndexCount < 1) {
91,372,183!
804
    sError("vgId:%d, failed get snapshot config index, configIndexCount:%d", pSyncNode->vgId,
×
805
           pSyncNode->raftCfg.configIndexCount);
806
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
807
    return -2;
×
808
  }
809
  SyncIndex lastIndex = (pSyncNode->raftCfg.configIndexArr)[0];
91,373,679✔
810

811
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
190,043,365✔
812
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
98,670,808✔
813
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
7,297,152✔
814
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
7,237,707✔
815
    }
816
  }
817
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
91,372,579✔
818
         lastIndex);
819

820
  return lastIndex;
91,373,457✔
821
}
822

823
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
197,981,889✔
824
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
370,692,658✔
825
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
287,640,605!
826
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
287,640,336✔
827
      return pSyncNode->peersId[i];
114,931,256✔
828
    }
829
  }
830
  return EMPTY_RAFT_ID;
83,046,730✔
831
}
832

833
static void epsetToString(const SEpSet* pEpSet, char* buffer, size_t bufferSize) {
83,074,872✔
834
  if (pEpSet == NULL || buffer == NULL) {
83,074,872!
835
    snprintf(buffer, bufferSize, "EpSet is NULL");
813!
836
    return;
813✔
837
  }
838

839
  size_t offset = 0;
83,074,059✔
840
  offset += snprintf(buffer + offset, bufferSize - offset, "EpSet: [");
83,074,059!
841

842
  for (int i = 0; i < pEpSet->numOfEps; ++i) {
281,053,564✔
843
    if (offset >= bufferSize) break;
197,980,188!
844
    offset += snprintf(buffer + offset, bufferSize - offset, "%s:%d%s", pEpSet->eps[i].fqdn, pEpSet->eps[i].port,
197,980,869!
845
                       (i + 1 < pEpSet->numOfEps) ? ", " : "");
197,980,188✔
846
  }
847

848
  if (offset < bufferSize) {
83,078,484✔
849
    snprintf(buffer + offset, bufferSize - offset, "]");
83,076,555!
850
  }
851
}
852

853
void syncGetRetryEpSet(int64_t rid, SEpSet* pEpSet) {
83,076,504✔
854
  pEpSet->numOfEps = 0;
83,076,504✔
855

856
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
83,076,702✔
857
  if (pSyncNode == NULL) return;
83,078,670!
858

859
  int index = -1;
83,078,670✔
860

861
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
83,078,670✔
862
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
863
  int j = 0;
83,077,853✔
864
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
281,672,503✔
865
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
198,598,316✔
866
    SEp* pEp = &pEpSet->eps[j];
197,976,988✔
867
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
197,977,367!
868
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
197,979,843✔
869
    pEpSet->numOfEps++;
197,978,219✔
870
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
197,981,663✔
871
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
197,977,419✔
872
           pEp->port);
873
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
197,977,419✔
874
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
72,601,324!
875
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
876
      index = j;
72,598,912✔
877
    }
878
    j++;
197,977,720✔
879
  }
880
  if (pEpSet->numOfEps > 0) {
83,076,308✔
881
    if (index != -1) {
83,075,785✔
882
      pEpSet->inUse = index;
72,604,871✔
883
    } else {
884
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
10,470,914✔
885
          pSyncNode->myRaftId.vgId == pSyncNode->leaderCache.vgId) {
9,249!
886
        pEpSet->inUse = pSyncNode->raftCfg.cfg.myIndex;
9,249✔
887
      } else {
888
        pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
10,462,187!
889
      }
890
    }
891
    // pEpSet->inUse = 0;
892
  }
893
  epsetSort(pEpSet);
83,077,820✔
894

895
  char buffer[1024];
83,054,330✔
896
  epsetToString(pEpSet, buffer, sizeof(buffer));
83,074,788✔
897
  sDebug("vgId:%d, sync get retry epset numOfEps:%d %s inUse:%d", pSyncNode->vgId, pEpSet->numOfEps, buffer,
83,076,206✔
898
         pEpSet->inUse);
899
  syncNodeRelease(pSyncNode);
83,076,206✔
900
}
901

902
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
646,969,251✔
903
  int32_t    code = 0;
646,969,251✔
904
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
646,969,251✔
905
  if (pSyncNode == NULL) {
646,970,560!
906
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
907
    if (terrno != 0) code = terrno;
×
908
    sError("sync propose error");
×
909
    TAOS_RETURN(code);
×
910
  }
911

912
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak, seq);
646,970,560✔
913
  syncNodeRelease(pSyncNode);
646,899,342✔
914
  return ret;
646,910,506✔
915
}
916

917
int32_t syncCheckMember(int64_t rid) {
×
918
  int32_t    code = 0;
×
919
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
×
920
  if (pSyncNode == NULL) {
×
921
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
922
    if (terrno != 0) code = terrno;
×
923
    sError("sync propose error");
×
924
    TAOS_RETURN(code);
×
925
  }
926

927
  if (pSyncNode->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
928
    syncNodeRelease(pSyncNode);
×
929
    return TSDB_CODE_SYN_WRONG_ROLE;
×
930
  }
931

932
  syncNodeRelease(pSyncNode);
×
933
  return 0;
×
934
}
935

936
int32_t syncIsCatchUp(int64_t rid) {
2,120,790✔
937
  int32_t    code = 0;
2,120,790✔
938
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
2,120,790✔
939
  if (pSyncNode == NULL) {
2,120,790!
940
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
941
    if (terrno != 0) code = terrno;
×
942
    sError("sync Node Acquire error since %d", ERRNO);
×
943
    TAOS_RETURN(code);
×
944
  }
945

946
  int32_t isCatchUp = 0;
2,120,790✔
947
  if (pSyncNode->pLogBuf->totalIndex < 0 || pSyncNode->pLogBuf->commitIndex < 0 ||
2,120,790!
948
      pSyncNode->pLogBuf->totalIndex < pSyncNode->pLogBuf->commitIndex ||
532,441!
949
      pSyncNode->pLogBuf->totalIndex - pSyncNode->pLogBuf->commitIndex > SYNC_LEARNER_CATCHUP) {
532,441✔
950
    sInfo("vgId:%d, Not catch up, wait one second, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64,
2,013,815!
951
          pSyncNode->vgId, pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex,
952
          pSyncNode->pLogBuf->matchIndex);
953
    isCatchUp = 0;
2,013,815✔
954
  } else {
955
    sInfo("vgId:%d, Catch up, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64, pSyncNode->vgId,
106,975!
956
          pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->matchIndex);
957
    isCatchUp = 1;
106,975✔
958
  }
959

960
  syncNodeRelease(pSyncNode);
2,120,790✔
961
  return isCatchUp;
2,120,790✔
962
}
963

964
ESyncRole syncGetRole(int64_t rid) {
2,120,790✔
965
  int32_t    code = 0;
2,120,790✔
966
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
2,120,790✔
967
  if (pSyncNode == NULL) {
2,120,790!
968
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
969
    if (terrno != 0) code = terrno;
×
970
    sError("sync Node Acquire error since %d", ERRNO);
×
971
    TAOS_RETURN(code);
×
972
  }
973

974
  ESyncRole role = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole;
2,120,790✔
975

976
  syncNodeRelease(pSyncNode);
2,120,790✔
977
  return role;
2,120,790✔
978
}
979

980
int64_t syncGetTerm(int64_t rid) {
7,720,699✔
981
  int32_t    code = 0;
7,720,699✔
982
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
7,720,699✔
983
  if (pSyncNode == NULL) {
7,720,699!
984
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
985
    if (terrno != 0) code = terrno;
×
986
    sError("sync Node Acquire error since %d", ERRNO);
×
987
    TAOS_RETURN(code);
×
988
  }
989

990
  int64_t term = raftStoreGetTerm(pSyncNode);
7,720,699✔
991

992
  syncNodeRelease(pSyncNode);
7,720,699✔
993
  return term;
7,720,699✔
994
}
995

996
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
647,415,125✔
997
  int32_t code = 0;
647,415,125✔
998
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
647,415,125✔
999
    code = TSDB_CODE_SYN_NOT_LEADER;
802,400✔
1000
    sNWarn(pSyncNode, "sync propose not leader, type:%s", TMSG_INFO(pMsg->msgType));
802,400!
1001
    TAOS_RETURN(code);
802,400✔
1002
  }
1003

1004
  if (!pSyncNode->restoreFinish) {
646,619,819!
1005
    code = TSDB_CODE_SYN_RESTORING;
13,572✔
1006
    sNWarn(pSyncNode, "failed to sync propose since not ready, type:%s, last:%" PRId64 ", cmt:%" PRId64,
13,572!
1007
           TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
1008
    TAOS_RETURN(code);
13,572✔
1009
  }
1010

1011
  // heartbeat timeout
1012
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER && syncNodeHeartbeatReplyTimeout(pSyncNode)) {
646,614,215✔
1013
    code = TSDB_CODE_SYN_PROPOSE_NOT_READY;
1,359✔
1014
    sNError(pSyncNode, "failed to sync propose since heartbeat timeout, type:%s, last:%" PRId64 ", cmt:%" PRId64,
1,359!
1015
            TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
1016
    TAOS_RETURN(code);
1,359✔
1017
  }
1018

1019
  // optimized one replica
1020
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
646,603,108✔
1021
    SyncIndex retIndex;
604,633,958✔
1022
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
604,648,615✔
1023
    if (code >= 0) {
604,571,660!
1024
      pMsg->info.conn.applyIndex = retIndex;
604,571,660✔
1025
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
604,608,212✔
1026

1027
      // after raft member change, need to handle 1->2 switching point
1028
      // at this point, need to switch entry handling thread
1029
      if (pSyncNode->replicaNum == 1) {
604,634,126!
1030
        sGDebug(&pMsg->info.traceId, "vgId:%d, index:%" PRId64 ", propose optimized msg type:%s", pSyncNode->vgId,
604,642,590!
1031
                retIndex, TMSG_INFO(pMsg->msgType));
1032
        return 1;
604,582,419✔
1033
      } else {
1034
        sGDebug(&pMsg->info.traceId,
×
1035
                "vgId:%d, index:%" PRId64 ", propose optimized msg, return to normal, type:%s, handle:%p",
1036
                pSyncNode->vgId, retIndex, TMSG_INFO(pMsg->msgType), pMsg->info.handle);
1037
        return 0;
×
1038
      }
1039
    } else {
1040
      code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1041
      sError("vgId:%d, failed to propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
×
1042
             TMSG_INFO(pMsg->msgType));
1043
      TAOS_RETURN(code);
×
1044
    }
1045
  } else {
1046
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
41,963,575✔
1047
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
41,964,621✔
1048
    SRpcMsg   rpcMsg = {.info.traceId = pMsg->info.traceId};
41,964,521✔
1049
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
41,964,470✔
1050
    if (code != 0) {
41,964,521!
1051
      sError("vgId:%d, failed to propose msg while serialize since %s", pSyncNode->vgId, terrstr());
×
1052
      code = syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum);
×
1053
      TAOS_RETURN(code);
×
1054
    }
1055

1056
    sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, propose msg, type:%s", pSyncNode->vgId, pMsg,
41,964,521!
1057
            TMSG_INFO(pMsg->msgType));
1058
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
41,964,521✔
1059
    if (code != 0) {
41,964,598✔
1060
      sWarn("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
610,550!
1061
      TAOS_CHECK_RETURN(syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum));
610,550✔
1062
    }
1063

1064
    if (seq != NULL) *seq = seqNum;
41,958,559✔
1065
    TAOS_RETURN(code);
41,958,582✔
1066
  }
1067
}
1068

1069
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId) {
77,560,204✔
1070
  pSyncTimer->pTimer = NULL;
77,560,204✔
1071
  pSyncTimer->counter = 0;
77,561,850✔
1072
  pSyncTimer->timerMS = pSyncNode->hbBaseLine;
77,560,976✔
1073
  pSyncTimer->timerCb = syncNodeEqPeerHeartbeatTimer;
77,561,850✔
1074
  pSyncTimer->destId = destId;
77,561,850✔
1075
  pSyncTimer->timeStamp = taosGetTimestampMs();
77,559,654✔
1076
  atomic_store_64(&pSyncTimer->logicClock, 0);
77,558,419✔
1077
  sInfo("vgId:%d, HbTimer init, timerMs:%d for addr:0x%" PRIx64, pSyncNode->vgId, pSyncTimer->timerMS, destId.addr);
77,561,850✔
1078
  return 0;
77,561,850✔
1079
}
1080

1081
static void syncHBSetTimerMS(SSyncTimer* pSyncTimer, int32_t ms) { pSyncTimer->timerMS = ms; }
×
1082

1083
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
1,052,901✔
1084
  int32_t code = 0;
1,052,901✔
1085
  int64_t tsNow = taosGetTimestampMs();
1,052,901✔
1086
  if (syncIsInit()) {
1,052,901!
1087
    SSyncHbTimerData* pData = syncHbTimerDataAcquire(pSyncTimer->hbDataRid);
1,052,901✔
1088
    if (pData == NULL) {
1,052,901✔
1089
      pData = taosMemoryMalloc(sizeof(SSyncHbTimerData));
1,052,431!
1090
      pData->rid = syncHbTimerDataAdd(pData);
1,052,431✔
1091
    }
1092
    pSyncTimer->hbDataRid = pData->rid;
1,052,901✔
1093
    pSyncTimer->timeStamp = tsNow;
1,052,901✔
1094

1095
    pData->syncNodeRid = pSyncNode->rid;
1,052,901✔
1096
    pData->pTimer = pSyncTimer;
1,052,901✔
1097
    pData->destId = pSyncTimer->destId;
1,052,901✔
1098
    pData->logicClock = pSyncTimer->logicClock;
1,052,901✔
1099
    pData->execTime = tsNow + pSyncTimer->timerMS;
1,052,901✔
1100

1101
    sInfo("vgId:%d, start hb timer, rid:%" PRId64 " addr:0x%" PRIx64 " at %d", pSyncNode->vgId, pData->rid,
1,052,901!
1102
          pData->destId.addr, pSyncTimer->timerMS);
1103

1104
    bool stopped = taosTmrResetPriority(pSyncTimer->timerCb, pSyncTimer->timerMS, (void*)(pData->rid),
1,052,901✔
1105
                                        syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
1,052,901✔
1106
    if (stopped) {
1,052,901✔
1107
      sWarn("vgId:%d, reset hb timer stopped:%d", pSyncNode->vgId, stopped);
470!
1108
    }
1109
  } else {
1110
    code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1111
    sError("vgId:%d, start ctrl hb timer error, sync env is stop", pSyncNode->vgId);
×
1112
  }
1113
  return code;
1,052,901✔
1114
}
1115

1116
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
11,053,248✔
1117
  int32_t ret = 0;
11,053,248✔
1118
  (void)atomic_add_fetch_64(&pSyncTimer->logicClock, 1);
11,053,248✔
1119
  bool stop = taosTmrStop(pSyncTimer->pTimer);
11,053,585✔
1120
  sDebug("vgId:%d, stop hb timer stop:%d", pSyncNode->vgId, stop);
11,051,989!
1121
  pSyncTimer->pTimer = NULL;
11,051,989✔
1122
  syncHbTimerDataRemove(pSyncTimer->hbDataRid);
11,053,047✔
1123
  pSyncTimer->hbDataRid = -1;
11,054,084✔
1124
  return ret;
11,054,084✔
1125
}
1126

1127
int32_t syncNodeLogStoreRestoreOnNeed(SSyncNode* pNode) {
4,724,209✔
1128
  int32_t code = 0;
4,724,209✔
1129
  if (pNode->pLogStore == NULL) {
4,724,209!
1130
    sError("vgId:%d, log store not created", pNode->vgId);
×
1131
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1132
  }
1133
  if (pNode->pFsm == NULL) {
4,724,209!
1134
    sError("vgId:%d, pFsm not registered", pNode->vgId);
×
1135
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1136
  }
1137
  if (pNode->pFsm->FpGetSnapshotInfo == NULL) {
4,724,209!
1138
    sError("vgId:%d, FpGetSnapshotInfo not registered", pNode->vgId);
×
1139
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1140
  }
1141
  SSnapshot snapshot = {0};
4,724,209✔
1142
  // TODO check return value
1143
  (void)pNode->pFsm->FpGetSnapshotInfo(pNode->pFsm, &snapshot);
4,724,209✔
1144

1145
  SyncIndex commitIndex = snapshot.lastApplyIndex;
4,724,209✔
1146
  SyncIndex firstVer = pNode->pLogStore->syncLogBeginIndex(pNode->pLogStore);
4,724,209✔
1147
  SyncIndex lastVer = pNode->pLogStore->syncLogLastIndex(pNode->pLogStore);
4,724,208✔
1148
  if ((lastVer < commitIndex || firstVer > commitIndex + 1) || pNode->fsmState == SYNC_FSM_STATE_INCOMPLETE) {
4,724,209!
1149
    sInfo("vgId:%d, restore log store from snapshot, firstVer:%" PRId64 ", lastVer:%" PRId64 ", commitIndex:%" PRId64,
867!
1150
          pNode->vgId, firstVer, lastVer, commitIndex);
1151
    if ((code = pNode->pLogStore->syncLogRestoreFromSnapshot(pNode->pLogStore, commitIndex)) != 0) {
867!
1152
      sError("vgId:%d, failed to restore log store from snapshot since %s. lastVer:%" PRId64 ", snapshotVer:%" PRId64,
×
1153
             pNode->vgId, terrstr(), lastVer, commitIndex);
1154
      TAOS_RETURN(code);
×
1155
    }
1156
  }
1157
  TAOS_RETURN(code);
4,724,209✔
1158
}
1159

1160
// open/close --------------
1161
SSyncNode* syncNodeOpen(SSyncInfo* pSyncInfo, int32_t vnodeVersion, int32_t electInterval, int32_t heartbeatInterval) {
4,720,820✔
1162
  int32_t    code = 0;
4,720,820✔
1163
  SSyncNode* pSyncNode = taosMemoryCalloc(1, sizeof(SSyncNode));
4,720,820!
1164
  if (pSyncNode == NULL) {
4,724,209!
1165
    terrno = TSDB_CODE_OUT_OF_MEMORY;
×
1166
    goto _error;
×
1167
  }
1168

1169
  if (!taosDirExist((char*)(pSyncInfo->path))) {
4,724,209✔
1170
    if (taosMkDir(pSyncInfo->path) != 0) {
3,440,119!
1171
      terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
1172
      sError("vgId:%d, failed to create dir:%s since %s", pSyncInfo->vgId, pSyncInfo->path, terrstr());
×
1173
      goto _error;
×
1174
    }
1175
  }
1176

1177
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
4,724,209!
1178
  snprintf(pSyncNode->raftStorePath, sizeof(pSyncNode->raftStorePath), "%s%sraft_store.json", pSyncInfo->path,
4,724,209✔
1179
           TD_DIRSEP);
1180
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
4,722,832✔
1181

1182
  if (!taosCheckExistFile(pSyncNode->configPath)) {
4,722,426✔
1183
    // create a new raft config file
1184
    sInfo("vgId:%d, create a new raft config file", pSyncInfo->vgId);
3,440,119✔
1185
    pSyncNode->vgId = pSyncInfo->vgId;
3,440,955✔
1186
    pSyncNode->mountVgId = pSyncInfo->mountVgId;
3,440,119✔
1187
    pSyncNode->raftCfg.isStandBy = pSyncInfo->isStandBy;
3,440,119!
1188
    pSyncNode->raftCfg.snapshotStrategy = pSyncInfo->snapshotStrategy;
3,440,119✔
1189
    pSyncNode->raftCfg.lastConfigIndex = pSyncInfo->syncCfg.lastIndex;
3,440,119✔
1190
    pSyncNode->raftCfg.batchSize = pSyncInfo->batchSize;
3,440,119✔
1191
    pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
3,440,119✔
1192
    pSyncNode->raftCfg.configIndexCount = 1;
3,440,119✔
1193
    pSyncNode->raftCfg.configIndexArr[0] = -1;
3,440,119✔
1194

1195
    if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
3,440,119!
1196
      terrno = code;
×
1197
      sError("vgId:%d, failed to create sync cfg file", pSyncNode->vgId);
×
1198
      goto _error;
×
1199
    }
1200
  } else {
1201
    // update syncCfg by raft_config.json
1202
    if ((code = syncReadCfgFile(pSyncNode)) != 0) {
1,283,893!
1203
      terrno = code;
×
1204
      sError("vgId:%d, failed to read sync cfg file", pSyncNode->vgId);
×
1205
      goto _error;
×
1206
    }
1207

1208
    if (vnodeVersion > pSyncNode->raftCfg.cfg.changeVersion) {
1,284,090✔
1209
      if (pSyncInfo->syncCfg.totalReplicaNum > 0 && syncIsConfigChanged(&pSyncNode->raftCfg.cfg, &pSyncInfo->syncCfg)) {
883,451!
1210
        sInfo("vgId:%d, use sync config from input options and write to cfg file", pSyncNode->vgId);
766,098!
1211
        pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
766,098✔
1212
        if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
766,098!
1213
          terrno = code;
×
1214
          sError("vgId:%d, failed to write sync cfg file", pSyncNode->vgId);
×
1215
          goto _error;
×
1216
        }
1217
      } else {
1218
        sInfo("vgId:%d, use sync config from sync cfg file", pSyncNode->vgId);
117,353!
1219
        pSyncInfo->syncCfg = pSyncNode->raftCfg.cfg;
117,353✔
1220
      }
1221
    } else {
1222
      sInfo("vgId:%d, skip save sync cfg file since request ver:%d <= file ver:%d", pSyncNode->vgId, vnodeVersion,
400,456!
1223
            pSyncInfo->syncCfg.changeVersion);
1224
    }
1225
  }
1226

1227
  // init by SSyncInfo
1228
  pSyncNode->vgId = pSyncInfo->vgId;
4,722,280✔
1229
  pSyncNode->mountVgId = pSyncInfo->mountVgId;
4,722,794✔
1230
  SSyncCfg* pCfg = &pSyncNode->raftCfg.cfg;
4,722,794✔
1231
  bool      updated = false;
4,722,280✔
1232
  sInfo("vgId:%d, start to open sync node, totalReplicaNum:%d replicaNum:%d selfIndex:%d", pSyncNode->vgId,
4,722,280✔
1233
        pCfg->totalReplicaNum, pCfg->replicaNum, pCfg->myIndex);
1234
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
12,511,021✔
1235
    SNodeInfo* pNode = &pCfg->nodeInfo[i];
7,786,812✔
1236
    if (tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort)) {
7,786,812!
1237
      updated = true;
×
1238
    }
1239
    sInfo("vgId:%d, index:%d ep:%s:%u dnode:%d cluster:%" PRId64, pSyncNode->vgId, i, pNode->nodeFqdn, pNode->nodePort,
7,786,812✔
1240
          pNode->nodeId, pNode->clusterId);
1241
  }
1242

1243
  if (vnodeVersion > pSyncInfo->syncCfg.changeVersion) {
4,724,209✔
1244
    if (updated) {
563,074!
1245
      sInfo("vgId:%d, save config info since dnode info changed", pSyncNode->vgId);
×
1246
      if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
×
1247
        terrno = code;
×
1248
        sError("vgId:%d, failed to write sync cfg file on dnode info updated", pSyncNode->vgId);
×
1249
        goto _error;
×
1250
      }
1251
    }
1252
  }
1253

1254
  pSyncNode->pWal = pSyncInfo->pWal;
4,724,209✔
1255
  pSyncNode->msgcb = pSyncInfo->msgcb;
4,724,209✔
1256
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
4,724,209✔
1257
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
4,724,209✔
1258
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
4,724,209✔
1259

1260
  // create raft log ring buffer
1261
  code = syncLogBufferCreate(&pSyncNode->pLogBuf);
4,724,209✔
1262
  if (pSyncNode->pLogBuf == NULL) {
4,722,427!
1263
    sError("failed to init sync log buffer since %s. vgId:%d", tstrerror(code), pSyncNode->vgId);
×
1264
    goto _error;
×
1265
  }
1266

1267
  // init replicaNum, replicasId
1268
  pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
4,723,670✔
1269
  pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
4,722,297✔
1270
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
12,509,326✔
1271
    if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
7,785,938!
1272
        false) {
1273
      sError("vgId:%d, failed to determine raft member id, replica:%d", pSyncNode->vgId, i);
×
1274
      goto _error;
×
1275
    }
1276
  }
1277

1278
  // init internal
1279
  pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
4,724,209✔
1280
  pSyncNode->myRaftId = pSyncNode->replicasId[pSyncNode->raftCfg.cfg.myIndex];
4,724,209✔
1281

1282
  // init peersNum, peers, peersId
1283
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
4,724,209✔
1284
  int32_t j = 0;
4,724,209✔
1285
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
12,511,021✔
1286
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
7,786,812✔
1287
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
3,062,631✔
1288
      pSyncNode->peersId[j] = pSyncNode->replicasId[i];
3,062,631✔
1289
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
3,062,631✔
1290
      j++;
3,062,631✔
1291
    }
1292
  }
1293

1294
  pSyncNode->arbTerm = -1;
4,724,209✔
1295
  (void)taosThreadMutexInit(&pSyncNode->arbTokenMutex, NULL);
4,724,209✔
1296
  syncUtilGenerateArbToken(pSyncNode->myNodeInfo.nodeId, pSyncInfo->vgId, pSyncNode->arbToken);
4,724,209✔
1297
  sInfo("vgId:%d, generate arb token:%s", pSyncNode->vgId, pSyncNode->arbToken);
4,724,037✔
1298

1299
  // init raft algorithm
1300
  pSyncNode->pFsm = pSyncInfo->pFsm;
4,724,209✔
1301
  pSyncInfo->pFsm = NULL;
4,724,209✔
1302
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
4,724,209✔
1303
  pSyncNode->leaderCache = EMPTY_RAFT_ID;
4,724,209✔
1304
  pSyncNode->leaderCacheEp.port = 0;
4,724,209✔
1305
  pSyncNode->leaderCacheEp.fqdn[0] = '\0';
4,724,209✔
1306

1307
  // init life cycle outside
1308

1309
  // TLA+ Spec
1310
  // InitHistoryVars == /\ elections = {}
1311
  //                    /\ allLogs   = {}
1312
  //                    /\ voterLog  = [i \in Server |-> [j \in {} |-> <<>>]]
1313
  // InitServerVars == /\ currentTerm = [i \in Server |-> 1]
1314
  //                   /\ state       = [i \in Server |-> Follower]
1315
  //                   /\ votedFor    = [i \in Server |-> Nil]
1316
  // InitCandidateVars == /\ votesResponded = [i \in Server |-> {}]
1317
  //                      /\ votesGranted   = [i \in Server |-> {}]
1318
  // \* The values nextIndex[i][i] and matchIndex[i][i] are never read, since the
1319
  // \* leader does not send itself messages. It's still easier to include these
1320
  // \* in the functions.
1321
  // InitLeaderVars == /\ nextIndex  = [i \in Server |-> [j \in Server |-> 1]]
1322
  //                   /\ matchIndex = [i \in Server |-> [j \in Server |-> 0]]
1323
  // InitLogVars == /\ log          = [i \in Server |-> << >>]
1324
  //                /\ commitIndex  = [i \in Server |-> 0]
1325
  // Init == /\ messages = [m \in {} |-> 0]
1326
  //         /\ InitHistoryVars
1327
  //         /\ InitServerVars
1328
  //         /\ InitCandidateVars
1329
  //         /\ InitLeaderVars
1330
  //         /\ InitLogVars
1331
  //
1332

1333
  // init TLA+ server vars
1334
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
4,724,209✔
1335
  pSyncNode->roleTimeMs = taosGetTimestampMs();
4,724,209✔
1336
  if ((code = raftStoreOpen(pSyncNode)) != 0) {
4,724,209!
1337
    terrno = code;
×
1338
    sError("vgId:%d, failed to open raft store at path %s", pSyncNode->vgId, pSyncNode->raftStorePath);
×
1339
    goto _error;
×
1340
  }
1341

1342
  // init TLA+ candidate vars
1343
  pSyncNode->pVotesGranted = voteGrantedCreate(pSyncNode);
4,723,416✔
1344
  if (pSyncNode->pVotesGranted == NULL) {
4,723,977!
1345
    sError("vgId:%d, failed to create VotesGranted", pSyncNode->vgId);
×
1346
    goto _error;
×
1347
  }
1348
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
4,724,025✔
1349
  if (pSyncNode->pVotesRespond == NULL) {
4,723,295!
1350
    sError("vgId:%d, failed to create VotesRespond", pSyncNode->vgId);
×
1351
    goto _error;
×
1352
  }
1353

1354
  // init TLA+ leader vars
1355
  pSyncNode->pNextIndex = syncIndexMgrCreate(pSyncNode);
4,723,073✔
1356
  if (pSyncNode->pNextIndex == NULL) {
4,720,282!
1357
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
×
1358
    goto _error;
×
1359
  }
1360
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
4,722,252✔
1361
  if (pSyncNode->pMatchIndex == NULL) {
4,723,689!
1362
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
×
1363
    goto _error;
×
1364
  }
1365

1366
  // init TLA+ log vars
1367
  pSyncNode->pLogStore = logStoreCreate(pSyncNode);
4,723,238✔
1368
  if (pSyncNode->pLogStore == NULL) {
4,723,996!
1369
    sError("vgId:%d, failed to create SyncLogStore", pSyncNode->vgId);
×
1370
    goto _error;
×
1371
  }
1372

1373
  SyncIndex commitIndex = SYNC_INDEX_INVALID;
4,722,320✔
1374
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
4,722,320!
1375
    SSnapshot snapshot = {0};
4,724,209✔
1376
    // TODO check return value
1377
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
4,724,209✔
1378
    if (snapshot.lastApplyIndex > commitIndex) {
4,724,209✔
1379
      commitIndex = snapshot.lastApplyIndex;
598,123✔
1380
      sNTrace(pSyncNode, "reset commit index by snapshot");
598,123✔
1381
    }
1382
    pSyncNode->fsmState = snapshot.state;
4,724,209✔
1383
    if (pSyncNode->fsmState == SYNC_FSM_STATE_INCOMPLETE) {
4,724,209!
1384
      sError("vgId:%d, fsm state is incomplete.", pSyncNode->vgId);
×
1385
      if (pSyncNode->replicaNum == 1) {
×
1386
        terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1387
        goto _error;
×
1388
      }
1389
    }
1390
  }
1391
  pSyncNode->commitIndex = commitIndex;
4,722,212✔
1392
  sInfo("vgId:%d, sync node commitIndex initialized as %" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
4,723,163✔
1393

1394
  // restore log store on need
1395
  if ((code = syncNodeLogStoreRestoreOnNeed(pSyncNode)) < 0) {
4,724,045!
1396
    terrno = code;
×
1397
    sError("vgId:%d, failed to restore log store since %s.", pSyncNode->vgId, terrstr());
×
1398
    goto _error;
×
1399
  }
1400

1401
  // timer ms init
1402
  pSyncNode->pingBaseLine = PING_TIMER_MS;
4,724,209✔
1403
  pSyncNode->electBaseLine = electInterval;
4,724,209✔
1404
  pSyncNode->hbBaseLine = heartbeatInterval;
4,724,209✔
1405

1406
  // init ping timer
1407
  pSyncNode->pPingTimer = NULL;
4,724,209✔
1408
  pSyncNode->pingTimerMS = pSyncNode->pingBaseLine;
4,724,209✔
1409
  atomic_store_64(&pSyncNode->pingTimerLogicClock, 0);
4,724,209✔
1410
  atomic_store_64(&pSyncNode->pingTimerLogicClockUser, 0);
4,724,209✔
1411
  pSyncNode->FpPingTimerCB = syncNodeEqPingTimer;
4,724,209✔
1412
  pSyncNode->pingTimerCounter = 0;
4,724,209✔
1413

1414
  // init elect timer
1415
  pSyncNode->pElectTimer = NULL;
4,724,209✔
1416
  pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
4,724,209✔
1417
  atomic_store_64(&pSyncNode->electTimerLogicClock, 0);
4,724,209✔
1418
  pSyncNode->FpElectTimerCB = syncNodeEqElectTimer;
4,724,209✔
1419
  pSyncNode->electTimerCounter = 0;
4,724,209✔
1420

1421
  // init heartbeat timer
1422
  pSyncNode->pHeartbeatTimer = NULL;
4,724,209✔
1423
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
4,724,209✔
1424
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, 0);
4,724,209✔
1425
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClockUser, 0);
4,724,209✔
1426
#ifdef BUILD_NO_CALL
1427
  pSyncNode->FpHeartbeatTimerCB = syncNodeEqHeartbeatTimer;
1428
#endif
1429
  pSyncNode->heartbeatTimerCounter = 0;
4,724,209✔
1430

1431
  // init peer heartbeat timer
1432
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
75,587,344✔
1433
    if ((code = syncHbTimerInit(pSyncNode, &(pSyncNode->peerHeartbeatTimerArr[i]), (pSyncNode->replicasId)[i])) != 0) {
70,863,135!
1434
      terrno = code;
×
1435
      goto _error;
×
1436
    }
1437
  }
1438

1439
  // tools
1440
  if ((code = syncRespMgrCreate(pSyncNode, SYNC_RESP_TTL_MS, &pSyncNode->pSyncRespMgr)) != 0) {
4,724,209!
1441
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
×
1442
    goto _error;
×
1443
  }
1444
  if (pSyncNode->pSyncRespMgr == NULL) {
4,724,209!
1445
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
×
1446
    goto _error;
×
1447
  }
1448

1449
  // restore state
1450
  pSyncNode->restoreFinish = false;
4,724,209✔
1451

1452
  // snapshot senders
1453
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
75,583,379✔
1454
    SSyncSnapshotSender* pSender = NULL;
70,859,170✔
1455
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
70,858,142✔
1456
    if (pSender == NULL) return NULL;
70,859,579!
1457

1458
    pSyncNode->senders[i] = pSender;
70,859,579✔
1459
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
70,859,579✔
1460
  }
1461

1462
  // snapshot receivers
1463
  code = snapshotReceiverCreate(pSyncNode, EMPTY_RAFT_ID, &pSyncNode->pNewNodeReceiver);
4,724,209✔
1464
  if (pSyncNode->pNewNodeReceiver == NULL) return NULL;
4,724,209!
1465
  sRDebug(pSyncNode->pNewNodeReceiver, "snapshot receiver create while open sync node, data:%p",
4,724,209✔
1466
          pSyncNode->pNewNodeReceiver);
1467

1468
  // is config changing
1469
  pSyncNode->changing = false;
4,724,209✔
1470

1471
  // replication mgr
1472
  if ((code = syncNodeLogReplInit(pSyncNode)) < 0) {
4,724,209!
1473
    terrno = code;
×
1474
    sError("vgId:%d, failed to init repl mgr since %s.", pSyncNode->vgId, terrstr());
×
1475
    goto _error;
×
1476
  }
1477

1478
  // peer state
1479
  if ((code = syncNodePeerStateInit(pSyncNode)) < 0) {
4,724,209!
1480
    terrno = code;
×
1481
    sError("vgId:%d, failed to init peer stat since %s.", pSyncNode->vgId, terrstr());
×
1482
    goto _error;
×
1483
  }
1484

1485
  //
1486
  // min match index
1487
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
4,724,209✔
1488

1489
  // start in syncNodeStart
1490
  // start raft
1491

1492
  int64_t timeNow = taosGetTimestampMs();
4,724,209✔
1493
  pSyncNode->startTime = timeNow;
4,724,209✔
1494
  pSyncNode->lastReplicateTime = timeNow;
4,724,209✔
1495

1496
  // snapshotting
1497
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
4,724,209✔
1498

1499
  // init log buffer
1500
  if ((code = syncLogBufferInit(pSyncNode->pLogBuf, pSyncNode)) < 0) {
4,724,209!
1501
    terrno = code;
×
1502
    sError("vgId:%d, failed to init sync log buffer since %s", pSyncNode->vgId, terrstr());
×
1503
    goto _error;
×
1504
  }
1505

1506
  pSyncNode->isStart = true;
4,724,209✔
1507
  pSyncNode->electNum = 0;
4,724,209✔
1508
  pSyncNode->becomeLeaderNum = 0;
4,724,209✔
1509
  pSyncNode->becomeAssignedLeaderNum = 0;
4,724,209✔
1510
  pSyncNode->configChangeNum = 0;
4,724,209✔
1511
  pSyncNode->hbSlowNum = 0;
4,724,209✔
1512
  pSyncNode->hbrSlowNum = 0;
4,724,209✔
1513
  pSyncNode->tmrRoutineNum = 0;
4,724,209✔
1514

1515
  sNInfo(pSyncNode, "sync node opened, node:%p electBaseLine:%d hbBaseLine:%d heartbeatTimeout:%d", pSyncNode,
4,724,209✔
1516
         pSyncNode->electBaseLine, pSyncNode->hbBaseLine, tsHeartbeatTimeout);
1517
  return pSyncNode;
4,724,209✔
1518

1519
_error:
514✔
1520
  if (pSyncInfo->pFsm) {
514!
1521
    taosMemoryFree(pSyncInfo->pFsm);
×
1522
    pSyncInfo->pFsm = NULL;
×
1523
  }
1524
  syncNodeClose(pSyncNode);
×
1525
  pSyncNode = NULL;
×
1526
  return NULL;
×
1527
}
1528

1529
#ifdef BUILD_NO_CALL
1530
void syncNodeMaybeUpdateCommitBySnapshot(SSyncNode* pSyncNode) {
1531
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
1532
    SSnapshot snapshot = {0};
1533
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
1534
    if (snapshot.lastApplyIndex > pSyncNode->commitIndex) {
1535
      pSyncNode->commitIndex = snapshot.lastApplyIndex;
1536
    }
1537
  }
1538
}
1539
#endif
1540

1541
int32_t syncNodeRestore(SSyncNode* pSyncNode) {
4,723,991✔
1542
  int32_t code = 0;
4,723,991✔
1543
  if (pSyncNode->pLogStore == NULL) {
4,723,991!
1544
    sError("vgId:%d, log store not created", pSyncNode->vgId);
×
1545
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1546
  }
1547
  if (pSyncNode->pLogBuf == NULL) {
4,723,991!
1548
    sError("vgId:%d, ring log buffer not created", pSyncNode->vgId);
×
1549
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1550
  }
1551

1552
  (void)taosThreadMutexLock(&pSyncNode->pLogBuf->mutex);
4,723,991✔
1553
  SyncIndex lastVer = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
4,723,991✔
1554
  SyncIndex commitIndex = pSyncNode->pLogStore->syncLogCommitIndex(pSyncNode->pLogStore);
4,723,991✔
1555
  SyncIndex endIndex = pSyncNode->pLogBuf->endIndex;
4,723,991✔
1556
  (void)taosThreadMutexUnlock(&pSyncNode->pLogBuf->mutex);
4,723,991✔
1557

1558
  if (lastVer != -1 && endIndex != lastVer + 1) {
4,723,991!
1559
    code = TSDB_CODE_WAL_LOG_INCOMPLETE;
×
1560
    sWarn("vgId:%d, failed to restore sync node since %s. expected lastLogIndex:%" PRId64 ", lastVer:%" PRId64,
×
1561
          pSyncNode->vgId, terrstr(), endIndex - 1, lastVer);
1562
    // TAOS_RETURN(code);
1563
  }
1564

1565
  // if (endIndex != lastVer + 1) return TSDB_CODE_SYN_INTERNAL_ERROR;
1566
  pSyncNode->commitIndex = TMAX(pSyncNode->commitIndex, commitIndex);
4,723,991✔
1567
  sInfo("vgId:%d, restore began, and keep syncing until commitIndex:%" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
4,723,991✔
1568

1569
  if (pSyncNode->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
9,447,982!
1570
      (code = syncLogBufferCommit(pSyncNode->pLogBuf, pSyncNode, pSyncNode->commitIndex, NULL, "restore")) < 0) {
4,723,991✔
1571
    TAOS_RETURN(code);
×
1572
  }
1573

1574
  TAOS_RETURN(code);
4,723,991✔
1575
}
1576

1577
int32_t syncNodeStart(SSyncNode* pSyncNode) {
4,723,991✔
1578
  // start raft
1579
  sInfo("vgId:%d, begin to start sync node", pSyncNode->vgId);
4,723,991✔
1580
  if (pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
4,723,991✔
1581
    syncNodeBecomeLearner(pSyncNode, "first start");
110,403✔
1582
  } else {
1583
    if (pSyncNode->replicaNum == 1) {
4,613,588✔
1584
      raftStoreNextTerm(pSyncNode);
3,329,352✔
1585
      syncNodeBecomeLeader(pSyncNode, "one replica start");
3,329,343✔
1586

1587
      // Raft 3.6.2 Committing entries from previous terms
1588
      TAOS_CHECK_RETURN(syncNodeAppendNoop(pSyncNode));
3,329,352!
1589
    } else {
1590
      SRaftId id = {0};
1,284,236✔
1591
      syncNodeBecomeFollower(pSyncNode, id, "first start");
1,284,236✔
1592
    }
1593
  }
1594

1595
  int32_t ret = 0;
4,723,991✔
1596
  ret = syncNodeStartPingTimer(pSyncNode);
4,723,991✔
1597
  if (ret != 0) {
4,723,991!
1598
    sError("vgId:%d, failed to start ping timer since %s", pSyncNode->vgId, tstrerror(ret));
×
1599
  }
1600
  sInfo("vgId:%d, sync node started", pSyncNode->vgId);
4,723,991✔
1601
  return ret;
4,723,991✔
1602
}
1603

1604
#ifdef BUILD_NO_CALL
1605
int32_t syncNodeStartStandBy(SSyncNode* pSyncNode) {
1606
  // state change
1607
  int32_t code = 0;
1608
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
1609
  pSyncNode->roleTimeMs = taosGetTimestampMs();
1610
  // TODO check return value
1611
  TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1612

1613
  // reset elect timer, long enough
1614
  int32_t electMS = TIMER_MAX_MS;
1615
  code = syncNodeRestartElectTimer(pSyncNode, electMS);
1616
  if (code < 0) {
1617
    sError("vgId:%d, failed to restart elect timer since %s", pSyncNode->vgId, terrstr());
1618
    return -1;
1619
  }
1620

1621
  code = syncNodeStartPingTimer(pSyncNode);
1622
  if (code < 0) {
1623
    sError("vgId:%d, failed to start ping timer since %s", pSyncNode->vgId, terrstr());
1624
    return -1;
1625
  }
1626
  return code;
1627
}
1628
#endif
1629

1630
void syncNodePreClose(SSyncNode* pSyncNode) {
4,723,161✔
1631
  int32_t code = 0;
4,723,161✔
1632
  if (pSyncNode == NULL) {
4,723,161!
1633
    sError("failed to pre close sync node since sync node is null");
×
1634
    return;
×
1635
  }
1636
  if (pSyncNode->pFsm == NULL) {
4,723,161!
1637
    sError("failed to pre close sync node since fsm is null");
×
1638
    return;
×
1639
  }
1640
  if (pSyncNode->pFsm->FpApplyQueueItems == NULL) {
4,723,785!
1641
    sError("failed to pre close sync node since FpApplyQueueItems is null");
×
1642
    return;
×
1643
  }
1644

1645
  // stop elect timer
1646
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
4,723,991!
1647
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1648
    return;
×
1649
  }
1650

1651
  // stop heartbeat timer
1652
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
4,723,991!
1653
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
1654
    return;
×
1655
  }
1656

1657
  // stop ping timer
1658
  if ((code = syncNodeStopPingTimer(pSyncNode)) != 0) {
4,723,582!
1659
    sError("vgId:%d, failed to stop ping timer since %s", pSyncNode->vgId, tstrerror(code));
×
1660
    return;
×
1661
  }
1662

1663
  // clean rsp
1664
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
4,723,980✔
1665
}
1666

1667
void syncNodePostClose(SSyncNode* pSyncNode) {
4,161,135✔
1668
  if (pSyncNode->pNewNodeReceiver != NULL) {
4,161,135!
1669
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
4,161,135!
1670
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1671
    }
1672

1673
    sDebug("vgId:%d, snapshot receiver destroy while preclose sync node, data:%p", pSyncNode->vgId,
4,161,135✔
1674
           pSyncNode->pNewNodeReceiver);
1675
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
4,161,135✔
1676
    pSyncNode->pNewNodeReceiver = NULL;
4,161,135✔
1677
  }
1678
}
4,161,135✔
1679

1680
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }
1,050,957!
1681

1682
void syncNodeClose(SSyncNode* pSyncNode) {
4,702,741✔
1683
  int32_t code = 0;
4,702,741✔
1684
  if (pSyncNode == NULL) return;
4,702,741!
1685
  sNInfo(pSyncNode, "sync close, node:%p", pSyncNode);
4,702,741✔
1686

1687
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
4,702,741✔
1688

1689
  if ((code = syncNodeStopPingTimer(pSyncNode)) != 0) {
4,702,741!
1690
    sError("vgId:%d, failed to stop ping timer since %s", pSyncNode->vgId, tstrerror(code));
×
1691
    return;
×
1692
  }
1693
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
4,702,741!
1694
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1695
    return;
×
1696
  }
1697
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
4,702,741!
1698
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
1699
    return;
×
1700
  }
1701
  syncNodeLogReplDestroy(pSyncNode);
4,702,741✔
1702

1703
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
4,701,246✔
1704
  pSyncNode->pSyncRespMgr = NULL;
4,702,741✔
1705
  voteGrantedDestroy(pSyncNode->pVotesGranted);
4,702,741✔
1706
  pSyncNode->pVotesGranted = NULL;
4,702,723✔
1707
  votesRespondDestory(pSyncNode->pVotesRespond);
4,701,887✔
1708
  pSyncNode->pVotesRespond = NULL;
4,702,741✔
1709
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
4,702,741✔
1710
  pSyncNode->pNextIndex = NULL;
4,702,723✔
1711
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
4,702,723✔
1712
  pSyncNode->pMatchIndex = NULL;
4,702,723✔
1713
  logStoreDestory(pSyncNode->pLogStore);
4,702,741✔
1714
  pSyncNode->pLogStore = NULL;
4,702,741✔
1715
  syncLogBufferDestroy(pSyncNode->pLogBuf);
4,702,741✔
1716
  pSyncNode->pLogBuf = NULL;
4,702,741✔
1717

1718
  (void)taosThreadMutexDestroy(&pSyncNode->arbTokenMutex);
4,702,741✔
1719

1720
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
75,239,944✔
1721
    if (pSyncNode->senders[i] != NULL) {
70,537,203!
1722
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", pSyncNode->vgId, pSyncNode->senders[i]);
70,538,569✔
1723

1724
      if (snapshotSenderIsStart(pSyncNode->senders[i])) {
70,538,569!
1725
        snapshotSenderStop(pSyncNode->senders[i], false);
×
1726
      }
1727

1728
      snapshotSenderDestroy(pSyncNode->senders[i]);
70,540,461✔
1729
      pSyncNode->senders[i] = NULL;
70,536,125✔
1730
    }
1731
  }
1732

1733
  if (pSyncNode->pNewNodeReceiver != NULL) {
4,702,741✔
1734
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
562,856!
1735
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1736
    }
1737

1738
    sDebug("vgId:%d, snapshot receiver destroy while close, data:%p", pSyncNode->vgId, pSyncNode->pNewNodeReceiver);
562,856✔
1739
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
562,856✔
1740
    pSyncNode->pNewNodeReceiver = NULL;
562,856✔
1741
  }
1742

1743
  if (pSyncNode->pFsm != NULL) {
4,702,741!
1744
    taosMemoryFree(pSyncNode->pFsm);
4,702,741!
1745
  }
1746

1747
  raftStoreClose(pSyncNode);
4,702,741✔
1748

1749
  taosMemoryFree(pSyncNode);
4,702,741!
1750
}
1751

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

1754
// timer control --------------
1755
int32_t syncNodeStartPingTimer(SSyncNode* pSyncNode) {
4,723,539✔
1756
  int32_t code = 0;
4,723,539✔
1757
  if (syncIsInit()) {
4,723,539!
1758
    bool stopped = taosTmrResetPriority(pSyncNode->FpPingTimerCB, pSyncNode->pingTimerMS, (void*)pSyncNode->rid,
9,442,896✔
1759
                                        syncEnv()->pTimerManager, &pSyncNode->pPingTimer, 2);
4,723,117✔
1760
    if (stopped) {
4,723,991!
1761
      sError("vgId:%d, failed to reset ping timer, ms:%d, stopped:%d", pSyncNode->vgId, pSyncNode->pingTimerMS,
×
1762
             stopped);
1763
    }
1764
    atomic_store_64(&pSyncNode->pingTimerLogicClock, pSyncNode->pingTimerLogicClockUser);
4,723,991✔
1765
  } else {
1766
    sError("vgId:%d, start ping timer error, sync env is stop", pSyncNode->vgId);
×
1767
  }
1768
  return code;
4,723,991✔
1769
}
1770

1771
int32_t syncNodeStopPingTimer(SSyncNode* pSyncNode) {
9,426,323✔
1772
  int32_t code = 0;
9,426,323✔
1773
  (void)atomic_add_fetch_64(&pSyncNode->pingTimerLogicClockUser, 1);
9,426,323✔
1774
  bool stop = taosTmrStop(pSyncNode->pPingTimer);
9,426,732✔
1775
  sDebug("vgId:%d, stop ping timer, stop:%d", pSyncNode->vgId, stop);
9,426,732✔
1776
  pSyncNode->pPingTimer = NULL;
9,426,732✔
1777
  return code;
9,426,732✔
1778
}
1779

1780
int32_t syncNodeStartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
49,788,854✔
1781
  int32_t code = 0;
49,788,854✔
1782
  if (syncIsInit()) {
49,788,854!
1783
    pSyncNode->electTimerMS = ms;
49,788,854✔
1784

1785
    int64_t execTime = taosGetTimestampMs() + ms;
49,788,717✔
1786
    atomic_store_64(&(pSyncNode->electTimerParam.executeTime), execTime);
49,788,717✔
1787
    atomic_store_64(&(pSyncNode->electTimerParam.logicClock), pSyncNode->electTimerLogicClock);
49,788,171✔
1788
    pSyncNode->electTimerParam.pSyncNode = pSyncNode;
49,788,949✔
1789
    pSyncNode->electTimerParam.pData = NULL;
49,788,949✔
1790

1791
    bool stopped = taosTmrReset(pSyncNode->FpElectTimerCB, pSyncNode->electTimerMS, (void*)(pSyncNode->rid),
99,549,436✔
1792
                                syncEnv()->pTimerManager, &pSyncNode->pElectTimer);
49,788,018✔
1793
    if (stopped) sWarn("vgId:%d, failed to reset elect timer, ms:%d", pSyncNode->vgId, ms);
49,788,949!
1794
  } else {
1795
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
×
1796
  }
1797
  return code;
49,788,949✔
1798
}
1799

1800
int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
62,991,989✔
1801
  int32_t code = 0;
62,991,989✔
1802
  (void)atomic_add_fetch_64(&pSyncNode->electTimerLogicClock, 1);
62,991,989✔
1803
  bool stop = taosTmrStop(pSyncNode->pElectTimer);
62,994,422✔
1804
  sTrace("vgId:%d, stop elect timer, stop:%d", pSyncNode->vgId, stop);
62,990,482✔
1805
  pSyncNode->pElectTimer = NULL;
62,990,482✔
1806

1807
  return code;
62,993,429✔
1808
}
1809

1810
int32_t syncNodeRestartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
49,788,949✔
1811
  int32_t ret = 0;
49,788,949✔
1812
  TAOS_CHECK_RETURN(syncNodeStopElectTimer(pSyncNode));
49,788,949!
1813
  TAOS_CHECK_RETURN(syncNodeStartElectTimer(pSyncNode, ms));
49,788,754✔
1814
  return ret;
49,788,833✔
1815
}
1816

1817
void syncNodeResetElectTimer(SSyncNode* pSyncNode) {
49,788,365✔
1818
  int32_t code = 0;
49,788,365✔
1819
  int32_t electMS;
1820

1821
  if (pSyncNode->raftCfg.isStandBy) {
49,788,365!
1822
    electMS = TIMER_MAX_MS;
×
1823
  } else {
1824
    electMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
49,788,949✔
1825
  }
1826

1827
  if ((code = syncNodeRestartElectTimer(pSyncNode, electMS)) != 0) {
49,788,949!
1828
    sWarn("vgId:%d, failed to restart elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1829
    return;
×
1830
  };
1831

1832
  sNTrace(pSyncNode, "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine,
49,788,949!
1833
          electMS);
1834
}
1835

1836
#ifdef BUILD_NO_CALL
1837
static int32_t syncNodeDoStartHeartbeatTimer(SSyncNode* pSyncNode) {
1838
  int32_t code = 0;
1839
  if (syncIsInit()) {
1840
    TAOS_CHECK_RETURN(taosTmrReset(pSyncNode->FpHeartbeatTimerCB, pSyncNode->heartbeatTimerMS, (void*)pSyncNode->rid,
1841
                                   syncEnv()->pTimerManager, &pSyncNode->pHeartbeatTimer));
1842
    atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, pSyncNode->heartbeatTimerLogicClockUser);
1843
  } else {
1844
    sError("vgId:%d, start heartbeat timer error, sync env is stop", pSyncNode->vgId);
1845
  }
1846

1847
  sNTrace(pSyncNode, "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
1848
  return code;
1849
}
1850
#endif
1851

1852
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
4,223,365✔
1853
  int32_t ret = 0;
4,223,365✔
1854

1855
#if 0
1856
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
1857
  ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
1858
#endif
1859

1860
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
5,276,266✔
1861
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
1,052,901✔
1862
    if (pSyncTimer != NULL) {
1,052,901!
1863
      TAOS_CHECK_RETURN(syncHbTimerStart(pSyncNode, pSyncTimer));
1,052,901!
1864
    }
1865
  }
1866

1867
  return ret;
4,225,480✔
1868
}
1869

1870
int32_t syncNodeSetHeartbeatTimerMs(SSyncNode* pSyncNode, int32_t ms) {
×
1871
  int32_t code = 0;
×
1872

1873
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
×
1874
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
×
1875
    if (pSyncTimer != NULL) {
×
1876
      syncHBSetTimerMS(pSyncTimer, ms);
×
1877
    }
1878
  }
1879

1880
  return code;
×
1881
}
1882

1883
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
12,077,342✔
1884
  int32_t code = 0;
12,077,342✔
1885

1886
#if 0
1887
  TAOS_CHECK_RETURN(atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1));
1888
  bool stop = taosTmrStop(pSyncNode->pHeartbeatTimer);
1889
  sDebug("vgId:%d, stop heartbeat timer, stop:%d", pSyncNode->vgId, stop);
1890
  pSyncNode->pHeartbeatTimer = NULL;
1891
#endif
1892

1893
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
23,131,426✔
1894
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
11,054,084✔
1895
    if (pSyncTimer != NULL) {
11,052,418!
1896
      TAOS_CHECK_RETURN(syncHbTimerStop(pSyncNode, pSyncTimer));
11,052,418!
1897
    }
1898
  }
1899

1900
  return code;
12,079,100✔
1901
}
1902

1903
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode, int32_t heartbeatInterval) {
×
1904
  int32_t code = 0;
×
1905
  sInfo("vgId:%d, sync Node Restart HeartbeatTimer, state=%d", pSyncNode->vgId, pSyncNode->state);
×
1906
  TAOS_CHECK_RETURN(syncNodeSetHeartbeatTimerMs(pSyncNode, heartbeatInterval));
×
1907
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
×
1908
    TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
×
1909
    TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
×
1910
  }
1911

1912
  return 0;
×
1913
}
1914

1915
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pNode, SRpcMsg* pMsg) {
107,304,850✔
1916
  SEpSet* epSet = NULL;
107,304,850✔
1917
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
158,074,441✔
1918
    if (destRaftId->addr == pNode->peersId[i].addr) {
158,041,427✔
1919
      epSet = &pNode->peersEpset[i];
107,274,238✔
1920
      break;
107,274,468✔
1921
    }
1922
  }
1923

1924
  int32_t code = -1;
107,306,435✔
1925
  if (pNode->syncSendMSg != NULL && epSet != NULL) {
107,306,435✔
1926
    syncUtilMsgHtoN(pMsg->pCont);
107,274,810✔
1927
    pMsg->info.noResp = 1;
107,269,345✔
1928
    code = pNode->syncSendMSg(epSet, pMsg);
107,269,555✔
1929
  }
1930

1931
  if (code < 0) {
107,307,667✔
1932
    sError("vgId:%d, failed to send sync msg since %s. epset:%p dnode:%d addr:0x%" PRIx64, pNode->vgId, tstrerror(code),
32,192!
1933
           epSet, DID(destRaftId), destRaftId->addr);
1934
    rpcFreeCont(pMsg->pCont);
32,192✔
1935
  }
1936

1937
  TAOS_RETURN(code);
107,307,667✔
1938
}
1939

1940
inline bool syncNodeInConfig(SSyncNode* pNode, const SSyncCfg* pCfg) {
639,855✔
1941
  bool b1 = false;
639,855✔
1942
  bool b2 = false;
639,855✔
1943

1944
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
760,071!
1945
    if (strcmp(pCfg->nodeInfo[i].nodeFqdn, pNode->myNodeInfo.nodeFqdn) == 0 &&
760,071!
1946
        pCfg->nodeInfo[i].nodePort == pNode->myNodeInfo.nodePort) {
760,071✔
1947
      b1 = true;
639,855✔
1948
      break;
639,855✔
1949
    }
1950
  }
1951

1952
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
760,071!
1953
    SRaftId raftId = {
760,071✔
1954
        .addr = SYNC_ADDR(&pCfg->nodeInfo[i]),
760,071✔
1955
        .vgId = pNode->vgId,
760,071✔
1956
    };
1957

1958
    if (syncUtilSameId(&raftId, &pNode->myRaftId)) {
760,071✔
1959
      b2 = true;
639,855✔
1960
      break;
639,855✔
1961
    }
1962
  }
1963

1964
  if (b1 != b2) {
639,855!
1965
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1966
    return false;
×
1967
  }
1968
  return b1;
639,855✔
1969
}
1970

1971
static bool syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg) {
1,260,761✔
1972
  if (pOldCfg->totalReplicaNum != pNewCfg->totalReplicaNum) return true;
1,260,761✔
1973
  if (pOldCfg->myIndex != pNewCfg->myIndex) return true;
739,813✔
1974
  for (int32_t i = 0; i < pOldCfg->totalReplicaNum; ++i) {
1,917,056✔
1975
    const SNodeInfo* pOldInfo = &pOldCfg->nodeInfo[i];
1,494,989✔
1976
    const SNodeInfo* pNewInfo = &pNewCfg->nodeInfo[i];
1,494,989✔
1977
    if (strcmp(pOldInfo->nodeFqdn, pNewInfo->nodeFqdn) != 0) return true;
1,494,989!
1978
    if (pOldInfo->nodePort != pNewInfo->nodePort) return true;
1,494,989!
1979
    if (pOldInfo->nodeRole != pNewInfo->nodeRole) return true;
1,494,989✔
1980
  }
1981

1982
  return false;
422,067✔
1983
}
1984

1985
int32_t syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncIndex lastConfigChangeIndex) {
494,663✔
1986
  int32_t  code = 0;
494,663✔
1987
  SSyncCfg oldConfig = pSyncNode->raftCfg.cfg;
494,663✔
1988
  if (!syncIsConfigChanged(&oldConfig, pNewConfig)) {
494,663✔
1989
    sInfo("vgId:1, sync not reconfig since not changed");
422,067✔
1990
    return 0;
422,067✔
1991
  }
1992

1993
  pSyncNode->raftCfg.cfg = *pNewConfig;
72,596✔
1994
  pSyncNode->raftCfg.lastConfigIndex = lastConfigChangeIndex;
72,596✔
1995

1996
  pSyncNode->configChangeNum++;
72,596✔
1997

1998
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
72,596✔
1999
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
72,596✔
2000

2001
  bool isDrop = false;
72,596✔
2002
  bool isAdd = false;
72,596✔
2003

2004
  if (IamInOld && !IamInNew) {
72,596!
2005
    isDrop = true;
×
2006
  } else {
2007
    isDrop = false;
72,596✔
2008
  }
2009

2010
  if (!IamInOld && IamInNew) {
72,596!
2011
    isAdd = true;
×
2012
  } else {
2013
    isAdd = false;
72,596✔
2014
  }
2015

2016
  // log begin config change
2017
  sNInfo(pSyncNode, "begin do config change, from %d to %d, from %" PRId64 " to %" PRId64 ", replicas:%d",
72,596!
2018
         pSyncNode->vgId, oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum, oldConfig.lastIndex,
2019
         pNewConfig->lastIndex);
2020

2021
  if (IamInNew) {
72,596!
2022
    pSyncNode->raftCfg.isStandBy = 0;  // change isStandBy to normal
72,596✔
2023
  }
2024
  if (isDrop) {
72,596!
2025
    pSyncNode->raftCfg.isStandBy = 1;  // set standby
×
2026
  }
2027

2028
  // add last config index
2029
  SRaftCfg* pCfg = &pSyncNode->raftCfg;
72,596✔
2030
  if (pCfg->configIndexCount >= MAX_CONFIG_INDEX_COUNT) {
72,596!
2031
    sNError(pSyncNode, "failed to add cfg index:%d since out of range", pCfg->configIndexCount);
×
2032
    terrno = TSDB_CODE_OUT_OF_RANGE;
×
2033
    return -1;
×
2034
  }
2035

2036
  pCfg->configIndexArr[pCfg->configIndexCount] = lastConfigChangeIndex;
72,596✔
2037
  pCfg->configIndexCount++;
72,596✔
2038

2039
  if (IamInNew) {
72,596!
2040
    //-----------------------------------------
2041
    int32_t ret = 0;
72,596✔
2042

2043
    // save snapshot senders
2044
    SRaftId oldReplicasId[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
72,596✔
2045
    memcpy(oldReplicasId, pSyncNode->replicasId, sizeof(oldReplicasId));
72,596!
2046
    SSyncSnapshotSender* oldSenders[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
72,596✔
2047
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
1,161,536✔
2048
      oldSenders[i] = pSyncNode->senders[i];
1,088,940✔
2049
      sSTrace(oldSenders[i], "snapshot sender save old");
1,088,940!
2050
    }
2051

2052
    // init internal
2053
    pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
72,596✔
2054
    if (syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId) == false) return terrno;
72,596!
2055

2056
    // init peersNum, peers, peersId
2057
    pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
72,596✔
2058
    int32_t j = 0;
72,596✔
2059
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
262,126✔
2060
      if (i != pSyncNode->raftCfg.cfg.myIndex) {
189,530✔
2061
        pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
116,934✔
2062
        syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
116,934✔
2063
        j++;
116,934✔
2064
      }
2065
    }
2066
    for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
189,530✔
2067
      if (syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]) == false)
116,934!
2068
        return terrno;
×
2069
    }
2070

2071
    // init replicaNum, replicasId
2072
    pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
72,596✔
2073
    pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
72,596✔
2074
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
262,126✔
2075
      if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
189,530!
2076
          false)
2077
        return terrno;
×
2078
    }
2079

2080
    // update quorum first
2081
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
72,596✔
2082

2083
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
72,596✔
2084
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
72,596✔
2085
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
72,596✔
2086
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
72,596✔
2087

2088
    // reset snapshot senders
2089

2090
    // clear new
2091
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
1,161,536✔
2092
      pSyncNode->senders[i] = NULL;
1,088,940✔
2093
    }
2094

2095
    // reset new
2096
    for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
262,126✔
2097
      // reset sender
2098
      bool reset = false;
189,530✔
2099
      for (int32_t j = 0; j < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++j) {
806,998✔
2100
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
773,193!
2101
          sNTrace(pSyncNode, "snapshot sender reset for:%" PRId64 ", newIndex:%d, dnode:%d, %p",
155,725!
2102
                  (pSyncNode->replicasId)[i].addr, i, DID(&pSyncNode->replicasId[i]), oldSenders[j]);
2103

2104
          pSyncNode->senders[i] = oldSenders[j];
155,725✔
2105
          oldSenders[j] = NULL;
155,725✔
2106
          reset = true;
155,725✔
2107

2108
          // reset replicaIndex
2109
          int32_t oldreplicaIndex = pSyncNode->senders[i]->replicaIndex;
155,725✔
2110
          pSyncNode->senders[i]->replicaIndex = i;
155,725✔
2111

2112
          sNTrace(pSyncNode, "snapshot sender udpate replicaIndex from %d to %d, dnode:%d, %p, reset:%d",
155,725!
2113
                  oldreplicaIndex, i, DID(&pSyncNode->replicasId[i]), pSyncNode->senders[i], reset);
2114

2115
          break;
155,725✔
2116
        }
2117
      }
2118
    }
2119

2120
    // create new
2121
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
1,161,536✔
2122
      if (pSyncNode->senders[i] == NULL) {
1,088,940✔
2123
        TAOS_CHECK_RETURN(snapshotSenderCreate(pSyncNode, i, &pSyncNode->senders[i]));
933,215!
2124
        if (pSyncNode->senders[i] == NULL) {
933,215!
2125
          // will be created later while send snapshot
2126
          sSError(pSyncNode->senders[i], "snapshot sender create failed while reconfig");
×
2127
        } else {
2128
          sSDebug(pSyncNode->senders[i], "snapshot sender create while reconfig, data:%p", pSyncNode->senders[i]);
933,215!
2129
        }
2130
      } else {
2131
        sSDebug(pSyncNode->senders[i], "snapshot sender already exist, data:%p", pSyncNode->senders[i]);
155,725!
2132
      }
2133
    }
2134

2135
    // free old
2136
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
1,161,536✔
2137
      if (oldSenders[i] != NULL) {
1,088,940✔
2138
        sSDebug(oldSenders[i], "snapshot sender destroy old, data:%p replica-index:%d", oldSenders[i], i);
933,215!
2139
        snapshotSenderDestroy(oldSenders[i]);
933,215✔
2140
        oldSenders[i] = NULL;
933,215✔
2141
      }
2142
    }
2143

2144
    // persist cfg
2145
    TAOS_CHECK_RETURN(syncWriteCfgFile(pSyncNode));
72,596!
2146
  } else {
2147
    // persist cfg
2148
    TAOS_CHECK_RETURN(syncWriteCfgFile(pSyncNode));
×
2149
    sNInfo(pSyncNode, "do not config change from %d to %d", oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum);
×
2150
  }
2151

2152
_END:
×
2153
  // log end config change
2154
  sNInfo(pSyncNode, "end do config change, from %d to %d", oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum);
72,596!
2155
  return 0;
72,596✔
2156
}
2157

2158
// raft state change --------------
2159
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
109,467✔
2160
  if (term > raftStoreGetTerm(pSyncNode)) {
109,467!
2161
    raftStoreSetTerm(pSyncNode, term);
×
2162
  }
2163
}
109,467✔
2164

2165
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm, SRaftId id, char* strFrom) {
28,456,118✔
2166
  SyncTerm currentTerm = raftStoreGetTerm(pSyncNode);
28,456,118✔
2167
  if (currentTerm > newTerm) {
28,456,118!
2168
    sNTrace(pSyncNode, "step down, ignore, new-term:%" PRId64 ", current-term:%" PRId64, newTerm, currentTerm);
×
2169
    return;
×
2170
  }
2171

2172
  do {
2173
    sNTrace(pSyncNode, "step down, new-term:%" PRId64 ", current-term:%" PRId64, newTerm, currentTerm);
28,456,118!
2174
  } while (0);
2175

2176
  if (pSyncNode->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
28,456,118✔
2177
    (void)taosThreadMutexLock(&pSyncNode->arbTokenMutex);
465✔
2178
    syncUtilGenerateArbToken(pSyncNode->myNodeInfo.nodeId, pSyncNode->vgId, pSyncNode->arbToken);
465✔
2179
    sInfo("vgId:%d, generate arb token, will step down from assigned leader, new arbToken:%s", pSyncNode->vgId,
465!
2180
          pSyncNode->arbToken);
2181
    (void)taosThreadMutexUnlock(&pSyncNode->arbTokenMutex);
465✔
2182
  }
2183

2184
  if (currentTerm < newTerm) {
28,456,095✔
2185
    raftStoreSetTerm(pSyncNode, newTerm);
909,562✔
2186
    char tmpBuf[64];
909,410✔
2187
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64 " from %" PRId64 ", since %s", newTerm,
909,562!
2188
             currentTerm, strFrom);
2189
    syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
909,562✔
2190
    raftStoreClearVote(pSyncNode);
909,562✔
2191
  } else {
2192
    if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
27,546,533✔
2193
      char tmpBuf[64];
5,487✔
2194
      snprintf(tmpBuf, sizeof(tmpBuf), "step down, with same term to %" PRId64 " from %" PRId64 ", since %s", newTerm, 
5,487!
2195
               currentTerm, strFrom);
2196
      syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
5,487✔
2197
    }
2198
  }
2199
}
2200

2201
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }
2,205,697✔
2202

2203
void syncNodeBecomeFollower(SSyncNode* pSyncNode, SRaftId leaderId, const char* debugStr) {
2,204,820✔
2204
  int32_t code = 0;  // maybe clear leader cache
2,204,820✔
2205
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
2,204,820✔
2206
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
11,043✔
2207
    pSyncNode->leaderCacheEp.port = 0;
11,043✔
2208
    pSyncNode->leaderCacheEp.fqdn[0] = '\0';
11,043✔
2209
  }
2210

2211
  pSyncNode->hbSlowNum = 0;
2,206,196✔
2212

2213
  pSyncNode->leaderCache = leaderId;  // state change
2,206,196✔
2214

2215
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
7,124,392✔
2216
    if (syncUtilSameId(&pSyncNode->replicasId[i], &leaderId)) {
5,833,245✔
2217
      pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[i].nodePort;
915,049✔
2218
      strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
915,049!
2219
      break;
915,049✔
2220
    }
2221
  }
2222
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
2,206,196✔
2223
  pSyncNode->roleTimeMs = taosGetTimestampMs();
2,206,196✔
2224
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
2,206,196!
2225
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2226
    return;
×
2227
  }
2228

2229
  // trace log
2230
  sNTrace(pSyncNode, "become follower %s", debugStr);
2,206,196!
2231

2232
  // send rsp to client
2233
  syncNodeLeaderChangeRsp(pSyncNode);
2,206,196✔
2234

2235
  // call back
2236
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
2,206,196!
2237
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
2,204,915✔
2238
  }
2239

2240
  // min match index
2241
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
2,207,436✔
2242

2243
  // reset log buffer
2244
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
2,206,196!
2245
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2246
    return;
×
2247
  }
2248

2249
  // reset elect timer
2250
  syncNodeResetElectTimer(pSyncNode);
2,206,196✔
2251

2252
  sInfo("vgId:%d, become follower. %s", pSyncNode->vgId, debugStr);
2,206,196!
2253
}
2254

2255
void syncNodeBecomeLearner(SSyncNode* pSyncNode, const char* debugStr) {
110,403✔
2256
  pSyncNode->hbSlowNum = 0;
110,403✔
2257

2258
  // state change
2259
  pSyncNode->state = TAOS_SYNC_STATE_LEARNER;
110,403✔
2260
  pSyncNode->roleTimeMs = taosGetTimestampMs();
110,403✔
2261

2262
  // trace log
2263
  sNTrace(pSyncNode, "become learner %s", debugStr);
110,403!
2264

2265
  // call back
2266
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLearnerCb != NULL) {
110,403!
2267
    pSyncNode->pFsm->FpBecomeLearnerCb(pSyncNode->pFsm);
110,403✔
2268
  }
2269

2270
  // min match index
2271
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
110,403✔
2272

2273
  // reset log buffer
2274
  int32_t code = 0;
110,403✔
2275
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
110,403!
2276
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2277
    return;
×
2278
  };
2279
}
2280

2281
// TLA+ Spec
2282
// \* Candidate i transitions to leader.
2283
// BecomeLeader(i) ==
2284
//     /\ state[i] = Candidate
2285
//     /\ votesGranted[i] \in Quorum
2286
//     /\ state'      = [state EXCEPT ![i] = Leader]
2287
//     /\ nextIndex'  = [nextIndex EXCEPT ![i] =
2288
//                          [j \in Server |-> Len(log[i]) + 1]]
2289
//     /\ matchIndex' = [matchIndex EXCEPT ![i] =
2290
//                          [j \in Server |-> 0]]
2291
//     /\ elections'  = elections \cup
2292
//                          {[eterm     |-> currentTerm[i],
2293
//                            eleader   |-> i,
2294
//                            elog      |-> log[i],
2295
//                            evotes    |-> votesGranted[i],
2296
//                            evoterLog |-> voterLog[i]]}
2297
//     /\ UNCHANGED <<messages, currentTerm, votedFor, candidateVars, logVars>>
2298
//
2299
void syncNodeBecomeLeader(SSyncNode* pSyncNode, const char* debugStr) {
3,778,206✔
2300
  int32_t code = 0;
3,778,206✔
2301
  pSyncNode->becomeLeaderNum++;
3,778,206✔
2302
  pSyncNode->hbrSlowNum = 0;
3,779,017✔
2303

2304
  // reset restoreFinish
2305
  pSyncNode->restoreFinish = false;
3,779,017✔
2306

2307
  // state change
2308
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
3,777,440✔
2309
  pSyncNode->roleTimeMs = taosGetTimestampMs();
3,779,017✔
2310

2311
  // set leader cache
2312
  pSyncNode->leaderCache = pSyncNode->myRaftId;
3,777,861✔
2313
  strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeFqdn,
3,778,402!
2314
          TSDB_FQDN_LEN);
2315
  pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodePort;
3,777,951✔
2316

2317
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
8,451,269✔
2318
    SyncIndex lastIndex;
4,673,132✔
2319
    SyncTerm  lastTerm;
4,673,132✔
2320
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
4,676,394✔
2321
    if (code != 0) {
4,674,690✔
2322
      sError("vgId:%d, failed to become leader since %s", pSyncNode->vgId, tstrerror(code));
9!
2323
      return;
×
2324
    }
2325
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
4,674,681✔
2326
  }
2327

2328
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
8,448,238✔
2329
    // maybe overwrite myself, no harm
2330
    // just do it!
2331
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
4,675,376✔
2332
  }
2333

2334
  // init peer mgr
2335
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
3,776,140!
2336
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2337
    return;
×
2338
  }
2339

2340
#if 0
2341
  // update sender private term
2342
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
2343
  if (pMySender != NULL) {
2344
    for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
2345
      if (pSyncNode->senders[i]->privateTerm > pMySender->privateTerm) {
2346
        pMySender->privateTerm = pSyncNode->senders[i]->privateTerm;
2347
      }
2348
    }
2349
    (pMySender->privateTerm) += 100;
2350
  }
2351
#endif
2352

2353
  // close receiver
2354
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
3,778,440!
2355
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2356
  }
2357

2358
  // stop elect timer
2359
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
3,777,742!
2360
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
2361
    return;
×
2362
  }
2363

2364
  // start heartbeat timer
2365
  if ((code = syncNodeStartHeartbeatTimer(pSyncNode)) != 0) {
3,776,449!
2366
    sError("vgId:%d, failed to start heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2367
    return;
×
2368
  }
2369

2370
  // send heartbeat right now
2371
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
3,778,423!
2372
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2373
    return;
×
2374
  }
2375

2376
  // call back
2377
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
3,776,320!
2378
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
3,776,521✔
2379
  }
2380

2381
  // min match index
2382
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
3,773,514✔
2383

2384
  // reset log buffer
2385
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
3,779,026!
2386
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2387
    return;
×
2388
  }
2389

2390
  // trace log
2391
  sNInfo(pSyncNode, "node become leader, %s", debugStr);
3,777,691✔
2392
}
2393

2394
void syncNodeBecomeAssignedLeader(SSyncNode* pSyncNode) {
935✔
2395
  int32_t code = 0;
935✔
2396
  pSyncNode->becomeAssignedLeaderNum++;
935✔
2397
  pSyncNode->hbrSlowNum = 0;
935✔
2398

2399
  // reset restoreFinish
2400
  // pSyncNode->restoreFinish = false;
2401

2402
  // state change
2403
  pSyncNode->state = TAOS_SYNC_STATE_ASSIGNED_LEADER;
935✔
2404
  pSyncNode->roleTimeMs = taosGetTimestampMs();
935✔
2405

2406
  // set leader cache
2407
  pSyncNode->leaderCache = pSyncNode->myRaftId;
935✔
2408

2409
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
2,805✔
2410
    SyncIndex lastIndex;
1,870✔
2411
    SyncTerm  lastTerm;
1,870✔
2412
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
1,870✔
2413
    if (code != 0) {
1,870!
2414
      sError("vgId:%d, failed to become assigned leader since %s", pSyncNode->vgId, tstrerror(code));
×
2415
      return;
×
2416
    }
2417
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
1,870✔
2418
  }
2419

2420
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
2,805✔
2421
    // maybe overwrite myself, no harm
2422
    // just do it!
2423
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
1,870✔
2424
  }
2425

2426
  // init peer mgr
2427
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
935!
2428
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2429
    return;
×
2430
  }
2431

2432
  // close receiver
2433
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
935!
2434
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2435
  }
2436

2437
  // stop elect timer
2438
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
935!
2439
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
2440
    return;
×
2441
  }
2442

2443
  // start heartbeat timer
2444
  if ((code = syncNodeStartHeartbeatTimer(pSyncNode)) != 0) {
935!
2445
    sError("vgId:%d, failed to start heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2446
    return;
×
2447
  }
2448

2449
  // send heartbeat right now
2450
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
935!
2451
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2452
    return;
×
2453
  }
2454

2455
  // call back
2456
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeAssignedLeaderCb != NULL) {
935!
2457
    pSyncNode->pFsm->FpBecomeAssignedLeaderCb(pSyncNode->pFsm);
935✔
2458
  }
2459

2460
  // min match index
2461
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
935✔
2462

2463
  // reset log buffer
2464
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
935!
2465
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2466
    return;
×
2467
  }
2468

2469
  // trace log
2470
  sNInfo(pSyncNode, "become assigned leader");
935!
2471
}
2472

2473
void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
449,674✔
2474
  if (pSyncNode->state != TAOS_SYNC_STATE_CANDIDATE) {
449,674!
2475
    sError("vgId:%d, failed leader from candidate since node state is wrong:%d", pSyncNode->vgId, pSyncNode->state);
×
2476
    return;
×
2477
  }
2478
  bool granted = voteGrantedMajority(pSyncNode->pVotesGranted);
449,674✔
2479
  if (!granted) {
449,674!
2480
    sError("vgId:%d, not granted by majority.", pSyncNode->vgId);
×
2481
    return;
×
2482
  }
2483
  syncNodeBecomeLeader(pSyncNode, "from candidate to leader");
449,674✔
2484

2485
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
449,674!
2486

2487
  int32_t ret = syncNodeAppendNoop(pSyncNode);
449,674✔
2488
  if (ret < 0) {
449,674!
2489
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, terrstr());
×
2490
  }
2491

2492
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
449,674✔
2493

2494
  sInfo("vgId:%d, become leader. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64, pSyncNode->vgId,
449,674!
2495
        raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2496
}
2497

2498
bool syncNodeIsMnode(SSyncNode* pSyncNode) { return (pSyncNode->vgId == 1); }
56,559,915✔
2499

2500
int32_t syncSetElectBaseline(int64_t rid, int32_t ms){
41,473✔
2501
  int32_t code = 0;
41,473✔
2502
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
41,473✔
2503
  if (pSyncNode == NULL) {
41,473!
2504
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
2505
    if (terrno != 0) code = terrno;
×
2506
    sError("failed to acquire rid:%" PRId64 " of tsNodeReftId for pSyncNode", rid);
×
2507
    TAOS_RETURN(code);
×
2508
  }
2509
  pSyncNode->electBaseLine = ms;
41,473✔
2510
  syncNodeResetElectTimer(pSyncNode);
41,473✔
2511
  return code;
41,473✔
2512
}
2513

2514
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
8,502,689✔
2515
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
135,988,548✔
2516
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
127,484,892✔
2517
    pSyncNode->peerStates[i].lastSendTime = 0;
127,486,886✔
2518
  }
2519

2520
  return 0;
8,503,656✔
2521
}
2522

2523
void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
496,320✔
2524
  if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
496,320!
2525
    sError("vgId:%d, failed candidate from follower since node state is wrong:%d", pSyncNode->vgId, pSyncNode->state);
×
2526
    return;
×
2527
  }
2528
  pSyncNode->state = TAOS_SYNC_STATE_CANDIDATE;
496,320✔
2529
  pSyncNode->roleTimeMs = taosGetTimestampMs();
496,320✔
2530
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
496,320✔
2531
  sInfo("vgId:%d, become candidate from follower. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64,
496,320!
2532
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2533

2534
  sNTrace(pSyncNode, "follower to candidate");
496,320!
2535
}
2536

2537
int32_t syncNodeAssignedLeader2Leader(SSyncNode* pSyncNode) {
×
2538
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) return TSDB_CODE_SYN_INTERNAL_ERROR;
×
2539
  syncNodeBecomeLeader(pSyncNode, "assigned leader to leader");
×
2540

2541
  sNTrace(pSyncNode, "assigned leader to leader");
×
2542

2543
  int32_t ret = syncNodeAppendNoop(pSyncNode);
×
2544
  if (ret < 0) {
×
2545
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, tstrerror(ret));
×
2546
  }
2547

2548
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
×
2549
  sInfo("vgId:%d, become leader from assigned leader. term:%" PRId64 ", commit index:%" PRId64
×
2550
        "assigned commit index:%" PRId64 ", last index:%" PRId64,
2551
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, pSyncNode->assignedCommitIndex,
2552
        lastIndex);
2553
  return 0;
×
2554
}
2555

2556
// just called by syncNodeVoteForSelf
2557
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
522,080✔
2558
  SyncTerm storeTerm = raftStoreGetTerm(pSyncNode);
522,080✔
2559
  if (term != storeTerm) {
522,080!
2560
    sError("vgId:%d, failed to vote for term, term:%" PRId64 ", storeTerm:%" PRId64, pSyncNode->vgId, term, storeTerm);
×
2561
    return;
×
2562
  }
2563
  sTrace("vgId:%d, begin hasVoted", pSyncNode->vgId);
522,080!
2564
  bool voted = raftStoreHasVoted(pSyncNode);
522,080✔
2565
  if (voted) {
522,080!
2566
    sError("vgId:%d, failed to vote for term since not voted", pSyncNode->vgId);
×
2567
    return;
×
2568
  }
2569

2570
  raftStoreVote(pSyncNode, pRaftId);
522,080✔
2571
}
2572

2573
// simulate get vote from outside
2574
void syncNodeVoteForSelf(SSyncNode* pSyncNode, SyncTerm currentTerm) {
522,080✔
2575
  syncNodeVoteForTerm(pSyncNode, currentTerm, &pSyncNode->myRaftId);
522,080✔
2576

2577
  SRpcMsg rpcMsg = {0};
522,080✔
2578
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
522,080✔
2579
  if (ret != 0) return;
522,080!
2580

2581
  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
522,080✔
2582
  pMsg->srcId = pSyncNode->myRaftId;
522,080✔
2583
  pMsg->destId = pSyncNode->myRaftId;
522,080✔
2584
  pMsg->term = currentTerm;
522,080✔
2585
  pMsg->voteGranted = true;
522,080✔
2586

2587
  voteGrantedVote(pSyncNode->pVotesGranted, pMsg);
522,080✔
2588
  votesRespondAdd(pSyncNode->pVotesRespond, pMsg);
522,080✔
2589
  rpcFreeCont(rpcMsg.pCont);
522,080✔
2590
}
2591

2592
// return if has a snapshot
2593
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
6,589,356✔
2594
  bool      ret = false;
6,589,356✔
2595
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
6,589,356✔
2596
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
6,590,798!
2597
    // TODO check return value
2598
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
6,591,393✔
2599
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
6,592,343✔
2600
      ret = true;
980,359✔
2601
    }
2602
  }
2603
  return ret;
6,592,227✔
2604
}
2605

2606
// return max(logLastIndex, snapshotLastIndex)
2607
// if no snapshot and log, return -1
2608
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
6,606,005✔
2609
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
6,606,005✔
2610
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
6,606,121✔
2611
    // TODO check return value
2612
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
6,606,733✔
2613
  }
2614
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
6,607,406✔
2615

2616
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
6,606,015✔
2617
  return lastIndex;
6,606,015✔
2618
}
2619

2620
// return the last term of snapshot and log
2621
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
2622
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
6,591,636✔
2623
  SyncTerm lastTerm = 0;
6,591,636✔
2624
  if (syncNodeHasSnapshot(pSyncNode)) {
6,591,636✔
2625
    // has snapshot
2626
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
980,359✔
2627
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
980,359!
2628
      // TODO check return value
2629
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
980,359✔
2630
    }
2631

2632
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
980,359✔
2633
    if (logLastIndex > snapshot.lastApplyIndex) {
980,359✔
2634
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
596,668✔
2635
    } else {
2636
      lastTerm = snapshot.lastApplyTerm;
383,691✔
2637
    }
2638

2639
  } else {
2640
    // no snapshot
2641
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
5,611,818✔
2642
  }
2643

2644
  return lastTerm;
6,589,895✔
2645
}
2646

2647
// get last index and term along with snapshot
2648
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
5,697,531✔
2649
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
5,697,531✔
2650
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
5,696,563✔
2651
  return 0;
5,696,850✔
2652
}
2653

2654
#ifdef BUILD_NO_CALL
2655
// return append-entries first try index
2656
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
2657
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
2658
  return syncStartIndex;
2659
}
2660

2661
// if index > 0, return index - 1
2662
// else, return -1
2663
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
2664
  SyncIndex preIndex = index - 1;
2665
  if (preIndex < SYNC_INDEX_INVALID) {
2666
    preIndex = SYNC_INDEX_INVALID;
2667
  }
2668

2669
  return preIndex;
2670
}
2671

2672
// if index < 0, return SYNC_TERM_INVALID
2673
// if index == 0, return 0
2674
// if index > 0, return preTerm
2675
// if error, return SYNC_TERM_INVALID
2676
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
2677
  if (index < SYNC_INDEX_BEGIN) {
2678
    return SYNC_TERM_INVALID;
2679
  }
2680

2681
  if (index == SYNC_INDEX_BEGIN) {
2682
    return 0;
2683
  }
2684

2685
  SyncTerm  preTerm = 0;
2686
  SyncIndex preIndex = index - 1;
2687

2688
  SSyncRaftEntry* pPreEntry = NULL;
2689
  SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
2690
  LRUHandle*      h = taosLRUCacheLookup(pCache, &preIndex, sizeof(preIndex));
2691
  int32_t         code = 0;
2692
  if (h) {
2693
    pPreEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2694
    code = 0;
2695

2696
    pSyncNode->pLogStore->cacheHit++;
2697
    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);
2698

2699
  } else {
2700
    pSyncNode->pLogStore->cacheMiss++;
2701
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);
2702

2703
    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
2704
  }
2705

2706
  SSnapshot snapshot = {.data = NULL,
2707
                        .lastApplyIndex = SYNC_INDEX_INVALID,
2708
                        .lastApplyTerm = SYNC_TERM_INVALID,
2709
                        .lastConfigIndex = SYNC_INDEX_INVALID};
2710

2711
  if (code == 0) {
2712
    if (pPreEntry == NULL) return -1;
2713
    preTerm = pPreEntry->term;
2714

2715
    if (h) {
2716
      taosLRUCacheRelease(pCache, h, false);
2717
    } else {
2718
      syncEntryDestroy(pPreEntry);
2719
    }
2720

2721
    return preTerm;
2722
  } else {
2723
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2724
      // TODO check return value
2725
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2726
      if (snapshot.lastApplyIndex == preIndex) {
2727
        return snapshot.lastApplyTerm;
2728
      }
2729
    }
2730
  }
2731

2732
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
2733
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
2734
  return SYNC_TERM_INVALID;
2735
}
2736

2737
// get pre index and term of "index"
2738
int32_t syncNodeGetPreIndexTerm(SSyncNode* pSyncNode, SyncIndex index, SyncIndex* pPreIndex, SyncTerm* pPreTerm) {
2739
  *pPreIndex = syncNodeGetPreIndex(pSyncNode, index);
2740
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
2741
  return 0;
2742
}
2743
#endif
2744

2745
static void syncNodeEqPingTimer(void* param, void* tmrId) {
24,546,892✔
2746
  if (!syncIsInit()) return;
24,546,892!
2747

2748
  int64_t    rid = (int64_t)param;
24,546,892✔
2749
  SSyncNode* pNode = syncNodeAcquire(rid);
24,546,892✔
2750

2751
  if (pNode == NULL) return;
24,546,892!
2752

2753
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
24,546,892!
2754
    SRpcMsg rpcMsg = {0};
24,546,892✔
2755
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
24,546,892✔
2756
                                    pNode->pingTimerMS, pNode);
2757
    if (code != 0) {
24,546,892!
2758
      sError("failed to build ping msg");
×
2759
      rpcFreeCont(rpcMsg.pCont);
×
2760
      goto _out;
×
2761
    }
2762

2763
    // sTrace("enqueue ping msg");
2764
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
24,546,892✔
2765
    if (code != 0) {
24,546,892✔
2766
      sError("failed to sync enqueue ping msg since %s", terrstr());
2,376!
2767
      rpcFreeCont(rpcMsg.pCont);
2,376✔
2768
      goto _out;
2,376✔
2769
    }
2770

2771
  _out:
24,546,892✔
2772
    if (taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
24,546,892!
2773
                     &pNode->pPingTimer))
2774
      sError("failed to reset ping timer");
×
2775
  }
2776
  syncNodeRelease(pNode);
24,546,892✔
2777
}
2778

2779
static void syncNodeEqElectTimer(void* param, void* tmrId) {
533,151✔
2780
  if (!syncIsInit()) return;
533,151!
2781

2782
  int64_t    rid = (int64_t)param;
533,151✔
2783
  SSyncNode* pNode = syncNodeAcquire(rid);
533,151✔
2784

2785
  if (pNode == NULL) return;
533,151✔
2786

2787
  if (pNode->syncEqMsg == NULL) {
529,729!
2788
    syncNodeRelease(pNode);
×
2789
    return;
×
2790
  }
2791

2792
  int64_t tsNow = taosGetTimestampMs();
529,729✔
2793
  if (tsNow < pNode->electTimerParam.executeTime) {
529,729✔
2794
    syncNodeRelease(pNode);
1,532✔
2795
    return;
1,532✔
2796
  }
2797

2798
  SRpcMsg rpcMsg = {0};
528,197✔
2799
  int32_t code =
2800
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
528,197✔
2801

2802
  if (code != 0) {
528,197!
2803
    sError("failed to build elect msg");
×
2804
    syncNodeRelease(pNode);
×
2805
    return;
×
2806
  }
2807

2808
  SyncTimeout* pTimeout = rpcMsg.pCont;
528,197✔
2809
  sNTrace(pNode, "enqueue elect msg lc:%" PRId64, pTimeout->logicClock);
528,197!
2810

2811
  code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
528,197✔
2812
  if (code != 0) {
528,197✔
2813
    sError("failed to sync enqueue elect msg since %s", terrstr());
28!
2814
    rpcFreeCont(rpcMsg.pCont);
28✔
2815
    syncNodeRelease(pNode);
28✔
2816
    return;
28✔
2817
  }
2818

2819
  syncNodeRelease(pNode);
528,169✔
2820
}
2821

2822
#ifdef BUILD_NO_CALL
2823
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
2824
  if (!syncIsInit()) return;
2825

2826
  int64_t    rid = (int64_t)param;
2827
  SSyncNode* pNode = syncNodeAcquire(rid);
2828

2829
  if (pNode == NULL) return;
2830

2831
  if (pNode->totalReplicaNum > 1) {
2832
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
2833
      SRpcMsg rpcMsg = {0};
2834
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
2835
                                      pNode->heartbeatTimerMS, pNode);
2836

2837
      if (code != 0) {
2838
        sError("failed to build heartbeat msg");
2839
        goto _out;
2840
      }
2841

2842
      sTrace("vgId:%d, enqueue heartbeat timer", pNode->vgId);
2843
      code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
2844
      if (code != 0) {
2845
        sError("failed to enqueue heartbeat msg since %s", terrstr());
2846
        rpcFreeCont(rpcMsg.pCont);
2847
        goto _out;
2848
      }
2849

2850
    _out:
2851
      if (taosTmrReset(syncNodeEqHeartbeatTimer, pNode->heartbeatTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
2852
                       &pNode->pHeartbeatTimer) != 0)
2853
        return;
2854

2855
    } else {
2856
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
2857
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
2858
    }
2859
  }
2860
}
2861
#endif
2862

2863
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
20,407,873✔
2864
  if (tsSyncLogHeartbeat) {
20,407,873!
2865
    sInfo("heartbeat timer start");
×
2866
  }
2867
  int32_t code = 0;
20,407,873✔
2868
  int64_t hbDataRid = (int64_t)param;
20,407,873✔
2869
  int64_t tsNow = taosGetTimestampMs();
20,407,873✔
2870

2871
  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
20,407,873✔
2872
  if (pData == NULL) {
20,407,873✔
2873
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
40!
2874
    return;
40✔
2875
  }
2876

2877
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
20,407,833✔
2878
  if (pSyncNode == NULL) {
20,407,833✔
2879
    syncHbTimerDataRelease(pData);
485✔
2880
    sError("hb timer get pSyncNode NULL");
485!
2881
    return;
485✔
2882
  }
2883

2884
  SSyncTimer* pSyncTimer = pData->pTimer;
20,407,348✔
2885

2886
  if (!pSyncNode->isStart) {
20,407,348!
2887
    syncNodeRelease(pSyncNode);
×
2888
    syncHbTimerDataRelease(pData);
×
2889
    sError("vgId:%d, hb timer sync node already stop", pSyncNode->vgId);
×
2890
    return;
×
2891
  }
2892

2893
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
20,407,348!
2894
    syncNodeRelease(pSyncNode);
×
2895
    syncHbTimerDataRelease(pData);
×
2896
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
×
2897
    return;
×
2898
  }
2899

2900
  if (tsSyncLogHeartbeat) {
20,407,348!
2901
    sInfo("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
×
2902
          pData->destId.addr);
2903
  } else {
2904
    sTrace("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
20,407,348!
2905
           pData->destId.addr);
2906
  }
2907

2908
  if (pSyncNode->totalReplicaNum > 1) {
20,407,348✔
2909
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
20,406,345✔
2910
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
20,406,345✔
2911

2912
    if (timerLogicClock == msgLogicClock) {
20,406,345✔
2913
      if (tsNow > pData->execTime) {
20,404,887✔
2914
        pData->execTime += pSyncTimer->timerMS;
20,390,734✔
2915

2916
        SRpcMsg rpcMsg = {0};
20,390,734✔
2917
        if ((code = syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId)) != 0) {
20,390,734!
2918
          sError("vgId:%d, failed to build heartbeat msg since %s", pSyncNode->vgId, tstrerror(code));
×
2919
          syncNodeRelease(pSyncNode);
×
2920
          syncHbTimerDataRelease(pData);
×
2921
          return;
×
2922
        }
2923

2924
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);
20,390,734✔
2925

2926
        SyncHeartbeat* pSyncMsg = rpcMsg.pCont;
20,390,734✔
2927
        pSyncMsg->srcId = pSyncNode->myRaftId;
20,390,734✔
2928
        pSyncMsg->destId = pData->destId;
20,390,734✔
2929
        pSyncMsg->term = raftStoreGetTerm(pSyncNode);
20,390,734✔
2930
        pSyncMsg->commitIndex = pSyncNode->commitIndex;
20,390,734✔
2931
        pSyncMsg->minMatchIndex = pSyncNode->minMatchIndex;
20,390,734✔
2932
        pSyncMsg->privateTerm = 0;
20,390,734✔
2933
        pSyncMsg->timeStamp = tsNow;
20,390,734✔
2934

2935
        // update reset time
2936
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
20,390,734✔
2937
        pSyncTimer->timeStamp = tsNow;
20,390,734✔
2938

2939
        // send msg
2940
        TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
20,390,734✔
2941
        TRACE_SET_ROOTID(&(rpcMsg.info.traceId), tGenIdPI64());
20,390,734✔
2942
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime, &(rpcMsg.info.traceId));
20,390,734✔
2943
        int ret = syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
20,390,734✔
2944
        if (ret != 0) {
20,390,734✔
2945
          sError("vgId:%d, failed to send heartbeat since %s", pSyncNode->vgId, tstrerror(ret));
32,192!
2946
        }
2947
      }
2948

2949
      if (syncIsInit()) {
20,404,887!
2950
        if (tsSyncLogHeartbeat) {
20,404,887!
2951
          sInfo("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
×
2952
        } else {
2953
          sTrace("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
20,404,887!
2954
        }
2955
        bool stopped = taosTmrResetPriority(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS, (void*)hbDataRid,
20,404,887✔
2956
                                            syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
20,404,887✔
2957
        if (stopped) sError("vgId:%d, reset peer hb timer error, %s", pSyncNode->vgId, tstrerror(code));
20,404,887!
2958

2959
      } else {
2960
        sError("sync env is stop, reset peer hb timer error");
×
2961
      }
2962

2963
    } else {
2964
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64, pSyncNode->vgId,
1,458!
2965
             timerLogicClock, msgLogicClock);
2966
    }
2967

2968
    if (tsSyncLogHeartbeat) {
20,406,345!
2969
      sInfo("vgId:%d, finish send sync-heartbeat", pSyncNode->vgId);
×
2970
    }
2971
  }
2972

2973
  syncHbTimerDataRelease(pData);
20,407,348✔
2974
  syncNodeRelease(pSyncNode);
20,407,348✔
2975
  if (tsSyncLogHeartbeat) {
20,407,348!
2976
    sInfo("heartbeat timer stop");
×
2977
  }
2978
}
2979

2980
#ifdef BUILD_NO_CALL
2981
static void deleteCacheEntry(const void* key, size_t keyLen, void* value, void* ud) {
2982
  (void)ud;
2983
  taosMemoryFree(value);
2984
}
2985

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

2990
  int32_t   code = 0;
2991
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2992
  LRUStatus status = taosLRUCacheInsert(pLogStore->pCache, &pEntry->index, sizeof(pEntry->index), pEntry, entryLen,
2993
                                        deleteCacheEntry, h, TAOS_LRU_PRIORITY_LOW, NULL);
2994
  if (status != TAOS_LRU_STATUS_OK) {
2995
    code = -1;
2996
  }
2997

2998
  return code;
2999
}
3000
#endif
3001

3002
void syncBuildConfigFromReq(SAlterVnodeReplicaReq* pReq, SSyncCfg* cfg) {  // TODO SAlterVnodeReplicaReq name is proper?
×
3003
  cfg->replicaNum = 0;
×
3004
  cfg->totalReplicaNum = 0;
×
3005
  int32_t code = 0;
×
3006

3007
  for (int i = 0; i < pReq->replica; ++i) {
×
3008
    SNodeInfo* pNode = &cfg->nodeInfo[i];
×
3009
    pNode->nodeId = pReq->replicas[i].id;
×
3010
    pNode->nodePort = pReq->replicas[i].port;
×
3011
    tstrncpy(pNode->nodeFqdn, pReq->replicas[i].fqdn, sizeof(pNode->nodeFqdn));
×
3012
    pNode->nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3013
    bool update = tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort);
×
3014
    sInfo("vgId:%d, replica:%d ep:%s:%u dnode:%d nodeRole:%d, update:%d", pReq->vgId, i, pNode->nodeFqdn,
×
3015
          pNode->nodePort, pNode->nodeId, pNode->nodeRole, update);
3016
    cfg->replicaNum++;
×
3017
  }
3018
  if (pReq->selfIndex != -1) {
×
3019
    cfg->myIndex = pReq->selfIndex;
×
3020
  }
3021
  for (int i = cfg->replicaNum; i < pReq->replica + pReq->learnerReplica; ++i) {
×
3022
    SNodeInfo* pNode = &cfg->nodeInfo[i];
×
3023
    pNode->nodeId = pReq->learnerReplicas[cfg->totalReplicaNum].id;
×
3024
    pNode->nodePort = pReq->learnerReplicas[cfg->totalReplicaNum].port;
×
3025
    pNode->nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
3026
    tstrncpy(pNode->nodeFqdn, pReq->learnerReplicas[cfg->totalReplicaNum].fqdn, sizeof(pNode->nodeFqdn));
×
3027
    bool update = tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort);
×
3028
    sInfo("vgId:%d, replica:%d ep:%s:%u dnode:%d nodeRole:%d, update:%d", pReq->vgId, i, pNode->nodeFqdn,
×
3029
          pNode->nodePort, pNode->nodeId, pNode->nodeRole, update);
3030
    cfg->totalReplicaNum++;
×
3031
  }
3032
  cfg->totalReplicaNum += pReq->replica;
×
3033
  if (pReq->learnerSelfIndex != -1) {
×
3034
    cfg->myIndex = pReq->replica + pReq->learnerSelfIndex;
×
3035
  }
3036
  cfg->changeVersion = pReq->changeVersion;
×
3037
}
×
3038

3039
int32_t syncNodeCheckChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry) {
×
3040
  int32_t code = 0;
×
3041
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3042
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3043
  }
3044

3045
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3046
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3047

3048
  SAlterVnodeTypeReq req = {0};
×
3049
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3050
    code = TSDB_CODE_INVALID_MSG;
×
3051
    TAOS_RETURN(code);
×
3052
  }
3053

3054
  SSyncCfg cfg = {0};
×
3055
  syncBuildConfigFromReq(&req, &cfg);
×
3056

3057
  if (cfg.totalReplicaNum >= 1 &&
×
3058
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
×
3059
    bool incfg = false;
×
3060
    for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3061
      if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3062
          ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3063
        incfg = true;
×
3064
        break;
×
3065
      }
3066
    }
3067

3068
    if (!incfg) {
×
3069
      SyncTerm currentTerm = raftStoreGetTerm(ths);
×
3070
      SRaftId  id = EMPTY_RAFT_ID;
×
3071
      syncNodeStepDown(ths, currentTerm, id, "changeConfig");
×
3072
      return 1;
×
3073
    }
3074
  }
3075
  return 0;
×
3076
}
3077

3078
void syncNodeLogConfigInfo(SSyncNode* ths, SSyncCfg* cfg, char* str) {
×
3079
  sInfo("vgId:%d, %s. SyncNode, replicaNum:%d, peersNum:%d, lastConfigIndex:%" PRId64
×
3080
        ", changeVersion:%d, "
3081
        "restoreFinish:%d",
3082
        ths->vgId, str, ths->replicaNum, ths->peersNum, ths->raftCfg.lastConfigIndex, ths->raftCfg.cfg.changeVersion,
3083
        ths->restoreFinish);
3084

3085
  sInfo("vgId:%d, %s, myNodeInfo, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3086
        ths->myNodeInfo.clusterId, ths->myNodeInfo.nodeId, ths->myNodeInfo.nodeFqdn, ths->myNodeInfo.nodePort,
3087
        ths->myNodeInfo.nodeRole);
3088

3089
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3090
    sInfo("vgId:%d, %s, peersNodeInfo%d, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3091
          i, ths->peersNodeInfo[i].clusterId, ths->peersNodeInfo[i].nodeId, ths->peersNodeInfo[i].nodeFqdn,
3092
          ths->peersNodeInfo[i].nodePort, ths->peersNodeInfo[i].nodeRole);
3093
  }
3094

3095
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3096
    char    buf[256];
×
3097
    int32_t len = 256;
×
3098
    int32_t n = 0;
×
3099
    n += tsnprintf(buf + n, len - n, "%s", "{");
×
3100
    for (int i = 0; i < ths->peersEpset->numOfEps; i++) {
×
3101
      n += tsnprintf(buf + n, len - n, "%s:%d%s", ths->peersEpset->eps[i].fqdn, ths->peersEpset->eps[i].port,
×
3102
                     (i + 1 < ths->peersEpset->numOfEps ? ", " : ""));
×
3103
    }
3104
    n += tsnprintf(buf + n, len - n, "%s", "}");
×
3105

3106
    sInfo("vgId:%d, %s, peersEpset%d, %s, inUse:%d", ths->vgId, str, i, buf, ths->peersEpset->inUse);
×
3107
  }
3108

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

3113
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3114
    sInfo("vgId:%d, %s, nodeInfo%d, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str, i,
×
3115
          ths->raftCfg.cfg.nodeInfo[i].clusterId, ths->raftCfg.cfg.nodeInfo[i].nodeId,
3116
          ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, ths->raftCfg.cfg.nodeInfo[i].nodePort,
3117
          ths->raftCfg.cfg.nodeInfo[i].nodeRole);
3118
  }
3119

3120
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3121
    sInfo("vgId:%d, %s, replicasId%d, addr:0x%" PRIx64, ths->vgId, str, i, ths->replicasId[i].addr);
×
3122
  }
3123
}
×
3124

3125
int32_t syncNodeRebuildPeerAndCfg(SSyncNode* ths, SSyncCfg* cfg) {
×
3126
  int32_t i = 0;
×
3127

3128
  // change peersNodeInfo
3129
  i = 0;
×
3130
  for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3131
    if (!(strcmp(ths->myNodeInfo.nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3132
          ths->myNodeInfo.nodePort == cfg->nodeInfo[j].nodePort)) {
×
3133
      ths->peersNodeInfo[i].nodeRole = cfg->nodeInfo[j].nodeRole;
×
3134
      ths->peersNodeInfo[i].clusterId = cfg->nodeInfo[j].clusterId;
×
3135
      tstrncpy(ths->peersNodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn, TSDB_FQDN_LEN);
×
3136
      ths->peersNodeInfo[i].nodeId = cfg->nodeInfo[j].nodeId;
×
3137
      ths->peersNodeInfo[i].nodePort = cfg->nodeInfo[j].nodePort;
×
3138

3139
      syncUtilNodeInfo2EpSet(&ths->peersNodeInfo[i], &ths->peersEpset[i]);
×
3140

3141
      if (syncUtilNodeInfo2RaftId(&ths->peersNodeInfo[i], ths->vgId, &ths->peersId[i]) == false) {
×
3142
        sError("vgId:%d, failed to determine raft member id, peer:%d", ths->vgId, i);
×
3143
        return terrno;
×
3144
      }
3145

3146
      i++;
×
3147
    }
3148
  }
3149
  ths->peersNum = i;
×
3150

3151
  // change cfg nodeInfo
3152
  ths->raftCfg.cfg.replicaNum = 0;
×
3153
  i = 0;
×
3154
  for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3155
    if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3156
      ths->raftCfg.cfg.replicaNum++;
×
3157
    }
3158
    ths->raftCfg.cfg.nodeInfo[i].nodeRole = cfg->nodeInfo[j].nodeRole;
×
3159
    ths->raftCfg.cfg.nodeInfo[i].clusterId = cfg->nodeInfo[j].clusterId;
×
3160
    tstrncpy(ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn, TSDB_FQDN_LEN);
×
3161
    ths->raftCfg.cfg.nodeInfo[i].nodeId = cfg->nodeInfo[j].nodeId;
×
3162
    ths->raftCfg.cfg.nodeInfo[i].nodePort = cfg->nodeInfo[j].nodePort;
×
3163
    if ((strcmp(ths->myNodeInfo.nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3164
         ths->myNodeInfo.nodePort == cfg->nodeInfo[j].nodePort)) {
×
3165
      ths->raftCfg.cfg.myIndex = i;
×
3166
    }
3167
    i++;
×
3168
  }
3169
  ths->raftCfg.cfg.totalReplicaNum = i;
×
3170

3171
  return 0;
×
3172
}
3173

3174
void syncNodeChangePeerAndCfgToVoter(SSyncNode* ths, SSyncCfg* cfg) {
×
3175
  // change peersNodeInfo
3176
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3177
    for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3178
      if (strcmp(ths->peersNodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3179
          ths->peersNodeInfo[i].nodePort == cfg->nodeInfo[j].nodePort) {
×
3180
        if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3181
          ths->peersNodeInfo[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3182
        }
3183
      }
3184
    }
3185
  }
3186

3187
  // change cfg nodeInfo
3188
  ths->raftCfg.cfg.replicaNum = 0;
×
3189
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3190
    for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3191
      if (strcmp(ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3192
          ths->raftCfg.cfg.nodeInfo[i].nodePort == cfg->nodeInfo[j].nodePort) {
×
3193
        if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3194
          ths->raftCfg.cfg.nodeInfo[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3195
          ths->raftCfg.cfg.replicaNum++;
×
3196
        }
3197
      }
3198
    }
3199
  }
3200
}
×
3201

3202
int32_t syncNodeRebuildAndCopyIfExist(SSyncNode* ths, int32_t oldtotalReplicaNum) {
×
3203
  int32_t code = 0;
×
3204
  // 1.rebuild replicasId, remove deleted one
3205
  SRaftId oldReplicasId[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
×
3206
  memcpy(oldReplicasId, ths->replicasId, sizeof(oldReplicasId));
×
3207

3208
  ths->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3209
  ths->totalReplicaNum = ths->raftCfg.cfg.totalReplicaNum;
×
3210
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3211
    if (syncUtilNodeInfo2RaftId(&ths->raftCfg.cfg.nodeInfo[i], ths->vgId, &ths->replicasId[i]) == false) return terrno;
×
3212
  }
3213

3214
  // 2.rebuild MatchIndex, remove deleted one
3215
  SSyncIndexMgr* oldIndex = ths->pMatchIndex;
×
3216

3217
  ths->pMatchIndex = syncIndexMgrCreate(ths);
×
3218
  if (ths->pMatchIndex == NULL) {
×
3219
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3220
    if (terrno != 0) code = terrno;
×
3221
    TAOS_RETURN(code);
×
3222
  }
3223

3224
  syncIndexMgrCopyIfExist(ths->pMatchIndex, oldIndex, oldReplicasId);
×
3225

3226
  syncIndexMgrDestroy(oldIndex);
×
3227

3228
  // 3.rebuild NextIndex, remove deleted one
3229
  SSyncIndexMgr* oldNextIndex = ths->pNextIndex;
×
3230

3231
  ths->pNextIndex = syncIndexMgrCreate(ths);
×
3232
  if (ths->pNextIndex == NULL) {
×
3233
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3234
    if (terrno != 0) code = terrno;
×
3235
    TAOS_RETURN(code);
×
3236
  }
3237

3238
  syncIndexMgrCopyIfExist(ths->pNextIndex, oldNextIndex, oldReplicasId);
×
3239

3240
  syncIndexMgrDestroy(oldNextIndex);
×
3241

3242
  // 4.rebuild pVotesGranted, pVotesRespond, no need to keep old vote state, only rebuild
3243
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3244
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3245

3246
  // 5.rebuild logReplMgr
3247
  for (int i = 0; i < oldtotalReplicaNum; ++i) {
×
3248
    sDebug("vgId:%d, old logReplMgrs i:%d, peerId:%d, restoreed:%d, [%" PRId64 " %" PRId64 ", %" PRId64 ")", ths->vgId,
×
3249
           i, ths->logReplMgrs[i]->peerId, ths->logReplMgrs[i]->restored, ths->logReplMgrs[i]->startIndex,
3250
           ths->logReplMgrs[i]->matchIndex, ths->logReplMgrs[i]->endIndex);
3251
  }
3252

3253
  SSyncLogReplMgr* oldLogReplMgrs = NULL;
×
3254
  int64_t          length = sizeof(SSyncLogReplMgr) * (TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA);
×
3255
  oldLogReplMgrs = taosMemoryMalloc(length);
×
3256
  if (NULL == oldLogReplMgrs) return terrno;
×
3257
  memset(oldLogReplMgrs, 0, length);
×
3258

3259
  for (int i = 0; i < oldtotalReplicaNum; i++) {
×
3260
    oldLogReplMgrs[i] = *(ths->logReplMgrs[i]);
×
3261
  }
3262

3263
  syncNodeLogReplDestroy(ths);
×
3264
  if ((code = syncNodeLogReplInit(ths)) != 0) {
×
3265
    taosMemoryFree(oldLogReplMgrs);
×
3266
    TAOS_RETURN(code);
×
3267
  }
3268

3269
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3270
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3271
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3272
        *(ths->logReplMgrs[i]) = oldLogReplMgrs[j];
×
3273
        ths->logReplMgrs[i]->peerId = i;
×
3274
      }
3275
    }
3276
  }
3277

3278
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3279
    sDebug("vgId:%d, new logReplMgrs i:%d, peerId:%d, restoreed:%d, [%" PRId64 " %" PRId64 ", %" PRId64 ")", ths->vgId,
×
3280
           i, ths->logReplMgrs[i]->peerId, ths->logReplMgrs[i]->restored, ths->logReplMgrs[i]->startIndex,
3281
           ths->logReplMgrs[i]->matchIndex, ths->logReplMgrs[i]->endIndex);
3282
  }
3283

3284
  // 6.rebuild sender
3285
  for (int i = 0; i < oldtotalReplicaNum; ++i) {
×
3286
    sDebug("vgId:%d, old sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3287
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3288
  }
3289

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

3294
      if (snapshotSenderIsStart(ths->senders[i])) {
×
3295
        snapshotSenderStop(ths->senders[i], false);
×
3296
      }
3297

3298
      snapshotSenderDestroy(ths->senders[i]);
×
3299
      ths->senders[i] = NULL;
×
3300
    }
3301
  }
3302

3303
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3304
    SSyncSnapshotSender* pSender = NULL;
×
3305
    int32_t              code = snapshotSenderCreate(ths, i, &pSender);
×
3306
    if (pSender == NULL) return terrno = code;
×
3307

3308
    ths->senders[i] = pSender;
×
3309
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
×
3310
  }
3311

3312
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3313
    sDebug("vgId:%d, new sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3314
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3315
  }
3316

3317
  // 7.rebuild synctimer
3318
  if ((code = syncNodeStopHeartbeatTimer(ths)) != 0) {
×
3319
    taosMemoryFree(oldLogReplMgrs);
×
3320
    TAOS_RETURN(code);
×
3321
  }
3322

3323
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3324
    if ((code = syncHbTimerInit(ths, &ths->peerHeartbeatTimerArr[i], ths->replicasId[i])) != 0) {
×
3325
      taosMemoryFree(oldLogReplMgrs);
×
3326
      TAOS_RETURN(code);
×
3327
    }
3328
  }
3329

3330
  if ((code = syncNodeStartHeartbeatTimer(ths)) != 0) {
×
3331
    taosMemoryFree(oldLogReplMgrs);
×
3332
    TAOS_RETURN(code);
×
3333
  }
3334

3335
  // 8.rebuild peerStates
3336
  SPeerState oldState[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA] = {0};
×
3337
  for (int i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; i++) {
×
3338
    oldState[i] = ths->peerStates[i];
×
3339
  }
3340

3341
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3342
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3343
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3344
        ths->peerStates[i] = oldState[j];
×
3345
      }
3346
    }
3347
  }
3348

3349
  taosMemoryFree(oldLogReplMgrs);
×
3350

3351
  return 0;
×
3352
}
3353

3354
void syncNodeChangeToVoter(SSyncNode* ths) {
×
3355
  // replicasId, only need to change replicaNum when 1->3
3356
  ths->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3357
  sDebug("vgId:%d, totalReplicaNum:%d", ths->vgId, ths->totalReplicaNum);
×
3358
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
×
3359
    sDebug("vgId:%d, i:%d, replicaId.addr:0x%" PRIx64, ths->vgId, i, ths->replicasId[i].addr);
×
3360
  }
3361

3362
  // pMatchIndex, pNextIndex, only need to change replicaNum when 1->3
3363
  ths->pMatchIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3364
  ths->pNextIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3365

3366
  sDebug("vgId:%d, pMatchIndex->totalReplicaNum:%d", ths->vgId, ths->pMatchIndex->totalReplicaNum);
×
3367
  for (int32_t i = 0; i < ths->pMatchIndex->totalReplicaNum; ++i) {
×
3368
    sDebug("vgId:%d, i:%d, match.index:%" PRId64, ths->vgId, i, ths->pMatchIndex->index[i]);
×
3369
  }
3370

3371
  // pVotesGranted, pVotesRespond
3372
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3373
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3374

3375
  // logRepMgrs
3376
  // no need to change logRepMgrs when 1->3
3377
}
×
3378

3379
void syncNodeResetPeerAndCfg(SSyncNode* ths) {
×
3380
  SNodeInfo node = {0};
×
3381
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3382
    memcpy(&ths->peersNodeInfo[i], &node, sizeof(SNodeInfo));
×
3383
  }
3384

3385
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3386
    memcpy(&ths->raftCfg.cfg.nodeInfo[i], &node, sizeof(SNodeInfo));
×
3387
  }
3388
}
×
3389

3390
int32_t syncNodeChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry, char* str) {
×
3391
  int32_t code = 0;
×
3392
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3393
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3394
  }
3395

3396
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3397
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3398

3399
  SAlterVnodeTypeReq req = {0};
×
3400
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3401
    code = TSDB_CODE_INVALID_MSG;
×
3402
    TAOS_RETURN(code);
×
3403
  }
3404

3405
  SSyncCfg cfg = {0};
×
3406
  syncBuildConfigFromReq(&req, &cfg);
×
3407

3408
  if (cfg.changeVersion <= ths->raftCfg.cfg.changeVersion) {
×
3409
    sInfo(
×
3410
        "vgId:%d, skip conf change entry since lower version. "
3411
        "this entry, index:%" PRId64 ", term:%" PRId64
3412
        ", totalReplicaNum:%d, changeVersion:%d; "
3413
        "current node, replicaNum:%d, peersNum:%d, lastConfigIndex:%" PRId64 ", changeVersion:%d",
3414
        ths->vgId, pEntry->index, pEntry->term, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum, ths->peersNum,
3415
        ths->raftCfg.lastConfigIndex, ths->raftCfg.cfg.changeVersion);
3416
    return 0;
×
3417
  }
3418

3419
  if (strcmp(str, "Commit") == 0) {
×
3420
    sInfo(
×
3421
        "vgId:%d, change config from %s. "
3422
        "this, i:%" PRId64
3423
        ", trNum:%d, vers:%d; "
3424
        "node, rNum:%d, pNum:%d, trNum:%d, "
3425
        "buffer: [%" PRId64 " %" PRId64 " %" PRId64 ", %" PRId64
3426
        "), "
3427
        "cond:(next i:%" PRId64 ", t:%" PRId64 " ==%s)",
3428
        ths->vgId, str, pEntry->index - 1, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum, ths->peersNum,
3429
        ths->totalReplicaNum, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex, ths->pLogBuf->matchIndex,
3430
        ths->pLogBuf->endIndex, pEntry->index, pEntry->term, TMSG_INFO(pEntry->originalRpcType));
3431
  } else {
3432
    sInfo(
×
3433
        "vgId:%d, change config from %s. "
3434
        "this, i:%" PRId64 ", t:%" PRId64
3435
        ", trNum:%d, vers:%d; "
3436
        "node, rNum:%d, pNum:%d, trNum:%d, "
3437
        "buffer: [%" PRId64 " %" PRId64 " %" PRId64 ", %" PRId64
3438
        "), "
3439
        "cond:(pre i:%" PRId64 "==ci:%" PRId64 ", bci:%" PRId64 ")",
3440
        ths->vgId, str, pEntry->index, pEntry->term, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum,
3441
        ths->peersNum, ths->totalReplicaNum, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3442
        ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex, pEntry->index - 1, ths->commitIndex,
3443
        ths->pLogBuf->commitIndex);
3444
  }
3445

3446
  syncNodeLogConfigInfo(ths, &cfg, "before config change");
×
3447

3448
  int32_t oldTotalReplicaNum = ths->totalReplicaNum;
×
3449

3450
  if (cfg.totalReplicaNum == 1 || cfg.totalReplicaNum == 2) {  // remove replica
×
3451

3452
    bool incfg = false;
×
3453
    for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3454
      if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3455
          ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3456
        incfg = true;
×
3457
        break;
×
3458
      }
3459
    }
3460

3461
    if (incfg) {  // remove other
×
3462
      syncNodeResetPeerAndCfg(ths);
×
3463

3464
      // no need to change myNodeInfo
3465

3466
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3467
        TAOS_RETURN(code);
×
3468
      };
3469

3470
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3471
        TAOS_RETURN(code);
×
3472
      };
3473
    } else {  // remove myself
3474
      // no need to do anything actually, to change the following to reduce distruptive server chance
3475

3476
      syncNodeResetPeerAndCfg(ths);
×
3477

3478
      // change myNodeInfo
3479
      ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
3480

3481
      // change peer and cfg
3482
      ths->peersNum = 0;
×
3483
      memcpy(&ths->raftCfg.cfg.nodeInfo[0], &ths->myNodeInfo, sizeof(SNodeInfo));
×
3484
      ths->raftCfg.cfg.replicaNum = 0;
×
3485
      ths->raftCfg.cfg.totalReplicaNum = 1;
×
3486

3487
      // change other
3488
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3489
        TAOS_RETURN(code);
×
3490
      }
3491

3492
      // change state
3493
      ths->state = TAOS_SYNC_STATE_LEARNER;
×
3494
    }
3495

3496
    ths->restoreFinish = false;
×
3497
  } else {                            // add replica, or change replica type
3498
    if (ths->totalReplicaNum == 3) {  // change replica type
×
3499
      sInfo("vgId:%d, begin change replica type", ths->vgId);
×
3500

3501
      // change myNodeInfo
3502
      for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3503
        if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3504
            ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3505
          if (cfg.nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3506
            ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3507
          }
3508
        }
3509
      }
3510

3511
      // change peer and cfg
3512
      syncNodeChangePeerAndCfgToVoter(ths, &cfg);
×
3513

3514
      // change other
3515
      syncNodeChangeToVoter(ths);
×
3516

3517
      // change state
3518
      if (ths->state == TAOS_SYNC_STATE_LEARNER) {
×
3519
        if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3520
          ths->state = TAOS_SYNC_STATE_FOLLOWER;
×
3521
        }
3522
      }
3523

3524
      ths->restoreFinish = false;
×
3525
    } else {  // add replica
3526
      sInfo("vgId:%d, begin add replica", ths->vgId);
×
3527

3528
      // no need to change myNodeInfo
3529

3530
      // change peer and cfg
3531
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3532
        TAOS_RETURN(code);
×
3533
      };
3534

3535
      // change other
3536
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3537
        TAOS_RETURN(code);
×
3538
      };
3539

3540
      // no need to change state
3541

3542
      if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
3543
        ths->restoreFinish = false;
×
3544
      }
3545
    }
3546
  }
3547

3548
  ths->quorum = syncUtilQuorum(ths->replicaNum);
×
3549

3550
  ths->raftCfg.lastConfigIndex = pEntry->index;
×
3551
  ths->raftCfg.cfg.lastIndex = pEntry->index;
×
3552
  ths->raftCfg.cfg.changeVersion = cfg.changeVersion;
×
3553

3554
  syncNodeLogConfigInfo(ths, &cfg, "after config change");
×
3555

3556
  if ((code = syncWriteCfgFile(ths)) != 0) {
×
3557
    sError("vgId:%d, failed to create sync cfg file", ths->vgId);
×
3558
    TAOS_RETURN(code);
×
3559
  };
3560

3561
  TAOS_RETURN(code);
×
3562
}
3563

3564
int32_t syncNodeAppend(SSyncNode* ths, SSyncRaftEntry* pEntry, SRpcMsg* pMsg) {
649,760,497✔
3565
  int32_t code = -1;
649,760,497✔
3566
  if (pEntry->dataLen < sizeof(SMsgHead)) {
649,760,497!
3567
    code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
3568
    sError("vgId:%d, msg:%p, cannot append an invalid client request with no msg head, type:%s dataLen:%d", ths->vgId,
×
3569
           pMsg, TMSG_INFO(pEntry->originalRpcType), pEntry->dataLen);
3570
    syncEntryDestroy(pEntry);
×
3571
    pEntry = NULL;
×
3572
    goto _out;
×
3573
  }
3574

3575
  // append to log buffer
3576
  if ((code = syncLogBufferAppend(ths->pLogBuf, ths, pEntry)) < 0) {
649,760,188!
3577
    sError("vgId:%d, index:%" PRId64 ", failed to enqueue sync log buffer", ths->vgId, pEntry->index);
×
3578
    int32_t ret = 0;
×
3579
    if ((ret = syncFsmExecute(ths, ths->pFsm, ths->state, raftStoreGetTerm(ths), pEntry, terrno, false)) != 0) {
×
3580
      sError("vgId:%d, index:%" PRId64 ", failed to execute fsm since %s", ths->vgId, pEntry->index, tstrerror(ret));
×
3581
    }
3582
    syncEntryDestroy(pEntry);
×
3583
    pEntry = NULL;
×
3584
    goto _out;
×
3585
  }
3586

3587
  code = 0;
649,750,979✔
3588
_out:;
649,750,979✔
3589
  // proceed match index, with replicating on needed
3590
  SyncIndex       matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL, "Append", pMsg);
649,750,979✔
3591
  const STraceId* trace = pEntry ? &pEntry->originRpcTraceId : NULL;
649,762,558✔
3592

3593
  if (pEntry != NULL) {
649,755,024✔
3594
    sGDebug(trace,
649,776,980!
3595
            "vgId:%d, index:%" PRId64 ", raft entry appended, msg:%p term:%" PRId64 " buf:[%" PRId64 " %" PRId64
3596
            " %" PRId64 ", %" PRId64 ")",
3597
            ths->vgId, pEntry->index, pMsg, pEntry->term, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3598
            ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex);
3599
  }
3600

3601
  if (code == 0 && ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
649,718,787!
3602
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
3,265✔
3603
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
3,265!
3604

3605
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
6,530!
3606
        syncLogBufferCommit(ths->pLogBuf, ths, ths->assignedCommitIndex, trace, "append-entry") < 0) {
3,265✔
3607
      sGError(trace, "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64, ths->vgId, index,
×
3608
              pMsg, ths->commitIndex);
3609
      code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
3610
    }
3611
  }
3612

3613
  // multi replica
3614
  if (ths->replicaNum > 1) {
649,754,160✔
3615
    TAOS_RETURN(code);
12,497,211✔
3616
  }
3617

3618
  // single replica
3619
  SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, matchIndex);
637,212,752✔
3620
  sGTrace(trace, "vgId:%d, index:%" PRId64 ", raft entry update commit, msg:%p return index:%" PRId64, ths->vgId,
637,209,026!
3621
          matchIndex, pMsg, returnIndex);
3622

3623
  if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
1,274,447,171!
3624
      (code = syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, trace, "append-entry")) < 0) {
637,239,439✔
3625
    sGError(trace,
×
3626
            "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64 " return index:%" PRId64,
3627
            ths->vgId, matchIndex, pMsg, ths->commitIndex, returnIndex);
3628
  }
3629

3630
  TAOS_RETURN(code);
637,217,450✔
3631
}
3632

3633
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
646,598,341✔
3634
  if (pSyncNode->totalReplicaNum == 1) {
646,598,341✔
3635
    return false;
633,868,483✔
3636
  }
3637

3638
  int32_t toCount = 0;
12,737,097✔
3639
  int64_t tsNow = taosGetTimestampMs();
12,737,097✔
3640
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
38,203,722✔
3641
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
25,466,720✔
3642
      continue;
220,271✔
3643
    }
3644
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
25,246,367✔
3645
    if (recvTime == 0 || recvTime == -1) {
25,246,354!
3646
      continue;
×
3647
    }
3648

3649
    if (tsNow - recvTime > tsHeartbeatTimeout) {
25,246,354✔
3650
      toCount++;
360,700✔
3651
    }
3652
  }
3653

3654
  bool b = (toCount >= pSyncNode->quorum ? true : false);
12,737,292✔
3655

3656
  return b;
12,737,292✔
3657
}
3658

3659
bool syncNodeSnapshotSending(SSyncNode* pSyncNode) {
×
3660
  if (pSyncNode == NULL) return false;
×
3661
  bool b = false;
×
3662
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
×
3663
    if (pSyncNode->senders[i] != NULL && pSyncNode->senders[i]->start) {
×
3664
      b = true;
×
3665
      break;
×
3666
    }
3667
  }
3668
  return b;
×
3669
}
3670

3671
bool syncNodeSnapshotRecving(SSyncNode* pSyncNode) {
×
3672
  if (pSyncNode == NULL) return false;
×
3673
  if (pSyncNode->pNewNodeReceiver == NULL) return false;
×
3674
  if (pSyncNode->pNewNodeReceiver->start) return true;
×
3675
  return false;
×
3676
}
3677

3678
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
3,779,762✔
3679
  int32_t   code = 0;
3,779,762✔
3680
  SyncIndex index = syncLogBufferGetEndIndex(ths->pLogBuf);
3,779,762✔
3681
  SyncTerm  term = raftStoreGetTerm(ths);
3,779,961✔
3682

3683
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
3,779,961✔
3684
  if (pEntry == NULL) {
3,779,125!
3685
    code = TSDB_CODE_OUT_OF_MEMORY;
×
3686
    TAOS_RETURN(code);
×
3687
  }
3688

3689
  code = syncNodeAppend(ths, pEntry, NULL);
3,779,125✔
3690
  TAOS_RETURN(code);
3,779,961✔
3691
}
3692

3693
#ifdef BUILD_NO_CALL
3694
static int32_t syncNodeAppendNoopOld(SSyncNode* ths) {
3695
  int32_t ret = 0;
3696

3697
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
3698
  SyncTerm        term = raftStoreGetTerm(ths);
3699
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
3700
  if (pEntry == NULL) return -1;
3701

3702
  LRUHandle* h = NULL;
3703

3704
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
3705
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry, false);
3706
    if (code != 0) {
3707
      sError("append noop error");
3708
      return -1;
3709
    }
3710

3711
    syncCacheEntry(ths->pLogStore, pEntry, &h);
3712
  }
3713

3714
  if (h) {
3715
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
3716
  } else {
3717
    syncEntryDestroy(pEntry);
3718
  }
3719

3720
  return ret;
3721
}
3722
#endif
3723

3724
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
19,361,652✔
3725
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
19,361,652✔
3726
  bool           resetElect = false;
19,361,652✔
3727

3728
  int64_t tsMs = taosGetTimestampMs();
19,361,652✔
3729

3730
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pNextIndex, &(pMsg->srcId));
19,361,652✔
3731
  syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);
19,361,652✔
3732
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
19,361,652✔
3733

3734
  int64_t netElapsed = tsMs - pMsg->timeStamp;
19,361,652✔
3735
  int64_t timeDiff = tsMs - lastRecvTime;
19,361,652✔
3736
  syncLogRecvHeartbeat(ths, pMsg, netElapsed, &pRpcMsg->info.traceId, timeDiff, pRpcMsg);
19,361,652✔
3737

3738
  if (!syncNodeInRaftGroup(ths, &pMsg->srcId)) {
19,361,652!
3739
    sWarn(
×
3740
        "vgId:%d, drop heartbeat msg from dnode:%d, because it come from another cluster:%d, differ from current "
3741
        "cluster:%d",
3742
        ths->vgId, DID(&(pMsg->srcId)), CID(&(pMsg->srcId)), CID(&(ths->myRaftId)));
3743
    return 0;
×
3744
  }
3745

3746
  SyncTerm currentTerm = raftStoreGetTerm(ths);
19,361,652✔
3747

3748
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
19,361,652✔
3749
    raftStoreSetTerm(ths, pMsg->term);
108,052✔
3750
    currentTerm = pMsg->term;
108,052✔
3751
  }
3752

3753
  int64_t tsMs2 = taosGetTimestampMs();
19,361,652✔
3754

3755
  int64_t processTime = tsMs2 - tsMs;
19,361,652✔
3756
  if (processTime > SYNC_HEARTBEAT_SLOW_MS) {
19,361,652!
3757
    sGError(&pRpcMsg->info.traceId,
×
3758
            "vgId:%d, process sync-heartbeat msg from dnode:%d, commit-index:%" PRId64 ", cluster:%d msgTerm:%" PRId64
3759
            " currentTerm:%" PRId64 ", processTime:%" PRId64,
3760
            ths->vgId, DID(&(pMsg->srcId)), pMsg->commitIndex, CID(&(pMsg->srcId)), pMsg->term, currentTerm,
3761
            processTime);
3762
  } else {
3763
    sGDebug(&pRpcMsg->info.traceId,
19,361,652!
3764
            "vgId:%d, process sync-heartbeat msg from dnode:%d, commit-index:%" PRId64 ", cluster:%d msgTerm:%" PRId64
3765
            " currentTerm:%" PRId64 ", processTime:%" PRId64,
3766
            ths->vgId, DID(&(pMsg->srcId)), pMsg->commitIndex, CID(&(pMsg->srcId)), pMsg->term, currentTerm,
3767
            processTime);
3768
  }
3769

3770
  if (pMsg->term == currentTerm &&
19,361,652✔
3771
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
19,202,764!
3772
    resetElect = true;
19,202,764✔
3773

3774
    ths->minMatchIndex = pMsg->minMatchIndex;
19,202,764✔
3775

3776
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
19,202,764✔
3777
      SRpcMsg rpcMsgLocalCmd = {0};
19,198,565✔
3778
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
19,198,565!
3779
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
19,198,675✔
3780

3781
      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
19,198,770✔
3782
      pSyncMsg->cmd =
19,198,675✔
3783
          (ths->state == TAOS_SYNC_STATE_LEARNER) ? SYNC_LOCAL_CMD_LEARNER_CMT : SYNC_LOCAL_CMD_FOLLOWER_CMT;
19,198,770✔
3784
      pSyncMsg->commitIndex = pMsg->commitIndex;
19,198,675✔
3785
      pSyncMsg->currentTerm = pMsg->term;
19,198,448✔
3786

3787
      if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
19,198,558!
3788
        int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
19,198,770✔
3789
        if (code != 0) {
19,197,580!
3790
          sError("vgId:%d, failed to enqueue sync-local-cmd msg(cmd=commit) from heartbeat since %s",
×
3791
                 ths->vgId, tstrerror(code));
3792
          rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3793
        } else {
3794
          sGTrace(&pRpcMsg->info.traceId,
19,197,580!
3795
                  "vgId:%d, enqueue sync-local-cmd msg(cmd=commit) from heartbeat, commit-index:%" PRId64
3796
                  ", term:%" PRId64,
3797
                  ths->vgId, pMsg->commitIndex, pMsg->term);
3798
        }
3799
      }
3800
    }
3801
  }
3802

3803
  if (pMsg->term >= currentTerm &&
19,361,447!
3804
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
19,361,652!
3805
    SRpcMsg rpcMsgLocalCmd = {0};
×
3806
    TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
×
3807
    rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
×
3808

3809
    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
×
3810
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
×
3811
    pSyncMsg->currentTerm = pMsg->term;
×
3812
    pSyncMsg->commitIndex = pMsg->commitIndex;
×
3813

3814
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
×
3815
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
×
3816
      if (code != 0) {
×
3817
        sError("vgId:%d, sync enqueue sync-local-cmd msg(cmd=step-down) error, code:%d", ths->vgId, code);
×
3818
        rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3819
      } else {
3820
        sTrace("vgId:%d, sync enqueue sync-local-cmd msg(cmd=step-down), new-term:%" PRId64, ths->vgId, pMsg->term);
×
3821
      }
3822
    }
3823
  }
3824

3825
  SRpcMsg rpcMsg = {0};
19,360,462✔
3826
  TAOS_CHECK_RETURN(syncBuildHeartbeatReply(&rpcMsg, ths->vgId));
19,360,256!
3827
  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
19,359,884✔
3828
  pMsgReply->destId = pMsg->srcId;
19,359,884✔
3829
  pMsgReply->srcId = ths->myRaftId;
19,360,484✔
3830
  pMsgReply->term = currentTerm;
19,359,253✔
3831
  pMsgReply->privateTerm = 8864;  // magic number
19,360,785✔
3832
  pMsgReply->startTime = ths->startTime;
19,360,881✔
3833
  pMsgReply->timeStamp = tsMs;
19,360,154✔
3834
  rpcMsg.info.traceId = pRpcMsg->info.traceId;
19,359,772✔
3835

3836
  // reply
3837
  int64_t tsMs3 = taosGetTimestampMs();
19,359,913✔
3838

3839
  int64_t processTime2 = tsMs3 - tsMs2;
19,359,913✔
3840
  TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
19,359,913✔
3841
  if (processTime2 > SYNC_HEARTBEAT_SLOW_MS) {
19,359,413✔
3842
    sGError(&rpcMsg.info.traceId,
689!
3843
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3844
            ", processTime:%" PRId64,
3845
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3846
  } else {
3847
    if(tsSyncLogHeartbeat){
19,358,724!
3848
      sGInfo(&rpcMsg.info.traceId,
×
3849
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3850
            ", processTime:%" PRId64,
3851
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3852
    }
3853
    else{
3854
      sGDebug(&rpcMsg.info.traceId,
19,358,724!
3855
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3856
            ", processTime:%" PRId64,
3857
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3858
    }
3859
  }
3860

3861
  TAOS_CHECK_RETURN(syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg));
19,359,413!
3862

3863
  if (resetElect) syncNodeResetElectTimer(ths);
19,361,652✔
3864
  return 0;
19,361,652✔
3865
}
3866

3867
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
19,073,835✔
3868
  int32_t code = 0;
19,073,835✔
3869

3870
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
19,073,835✔
3871
  SSyncLogReplMgr*    pMgr = syncNodeGetLogReplMgr(ths, &pMsg->srcId);
19,073,835✔
3872
  if (pMgr == NULL) {
19,073,835!
3873
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3874
    if (terrno != 0) code = terrno;
×
3875
    sError("vgId:%d, failed to get log repl mgr for the peer at addr 0x016%" PRIx64, ths->vgId, pMsg->srcId.addr);
×
3876
    TAOS_RETURN(code);
×
3877
  }
3878

3879
  int64_t tsMs = taosGetTimestampMs();
19,073,835✔
3880
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pMatchIndex, &pMsg->srcId);
19,073,835✔
3881
  syncLogRecvHeartbeatReply(ths, pMsg, tsMs - pMsg->timeStamp, &pRpcMsg->info.traceId, tsMs - lastRecvTime);
19,073,835✔
3882

3883
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
19,073,835✔
3884
  syncIndexMgrIncRecvCount(ths->pMatchIndex, &(pMsg->srcId));
19,073,835✔
3885

3886
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
19,073,651✔
3887
}
3888

3889
#ifdef BUILD_NO_CALL
3890
int32_t syncNodeOnHeartbeatReplyOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
3891
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
3892

3893
  int64_t tsMs = taosGetTimestampMs();
3894
  int64_t timeDiff = tsMs - pMsg->timeStamp;
3895
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff, &pRpcMsg->info.traceId, timeDiff);
3896

3897
  // update last reply time, make decision whether the other node is alive or not
3898
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
3899
  return 0;
3900
}
3901
#endif
3902

3903
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
19,198,770✔
3904
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
19,198,770✔
3905
  syncLogRecvLocalCmd(ths, pMsg, &pRpcMsg->info.traceId);
19,198,770✔
3906

3907
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
19,198,770!
3908
    SRaftId id = EMPTY_RAFT_ID;
×
3909
    syncNodeStepDown(ths, pMsg->currentTerm, id, "localCmd");
×
3910

3911
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT || pMsg->cmd == SYNC_LOCAL_CMD_LEARNER_CMT) {
38,397,540!
3912
    if (syncLogBufferIsEmpty(ths->pLogBuf)) {
19,198,770!
3913
      sError("vgId:%d, sync log buffer is empty", ths->vgId);
×
3914
      return 0;
×
3915
    }
3916
    SyncTerm matchTerm = syncLogBufferGetLastMatchTerm(ths->pLogBuf);
19,198,770✔
3917
    if (matchTerm < 0) {
19,198,770!
3918
      return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3919
    }
3920
    if (pMsg->currentTerm == matchTerm) {
19,198,770✔
3921
      SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, pMsg->commitIndex);
17,887,495✔
3922
      sTrace("vgId:%d, raft entry update commit, return index:%" PRId64, ths->vgId, returnIndex);
17,887,495!
3923
    }
3924
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
38,397,540!
3925
        syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, &pRpcMsg->info.traceId, "heartbeat") < 0) {
19,198,770✔
3926
      sError("vgId:%d, failed to commit raft log since %s. commit index:%" PRId64, ths->vgId, terrstr(),
×
3927
             ths->commitIndex);
3928
    }
3929
  } else {
3930
    sError("error local cmd");
×
3931
  }
3932

3933
  return 0;
19,198,770✔
3934
}
3935

3936
// TLA+ Spec
3937
// ClientRequest(i, v) ==
3938
//     /\ state[i] = Leader
3939
//     /\ LET entry == [term  |-> currentTerm[i],
3940
//                      value |-> v]
3941
//            newLog == Append(log[i], entry)
3942
//        IN  log' = [log EXCEPT ![i] = newLog]
3943
//     /\ UNCHANGED <<messages, serverVars, candidateVars,
3944
//                    leaderVars, commitIndex>>
3945
//
3946

3947
int32_t syncNodeOnClientRequest(SSyncNode* ths, SRpcMsg* pMsg, SyncIndex* pRetIndex) {
645,987,422✔
3948
  sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, process client request", ths->vgId, pMsg);
645,987,422!
3949
  int32_t code = 0;
645,987,422✔
3950

3951
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
645,987,422✔
3952
  SyncTerm        term = raftStoreGetTerm(ths);
646,002,559✔
3953
  SSyncRaftEntry* pEntry = NULL;
646,006,541✔
3954
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
646,006,541✔
3955
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
41,354,071✔
3956
  } else {
3957
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
604,628,947✔
3958
  }
3959

3960
  if (pEntry == NULL) {
645,991,284!
3961
    sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to process client request since %s", ths->vgId, pMsg,
×
3962
            terrstr());
3963
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3964
  }
3965

3966
  // 1->2, config change is add in write thread, and will continue in sync thread
3967
  // need save message for it
3968
  if (pMsg->msgType == TDMT_SYNC_CONFIG_CHANGE) {
645,991,284!
3969
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
×
3970
    uint64_t  seqNum = syncRespMgrAdd(ths->pSyncRespMgr, &stub);
×
3971
    pEntry->seqNum = seqNum;
×
3972
  }
3973

3974
  if (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
645,989,522!
3975
    if (pRetIndex) {
645,994,786✔
3976
      (*pRetIndex) = index;
604,633,836✔
3977
    }
3978

3979
    if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE) {
645,997,707!
3980
      int32_t code = syncNodeCheckChangeConfig(ths, pEntry);
×
3981
      if (code < 0) {
×
3982
        sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to check change config since %s", ths->vgId, pMsg,
×
3983
                terrstr());
3984
        syncEntryDestroy(pEntry);
×
3985
        pEntry = NULL;
×
3986
        TAOS_RETURN(code);
×
3987
      }
3988

3989
      if (code > 0) {
×
3990
        SRpcMsg rsp = {.code = pMsg->code, .info = pMsg->info};
×
3991
        int32_t num = syncRespMgrGetAndDel(ths->pSyncRespMgr, pEntry->seqNum, &rsp.info);
×
3992
        sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, get response stub for config change, seqNum:%" PRIu64 " num:%d",
×
3993
                ths->vgId, pMsg, pEntry->seqNum, num);
3994
        if (rsp.info.handle != NULL) {
×
3995
          tmsgSendRsp(&rsp);
×
3996
        }
3997
        syncEntryDestroy(pEntry);
×
3998
        pEntry = NULL;
×
3999
        TAOS_RETURN(code);
×
4000
      }
4001
    }
4002

4003
    code = syncNodeAppend(ths, pEntry, pMsg);
645,991,436✔
4004
    return code;
645,930,126✔
4005
  } else {
4006
    syncEntryDestroy(pEntry);
×
4007
    pEntry = NULL;
×
4008
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4009
  }
4010
}
4011

4012
const char* syncStr(ESyncState state) {
132,535,389✔
4013
  switch (state) {
132,535,389!
4014
    case TAOS_SYNC_STATE_FOLLOWER:
57,839,812✔
4015
      return "follower";
57,839,812✔
4016
    case TAOS_SYNC_STATE_CANDIDATE:
1,189,901✔
4017
      return "candidate";
1,189,901✔
4018
    case TAOS_SYNC_STATE_LEADER:
66,570,629✔
4019
      return "leader";
66,570,629✔
4020
    case TAOS_SYNC_STATE_ERROR:
×
4021
      return "error";
×
4022
    case TAOS_SYNC_STATE_OFFLINE:
1,661,982✔
4023
      return "offline";
1,661,982✔
4024
    case TAOS_SYNC_STATE_LEARNER:
5,256,874✔
4025
      return "learner";
5,256,874✔
4026
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
9,800✔
4027
      return "assigned leader";
9,800✔
4028
    default:
6,391✔
4029
      return "unknown";
6,391✔
4030
  }
4031
}
4032

4033
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
494,663✔
4034
  for (int32_t i = 0; i < pNewCfg->totalReplicaNum; ++i) {
557,434!
4035
    SRaftId raftId = {
557,434✔
4036
        .addr = SYNC_ADDR(&pNewCfg->nodeInfo[i]),
557,434✔
4037
        .vgId = ths->vgId,
557,434✔
4038
    };
4039

4040
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
557,434✔
4041
      pNewCfg->myIndex = i;
494,663✔
4042
      return 0;
494,663✔
4043
    }
4044
  }
4045

4046
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4047
}
4048

4049
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
646,599,239✔
4050
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
646,599,239✔
4051
}
4052

4053
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
85,149,502✔
4054
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
164,694,771!
4055
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
164,694,671✔
4056
      return true;
85,149,296✔
4057
    }
4058
  }
4059
  return false;
×
4060
}
4061

4062
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
13,002,918✔
4063
  SSyncSnapshotSender* pSender = NULL;
13,002,918✔
4064
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
52,722,129✔
4065
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
39,721,497✔
4066
      pSender = (ths->senders)[i];
13,002,674✔
4067
    }
4068
  }
4069
  return pSender;
13,004,330✔
4070
}
4071

4072
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
12,106,985✔
4073
  SSyncTimer* pTimer = NULL;
12,106,985✔
4074
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
52,391,976✔
4075
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
40,287,240✔
4076
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
12,106,155✔
4077
    }
4078
  }
4079
  return pTimer;
12,105,319✔
4080
}
4081

4082
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
551,875✔
4083
  SPeerState* pState = NULL;
551,875✔
4084
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
1,773,531✔
4085
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
1,221,656✔
4086
      pState = &((ths->peerStates)[i]);
551,875✔
4087
    }
4088
  }
4089
  return pState;
551,875✔
4090
}
4091

4092
#ifdef BUILD_NO_CALL
4093
bool syncNodeNeedSendAppendEntries(SSyncNode* ths, const SRaftId* pDestId, const SyncAppendEntries* pMsg) {
4094
  SPeerState* pState = syncNodeGetPeerState(ths, pDestId);
4095
  if (pState == NULL) {
4096
    sError("vgId:%d, replica maybe dropped", ths->vgId);
4097
    return false;
4098
  }
4099

4100
  SyncIndex sendIndex = pMsg->prevLogIndex + 1;
4101
  int64_t   tsNow = taosGetTimestampMs();
4102

4103
  if (pState->lastSendIndex == sendIndex && tsNow - pState->lastSendTime < SYNC_APPEND_ENTRIES_TIMEOUT_MS) {
4104
    return false;
4105
  }
4106

4107
  return true;
4108
}
4109

4110
bool syncNodeCanChange(SSyncNode* pSyncNode) {
4111
  if (pSyncNode->changing) {
4112
    sError("sync cannot change");
4113
    return false;
4114
  }
4115

4116
  if ((pSyncNode->commitIndex >= SYNC_INDEX_BEGIN)) {
4117
    SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);
4118
    if (pSyncNode->commitIndex != lastIndex) {
4119
      sError("sync cannot change2");
4120
      return false;
4121
    }
4122
  }
4123

4124
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
4125
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
4126
    if (pSender != NULL && pSender->start) {
4127
      sError("sync cannot change3");
4128
      return false;
4129
    }
4130
  }
4131

4132
  return true;
4133
}
4134
#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