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

taosdata / TDengine / #4808

16 Oct 2025 11:40AM UTC coverage: 57.938% (-0.6%) from 58.524%
#4808

push

travis-ci

web-flow
fix(tref): increase TSDB_REF_OBJECTS from 100 to 2000 for improved reference handling (#33281)

137662 of 303532 branches covered (45.35%)

Branch coverage included in aggregate %.

209234 of 295200 relevant lines covered (70.88%)

4035326.15 hits per line

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

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

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

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

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

89
int32_t syncStart(int64_t rid) {
10,912✔
90
  int32_t    code = 0;
10,912✔
91
  int32_t    vgId = 0;
10,912✔
92
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
10,912✔
93
  if (pSyncNode == NULL) {
10,912!
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;
10,912✔
100
  sInfo("vgId:%d, begin to start sync", pSyncNode->vgId);
10,912✔
101

102
  if ((code = syncNodeRestore(pSyncNode)) < 0) {
10,912!
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);
10,912✔
107

108
  if ((code = syncNodeStart(pSyncNode)) < 0) {
10,912!
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);
10,912✔
113

114
  syncNodeRelease(pSyncNode);
10,912✔
115

116
  sInfo("vgId:%d, sync started", vgId);
10,912✔
117

118
  TAOS_RETURN(code);
10,912✔
119

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

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

129
  if (pSyncNode == NULL) {
13,413!
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;
13,413✔
137

138
  syncNodeRelease(pSyncNode);
13,413✔
139

140
  return 0;
13,412✔
141
}
142

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

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

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

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

177
int32_t syncReconfig(int64_t rid, SSyncCfg* pNewCfg) {
1,382✔
178
  int32_t    code = 0;
1,382✔
179
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,382✔
180
  if (pSyncNode == NULL) {
1,382!
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) {
1,382✔
187
    syncNodeRelease(pSyncNode);
126✔
188
    sInfo("vgId:%d, no need Reconfig, current index:%" PRId64 ", new index:%" PRId64, pSyncNode->vgId,
126!
189
          pSyncNode->raftCfg.lastConfigIndex, pNewCfg->lastIndex);
190
    return 0;
126✔
191
  }
192

193
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
1,256!
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));
1,256!
201

202
  if (syncNodeDoConfigChange(pSyncNode, pNewCfg, pNewCfg->lastIndex) != 0) {
1,256!
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) {
1,256!
209
    // TODO check return value
210
    TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1,068!
211

212
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
17,088✔
213
      TAOS_CHECK_RETURN(syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]));
16,020!
214
    }
215

216
    TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
1,068!
217
    // syncNodeReplicate(pSyncNode);
218
  }
219

220
  syncNodeRelease(pSyncNode);
1,256✔
221
  TAOS_RETURN(code);
1,256✔
222
}
223

224
int32_t syncProcessMsg(int64_t rid, SRpcMsg* pMsg) {
912,633✔
225
  int32_t code = -1;
912,633✔
226
  if (!syncIsInit()) {
912,633!
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);
912,635✔
233
  if (pSyncNode == NULL) {
912,645✔
234
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
7✔
235
    if (terrno != 0) code = terrno;
7!
236
    TAOS_RETURN(code);
×
237
  }
238

239
  switch (pMsg->msgType) {
912,638!
240
    case TDMT_SYNC_HEARTBEAT:
76,895✔
241
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
76,895✔
242
      break;
76,895✔
243
    case TDMT_SYNC_HEARTBEAT_REPLY:
75,938✔
244
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
75,938✔
245
      break;
75,938✔
246
    case TDMT_SYNC_TIMEOUT:
53,971✔
247
      code = syncNodeOnTimeout(pSyncNode, pMsg);
53,971✔
248
      break;
53,966✔
249
    case TDMT_SYNC_TIMEOUT_ELECTION:
1,446✔
250
      code = syncNodeOnTimeout(pSyncNode, pMsg);
1,446✔
251
      break;
1,446✔
252
    case TDMT_SYNC_CLIENT_REQUEST:
167,036✔
253
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
167,036✔
254
      break;
167,036✔
255
    case TDMT_SYNC_REQUEST_VOTE:
2,542✔
256
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
2,542✔
257
      break;
2,542✔
258
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
2,477✔
259
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
2,477✔
260
      break;
2,477✔
261
    case TDMT_SYNC_APPEND_ENTRIES:
225,450✔
262
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
225,450✔
263
      break;
225,450✔
264
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
226,633✔
265
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
226,633✔
266
      break;
226,632✔
267
    case TDMT_SYNC_SNAPSHOT_SEND:
1,730✔
268
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
1,730✔
269
      break;
1,730✔
270
    case TDMT_SYNC_SNAPSHOT_RSP:
1,730✔
271
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
1,730✔
272
      break;
1,730✔
273
    case TDMT_SYNC_LOCAL_CMD:
76,765✔
274
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
76,765✔
275
      break;
76,765✔
276
    case TDMT_SYNC_FORCE_FOLLOWER:
20✔
277
      code = syncForceBecomeFollower(pSyncNode, pMsg);
20✔
278
      break;
20✔
279
    case TDMT_SYNC_SET_ASSIGNED_LEADER:
5✔
280
      code = syncBecomeAssignedLeader(pSyncNode, pMsg);
5✔
281
      break;
5✔
282
    default:
×
283
      code = TSDB_CODE_MSG_NOT_PROCESSED;
×
284
  }
285

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

294
int32_t syncLeaderTransfer(int64_t rid) {
10,912✔
295
  int32_t    code = 0;
10,912✔
296
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
10,912✔
297
  if (pSyncNode == NULL) {
10,912!
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);
10,912✔
304
  syncNodeRelease(pSyncNode);
10,912✔
305
  return ret;
10,912✔
306
}
307

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

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

320
  return 0;
20✔
321
}
322

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

328
  SVArbSetAssignedLeaderReq req = {0};
5✔
329
  if (tDeserializeSVArbSetAssignedLeaderReq((char*)pRpcMsg->pCont + sizeof(SMsgHead), pRpcMsg->contLen, &req) != 0) {
5!
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) {
5!
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);
5✔
342

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

351
  if (ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2!
352
    code = TSDB_CODE_SUCCESS;
2✔
353
    raftStoreNextTerm(ths);
2✔
354
    if (terrno != TSDB_CODE_SUCCESS) {
2!
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);
2✔
360

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

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

371
  contLen = tSerializeSVArbSetAssignedLeaderRsp(NULL, 0, &rsp);
2✔
372
  if (contLen <= 0) {
2!
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);
2✔
378
  if (!pHead) {
2!
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) {
2!
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;
2✔
391

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

400
  tmsgSendRsp(&rspMsg);
5✔
401

402
  tFreeSVArbSetAssignedLeaderReq(&req);
5✔
403
  TAOS_RETURN(code);
5✔
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) {
80,882✔
431
  SyncIndex minMatchIndex = SYNC_INDEX_INVALID;
80,882✔
432

433
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
241,808✔
434
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
160,926✔
435
    if (minMatchIndex == SYNC_INDEX_INVALID) {
160,926✔
436
      minMatchIndex = matchIndex;
84,671✔
437
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
76,255✔
438
      minMatchIndex = matchIndex;
1,135✔
439
    }
440
  }
441
  return minMatchIndex;
80,882✔
442
}
443

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

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

458
  SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
15,829✔
459
  SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore);
15,829✔
460
  bool      isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore);
15,829✔
461

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

468
  int64_t logRetention = 0;
15,737✔
469

470
  if (syncNodeIsMnode(pSyncNode)) {
15,737✔
471
    // mnode
472
    logRetention = tsMndLogRetention;
2,417✔
473
  } else {
474
    // vnode
475
    if (pSyncNode->replicaNum > 1) {
13,321✔
476
      logRetention = SYNC_VNODE_LOG_RETENTION;
857✔
477
    }
478
  }
479

480
  if (pSyncNode->totalReplicaNum > 1) {
15,738✔
481
    if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER &&
1,293✔
482
        pSyncNode->state != TAOS_SYNC_STATE_LEARNER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
137!
483
      sNTrace(pSyncNode, "new-snapshot-index:%" PRId64 " candidate or unknown state, do not delete wal",
2!
484
              lastApplyIndex);
485
      syncNodeRelease(pSyncNode);
2✔
486
      return 0;
2✔
487
    }
488
    SyncIndex retentionIndex =
1,291✔
489
        TMAX(pSyncNode->minMatchIndex, syncLogRetentionIndex(pSyncNode, SYNC_WAL_LOG_RETENTION_SIZE));
1,291✔
490
    logRetention += TMAX(0, lastApplyIndex - retentionIndex);
1,291✔
491
  }
492

493
_DEL_WAL:
14,445✔
494

495
  do {
496
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
15,736✔
497
    SyncIndex          snapshotVer = walGetSnapshotVer(pData->pWal);
15,736✔
498
    SyncIndex          walCommitVer = walGetCommittedVer(pData->pWal);
15,735✔
499
    SyncIndex          wallastVer = walGetLastVer(pData->pWal);
15,736✔
500
    if (lastApplyIndex <= walCommitVer) {
15,736✔
501
      SyncIndex snapshottingIndex = atomic_load_64(&pSyncNode->snapshottingIndex);
15,735✔
502

503
      if (snapshottingIndex == SYNC_INDEX_INVALID) {
15,736!
504
        atomic_store_64(&pSyncNode->snapshottingIndex, lastApplyIndex);
15,736✔
505
        pSyncNode->snapshottingTime = taosGetTimestampMs();
15,736✔
506

507
        code = walBeginSnapshot(pData->pWal, lastApplyIndex, logRetention);
15,736✔
508
        if (code == 0) {
15,736!
509
          sNTrace(pSyncNode, "wal snapshot begin, index:%" PRId64 ", last apply index:%" PRId64,
15,736✔
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);
15,737✔
525
  TAOS_RETURN(code);
15,736✔
526
}
527

528
int32_t syncEndSnapshot(int64_t rid) {
15,828✔
529
  int32_t    code = 0;
15,828✔
530
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
15,828✔
531
  if (pSyncNode == NULL) {
15,830!
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) {
15,830✔
539
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
15,734✔
540
    code = walEndSnapshot(pData->pWal);
15,734✔
541
    if (code != 0) {
15,736!
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));
15,736✔
547
      atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
15,736✔
548
    }
549
  }
550

551
  syncNodeRelease(pSyncNode);
15,830✔
552
  TAOS_RETURN(code);
15,830✔
553
}
554

555
bool syncNodeIsReadyForRead(SSyncNode* pSyncNode) {
1,340,757✔
556
  if (pSyncNode == NULL) {
1,340,757!
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) {
1,340,757✔
563
    terrno = TSDB_CODE_SYN_NOT_LEADER;
164,555✔
564
    return false;
164,555✔
565
  }
566

567
  if (!pSyncNode->restoreFinish) {
1,176,202✔
568
    terrno = TSDB_CODE_SYN_RESTORING;
355✔
569
    return false;
355✔
570
  }
571

572
  return true;
1,175,847✔
573
}
574

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

582
  bool ready = syncNodeIsReadyForRead(pSyncNode);
1,094,416✔
583

584
  syncNodeRelease(pSyncNode);
1,094,468✔
585
  return ready;
1,094,406✔
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) {
10,912✔
613
  if (pSyncNode->peersNum == 0) {
10,912✔
614
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
7,042✔
615
    return 0;
7,042✔
616
  }
617

618
  int32_t ret = 0;
3,870✔
619
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && pSyncNode->replicaNum > 1) {
3,870✔
620
    SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
1,232✔
621
    if (pSyncNode->peersNum == 2) {
1,232✔
622
      SyncIndex matchIndex0 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[0]));
915✔
623
      SyncIndex matchIndex1 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[1]));
915✔
624
      if (matchIndex1 > matchIndex0) {
915✔
625
        newLeader = (pSyncNode->peersNodeInfo)[1];
9✔
626
      }
627
    }
628
    ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
1,232✔
629
  }
630

631
  return ret;
3,870✔
632
}
633

634
int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader) {
1,232✔
635
  if (pSyncNode->replicaNum == 1) {
1,232!
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);
1,232!
641

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

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

650
  int32_t ret = syncNodePropose(pSyncNode, &rpcMsg, false, NULL);
1,232✔
651
  rpcFreeCont(rpcMsg.pCont);
1,232✔
652
  return ret;
1,232✔
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) {
1,543,208✔
676
  SSyncState state = {.state = TAOS_SYNC_STATE_ERROR};
1,543,208✔
677

678
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,543,208✔
679
  if (pSyncNode != NULL) {
1,543,545✔
680
    state.state = pSyncNode->state;
1,543,494✔
681
    state.roleTimeMs = pSyncNode->roleTimeMs;
1,543,494✔
682
    state.startTimeMs = pSyncNode->startTime;
1,543,494✔
683
    state.restored = pSyncNode->restoreFinish;
1,543,494✔
684
    if (pSyncNode->vgId != 1) {
1,543,494✔
685
      state.canRead = syncNodeIsReadyForRead(pSyncNode);
246,526✔
686
    } else {
687
      state.canRead = state.restored;
1,296,968✔
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);
1,543,494✔
704
    syncNodeRelease(pSyncNode);
1,543,573✔
705
  }
706

707
  return state;
1,543,575✔
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) {
236,805✔
737
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
236,805✔
738
  if (pSyncNode != NULL) {
236,805!
739
    *syncCommitIndex = pSyncNode->commitIndex;
236,805✔
740
    syncNodeRelease(pSyncNode);
236,805✔
741
  }
742
}
236,805✔
743

744
int32_t syncGetArbToken(int64_t rid, char* outToken) {
33,236✔
745
  int32_t    code = 0;
33,236✔
746
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
33,236✔
747
  if (pSyncNode == NULL) {
33,236!
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);
33,236✔
754
  (void)taosThreadMutexLock(&pSyncNode->arbTokenMutex);
33,236✔
755
  tstrncpy(outToken, pSyncNode->arbToken, TSDB_ARB_TOKEN_SIZE);
33,236✔
756
  (void)taosThreadMutexUnlock(&pSyncNode->arbTokenMutex);
33,236✔
757

758
  syncNodeRelease(pSyncNode);
33,236✔
759
  TAOS_RETURN(code);
33,236✔
760
}
761

762
int32_t syncCheckSynced(int64_t rid) {
9✔
763
  int32_t    code = 0;
9✔
764
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
9✔
765
  if (pSyncNode == NULL) {
9!
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) {
9!
772
    code = TSDB_CODE_SYN_NOT_LEADER;
×
773
    syncNodeRelease(pSyncNode);
×
774
    TAOS_RETURN(code);
×
775
  }
776

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

784
  syncNodeRelease(pSyncNode);
9✔
785
  TAOS_RETURN(code);
9✔
786
}
787

788
int32_t syncUpdateArbTerm(int64_t rid, SyncTerm arbTerm) {
270✔
789
  int32_t    code = 0;
270✔
790
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
270✔
791
  if (pSyncNode == NULL) {
270!
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);
270✔
798
  syncNodeRelease(pSyncNode);
270✔
799
  TAOS_RETURN(code);
270✔
800
}
801

802
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
520,389✔
803
  if (pSyncNode->raftCfg.configIndexCount < 1) {
520,389!
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];
520,389✔
810

811
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
1,085,378✔
812
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
564,989✔
813
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
44,600✔
814
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
44,457✔
815
    }
816
  }
817
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
520,389✔
818
         lastIndex);
819

820
  return lastIndex;
520,389✔
821
}
822

823
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
405,390✔
824
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
771,405✔
825
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
607,709✔
826
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
607,698✔
827
      return pSyncNode->peersId[i];
241,694✔
828
    }
829
  }
830
  return EMPTY_RAFT_ID;
163,696✔
831
}
832

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

839
  size_t offset = 0;
163,796✔
840
  offset += snprintf(buffer + offset, bufferSize - offset, "EpSet: [");
163,796✔
841

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

848
  if (offset < bufferSize) {
163,796✔
849
    snprintf(buffer + offset, bufferSize - offset, "]");
163,794✔
850
  }
851
}
852

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

856
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
163,790✔
857
  if (pSyncNode == NULL) return;
163,797!
858

859
  int index = -1;
163,797✔
860

861
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
163,797✔
862
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
863
  int j = 0;
163,797✔
864
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
570,829✔
865
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
407,028✔
866
    SEp* pEp = &pEpSet->eps[j];
405,395✔
867
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
405,395✔
868
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
405,395✔
869
    pEpSet->numOfEps++;
405,395✔
870
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
405,395✔
871
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
405,394✔
872
           pEp->port);
873
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
405,399✔
874
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
134,131✔
875
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
876
      index = j;
134,129✔
877
    }
878
    j++;
405,399✔
879
  }
880
  if (pEpSet->numOfEps > 0) {
163,801✔
881
    if (index != -1) {
163,795✔
882
      pEpSet->inUse = index;
134,131✔
883
    } else {
884
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
29,664!
885
          pSyncNode->myRaftId.vgId == pSyncNode->leaderCache.vgId) {
×
886
        pEpSet->inUse = pSyncNode->raftCfg.cfg.myIndex;
×
887
      } else {
888
        pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
29,664✔
889
      }
890
    }
891
    // pEpSet->inUse = 0;
892
  }
893
  epsetSort(pEpSet);
163,801✔
894

895
  char buffer[1024];
896
  epsetToString(pEpSet, buffer, sizeof(buffer));
163,797✔
897
  sDebug("vgId:%d, sync get retry epset numOfEps:%d %s inUse:%d", pSyncNode->vgId, pEpSet->numOfEps, buffer,
163,793✔
898
         pEpSet->inUse);
899
  syncNodeRelease(pSyncNode);
163,793✔
900
}
901

902
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
1,437,297✔
903
  int32_t    code = 0;
1,437,297✔
904
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,437,297✔
905
  if (pSyncNode == NULL) {
1,437,300!
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);
1,437,300✔
913
  syncNodeRelease(pSyncNode);
1,437,220✔
914
  return ret;
1,437,270✔
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) {
4,665✔
937
  int32_t    code = 0;
4,665✔
938
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,665✔
939
  if (pSyncNode == NULL) {
4,665!
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;
4,665✔
947
  if (pSyncNode->pLogBuf->totalIndex < 0 || pSyncNode->pLogBuf->commitIndex < 0 ||
4,665!
948
      pSyncNode->pLogBuf->totalIndex < pSyncNode->pLogBuf->commitIndex ||
697!
949
      pSyncNode->pLogBuf->totalIndex - pSyncNode->pLogBuf->commitIndex > SYNC_LEARNER_CATCHUP) {
697✔
950
    sInfo("vgId:%d, Not catch up, wait one second, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64,
4,379!
951
          pSyncNode->vgId, pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex,
952
          pSyncNode->pLogBuf->matchIndex);
953
    isCatchUp = 0;
4,379✔
954
  } else {
955
    sInfo("vgId:%d, Catch up, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64, pSyncNode->vgId,
286!
956
          pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->matchIndex);
957
    isCatchUp = 1;
286✔
958
  }
959

960
  syncNodeRelease(pSyncNode);
4,665✔
961
  return isCatchUp;
4,665✔
962
}
963

964
ESyncRole syncGetRole(int64_t rid) {
4,665✔
965
  int32_t    code = 0;
4,665✔
966
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,665✔
967
  if (pSyncNode == NULL) {
4,665!
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;
4,665✔
975

976
  syncNodeRelease(pSyncNode);
4,665✔
977
  return role;
4,665✔
978
}
979

980
int64_t syncGetTerm(int64_t rid) {
13,255✔
981
  int32_t    code = 0;
13,255✔
982
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
13,255✔
983
  if (pSyncNode == NULL) {
13,255!
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);
13,255✔
991

992
  syncNodeRelease(pSyncNode);
13,255✔
993
  return term;
13,255✔
994
}
995

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

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

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

1019
  // optimized one replica
1020
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
1,435,069✔
1021
    SyncIndex retIndex;
1022
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
1,266,475✔
1023
    if (code >= 0) {
1,266,393!
1024
      pMsg->info.conn.applyIndex = retIndex;
1,266,400✔
1025
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
1,266,400✔
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) {
1,266,449!
1030
        sGDebug(&pMsg->info.traceId, "vgId:%d, index:%" PRId64 ", propose optimized msg type:%s", pSyncNode->vgId,
1,266,449!
1031
                retIndex, TMSG_INFO(pMsg->msgType));
1032
        return 1;
1,266,416✔
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};
168,599✔
1047
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
168,600✔
1048
    SRpcMsg   rpcMsg = {.info.traceId = pMsg->info.traceId};
168,600✔
1049
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
168,600✔
1050
    if (code != 0) {
168,599!
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,
168,599!
1057
            TMSG_INFO(pMsg->msgType));
1058
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
168,599✔
1059
    if (code != 0) {
168,599✔
1060
      sWarn("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
1,563!
1061
      TAOS_CHECK_RETURN(syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum));
1,564✔
1062
    }
1063

1064
    if (seq != NULL) *seq = seqNum;
168,599✔
1065
    TAOS_RETURN(code);
168,599✔
1066
  }
1067
}
1068

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

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

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

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

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

1104
    bool stopped = taosTmrResetPriority(pSyncTimer->timerCb, pSyncTimer->timerMS, (void*)(pData->rid),
2,886✔
1105
                                        syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
2,886✔
1106
    if (stopped) {
2,886✔
1107
      sWarn("vgId:%d, reset hb timer stopped:%d", pSyncNode->vgId, stopped);
1!
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;
2,886✔
1114
}
1115

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

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

1145
  SyncIndex commitIndex = snapshot.lastApplyIndex;
10,912✔
1146
  SyncIndex firstVer = pNode->pLogStore->syncLogBeginIndex(pNode->pLogStore);
10,912✔
1147
  SyncIndex lastVer = pNode->pLogStore->syncLogLastIndex(pNode->pLogStore);
10,912✔
1148
  if ((lastVer < commitIndex || firstVer > commitIndex + 1) || pNode->fsmState == SYNC_FSM_STATE_INCOMPLETE) {
10,912!
1149
    sInfo("vgId:%d, restore log store from snapshot, firstVer:%" PRId64 ", lastVer:%" PRId64 ", commitIndex:%" PRId64,
×
1150
          pNode->vgId, firstVer, lastVer, commitIndex);
1151
    if ((code = pNode->pLogStore->syncLogRestoreFromSnapshot(pNode->pLogStore, commitIndex)) != 0) {
×
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);
10,912✔
1158
}
1159

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

1169
  if (!taosDirExist((char*)(pSyncInfo->path))) {
10,912✔
1170
    if (taosMkDir(pSyncInfo->path) != 0) {
7,895!
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));
10,909✔
1178
  snprintf(pSyncNode->raftStorePath, sizeof(pSyncNode->raftStorePath), "%s%sraft_store.json", pSyncInfo->path,
10,909✔
1179
           TD_DIRSEP);
1180
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
10,909✔
1181

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

1195
    if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
7,894!
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) {
3,017!
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) {
3,017✔
1209
      if (pSyncInfo->syncCfg.totalReplicaNum > 0 && syncIsConfigChanged(&pSyncNode->raftCfg.cfg, &pSyncInfo->syncCfg)) {
1,830!
1210
        sInfo("vgId:%d, use sync config from input options and write to cfg file", pSyncNode->vgId);
1,560!
1211
        pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
1,560✔
1212
        if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
1,560!
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);
270!
1219
        pSyncInfo->syncCfg = pSyncNode->raftCfg.cfg;
270✔
1220
      }
1221
    } else {
1222
      sInfo("vgId:%d, skip save sync cfg file since request ver:%d <= file ver:%d", pSyncNode->vgId, vnodeVersion,
1,187!
1223
            pSyncInfo->syncCfg.changeVersion);
1224
    }
1225
  }
1226

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

1243
  if (vnodeVersion > pSyncInfo->syncCfg.changeVersion) {
10,912✔
1244
    if (updated) {
1,337!
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;
10,912✔
1255
  pSyncNode->msgcb = pSyncInfo->msgcb;
10,912✔
1256
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
10,912✔
1257
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
10,912✔
1258
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
10,912✔
1259

1260
  // create raft log ring buffer
1261
  code = syncLogBufferCreate(&pSyncNode->pLogBuf);
10,912✔
1262
  if (pSyncNode->pLogBuf == NULL) {
10,911!
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;
10,911✔
1269
  pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
10,911✔
1270
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
29,474✔
1271
    if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
18,562!
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];
10,912✔
1280
  pSyncNode->myRaftId = pSyncNode->replicasId[pSyncNode->raftCfg.cfg.myIndex];
10,912✔
1281

1282
  // init peersNum, peers, peersId
1283
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
10,912✔
1284
  int32_t j = 0;
10,912✔
1285
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
29,475✔
1286
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
18,563✔
1287
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
7,651✔
1288
      pSyncNode->peersId[j] = pSyncNode->replicasId[i];
7,651✔
1289
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
7,651✔
1290
      j++;
7,651✔
1291
    }
1292
  }
1293

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

1299
  // init raft algorithm
1300
  pSyncNode->pFsm = pSyncInfo->pFsm;
10,912✔
1301
  pSyncInfo->pFsm = NULL;
10,912✔
1302
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
10,912✔
1303
  pSyncNode->leaderCache = EMPTY_RAFT_ID;
10,912✔
1304
  pSyncNode->leaderCacheEp.port = 0;
10,912✔
1305
  pSyncNode->leaderCacheEp.fqdn[0] = '\0';
10,912✔
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;
10,912✔
1335
  pSyncNode->roleTimeMs = taosGetTimestampMs();
10,912✔
1336
  if ((code = raftStoreOpen(pSyncNode)) != 0) {
10,912!
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);
10,912✔
1344
  if (pSyncNode->pVotesGranted == NULL) {
10,912!
1345
    sError("vgId:%d, failed to create VotesGranted", pSyncNode->vgId);
×
1346
    goto _error;
×
1347
  }
1348
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
10,912✔
1349
  if (pSyncNode->pVotesRespond == NULL) {
10,912!
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);
10,912✔
1356
  if (pSyncNode->pNextIndex == NULL) {
10,912!
1357
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
×
1358
    goto _error;
×
1359
  }
1360
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
10,912✔
1361
  if (pSyncNode->pMatchIndex == NULL) {
10,912!
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);
10,912✔
1368
  if (pSyncNode->pLogStore == NULL) {
10,909!
1369
    sError("vgId:%d, failed to create SyncLogStore", pSyncNode->vgId);
×
1370
    goto _error;
×
1371
  }
1372

1373
  SyncIndex commitIndex = SYNC_INDEX_INVALID;
10,909✔
1374
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
10,909!
1375
    SSnapshot snapshot = {0};
10,912✔
1376
    // TODO check return value
1377
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
10,912✔
1378
    if (snapshot.lastApplyIndex > commitIndex) {
10,912✔
1379
      commitIndex = snapshot.lastApplyIndex;
1,404✔
1380
      sNTrace(pSyncNode, "reset commit index by snapshot");
1,404✔
1381
    }
1382
    pSyncNode->fsmState = snapshot.state;
10,912✔
1383
    if (pSyncNode->fsmState == SYNC_FSM_STATE_INCOMPLETE) {
10,912!
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;
10,909✔
1392
  sInfo("vgId:%d, sync node commitIndex initialized as %" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
10,909✔
1393

1394
  // restore log store on need
1395
  if ((code = syncNodeLogStoreRestoreOnNeed(pSyncNode)) < 0) {
10,909!
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;
10,912✔
1403
  pSyncNode->electBaseLine = electInterval;
10,912✔
1404
  pSyncNode->hbBaseLine = heartbeatInterval;
10,912✔
1405

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

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

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

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

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

1449
  // restore state
1450
  pSyncNode->restoreFinish = false;
10,912✔
1451

1452
  // snapshot senders
1453
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
174,496✔
1454
    SSyncSnapshotSender* pSender = NULL;
163,591✔
1455
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
163,591✔
1456
    if (pSender == NULL) return NULL;
163,588!
1457

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

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

1468
  // is config changing
1469
  pSyncNode->changing = false;
10,911✔
1470

1471
  // replication mgr
1472
  if ((code = syncNodeLogReplInit(pSyncNode)) < 0) {
10,911!
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) {
10,912!
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;
10,912✔
1488

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

1492
  int64_t timeNow = taosGetTimestampMs();
10,912✔
1493
  pSyncNode->startTime = timeNow;
10,912✔
1494
  pSyncNode->lastReplicateTime = timeNow;
10,912✔
1495

1496
  // snapshotting
1497
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
10,912✔
1498

1499
  // init log buffer
1500
  if ((code = syncLogBufferInit(pSyncNode->pLogBuf, pSyncNode)) < 0) {
10,912!
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;
10,912✔
1507
  pSyncNode->electNum = 0;
10,912✔
1508
  pSyncNode->becomeLeaderNum = 0;
10,912✔
1509
  pSyncNode->becomeAssignedLeaderNum = 0;
10,912✔
1510
  pSyncNode->configChangeNum = 0;
10,912✔
1511
  pSyncNode->hbSlowNum = 0;
10,912✔
1512
  pSyncNode->hbrSlowNum = 0;
10,912✔
1513
  pSyncNode->tmrRoutineNum = 0;
10,912✔
1514

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

1519
_error:
×
1520
  if (pSyncInfo->pFsm) {
×
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) {
10,912✔
1542
  int32_t code = 0;
10,912✔
1543
  if (pSyncNode->pLogStore == NULL) {
10,912!
1544
    sError("vgId:%d, log store not created", pSyncNode->vgId);
×
1545
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1546
  }
1547
  if (pSyncNode->pLogBuf == NULL) {
10,912!
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);
10,912✔
1553
  SyncIndex lastVer = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
10,912✔
1554
  SyncIndex commitIndex = pSyncNode->pLogStore->syncLogCommitIndex(pSyncNode->pLogStore);
10,912✔
1555
  SyncIndex endIndex = pSyncNode->pLogBuf->endIndex;
10,912✔
1556
  (void)taosThreadMutexUnlock(&pSyncNode->pLogBuf->mutex);
10,912✔
1557

1558
  if (lastVer != -1 && endIndex != lastVer + 1) {
10,912!
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);
10,912✔
1567
  sInfo("vgId:%d, restore began, and keep syncing until commitIndex:%" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
10,912✔
1568

1569
  if (pSyncNode->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
21,824!
1570
      (code = syncLogBufferCommit(pSyncNode->pLogBuf, pSyncNode, pSyncNode->commitIndex, NULL, "restore")) < 0) {
10,912✔
1571
    TAOS_RETURN(code);
×
1572
  }
1573

1574
  TAOS_RETURN(code);
10,912✔
1575
}
1576

1577
int32_t syncNodeStart(SSyncNode* pSyncNode) {
10,912✔
1578
  // start raft
1579
  sInfo("vgId:%d, begin to start sync node", pSyncNode->vgId);
10,912✔
1580
  if (pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
10,912✔
1581
    syncNodeBecomeLearner(pSyncNode, "first start");
293✔
1582
  } else {
1583
    if (pSyncNode->replicaNum == 1) {
10,619✔
1584
      raftStoreNextTerm(pSyncNode);
7,208✔
1585
      syncNodeBecomeLeader(pSyncNode, "one replica start");
7,208✔
1586

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

1595
  int32_t ret = 0;
10,912✔
1596
  ret = syncNodeStartPingTimer(pSyncNode);
10,912✔
1597
  if (ret != 0) {
10,912!
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);
10,912✔
1601
  return ret;
10,912✔
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) {
10,912✔
1631
  int32_t code = 0;
10,912✔
1632
  if (pSyncNode == NULL) {
10,912!
1633
    sError("failed to pre close sync node since sync node is null");
×
1634
    return;
×
1635
  }
1636
  if (pSyncNode->pFsm == NULL) {
10,912!
1637
    sError("failed to pre close sync node since fsm is null");
×
1638
    return;
×
1639
  }
1640
  if (pSyncNode->pFsm->FpApplyQueueItems == NULL) {
10,912!
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) {
10,912!
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) {
10,912!
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) {
10,912!
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);
10,912✔
1665
}
1666

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

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

1680
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }
2,882!
1681

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

1687
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
10,855✔
1688

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

1703
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
10,854✔
1704
  pSyncNode->pSyncRespMgr = NULL;
10,853✔
1705
  voteGrantedDestroy(pSyncNode->pVotesGranted);
10,853✔
1706
  pSyncNode->pVotesGranted = NULL;
10,855✔
1707
  votesRespondDestory(pSyncNode->pVotesRespond);
10,855✔
1708
  pSyncNode->pVotesRespond = NULL;
10,855✔
1709
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
10,855✔
1710
  pSyncNode->pNextIndex = NULL;
10,851✔
1711
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
10,851✔
1712
  pSyncNode->pMatchIndex = NULL;
10,852✔
1713
  logStoreDestory(pSyncNode->pLogStore);
10,852✔
1714
  pSyncNode->pLogStore = NULL;
10,855✔
1715
  syncLogBufferDestroy(pSyncNode->pLogBuf);
10,855✔
1716
  pSyncNode->pLogBuf = NULL;
10,855✔
1717

1718
  (void)taosThreadMutexDestroy(&pSyncNode->arbTokenMutex);
10,855✔
1719

1720
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
173,636✔
1721
    if (pSyncNode->senders[i] != NULL) {
162,781✔
1722
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", pSyncNode->vgId, pSyncNode->senders[i]);
162,780✔
1723

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

1728
      snapshotSenderDestroy(pSyncNode->senders[i]);
162,796✔
1729
      pSyncNode->senders[i] = NULL;
162,776✔
1730
    }
1731
  }
1732

1733
  if (pSyncNode->pNewNodeReceiver != NULL) {
10,855✔
1734
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
1,337!
1735
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1736
    }
1737

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

1743
  if (pSyncNode->pFsm != NULL) {
10,855✔
1744
    taosMemoryFree(pSyncNode->pFsm);
10,854!
1745
  }
1746

1747
  raftStoreClose(pSyncNode);
10,855✔
1748

1749
  taosMemoryFree(pSyncNode);
10,855!
1750
}
1751

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

1754
// timer control --------------
1755
int32_t syncNodeStartPingTimer(SSyncNode* pSyncNode) {
10,912✔
1756
  int32_t code = 0;
10,912✔
1757
  if (syncIsInit()) {
10,912!
1758
    bool stopped = taosTmrResetPriority(pSyncNode->FpPingTimerCB, pSyncNode->pingTimerMS, (void*)pSyncNode->rid,
10,912✔
1759
                                        syncEnv()->pTimerManager, &pSyncNode->pPingTimer, 2);
10,912✔
1760
    if (stopped) {
10,912!
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);
10,912✔
1765
  } else {
1766
    sError("vgId:%d, start ping timer error, sync env is stop", pSyncNode->vgId);
×
1767
  }
1768
  return code;
10,912✔
1769
}
1770

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

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

1785
    int64_t execTime = taosGetTimestampMs() + ms;
290,417✔
1786
    atomic_store_64(&(pSyncNode->electTimerParam.executeTime), execTime);
290,417✔
1787
    atomic_store_64(&(pSyncNode->electTimerParam.logicClock), pSyncNode->electTimerLogicClock);
290,418✔
1788
    pSyncNode->electTimerParam.pSyncNode = pSyncNode;
290,418✔
1789
    pSyncNode->electTimerParam.pData = NULL;
290,418✔
1790

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

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

1807
  return code;
320,632✔
1808
}
1809

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

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

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

1827
  if ((code = syncNodeRestartElectTimer(pSyncNode, electMS)) != 0) {
290,418!
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,
290,418!
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) {
9,515✔
1853
  int32_t ret = 0;
9,515✔
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) {
12,401✔
1861
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
2,886✔
1862
    if (pSyncTimer != NULL) {
2,886!
1863
      TAOS_CHECK_RETURN(syncHbTimerStart(pSyncNode, pSyncTimer));
2,886!
1864
    }
1865
  }
1866

1867
  return ret;
9,515✔
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) {
28,816✔
1884
  int32_t code = 0;
28,816✔
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) {
56,886✔
1894
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
28,070✔
1895
    if (pSyncTimer != NULL) {
28,070!
1896
      TAOS_CHECK_RETURN(syncHbTimerStop(pSyncNode, pSyncTimer));
28,070!
1897
    }
1898
  }
1899

1900
  return code;
28,816✔
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) {
621,107✔
1916
  SEpSet* epSet = NULL;
621,107✔
1917
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
920,229✔
1918
    if (destRaftId->addr == pNode->peersId[i].addr) {
919,959✔
1919
      epSet = &pNode->peersEpset[i];
620,837✔
1920
      break;
620,837✔
1921
    }
1922
  }
1923

1924
  int32_t code = -1;
621,107✔
1925
  if (pNode->syncSendMSg != NULL && epSet != NULL) {
621,107!
1926
    syncUtilMsgHtoN(pMsg->pCont);
620,837✔
1927
    pMsg->info.noResp = 1;
620,837✔
1928
    code = pNode->syncSendMSg(epSet, pMsg);
620,837✔
1929
  }
1930

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

1937
  TAOS_RETURN(code);
621,119✔
1938
}
1939

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

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

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

1958
    if (syncUtilSameId(&raftId, &pNode->myRaftId)) {
2,264✔
1959
      b2 = true;
1,816✔
1960
      break;
1,816✔
1961
    }
1962
  }
1963

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

1971
static bool syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg) {
2,816✔
1972
  if (pOldCfg->totalReplicaNum != pNewCfg->totalReplicaNum) return true;
2,816✔
1973
  if (pOldCfg->myIndex != pNewCfg->myIndex) return true;
1,716✔
1974
  for (int32_t i = 0; i < pOldCfg->totalReplicaNum; ++i) {
4,272✔
1975
    const SNodeInfo* pOldInfo = &pOldCfg->nodeInfo[i];
3,296✔
1976
    const SNodeInfo* pNewInfo = &pNewCfg->nodeInfo[i];
3,296✔
1977
    if (strcmp(pOldInfo->nodeFqdn, pNewInfo->nodeFqdn) != 0) return true;
3,296!
1978
    if (pOldInfo->nodePort != pNewInfo->nodePort) return true;
3,296!
1979
    if (pOldInfo->nodeRole != pNewInfo->nodeRole) return true;
3,296✔
1980
  }
1981

1982
  return false;
976✔
1983
}
1984

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

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

1996
  pSyncNode->configChangeNum++;
280✔
1997

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

2001
  bool isDrop = false;
280✔
2002
  bool isAdd = false;
280✔
2003

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

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

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

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

2028
  // add last config index
2029
  SRaftCfg* pCfg = &pSyncNode->raftCfg;
280✔
2030
  if (pCfg->configIndexCount >= MAX_CONFIG_INDEX_COUNT) {
280!
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;
280✔
2037
  pCfg->configIndexCount++;
280✔
2038

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

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

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

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

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

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

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

2088
    // reset snapshot senders
2089

2090
    // clear new
2091
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
4,480✔
2092
      pSyncNode->senders[i] = NULL;
4,200✔
2093
    }
2094

2095
    // reset new
2096
    for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
1,018✔
2097
      // reset sender
2098
      bool reset = false;
738✔
2099
      for (int32_t j = 0; j < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++j) {
3,173✔
2100
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
3,039!
2101
          sNTrace(pSyncNode, "snapshot sender reset for:%" PRId64 ", newIndex:%d, dnode:%d, %p",
604!
2102
                  (pSyncNode->replicasId)[i].addr, i, DID(&pSyncNode->replicasId[i]), oldSenders[j]);
2103

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

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

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

2115
          break;
604✔
2116
        }
2117
      }
2118
    }
2119

2120
    // create new
2121
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
4,480✔
2122
      if (pSyncNode->senders[i] == NULL) {
4,200✔
2123
        TAOS_CHECK_RETURN(snapshotSenderCreate(pSyncNode, i, &pSyncNode->senders[i]));
3,596!
2124
        if (pSyncNode->senders[i] == NULL) {
3,596!
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]);
3,596!
2129
        }
2130
      } else {
2131
        sSDebug(pSyncNode->senders[i], "snapshot sender already exist, data:%p", pSyncNode->senders[i]);
604!
2132
      }
2133
    }
2134

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

2144
    // persist cfg
2145
    TAOS_CHECK_RETURN(syncWriteCfgFile(pSyncNode));
280!
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);
280!
2155
  return 0;
280✔
2156
}
2157

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

2165
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm, SRaftId id, char* strFrom) {
206,872✔
2166
  SyncTerm currentTerm = raftStoreGetTerm(pSyncNode);
206,872✔
2167
  if (currentTerm > newTerm) {
206,872!
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);
206,872!
2174
  } while (0);
2175

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

2184
  if (currentTerm < newTerm) {
206,872✔
2185
    raftStoreSetTerm(pSyncNode, newTerm);
2,545✔
2186
    char tmpBuf[64];
2187
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64 " from %" PRId64 ", since %s", newTerm,
2,545✔
2188
             currentTerm, strFrom);
2189
    syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
2,545✔
2190
    raftStoreClearVote(pSyncNode);
2,545✔
2191
  } else {
2192
    if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
204,327✔
2193
      char tmpBuf[64];
2194
      snprintf(tmpBuf, sizeof(tmpBuf), "step down, with same term to %" PRId64 " from %" PRId64 ", since %s", newTerm, 
5✔
2195
               currentTerm, strFrom);
2196
      syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
5✔
2197
    }
2198
  }
2199
}
2200

2201
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }
5,981✔
2202

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

2211
  pSyncNode->hbSlowNum = 0;
5,981✔
2212

2213
  pSyncNode->leaderCache = leaderId;  // state change
5,981✔
2214

2215
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
18,963✔
2216
    if (syncUtilSameId(&pSyncNode->replicasId[i], &leaderId)) {
15,532✔
2217
      pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[i].nodePort;
2,550✔
2218
      strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
2,550✔
2219
      break;
2,550✔
2220
    }
2221
  }
2222
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
5,981✔
2223
  pSyncNode->roleTimeMs = taosGetTimestampMs();
5,981✔
2224
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
5,981!
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);
5,981!
2231

2232
  // send rsp to client
2233
  syncNodeLeaderChangeRsp(pSyncNode);
5,981✔
2234

2235
  // call back
2236
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
5,981!
2237
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
5,981✔
2238
  }
2239

2240
  // min match index
2241
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
5,981✔
2242

2243
  // reset log buffer
2244
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
5,981!
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);
5,981✔
2251

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

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

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

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

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

2270
  // min match index
2271
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
293✔
2272

2273
  // reset log buffer
2274
  int32_t code = 0;
293✔
2275
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
293!
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) {
8,445✔
2300
  int32_t code = 0;
8,445✔
2301
  pSyncNode->becomeLeaderNum++;
8,445✔
2302
  pSyncNode->hbrSlowNum = 0;
8,445✔
2303

2304
  // reset restoreFinish
2305
  pSyncNode->restoreFinish = false;
8,445✔
2306

2307
  // state change
2308
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
8,445✔
2309
  pSyncNode->roleTimeMs = taosGetTimestampMs();
8,445✔
2310

2311
  // set leader cache
2312
  pSyncNode->leaderCache = pSyncNode->myRaftId;
8,445✔
2313
  strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeFqdn,
8,445✔
2314
          TSDB_FQDN_LEN);
2315
  pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodePort;
8,445✔
2316

2317
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
19,301✔
2318
    SyncIndex lastIndex;
2319
    SyncTerm  lastTerm;
2320
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
10,856✔
2321
    if (code != 0) {
10,856!
2322
      sError("vgId:%d, failed to become leader since %s", pSyncNode->vgId, tstrerror(code));
×
2323
      return;
×
2324
    }
2325
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
10,856✔
2326
  }
2327

2328
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
19,301✔
2329
    // maybe overwrite myself, no harm
2330
    // just do it!
2331
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
10,856✔
2332
  }
2333

2334
  // init peer mgr
2335
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
8,445!
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)) {
8,445!
2355
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2356
  }
2357

2358
  // stop elect timer
2359
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
8,445!
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) {
8,445!
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) {
8,445!
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) {
8,445!
2378
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
8,445✔
2379
  }
2380

2381
  // min match index
2382
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
8,445✔
2383

2384
  // reset log buffer
2385
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
8,445!
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);
8,445✔
2392
}
2393

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

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

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

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

2409
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
6✔
2410
    SyncIndex lastIndex;
2411
    SyncTerm  lastTerm;
2412
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
4✔
2413
    if (code != 0) {
4!
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;
4✔
2418
  }
2419

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

2426
  // init peer mgr
2427
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
2!
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)) {
2!
2434
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2435
  }
2436

2437
  // stop elect timer
2438
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
2!
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) {
2!
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) {
2!
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) {
2!
2457
    pSyncNode->pFsm->FpBecomeAssignedLeaderCb(pSyncNode->pFsm);
2✔
2458
  }
2459

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

2463
  // reset log buffer
2464
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
2!
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");
2!
2471
}
2472

2473
void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
1,237✔
2474
  if (pSyncNode->state != TAOS_SYNC_STATE_CANDIDATE) {
1,237!
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);
1,237✔
2479
  if (!granted) {
1,237!
2480
    sError("vgId:%d, not granted by majority.", pSyncNode->vgId);
×
2481
    return;
×
2482
  }
2483
  syncNodeBecomeLeader(pSyncNode, "from candidate to leader");
1,237✔
2484

2485
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
1,237!
2486

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

2492
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,237✔
2493

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

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

2500
int32_t syncSetElectBaseline(int64_t rid, int32_t ms){
120✔
2501
  int32_t code = 0;
120✔
2502
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
120✔
2503
  if (pSyncNode == NULL) {
120!
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;
120✔
2510
  syncNodeResetElectTimer(pSyncNode);
120✔
2511
  return code;
120✔
2512
}
2513

2514
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
19,357✔
2515
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
309,734✔
2516
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
290,377✔
2517
    pSyncNode->peerStates[i].lastSendTime = 0;
290,377✔
2518
  }
2519

2520
  return 0;
19,357✔
2521
}
2522

2523
void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
1,352✔
2524
  if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
1,352!
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;
1,352✔
2529
  pSyncNode->roleTimeMs = taosGetTimestampMs();
1,352✔
2530
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,352✔
2531
  sInfo("vgId:%d, become candidate from follower. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64,
1,352!
2532
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2533

2534
  sNTrace(pSyncNode, "follower to candidate");
1,352!
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) {
1,433✔
2558
  SyncTerm storeTerm = raftStoreGetTerm(pSyncNode);
1,433✔
2559
  if (term != storeTerm) {
1,433!
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);
1,433!
2564
  bool voted = raftStoreHasVoted(pSyncNode);
1,433✔
2565
  if (voted) {
1,433!
2566
    sError("vgId:%d, failed to vote for term since not voted", pSyncNode->vgId);
×
2567
    return;
×
2568
  }
2569

2570
  raftStoreVote(pSyncNode, pRaftId);
1,433✔
2571
}
2572

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

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

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

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

2592
// return if has a snapshot
2593
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
16,103✔
2594
  bool      ret = false;
16,103✔
2595
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
16,103✔
2596
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
16,103!
2597
    // TODO check return value
2598
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
16,103✔
2599
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
16,103✔
2600
      ret = true;
2,491✔
2601
    }
2602
  }
2603
  return ret;
16,103✔
2604
}
2605

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

2616
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
16,171✔
2617
  return lastIndex;
16,171✔
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) {
16,103✔
2623
  SyncTerm lastTerm = 0;
16,103✔
2624
  if (syncNodeHasSnapshot(pSyncNode)) {
16,103✔
2625
    // has snapshot
2626
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2,491✔
2627
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2,491!
2628
      // TODO check return value
2629
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2,491✔
2630
    }
2631

2632
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
2,491✔
2633
    if (logLastIndex > snapshot.lastApplyIndex) {
2,491✔
2634
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1,498✔
2635
    } else {
2636
      lastTerm = snapshot.lastApplyTerm;
993✔
2637
    }
2638

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

2644
  return lastTerm;
16,103✔
2645
}
2646

2647
// get last index and term along with snapshot
2648
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
13,561✔
2649
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
13,561✔
2650
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
13,561✔
2651
  return 0;
13,561✔
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) {
53,981✔
2746
  if (!syncIsInit()) return;
53,981!
2747

2748
  int64_t    rid = (int64_t)param;
53,981✔
2749
  SSyncNode* pNode = syncNodeAcquire(rid);
53,981✔
2750

2751
  if (pNode == NULL) return;
53,981!
2752

2753
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
53,981!
2754
    SRpcMsg rpcMsg = {0};
53,981✔
2755
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
53,981✔
2756
                                    pNode->pingTimerMS, pNode);
2757
    if (code != 0) {
53,981!
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);
53,981✔
2765
    if (code != 0) {
53,981!
2766
      sError("failed to sync enqueue ping msg since %s", terrstr());
×
2767
      rpcFreeCont(rpcMsg.pCont);
×
2768
      goto _out;
×
2769
    }
2770

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

2779
static void syncNodeEqElectTimer(void* param, void* tmrId) {
1,450✔
2780
  if (!syncIsInit()) return;
1,454!
2781

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

2785
  if (pNode == NULL) return;
1,450✔
2786

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

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

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

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

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

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

2819
  syncNodeRelease(pNode);
1,446✔
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) {
78,299✔
2864
  if (tsSyncLogHeartbeat) {
78,299!
2865
    sInfo("heartbeat timer start");
×
2866
  }
2867
  int32_t code = 0;
78,299✔
2868
  int64_t hbDataRid = (int64_t)param;
78,299✔
2869
  int64_t tsNow = taosGetTimestampMs();
78,299✔
2870

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

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

2884
  SSyncTimer* pSyncTimer = pData->pTimer;
78,298✔
2885

2886
  if (!pSyncNode->isStart) {
78,298!
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) {
78,298!
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) {
78,298!
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,
78,298!
2905
           pData->destId.addr);
2906
  }
2907

2908
  if (pSyncNode->totalReplicaNum > 1) {
78,298✔
2909
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
78,296✔
2910
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
78,296✔
2911

2912
    if (timerLogicClock == msgLogicClock) {
78,296✔
2913
      if (tsNow > pData->execTime) {
78,293✔
2914
        pData->execTime += pSyncTimer->timerMS;
78,271✔
2915

2916
        SRpcMsg rpcMsg = {0};
78,271✔
2917
        if ((code = syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId)) != 0) {
78,271!
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);
78,271✔
2925

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

2935
        // update reset time
2936
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
78,271✔
2937
        pSyncTimer->timeStamp = tsNow;
78,271✔
2938

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

2949
      if (syncIsInit()) {
78,293!
2950
        if (tsSyncLogHeartbeat) {
78,293!
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);
78,293!
2954
        }
2955
        bool stopped = taosTmrResetPriority(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS, (void*)hbDataRid,
78,293✔
2956
                                            syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
78,293✔
2957
        if (stopped) sError("vgId:%d, reset peer hb timer error, %s", pSyncNode->vgId, tstrerror(code));
78,293!
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,
3!
2965
             timerLogicClock, msgLogicClock);
2966
    }
2967

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

2973
  syncHbTimerDataRelease(pData);
78,298✔
2974
  syncNodeRelease(pSyncNode);
78,298✔
2975
  if (tsSyncLogHeartbeat) {
78,298!
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) {
1,441,954✔
3565
  int32_t code = -1;
1,441,954✔
3566
  if (pEntry->dataLen < sizeof(SMsgHead)) {
1,441,954!
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) {
1,441,954✔
3577
    sError("vgId:%d, index:%" PRId64 ", failed to enqueue sync log buffer", ths->vgId, pEntry->index);
6!
3578
    int32_t ret = 0;
6✔
3579
    if ((ret = syncFsmExecute(ths, ths->pFsm, ths->state, raftStoreGetTerm(ths), pEntry, terrno, false)) != 0) {
6!
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;
1,441,947✔
3588
_out:;
1,441,947✔
3589
  // proceed match index, with replicating on needed
3590
  SyncIndex       matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL, "Append", pMsg);
1,441,947✔
3591
  const STraceId* trace = pEntry ? &pEntry->originRpcTraceId : NULL;
1,441,927✔
3592

3593
  if (pEntry != NULL) {
1,441,927✔
3594
    sGDebug(trace,
1,441,926!
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) {
1,441,927✔
3602
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
5✔
3603
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
5!
3604

3605
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
×
3606
        syncLogBufferCommit(ths->pLogBuf, ths, ths->assignedCommitIndex, trace, "append-entry") < 0) {
5✔
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) {
1,441,896✔
3615
    TAOS_RETURN(code);
97,137✔
3616
  }
3617

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

3623
  if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
2,689,519!
3624
      (code = syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, trace, "append-entry")) < 0) {
1,344,762✔
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);
1,344,757✔
3631
}
3632

3633
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
1,435,075✔
3634
  if (pSyncNode->totalReplicaNum == 1) {
1,435,075✔
3635
    return false;
1,336,296✔
3636
  }
3637

3638
  int32_t toCount = 0;
98,779✔
3639
  int64_t tsNow = taosGetTimestampMs();
98,778✔
3640
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
294,522✔
3641
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
195,745✔
3642
      continue;
1,602✔
3643
    }
3644
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
194,143✔
3645
    if (recvTime == 0 || recvTime == -1) {
194,142!
3646
      continue;
×
3647
    }
3648

3649
    if (tsNow - recvTime > tsHeartbeatTimeout) {
194,142✔
3650
      toCount++;
639✔
3651
    }
3652
  }
3653

3654
  bool b = (toCount >= pSyncNode->quorum ? true : false);
98,777✔
3655

3656
  return b;
98,777✔
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) {
8,447✔
3679
  int32_t   code = 0;
8,447✔
3680
  SyncIndex index = syncLogBufferGetEndIndex(ths->pLogBuf);
8,447✔
3681
  SyncTerm  term = raftStoreGetTerm(ths);
8,447✔
3682

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

3689
  code = syncNodeAppend(ths, pEntry, NULL);
8,447✔
3690
  TAOS_RETURN(code);
8,447✔
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) {
76,895✔
3725
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
76,895✔
3726
  bool           resetElect = false;
76,895✔
3727

3728
  int64_t tsMs = taosGetTimestampMs();
76,895✔
3729

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

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

3738
  if (!syncNodeInRaftGroup(ths, &pMsg->srcId)) {
76,894!
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);
76,895✔
3747

3748
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
76,895✔
3749
    raftStoreSetTerm(ths, pMsg->term);
287✔
3750
    currentTerm = pMsg->term;
287✔
3751
  }
3752

3753
  int64_t tsMs2 = taosGetTimestampMs();
76,895✔
3754

3755
  int64_t processTime = tsMs2 - tsMs;
76,895✔
3756
  if (processTime > SYNC_HEARTBEAT_SLOW_MS) {
76,895!
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,
76,895!
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 &&
76,895✔
3771
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
76,768!
3772
    resetElect = true;
76,769✔
3773

3774
    ths->minMatchIndex = pMsg->minMatchIndex;
76,769✔
3775

3776
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
76,769✔
3777
      SRpcMsg rpcMsgLocalCmd = {0};
76,765✔
3778
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
76,765!
3779
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
76,765✔
3780

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

3787
      if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
76,765!
3788
        int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
76,765✔
3789
        if (code != 0) {
76,765!
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,
76,765!
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 &&
76,894!
3804
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
76,894!
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};
76,894✔
3826
  TAOS_CHECK_RETURN(syncBuildHeartbeatReply(&rpcMsg, ths->vgId));
76,894!
3827
  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
76,895✔
3828
  pMsgReply->destId = pMsg->srcId;
76,895✔
3829
  pMsgReply->srcId = ths->myRaftId;
76,895✔
3830
  pMsgReply->term = currentTerm;
76,895✔
3831
  pMsgReply->privateTerm = 8864;  // magic number
76,895✔
3832
  pMsgReply->startTime = ths->startTime;
76,895✔
3833
  pMsgReply->timeStamp = tsMs;
76,895✔
3834
  rpcMsg.info.traceId = pRpcMsg->info.traceId;
76,895✔
3835

3836
  // reply
3837
  int64_t tsMs3 = taosGetTimestampMs();
76,895✔
3838

3839
  int64_t processTime2 = tsMs3 - tsMs2;
76,895✔
3840
  TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
76,895✔
3841
  if (processTime2 > SYNC_HEARTBEAT_SLOW_MS) {
76,894!
3842
    sGError(&rpcMsg.info.traceId,
×
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){
76,894!
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,
76,894!
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));
76,894!
3862

3863
  if (resetElect) syncNodeResetElectTimer(ths);
76,895✔
3864
  return 0;
76,895✔
3865
}
3866

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

3870
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
75,938✔
3871
  SSyncLogReplMgr*    pMgr = syncNodeGetLogReplMgr(ths, &pMsg->srcId);
75,938✔
3872
  if (pMgr == NULL) {
75,937!
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();
75,937✔
3880
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pMatchIndex, &pMsg->srcId);
75,937✔
3881
  syncLogRecvHeartbeatReply(ths, pMsg, tsMs - pMsg->timeStamp, &pRpcMsg->info.traceId, tsMs - lastRecvTime);
75,937✔
3882

3883
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
75,937✔
3884
  syncIndexMgrIncRecvCount(ths->pMatchIndex, &(pMsg->srcId));
75,936✔
3885

3886
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
75,936✔
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) {
76,765✔
3904
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
76,765✔
3905
  syncLogRecvLocalCmd(ths, pMsg, &pRpcMsg->info.traceId);
76,765✔
3906

3907
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
76,765!
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) {
153,530!
3912
    if (syncLogBufferIsEmpty(ths->pLogBuf)) {
76,765!
3913
      sError("vgId:%d, sync log buffer is empty", ths->vgId);
×
3914
      return 0;
×
3915
    }
3916
    SyncTerm matchTerm = syncLogBufferGetLastMatchTerm(ths->pLogBuf);
76,765✔
3917
    if (matchTerm < 0) {
76,765!
3918
      return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3919
    }
3920
    if (pMsg->currentTerm == matchTerm) {
76,765✔
3921
      SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, pMsg->commitIndex);
72,793✔
3922
      sTrace("vgId:%d, raft entry update commit, return index:%" PRId64, ths->vgId, returnIndex);
72,793!
3923
    }
3924
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
153,530!
3925
        syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, &pRpcMsg->info.traceId, "heartbeat") < 0) {
76,765✔
3926
      sError("vgId:%d, failed to commit raft log since %s. commit index:%" PRId64, ths->vgId, terrstr(),
1!
3927
             ths->commitIndex);
3928
    }
3929
  } else {
3930
    sError("error local cmd");
×
3931
  }
3932

3933
  return 0;
76,765✔
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) {
1,433,509✔
3948
  sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, process client request", ths->vgId, pMsg);
1,433,509!
3949
  int32_t code = 0;
1,433,509✔
3950

3951
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
1,433,509✔
3952
  SyncTerm        term = raftStoreGetTerm(ths);
1,433,512✔
3953
  SSyncRaftEntry* pEntry = NULL;
1,433,509✔
3954
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
1,433,509✔
3955
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
167,036✔
3956
  } else {
3957
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
1,266,473✔
3958
  }
3959

3960
  if (pEntry == NULL) {
1,433,510!
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) {
1,433,510!
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) {
1,433,510!
3975
    if (pRetIndex) {
1,433,510✔
3976
      (*pRetIndex) = index;
1,266,476✔
3977
    }
3978

3979
    if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE) {
1,433,510!
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);
1,433,510✔
4004
    return code;
1,433,422✔
4005
  } else {
4006
    syncEntryDestroy(pEntry);
×
4007
    pEntry = NULL;
×
4008
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4009
  }
4010
}
4011

4012
const char* syncStr(ESyncState state) {
636,419✔
4013
  switch (state) {
636,419!
4014
    case TAOS_SYNC_STATE_FOLLOWER:
355,884✔
4015
      return "follower";
355,884✔
4016
    case TAOS_SYNC_STATE_CANDIDATE:
2,735✔
4017
      return "candidate";
2,735✔
4018
    case TAOS_SYNC_STATE_LEADER:
245,727✔
4019
      return "leader";
245,727✔
4020
    case TAOS_SYNC_STATE_ERROR:
×
4021
      return "error";
×
4022
    case TAOS_SYNC_STATE_OFFLINE:
4,652✔
4023
      return "offline";
4,652✔
4024
    case TAOS_SYNC_STATE_LEARNER:
27,409✔
4025
      return "learner";
27,409✔
4026
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
19✔
4027
      return "assigned leader";
19✔
4028
    default:
×
4029
      return "unknown";
×
4030
  }
4031
}
4032

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

4040
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
1,496✔
4041
      pNewCfg->myIndex = i;
1,256✔
4042
      return 0;
1,256✔
4043
    }
4044
  }
4045

4046
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4047
}
4048

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

4053
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
537,456✔
4054
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
1,058,167!
4055
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
1,058,167✔
4056
      return true;
537,456✔
4057
    }
4058
  }
4059
  return false;
×
4060
}
4061

4062
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
48,534✔
4063
  SSyncSnapshotSender* pSender = NULL;
48,534✔
4064
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
194,255✔
4065
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
145,719✔
4066
      pSender = (ths->senders)[i];
48,539✔
4067
    }
4068
  }
4069
  return pSender;
48,536✔
4070
}
4071

4072
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
30,956✔
4073
  SSyncTimer* pTimer = NULL;
30,956✔
4074
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
128,900✔
4075
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
97,943✔
4076
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
30,956✔
4077
    }
4078
  }
4079
  return pTimer;
30,957✔
4080
}
4081

4082
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
3,515✔
4083
  SPeerState* pState = NULL;
3,515✔
4084
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
11,676✔
4085
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
8,161✔
4086
      pState = &((ths->peerStates)[i]);
3,515✔
4087
    }
4088
  }
4089
  return pState;
3,515✔
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