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

taosdata / TDengine / #4550

21 Jul 2025 05:44AM UTC coverage: 54.508% (+0.2%) from 54.273%
#4550

push

travis-ci

web-flow
Merge pull request #32061 from taosdata/new_testcases

skip tsim cases

133505 of 315239 branches covered (42.35%)

Branch coverage included in aggregate %.

202054 of 300373 relevant lines covered (67.27%)

4175333.65 hits per line

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

54.01
/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) {
14,848✔
64
  sInfo("vgId:%d, start to open sync", pSyncInfo->vgId);
14,848✔
65
  SSyncNode* pSyncNode = syncNodeOpen(pSyncInfo, vnodeVersion);
14,848✔
66
  if (pSyncNode == NULL) {
14,849!
67
    sError("vgId:%d, failed to open sync node", pSyncInfo->vgId);
×
68
    return -1;
×
69
  }
70

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

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

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

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

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

112
  syncNodeRelease(pSyncNode);
14,849✔
113

114
  sInfo("vgId:%d, sync started", vgId);
14,849✔
115

116
  TAOS_RETURN(code);
14,849✔
117

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

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

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

134
  *cfg = pSyncNode->raftCfg.cfg;
21,732✔
135

136
  syncNodeRelease(pSyncNode);
21,732✔
137

138
  return 0;
21,729✔
139
}
140

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

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

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

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

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

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

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

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

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

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

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

214
    TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
1,954!
215
    // syncNodeReplicate(pSyncNode);
216
  }
217

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

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

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

237
  switch (pMsg->msgType) {
884,938!
238
    case TDMT_SYNC_HEARTBEAT:
42,363✔
239
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
42,363✔
240
      break;
42,363✔
241
    case TDMT_SYNC_HEARTBEAT_REPLY:
41,162✔
242
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
41,162✔
243
      break;
41,162✔
244
    case TDMT_SYNC_TIMEOUT:
46,071✔
245
      code = syncNodeOnTimeout(pSyncNode, pMsg);
46,071✔
246
      break;
46,064✔
247
    case TDMT_SYNC_TIMEOUT_ELECTION:
1,460✔
248
      code = syncNodeOnTimeout(pSyncNode, pMsg);
1,460✔
249
      break;
1,460✔
250
    case TDMT_SYNC_CLIENT_REQUEST:
196,302✔
251
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
196,302✔
252
      break;
196,302✔
253
    case TDMT_SYNC_REQUEST_VOTE:
2,570✔
254
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
2,570✔
255
      break;
2,570✔
256
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
2,413✔
257
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
2,413✔
258
      break;
2,413✔
259
    case TDMT_SYNC_APPEND_ENTRIES:
254,958✔
260
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
254,958✔
261
      break;
254,958✔
262
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
254,741✔
263
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
254,741✔
264
      break;
254,741✔
265
    case TDMT_SYNC_SNAPSHOT_SEND:
347✔
266
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
347✔
267
      break;
347✔
268
    case TDMT_SYNC_SNAPSHOT_RSP:
347✔
269
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
347✔
270
      break;
347✔
271
    case TDMT_SYNC_LOCAL_CMD:
42,188✔
272
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
42,188✔
273
      break;
42,188✔
274
    case TDMT_SYNC_FORCE_FOLLOWER:
14✔
275
      code = syncForceBecomeFollower(pSyncNode, pMsg);
14✔
276
      break;
14✔
277
    case TDMT_SYNC_SET_ASSIGNED_LEADER:
2✔
278
      code = syncBecomeAssignedLeader(pSyncNode, pMsg);
2✔
279
      break;
2✔
280
    default:
×
281
      code = TSDB_CODE_MSG_NOT_PROCESSED;
×
282
  }
283

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

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

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

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

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

318
  return 0;
14✔
319
}
320

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

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

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

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

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

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

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

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

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

388
  code = TSDB_CODE_SUCCESS;
2✔
389

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

398
  tmsgSendRsp(&rspMsg);
2✔
399

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

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

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

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

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

431
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
141,607✔
432
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
94,506✔
433
    if (minMatchIndex == SYNC_INDEX_INVALID) {
94,506✔
434
      minMatchIndex = matchIndex;
51,656✔
435
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
42,850✔
436
      minMatchIndex = matchIndex;
1,419✔
437
    }
438
  }
439
  return minMatchIndex;
47,101✔
440
}
441

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

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

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

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

466
  int64_t logRetention = 0;
25,882✔
467

468
  if (syncNodeIsMnode(pSyncNode)) {
25,882✔
469
    // mnode
470
    logRetention = tsMndLogRetention;
4,160✔
471
  } else {
472
    // vnode
473
    if (pSyncNode->replicaNum > 1) {
21,722✔
474
      logRetention = SYNC_VNODE_LOG_RETENTION;
323✔
475
    }
476
  }
477

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

491
_DEL_WAL:
25,219✔
492

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

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

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

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

522
  syncNodeRelease(pSyncNode);
25,874✔
523
  TAOS_RETURN(code);
25,874✔
524
}
525

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

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

549
  syncNodeRelease(pSyncNode);
25,892✔
550
  TAOS_RETURN(code);
25,892✔
551
}
552

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

560
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,740,428✔
561
    terrno = TSDB_CODE_SYN_NOT_LEADER;
59,036✔
562
    return false;
59,036✔
563
  }
564

565
  if (!pSyncNode->restoreFinish) {
2,681,392✔
566
    terrno = TSDB_CODE_SYN_RESTORING;
199✔
567
    return false;
199✔
568
  }
569

570
  return true;
2,681,193✔
571
}
572

573
bool syncIsReadyForRead(int64_t rid) {
2,533,031✔
574
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
2,533,031✔
575
  if (pSyncNode == NULL) {
2,534,053!
576
    sError("sync ready for read error");
×
577
    return false;
×
578
  }
579

580
  bool ready = syncNodeIsReadyForRead(pSyncNode);
2,534,053✔
581

582
  syncNodeRelease(pSyncNode);
2,533,956✔
583
  return ready;
2,533,719✔
584
}
585

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

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

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

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

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

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

629
  return ret;
3,781✔
630
}
631

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

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

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

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

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

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

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

685
  return state;
1,033,708✔
686
}
687

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

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

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

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

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

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

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

736
  syncNodeRelease(pSyncNode);
39,917✔
737
  TAOS_RETURN(code);
39,917✔
738
}
739

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

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

755
  bool isSync = pSyncNode->commitIndex >= pSyncNode->assignedCommitIndex;
3✔
756
  code = (isSync ? TSDB_CODE_SUCCESS : TSDB_CODE_VND_ARB_NOT_SYNCED);
3!
757
  if (!isSync) {
3!
758
    sInfo("vgId:%d, not synced, assignedCommitIndex:%" PRId64 ", commitIndex:%" PRId64, pSyncNode->vgId,
×
759
          pSyncNode->assignedCommitIndex, pSyncNode->commitIndex);
760
  }
761

762
  syncNodeRelease(pSyncNode);
3✔
763
  TAOS_RETURN(code);
3✔
764
}
765

766
int32_t syncUpdateArbTerm(int64_t rid, SyncTerm arbTerm) {
170✔
767
  int32_t    code = 0;
170✔
768
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
170✔
769
  if (pSyncNode == NULL) {
170!
770
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
771
    if (terrno != 0) code = terrno;
×
772
    TAOS_RETURN(code);
×
773
  }
774

775
  pSyncNode->arbTerm = TMAX(arbTerm, pSyncNode->arbTerm);
170✔
776
  syncNodeRelease(pSyncNode);
170✔
777
  TAOS_RETURN(code);
170✔
778
}
779

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

789
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
1,573,640✔
790
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
794,947✔
791
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
16,254✔
792
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
16,095✔
793
    }
794
  }
795
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
778,693!
796
         lastIndex);
797

798
  return lastIndex;
778,694✔
799
}
800

801
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
193,926✔
802
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
349,480✔
803
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
253,427✔
804
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
253,417✔
805
      return pSyncNode->peersId[i];
97,873✔
806
    }
807
  }
808
  return EMPTY_RAFT_ID;
96,053✔
809
}
810

811
static void epsetToString(const SEpSet* pEpSet, char* buffer, size_t bufferSize) {
96,144✔
812
  if (pEpSet == NULL || buffer == NULL) {
96,144!
813
    snprintf(buffer, bufferSize, "EpSet is NULL");
×
814
    return;
×
815
  }
816

817
  size_t offset = 0;
96,145✔
818
  offset += snprintf(buffer + offset, bufferSize - offset, "EpSet: [");
96,145✔
819

820
  for (int i = 0; i < pEpSet->numOfEps; ++i) {
290,068✔
821
    if (offset >= bufferSize) break;
193,923!
822
    offset += snprintf(buffer + offset, bufferSize - offset, "%s:%d%s", pEpSet->eps[i].fqdn, pEpSet->eps[i].port,
193,923✔
823
                       (i + 1 < pEpSet->numOfEps) ? ", " : "");
193,923✔
824
  }
825

826
  if (offset < bufferSize) {
96,145!
827
    snprintf(buffer + offset, bufferSize - offset, "]");
96,148✔
828
  }
829
}
830

831
void syncGetRetryEpSet(int64_t rid, SEpSet* pEpSet) {
96,146✔
832
  pEpSet->numOfEps = 0;
96,146✔
833

834
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
96,146✔
835
  if (pSyncNode == NULL) return;
96,148!
836

837
  int index = -1;
96,148✔
838

839
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
96,148✔
840
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
841
  int j = 0;
96,148✔
842
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
291,681✔
843
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
195,532✔
844
    SEp* pEp = &pEpSet->eps[j];
193,931✔
845
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
193,931✔
846
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
193,931✔
847
    pEpSet->numOfEps++;
193,931✔
848
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
193,931✔
849
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
193,931✔
850
           pEp->port);
851
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
193,932✔
852
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
69,486!
853
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
854
      index = j;
69,486✔
855
    }
856
    j++;
193,932✔
857
  }
858
  if (pEpSet->numOfEps > 0) {
96,149✔
859
    if (index != -1) {
96,148✔
860
      pEpSet->inUse = index;
69,487✔
861
    } else {
862
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
26,661✔
863
          pSyncNode->myRaftId.vgId == pSyncNode->leaderCache.vgId) {
46!
864
        pEpSet->inUse = pSyncNode->raftCfg.cfg.myIndex;
46✔
865
      } else {
866
        pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
26,615✔
867
      }
868
    }
869
    // pEpSet->inUse = 0;
870
  }
871
  epsetSort(pEpSet);
96,149✔
872

873
  char buffer[1024];
874
  epsetToString(pEpSet, buffer, sizeof(buffer));
96,147✔
875
  sDebug("vgId:%d, sync get retry epset numOfEps:%d %s inUse:%d", pSyncNode->vgId, pEpSet->numOfEps, buffer,
96,146✔
876
         pEpSet->inUse);
877
  syncNodeRelease(pSyncNode);
96,146✔
878
}
879

880
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
2,042,971✔
881
  int32_t    code = 0;
2,042,971✔
882
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
2,042,971✔
883
  if (pSyncNode == NULL) {
2,042,976!
884
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
885
    if (terrno != 0) code = terrno;
×
886
    sError("sync propose error");
×
887
    TAOS_RETURN(code);
×
888
  }
889

890
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak, seq);
2,042,976✔
891
  syncNodeRelease(pSyncNode);
2,042,846✔
892
  return ret;
2,042,882✔
893
}
894

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

905
  if (pSyncNode->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
906
    syncNodeRelease(pSyncNode);
×
907
    return TSDB_CODE_SYN_WRONG_ROLE;
×
908
  }
909

910
  syncNodeRelease(pSyncNode);
×
911
  return 0;
×
912
}
913

914
int32_t syncIsCatchUp(int64_t rid) {
4,692✔
915
  int32_t    code = 0;
4,692✔
916
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,692✔
917
  if (pSyncNode == NULL) {
4,692!
918
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
919
    if (terrno != 0) code = terrno;
×
920
    sError("sync Node Acquire error since %d", ERRNO);
×
921
    TAOS_RETURN(code);
×
922
  }
923

924
  int32_t isCatchUp = 0;
4,692✔
925
  if (pSyncNode->pLogBuf->totalIndex < 0 || pSyncNode->pLogBuf->commitIndex < 0 ||
4,692!
926
      pSyncNode->pLogBuf->totalIndex < pSyncNode->pLogBuf->commitIndex ||
727✔
927
      pSyncNode->pLogBuf->totalIndex - pSyncNode->pLogBuf->commitIndex > SYNC_LEARNER_CATCHUP) {
726✔
928
    sInfo("vgId:%d, Not catch up, wait one second, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64,
4,426!
929
          pSyncNode->vgId, pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex,
930
          pSyncNode->pLogBuf->matchIndex);
931
    isCatchUp = 0;
4,426✔
932
  } else {
933
    sInfo("vgId:%d, Catch up, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64, pSyncNode->vgId,
266!
934
          pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->matchIndex);
935
    isCatchUp = 1;
266✔
936
  }
937

938
  syncNodeRelease(pSyncNode);
4,692✔
939
  return isCatchUp;
4,692✔
940
}
941

942
ESyncRole syncGetRole(int64_t rid) {
4,692✔
943
  int32_t    code = 0;
4,692✔
944
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,692✔
945
  if (pSyncNode == NULL) {
4,692!
946
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
947
    if (terrno != 0) code = terrno;
×
948
    sError("sync Node Acquire error since %d", ERRNO);
×
949
    TAOS_RETURN(code);
×
950
  }
951

952
  ESyncRole role = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole;
4,692✔
953

954
  syncNodeRelease(pSyncNode);
4,692✔
955
  return role;
4,692✔
956
}
957

958
int64_t syncGetTerm(int64_t rid) {
15,767✔
959
  int32_t    code = 0;
15,767✔
960
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
15,767✔
961
  if (pSyncNode == NULL) {
15,767!
962
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
963
    if (terrno != 0) code = terrno;
×
964
    sError("sync Node Acquire error since %d", ERRNO);
×
965
    TAOS_RETURN(code);
×
966
  }
967

968
  int64_t term = raftStoreGetTerm(pSyncNode);
15,767✔
969

970
  syncNodeRelease(pSyncNode);
15,767✔
971
  return term;
15,767✔
972
}
973

974
int32_t syncNodePropose(SSyncNode* pSyncNode, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
2,044,174✔
975
  int32_t code = 0;
2,044,174✔
976
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,044,174✔
977
    code = TSDB_CODE_SYN_NOT_LEADER;
8,966✔
978
    sNWarn(pSyncNode, "sync propose not leader, type:%s", TMSG_INFO(pMsg->msgType));
8,966!
979
    TAOS_RETURN(code);
8,966✔
980
  }
981

982
  if (!pSyncNode->restoreFinish) {
2,035,208✔
983
    code = TSDB_CODE_SYN_PROPOSE_NOT_READY;
36✔
984
    sNWarn(pSyncNode, "failed to sync propose since not ready, type:%s, last:%" PRId64 ", cmt:%" PRId64,
36!
985
           TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
986
    TAOS_RETURN(code);
36✔
987
  }
988

989
  // heartbeat timeout
990
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER && syncNodeHeartbeatReplyTimeout(pSyncNode)) {
2,035,172✔
991
    code = TSDB_CODE_SYN_PROPOSE_NOT_READY;
2✔
992
    sNError(pSyncNode, "failed to sync propose since heartbeat timeout, type:%s, last:%" PRId64 ", cmt:%" PRId64,
2!
993
            TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
994
    TAOS_RETURN(code);
2✔
995
  }
996

997
  // optimized one replica
998
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
2,035,171✔
999
    SyncIndex retIndex;
1000
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
1,837,197✔
1001
    if (code >= 0) {
1,837,042!
1002
      pMsg->info.conn.applyIndex = retIndex;
1,837,061✔
1003
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
1,837,061✔
1004

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

1034
    sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, propose msg, type:%s", pSyncNode->vgId, pMsg,
197,969!
1035
            TMSG_INFO(pMsg->msgType));
1036
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
197,969✔
1037
    if (code != 0) {
197,970✔
1038
      sWarn("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
1,668!
1039
      TAOS_CHECK_RETURN(syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum));
1,668✔
1040
    }
1041

1042
    if (seq != NULL) *seq = seqNum;
197,949✔
1043
    TAOS_RETURN(code);
197,949✔
1044
  }
1045
}
1046

1047
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId) {
252,045✔
1048
  pSyncTimer->pTimer = NULL;
252,045✔
1049
  pSyncTimer->counter = 0;
252,045✔
1050
  pSyncTimer->timerMS = pSyncNode->hbBaseLine;
252,045✔
1051
  pSyncTimer->timerCb = syncNodeEqPeerHeartbeatTimer;
252,045✔
1052
  pSyncTimer->destId = destId;
252,045✔
1053
  pSyncTimer->timeStamp = taosGetTimestampMs();
252,045✔
1054
  atomic_store_64(&pSyncTimer->logicClock, 0);
252,045✔
1055
  return 0;
252,045✔
1056
}
1057

1058
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
2,893✔
1059
  int32_t code = 0;
2,893✔
1060
  int64_t tsNow = taosGetTimestampMs();
2,893✔
1061
  if (syncIsInit()) {
2,893!
1062
    SSyncHbTimerData* pData = syncHbTimerDataAcquire(pSyncTimer->hbDataRid);
2,893✔
1063
    if (pData == NULL) {
2,893✔
1064
      pData = taosMemoryMalloc(sizeof(SSyncHbTimerData));
2,892!
1065
      pData->rid = syncHbTimerDataAdd(pData);
2,892✔
1066
    }
1067
    pSyncTimer->hbDataRid = pData->rid;
2,893✔
1068
    pSyncTimer->timeStamp = tsNow;
2,893✔
1069

1070
    pData->syncNodeRid = pSyncNode->rid;
2,893✔
1071
    pData->pTimer = pSyncTimer;
2,893✔
1072
    pData->destId = pSyncTimer->destId;
2,893✔
1073
    pData->logicClock = pSyncTimer->logicClock;
2,893✔
1074
    pData->execTime = tsNow + pSyncTimer->timerMS;
2,893✔
1075

1076
    sTrace("vgId:%d, start hb timer, rid:%" PRId64 " addr:0x%" PRIx64 " at %d", pSyncNode->vgId, pData->rid,
2,893!
1077
           pData->destId.addr, pSyncTimer->timerMS);
1078

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

1092
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer) {
29,734✔
1093
  int32_t ret = 0;
29,734✔
1094
  (void)atomic_add_fetch_64(&pSyncTimer->logicClock, 1);
29,734✔
1095
  bool stop = taosTmrStop(pSyncTimer->pTimer);
29,735✔
1096
  sDebug("vgId:%d, stop hb timer stop:%d", pSyncNode->vgId, stop);
29,735✔
1097
  pSyncTimer->pTimer = NULL;
29,735✔
1098
  syncHbTimerDataRemove(pSyncTimer->hbDataRid);
29,735✔
1099
  pSyncTimer->hbDataRid = -1;
29,735✔
1100
  return ret;
29,735✔
1101
}
1102

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

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

1136
// open/close --------------
1137
SSyncNode* syncNodeOpen(SSyncInfo* pSyncInfo, int32_t vnodeVersion) {
14,838✔
1138
  int32_t    code = 0;
14,838✔
1139
  SSyncNode* pSyncNode = taosMemoryCalloc(1, sizeof(SSyncNode));
14,838!
1140
  if (pSyncNode == NULL) {
14,849!
1141
    terrno = TSDB_CODE_OUT_OF_MEMORY;
×
1142
    goto _error;
×
1143
  }
1144

1145
  if (!taosDirExist((char*)(pSyncInfo->path))) {
14,849✔
1146
    if (taosMkDir(pSyncInfo->path) != 0) {
11,399!
1147
      terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
1148
      sError("vgId:%d, failed to create dir:%s since %s", pSyncInfo->vgId, pSyncInfo->path, terrstr());
×
1149
      goto _error;
×
1150
    }
1151
  }
1152

1153
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
14,844✔
1154
  snprintf(pSyncNode->raftStorePath, sizeof(pSyncNode->raftStorePath), "%s%sraft_store.json", pSyncInfo->path,
14,844✔
1155
           TD_DIRSEP);
1156
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
14,844✔
1157

1158
  if (!taosCheckExistFile(pSyncNode->configPath)) {
14,844✔
1159
    // create a new raft config file
1160
    sInfo("vgId:%d, create a new raft config file", pSyncInfo->vgId);
11,398✔
1161
    pSyncNode->vgId = pSyncInfo->vgId;
11,399✔
1162
    pSyncNode->mountVgId = pSyncInfo->mountVgId;
11,399✔
1163
    pSyncNode->raftCfg.isStandBy = pSyncInfo->isStandBy;
11,399✔
1164
    pSyncNode->raftCfg.snapshotStrategy = pSyncInfo->snapshotStrategy;
11,399✔
1165
    pSyncNode->raftCfg.lastConfigIndex = pSyncInfo->syncCfg.lastIndex;
11,399✔
1166
    pSyncNode->raftCfg.batchSize = pSyncInfo->batchSize;
11,399✔
1167
    pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
11,399✔
1168
    pSyncNode->raftCfg.configIndexCount = 1;
11,399✔
1169
    pSyncNode->raftCfg.configIndexArr[0] = -1;
11,399✔
1170

1171
    if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
11,399!
1172
      terrno = code;
×
1173
      sError("vgId:%d, failed to create sync cfg file", pSyncNode->vgId);
×
1174
      goto _error;
×
1175
    }
1176
  } else {
1177
    // update syncCfg by raft_config.json
1178
    if ((code = syncReadCfgFile(pSyncNode)) != 0) {
3,444!
1179
      terrno = code;
×
1180
      sError("vgId:%d, failed to read sync cfg file", pSyncNode->vgId);
×
1181
      goto _error;
×
1182
    }
1183

1184
    if (vnodeVersion > pSyncNode->raftCfg.cfg.changeVersion) {
3,449✔
1185
      if (pSyncInfo->syncCfg.totalReplicaNum > 0 && syncIsConfigChanged(&pSyncNode->raftCfg.cfg, &pSyncInfo->syncCfg)) {
2,113!
1186
        sInfo("vgId:%d, use sync config from input options and write to cfg file", pSyncNode->vgId);
1,739!
1187
        pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
1,739✔
1188
        if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
1,739!
1189
          terrno = code;
×
1190
          sError("vgId:%d, failed to write sync cfg file", pSyncNode->vgId);
×
1191
          goto _error;
×
1192
        }
1193
      } else {
1194
        sInfo("vgId:%d, use sync config from sync cfg file", pSyncNode->vgId);
374!
1195
        pSyncInfo->syncCfg = pSyncNode->raftCfg.cfg;
374✔
1196
      }
1197
    } else {
1198
      sInfo("vgId:%d, skip save sync cfg file since request ver:%d <= file ver:%d", pSyncNode->vgId, vnodeVersion,
1,336!
1199
            pSyncInfo->syncCfg.changeVersion);
1200
    }
1201
  }
1202

1203
  // init by SSyncInfo
1204
  pSyncNode->vgId = pSyncInfo->vgId;
14,849✔
1205
  pSyncNode->mountVgId = pSyncInfo->mountVgId;
14,849✔
1206
  SSyncCfg* pCfg = &pSyncNode->raftCfg.cfg;
14,849✔
1207
  bool      updated = false;
14,849✔
1208
  sInfo("vgId:%d, start to open sync node, totalReplicaNum:%d replicaNum:%d selfIndex:%d", pSyncNode->vgId,
14,849✔
1209
        pCfg->totalReplicaNum, pCfg->replicaNum, pCfg->myIndex);
1210
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
37,770✔
1211
    SNodeInfo* pNode = &pCfg->nodeInfo[i];
22,921✔
1212
    if (tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort)) {
22,921!
1213
      updated = true;
×
1214
    }
1215
    sInfo("vgId:%d, index:%d ep:%s:%u dnode:%d cluster:%" PRId64, pSyncNode->vgId, i, pNode->nodeFqdn, pNode->nodePort,
22,921✔
1216
          pNode->nodeId, pNode->clusterId);
1217
  }
1218

1219
  if (vnodeVersion > pSyncInfo->syncCfg.changeVersion) {
14,849✔
1220
    if (updated) {
2,320!
1221
      sInfo("vgId:%d, save config info since dnode info changed", pSyncNode->vgId);
×
1222
      if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
×
1223
        terrno = code;
×
1224
        sError("vgId:%d, failed to write sync cfg file on dnode info updated", pSyncNode->vgId);
×
1225
        goto _error;
×
1226
      }
1227
    }
1228
  }
1229

1230
  pSyncNode->pWal = pSyncInfo->pWal;
14,849✔
1231
  pSyncNode->msgcb = pSyncInfo->msgcb;
14,849✔
1232
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
14,849✔
1233
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
14,849✔
1234
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
14,849✔
1235

1236
  // create raft log ring buffer
1237
  code = syncLogBufferCreate(&pSyncNode->pLogBuf);
14,849✔
1238
  if (pSyncNode->pLogBuf == NULL) {
14,849!
1239
    sError("failed to init sync log buffer since %s. vgId:%d", tstrerror(code), pSyncNode->vgId);
×
1240
    goto _error;
×
1241
  }
1242

1243
  // init replicaNum, replicasId
1244
  pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
14,849✔
1245
  pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
14,849✔
1246
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
37,770✔
1247
    if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
22,921!
1248
        false) {
1249
      sError("vgId:%d, failed to determine raft member id, replica:%d", pSyncNode->vgId, i);
×
1250
      goto _error;
×
1251
    }
1252
  }
1253

1254
  // init internal
1255
  pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
14,849✔
1256
  pSyncNode->myRaftId = pSyncNode->replicasId[pSyncNode->raftCfg.cfg.myIndex];
14,849✔
1257

1258
  // init peersNum, peers, peersId
1259
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
14,849✔
1260
  int32_t j = 0;
14,849✔
1261
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
37,770✔
1262
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
22,921✔
1263
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
8,072✔
1264
      pSyncNode->peersId[j] = pSyncNode->replicasId[i];
8,072✔
1265
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
8,072✔
1266
      j++;
8,072✔
1267
    }
1268
  }
1269

1270
  pSyncNode->arbTerm = -1;
14,849✔
1271
  (void)taosThreadMutexInit(&pSyncNode->arbTokenMutex, NULL);
14,849✔
1272
  syncUtilGenerateArbToken(pSyncNode->myNodeInfo.nodeId, pSyncInfo->vgId, pSyncNode->arbToken);
14,849✔
1273
  sInfo("vgId:%d, generate arb token:%s", pSyncNode->vgId, pSyncNode->arbToken);
14,849✔
1274

1275
  // init raft algorithm
1276
  pSyncNode->pFsm = pSyncInfo->pFsm;
14,849✔
1277
  pSyncInfo->pFsm = NULL;
14,849✔
1278
  pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
14,849✔
1279
  pSyncNode->leaderCache = EMPTY_RAFT_ID;
14,849✔
1280
  pSyncNode->leaderCacheEp.port = 0;
14,849✔
1281
  pSyncNode->leaderCacheEp.fqdn[0] = '\0';
14,849✔
1282

1283
  // init life cycle outside
1284

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

1309
  // init TLA+ server vars
1310
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
14,849✔
1311
  pSyncNode->roleTimeMs = taosGetTimestampMs();
14,849✔
1312
  if ((code = raftStoreOpen(pSyncNode)) != 0) {
14,849!
1313
    terrno = code;
×
1314
    sError("vgId:%d, failed to open raft store at path %s", pSyncNode->vgId, pSyncNode->raftStorePath);
×
1315
    goto _error;
×
1316
  }
1317

1318
  // init TLA+ candidate vars
1319
  pSyncNode->pVotesGranted = voteGrantedCreate(pSyncNode);
14,849✔
1320
  if (pSyncNode->pVotesGranted == NULL) {
14,849!
1321
    sError("vgId:%d, failed to create VotesGranted", pSyncNode->vgId);
×
1322
    goto _error;
×
1323
  }
1324
  pSyncNode->pVotesRespond = votesRespondCreate(pSyncNode);
14,849✔
1325
  if (pSyncNode->pVotesRespond == NULL) {
14,849!
1326
    sError("vgId:%d, failed to create VotesRespond", pSyncNode->vgId);
×
1327
    goto _error;
×
1328
  }
1329

1330
  // init TLA+ leader vars
1331
  pSyncNode->pNextIndex = syncIndexMgrCreate(pSyncNode);
14,849✔
1332
  if (pSyncNode->pNextIndex == NULL) {
14,848!
1333
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
×
1334
    goto _error;
×
1335
  }
1336
  pSyncNode->pMatchIndex = syncIndexMgrCreate(pSyncNode);
14,848✔
1337
  if (pSyncNode->pMatchIndex == NULL) {
14,849!
1338
    sError("vgId:%d, failed to create SyncIndexMgr", pSyncNode->vgId);
×
1339
    goto _error;
×
1340
  }
1341

1342
  // init TLA+ log vars
1343
  pSyncNode->pLogStore = logStoreCreate(pSyncNode);
14,849✔
1344
  if (pSyncNode->pLogStore == NULL) {
14,849!
1345
    sError("vgId:%d, failed to create SyncLogStore", pSyncNode->vgId);
×
1346
    goto _error;
×
1347
  }
1348

1349
  SyncIndex commitIndex = SYNC_INDEX_INVALID;
14,849✔
1350
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
14,849!
1351
    SSnapshot snapshot = {0};
14,849✔
1352
    // TODO check return value
1353
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
14,849✔
1354
    if (snapshot.lastApplyIndex > commitIndex) {
14,849✔
1355
      commitIndex = snapshot.lastApplyIndex;
1,393✔
1356
      sNTrace(pSyncNode, "reset commit index by snapshot");
1,393!
1357
    }
1358
    pSyncNode->fsmState = snapshot.state;
14,849✔
1359
    if (pSyncNode->fsmState == SYNC_FSM_STATE_INCOMPLETE) {
14,849!
1360
      sError("vgId:%d, fsm state is incomplete.", pSyncNode->vgId);
×
1361
      if (pSyncNode->replicaNum == 1) {
×
1362
        terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1363
        goto _error;
×
1364
      }
1365
    }
1366
  }
1367
  pSyncNode->commitIndex = commitIndex;
14,841✔
1368
  sInfo("vgId:%d, sync node commitIndex initialized as %" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
14,841✔
1369

1370
  // restore log store on need
1371
  if ((code = syncNodeLogStoreRestoreOnNeed(pSyncNode)) < 0) {
14,841!
1372
    terrno = code;
×
1373
    sError("vgId:%d, failed to restore log store since %s.", pSyncNode->vgId, terrstr());
×
1374
    goto _error;
×
1375
  }
1376

1377
  // timer ms init
1378
  pSyncNode->pingBaseLine = PING_TIMER_MS;
14,849✔
1379
  pSyncNode->electBaseLine = tsElectInterval;
14,849✔
1380
  pSyncNode->hbBaseLine = tsHeartbeatInterval;
14,849✔
1381

1382
  // init ping timer
1383
  pSyncNode->pPingTimer = NULL;
14,849✔
1384
  pSyncNode->pingTimerMS = pSyncNode->pingBaseLine;
14,849✔
1385
  atomic_store_64(&pSyncNode->pingTimerLogicClock, 0);
14,849✔
1386
  atomic_store_64(&pSyncNode->pingTimerLogicClockUser, 0);
14,849✔
1387
  pSyncNode->FpPingTimerCB = syncNodeEqPingTimer;
14,849✔
1388
  pSyncNode->pingTimerCounter = 0;
14,849✔
1389

1390
  // init elect timer
1391
  pSyncNode->pElectTimer = NULL;
14,849✔
1392
  pSyncNode->electTimerMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
14,849✔
1393
  atomic_store_64(&pSyncNode->electTimerLogicClock, 0);
14,849✔
1394
  pSyncNode->FpElectTimerCB = syncNodeEqElectTimer;
14,849✔
1395
  pSyncNode->electTimerCounter = 0;
14,849✔
1396

1397
  // init heartbeat timer
1398
  pSyncNode->pHeartbeatTimer = NULL;
14,849✔
1399
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
14,849✔
1400
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClock, 0);
14,849✔
1401
  atomic_store_64(&pSyncNode->heartbeatTimerLogicClockUser, 0);
14,849✔
1402
#ifdef BUILD_NO_CALL
1403
  pSyncNode->FpHeartbeatTimerCB = syncNodeEqHeartbeatTimer;
1404
#endif
1405
  pSyncNode->heartbeatTimerCounter = 0;
14,849✔
1406

1407
  // init peer heartbeat timer
1408
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
237,584✔
1409
    if ((code = syncHbTimerInit(pSyncNode, &(pSyncNode->peerHeartbeatTimerArr[i]), (pSyncNode->replicasId)[i])) != 0) {
222,735!
1410
      terrno = code;
×
1411
      goto _error;
×
1412
    }
1413
  }
1414

1415
  // tools
1416
  if ((code = syncRespMgrCreate(pSyncNode, SYNC_RESP_TTL_MS, &pSyncNode->pSyncRespMgr)) != 0) {
14,849!
1417
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
×
1418
    goto _error;
×
1419
  }
1420
  if (pSyncNode->pSyncRespMgr == NULL) {
14,849!
1421
    sError("vgId:%d, failed to create SyncRespMgr", pSyncNode->vgId);
×
1422
    goto _error;
×
1423
  }
1424

1425
  // restore state
1426
  pSyncNode->restoreFinish = false;
14,849✔
1427

1428
  // snapshot senders
1429
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
237,512✔
1430
    SSyncSnapshotSender* pSender = NULL;
222,667✔
1431
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
222,667✔
1432
    if (pSender == NULL) return NULL;
222,653!
1433

1434
    pSyncNode->senders[i] = pSender;
222,653✔
1435
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
222,653✔
1436
  }
1437

1438
  // snapshot receivers
1439
  code = snapshotReceiverCreate(pSyncNode, EMPTY_RAFT_ID, &pSyncNode->pNewNodeReceiver);
14,845✔
1440
  if (pSyncNode->pNewNodeReceiver == NULL) return NULL;
14,848!
1441
  sRDebug(pSyncNode->pNewNodeReceiver, "snapshot receiver create while open sync node, data:%p",
14,848✔
1442
          pSyncNode->pNewNodeReceiver);
1443

1444
  // is config changing
1445
  pSyncNode->changing = false;
14,848✔
1446

1447
  // replication mgr
1448
  if ((code = syncNodeLogReplInit(pSyncNode)) < 0) {
14,848!
1449
    terrno = code;
×
1450
    sError("vgId:%d, failed to init repl mgr since %s.", pSyncNode->vgId, terrstr());
×
1451
    goto _error;
×
1452
  }
1453

1454
  // peer state
1455
  if ((code = syncNodePeerStateInit(pSyncNode)) < 0) {
14,849!
1456
    terrno = code;
×
1457
    sError("vgId:%d, failed to init peer stat since %s.", pSyncNode->vgId, terrstr());
×
1458
    goto _error;
×
1459
  }
1460

1461
  //
1462
  // min match index
1463
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
14,849✔
1464

1465
  // start in syncNodeStart
1466
  // start raft
1467

1468
  int64_t timeNow = taosGetTimestampMs();
14,849✔
1469
  pSyncNode->startTime = timeNow;
14,849✔
1470
  pSyncNode->lastReplicateTime = timeNow;
14,849✔
1471

1472
  // snapshotting
1473
  atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
14,849✔
1474

1475
  // init log buffer
1476
  if ((code = syncLogBufferInit(pSyncNode->pLogBuf, pSyncNode)) < 0) {
14,849!
1477
    terrno = code;
×
1478
    sError("vgId:%d, failed to init sync log buffer since %s", pSyncNode->vgId, terrstr());
×
1479
    goto _error;
×
1480
  }
1481

1482
  pSyncNode->isStart = true;
14,849✔
1483
  pSyncNode->electNum = 0;
14,849✔
1484
  pSyncNode->becomeLeaderNum = 0;
14,849✔
1485
  pSyncNode->becomeAssignedLeaderNum = 0;
14,849✔
1486
  pSyncNode->configChangeNum = 0;
14,849✔
1487
  pSyncNode->hbSlowNum = 0;
14,849✔
1488
  pSyncNode->hbrSlowNum = 0;
14,849✔
1489
  pSyncNode->tmrRoutineNum = 0;
14,849✔
1490

1491
  sNInfo(pSyncNode, "sync node opened, node:%p electInterval:%d heartbeatInterval:%d heartbeatTimeout:%d", pSyncNode,
14,849✔
1492
         tsElectInterval, tsHeartbeatInterval, tsHeartbeatTimeout);
1493
  return pSyncNode;
14,849✔
1494

1495
_error:
×
1496
  if (pSyncInfo->pFsm) {
×
1497
    taosMemoryFree(pSyncInfo->pFsm);
×
1498
    pSyncInfo->pFsm = NULL;
×
1499
  }
1500
  syncNodeClose(pSyncNode);
×
1501
  pSyncNode = NULL;
×
1502
  return NULL;
×
1503
}
1504

1505
#ifdef BUILD_NO_CALL
1506
void syncNodeMaybeUpdateCommitBySnapshot(SSyncNode* pSyncNode) {
1507
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
1508
    SSnapshot snapshot = {0};
1509
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
1510
    if (snapshot.lastApplyIndex > pSyncNode->commitIndex) {
1511
      pSyncNode->commitIndex = snapshot.lastApplyIndex;
1512
    }
1513
  }
1514
}
1515
#endif
1516

1517
int32_t syncNodeRestore(SSyncNode* pSyncNode) {
14,849✔
1518
  int32_t code = 0;
14,849✔
1519
  if (pSyncNode->pLogStore == NULL) {
14,849!
1520
    sError("vgId:%d, log store not created", pSyncNode->vgId);
×
1521
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1522
  }
1523
  if (pSyncNode->pLogBuf == NULL) {
14,849!
1524
    sError("vgId:%d, ring log buffer not created", pSyncNode->vgId);
×
1525
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1526
  }
1527

1528
  (void)taosThreadMutexLock(&pSyncNode->pLogBuf->mutex);
14,849✔
1529
  SyncIndex lastVer = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
14,848✔
1530
  SyncIndex commitIndex = pSyncNode->pLogStore->syncLogCommitIndex(pSyncNode->pLogStore);
14,848✔
1531
  SyncIndex endIndex = pSyncNode->pLogBuf->endIndex;
14,848✔
1532
  (void)taosThreadMutexUnlock(&pSyncNode->pLogBuf->mutex);
14,848✔
1533

1534
  if (lastVer != -1 && endIndex != lastVer + 1) {
14,849!
1535
    code = TSDB_CODE_WAL_LOG_INCOMPLETE;
×
1536
    sWarn("vgId:%d, failed to restore sync node since %s. expected lastLogIndex:%" PRId64 ", lastVer:%" PRId64,
×
1537
          pSyncNode->vgId, terrstr(), endIndex - 1, lastVer);
1538
    // TAOS_RETURN(code);
1539
  }
1540

1541
  // if (endIndex != lastVer + 1) return TSDB_CODE_SYN_INTERNAL_ERROR;
1542
  pSyncNode->commitIndex = TMAX(pSyncNode->commitIndex, commitIndex);
14,849✔
1543
  sInfo("vgId:%d, restore began, and keep syncing until commitIndex:%" PRId64, pSyncNode->vgId, pSyncNode->commitIndex);
14,849✔
1544

1545
  if (pSyncNode->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
29,698!
1546
      (code = syncLogBufferCommit(pSyncNode->pLogBuf, pSyncNode, pSyncNode->commitIndex, NULL, "restore")) < 0) {
14,849✔
1547
    TAOS_RETURN(code);
×
1548
  }
1549

1550
  TAOS_RETURN(code);
14,849✔
1551
}
1552

1553
int32_t syncNodeStart(SSyncNode* pSyncNode) {
14,849✔
1554
  // start raft
1555
  sInfo("vgId:%d, begin to start sync node", pSyncNode->vgId);
14,849✔
1556
  if (pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
14,849✔
1557
    syncNodeBecomeLearner(pSyncNode, "first start");
270✔
1558
  } else {
1559
    if (pSyncNode->replicaNum == 1) {
14,579✔
1560
      raftStoreNextTerm(pSyncNode);
11,170✔
1561
      syncNodeBecomeLeader(pSyncNode, "one replica start");
11,170✔
1562

1563
      // Raft 3.6.2 Committing entries from previous terms
1564
      TAOS_CHECK_RETURN(syncNodeAppendNoop(pSyncNode));
11,170!
1565
    } else {
1566
      SRaftId id = {0};
3,409✔
1567
      syncNodeBecomeFollower(pSyncNode, id, "first start");
3,409✔
1568
    }
1569
  }
1570

1571
  int32_t ret = 0;
14,849✔
1572
  ret = syncNodeStartPingTimer(pSyncNode);
14,849✔
1573
  if (ret != 0) {
14,849!
1574
    sError("vgId:%d, failed to start ping timer since %s", pSyncNode->vgId, tstrerror(ret));
×
1575
  }
1576
  sInfo("vgId:%d, sync node started", pSyncNode->vgId);
14,849✔
1577
  return ret;
14,849✔
1578
}
1579

1580
#ifdef BUILD_NO_CALL
1581
int32_t syncNodeStartStandBy(SSyncNode* pSyncNode) {
1582
  // state change
1583
  int32_t code = 0;
1584
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
1585
  pSyncNode->roleTimeMs = taosGetTimestampMs();
1586
  // TODO check return value
1587
  TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1588

1589
  // reset elect timer, long enough
1590
  int32_t electMS = TIMER_MAX_MS;
1591
  code = syncNodeRestartElectTimer(pSyncNode, electMS);
1592
  if (code < 0) {
1593
    sError("vgId:%d, failed to restart elect timer since %s", pSyncNode->vgId, terrstr());
1594
    return -1;
1595
  }
1596

1597
  code = syncNodeStartPingTimer(pSyncNode);
1598
  if (code < 0) {
1599
    sError("vgId:%d, failed to start ping timer since %s", pSyncNode->vgId, terrstr());
1600
    return -1;
1601
  }
1602
  return code;
1603
}
1604
#endif
1605

1606
void syncNodePreClose(SSyncNode* pSyncNode) {
14,849✔
1607
  int32_t code = 0;
14,849✔
1608
  if (pSyncNode == NULL) {
14,849!
1609
    sError("failed to pre close sync node since sync node is null");
×
1610
    return;
×
1611
  }
1612
  if (pSyncNode->pFsm == NULL) {
14,849!
1613
    sError("failed to pre close sync node since fsm is null");
×
1614
    return;
×
1615
  }
1616
  if (pSyncNode->pFsm->FpApplyQueueItems == NULL) {
14,849!
1617
    sError("failed to pre close sync node since FpApplyQueueItems is null");
×
1618
    return;
×
1619
  }
1620

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

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

1633
  // stop ping timer
1634
  if ((code = syncNodeStopPingTimer(pSyncNode)) != 0) {
14,849!
1635
    sError("vgId:%d, failed to stop ping timer since %s", pSyncNode->vgId, tstrerror(code));
×
1636
    return;
×
1637
  }
1638

1639
  // clean rsp
1640
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
14,849✔
1641
}
1642

1643
void syncNodePostClose(SSyncNode* pSyncNode) {
12,529✔
1644
  if (pSyncNode->pNewNodeReceiver != NULL) {
12,529!
1645
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
12,529!
1646
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1647
    }
1648

1649
    sDebug("vgId:%d, snapshot receiver destroy while preclose sync node, data:%p", pSyncNode->vgId,
12,529✔
1650
           pSyncNode->pNewNodeReceiver);
1651
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
12,529✔
1652
    pSyncNode->pNewNodeReceiver = NULL;
12,528✔
1653
  }
1654
}
12,528✔
1655

1656
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }
2,886!
1657

1658
void syncNodeClose(SSyncNode* pSyncNode) {
14,849✔
1659
  int32_t code = 0;
14,849✔
1660
  if (pSyncNode == NULL) return;
14,849!
1661
  sNInfo(pSyncNode, "sync close, node:%p", pSyncNode);
14,849✔
1662

1663
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
14,849✔
1664

1665
  if ((code = syncNodeStopPingTimer(pSyncNode)) != 0) {
14,849!
1666
    sError("vgId:%d, failed to stop ping timer since %s", pSyncNode->vgId, tstrerror(code));
×
1667
    return;
×
1668
  }
1669
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
14,849!
1670
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1671
    return;
×
1672
  }
1673
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
14,849!
1674
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
1675
    return;
×
1676
  }
1677
  syncNodeLogReplDestroy(pSyncNode);
14,848✔
1678

1679
  syncRespMgrDestroy(pSyncNode->pSyncRespMgr);
14,848✔
1680
  pSyncNode->pSyncRespMgr = NULL;
14,848✔
1681
  voteGrantedDestroy(pSyncNode->pVotesGranted);
14,848✔
1682
  pSyncNode->pVotesGranted = NULL;
14,848✔
1683
  votesRespondDestory(pSyncNode->pVotesRespond);
14,848✔
1684
  pSyncNode->pVotesRespond = NULL;
14,848✔
1685
  syncIndexMgrDestroy(pSyncNode->pNextIndex);
14,848✔
1686
  pSyncNode->pNextIndex = NULL;
14,845✔
1687
  syncIndexMgrDestroy(pSyncNode->pMatchIndex);
14,845✔
1688
  pSyncNode->pMatchIndex = NULL;
14,847✔
1689
  logStoreDestory(pSyncNode->pLogStore);
14,847✔
1690
  pSyncNode->pLogStore = NULL;
14,848✔
1691
  syncLogBufferDestroy(pSyncNode->pLogBuf);
14,848✔
1692
  pSyncNode->pLogBuf = NULL;
14,847✔
1693

1694
  (void)taosThreadMutexDestroy(&pSyncNode->arbTokenMutex);
14,847✔
1695

1696
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
237,528✔
1697
    if (pSyncNode->senders[i] != NULL) {
222,680✔
1698
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", pSyncNode->vgId, pSyncNode->senders[i]);
222,675✔
1699

1700
      if (snapshotSenderIsStart(pSyncNode->senders[i])) {
222,676!
1701
        snapshotSenderStop(pSyncNode->senders[i], false);
×
1702
      }
1703

1704
      snapshotSenderDestroy(pSyncNode->senders[i]);
222,694✔
1705
      pSyncNode->senders[i] = NULL;
222,689✔
1706
    }
1707
  }
1708

1709
  if (pSyncNode->pNewNodeReceiver != NULL) {
14,848✔
1710
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
2,320!
1711
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1712
    }
1713

1714
    sDebug("vgId:%d, snapshot receiver destroy while close, data:%p", pSyncNode->vgId, pSyncNode->pNewNodeReceiver);
2,320✔
1715
    snapshotReceiverDestroy(pSyncNode->pNewNodeReceiver);
2,320✔
1716
    pSyncNode->pNewNodeReceiver = NULL;
2,320✔
1717
  }
1718

1719
  if (pSyncNode->pFsm != NULL) {
14,848!
1720
    taosMemoryFree(pSyncNode->pFsm);
14,848!
1721
  }
1722

1723
  raftStoreClose(pSyncNode);
14,848✔
1724

1725
  taosMemoryFree(pSyncNode);
14,849!
1726
}
1727

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

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

1747
int32_t syncNodeStopPingTimer(SSyncNode* pSyncNode) {
29,698✔
1748
  int32_t code = 0;
29,698✔
1749
  (void)atomic_add_fetch_64(&pSyncNode->pingTimerLogicClockUser, 1);
29,698✔
1750
  bool stop = taosTmrStop(pSyncNode->pPingTimer);
29,697✔
1751
  sDebug("vgId:%d, stop ping timer, stop:%d", pSyncNode->vgId, stop);
29,698✔
1752
  pSyncNode->pPingTimer = NULL;
29,698✔
1753
  return code;
29,698✔
1754
}
1755

1756
int32_t syncNodeStartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
295,964✔
1757
  int32_t code = 0;
295,964✔
1758
  if (syncIsInit()) {
295,964!
1759
    pSyncNode->electTimerMS = ms;
295,964✔
1760

1761
    int64_t execTime = taosGetTimestampMs() + ms;
295,964✔
1762
    atomic_store_64(&(pSyncNode->electTimerParam.executeTime), execTime);
295,964✔
1763
    atomic_store_64(&(pSyncNode->electTimerParam.logicClock), pSyncNode->electTimerLogicClock);
295,964✔
1764
    pSyncNode->electTimerParam.pSyncNode = pSyncNode;
295,964✔
1765
    pSyncNode->electTimerParam.pData = NULL;
295,964✔
1766

1767
    bool stopped = taosTmrReset(pSyncNode->FpElectTimerCB, pSyncNode->electTimerMS, (void*)(pSyncNode->rid),
295,964✔
1768
                                syncEnv()->pTimerManager, &pSyncNode->pElectTimer);
295,964✔
1769
    if (stopped) sWarn("vgId:%d, failed to reset elect timer, ms:%d", pSyncNode->vgId, ms);
295,964!
1770
  } else {
1771
    sError("vgId:%d, start elect timer error, sync env is stop", pSyncNode->vgId);
×
1772
  }
1773
  return code;
295,964✔
1774
}
1775

1776
int32_t syncNodeStopElectTimer(SSyncNode* pSyncNode) {
338,044✔
1777
  int32_t code = 0;
338,044✔
1778
  (void)atomic_add_fetch_64(&pSyncNode->electTimerLogicClock, 1);
338,044✔
1779
  bool stop = taosTmrStop(pSyncNode->pElectTimer);
338,044✔
1780
  sTrace("vgId:%d, stop elect timer, stop:%d", pSyncNode->vgId, stop);
338,044!
1781
  pSyncNode->pElectTimer = NULL;
338,044✔
1782

1783
  return code;
338,044✔
1784
}
1785

1786
int32_t syncNodeRestartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
295,964✔
1787
  int32_t ret = 0;
295,964✔
1788
  TAOS_CHECK_RETURN(syncNodeStopElectTimer(pSyncNode));
295,964!
1789
  TAOS_CHECK_RETURN(syncNodeStartElectTimer(pSyncNode, ms));
295,964!
1790
  return ret;
295,964✔
1791
}
1792

1793
void syncNodeResetElectTimer(SSyncNode* pSyncNode) {
295,964✔
1794
  int32_t code = 0;
295,964✔
1795
  int32_t electMS;
1796

1797
  if (pSyncNode->raftCfg.isStandBy) {
295,964!
1798
    electMS = TIMER_MAX_MS;
×
1799
  } else {
1800
    electMS = syncUtilElectRandomMS(pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine);
295,964✔
1801
  }
1802

1803
  if ((code = syncNodeRestartElectTimer(pSyncNode, electMS)) != 0) {
295,964!
1804
    sWarn("vgId:%d, failed to restart elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
1805
    return;
×
1806
  };
1807

1808
  sNTrace(pSyncNode, "reset elect timer, min:%d, max:%d, ms:%d", pSyncNode->electBaseLine, 2 * pSyncNode->electBaseLine,
295,964!
1809
          electMS);
1810
}
1811

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

1823
  sNTrace(pSyncNode, "start heartbeat timer, ms:%d", pSyncNode->heartbeatTimerMS);
1824
  return code;
1825
}
1826
#endif
1827

1828
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
14,336✔
1829
  int32_t ret = 0;
14,336✔
1830

1831
#if 0
1832
  pSyncNode->heartbeatTimerMS = pSyncNode->hbBaseLine;
1833
  ret = syncNodeDoStartHeartbeatTimer(pSyncNode);
1834
#endif
1835

1836
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
17,228✔
1837
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
2,893✔
1838
    if (pSyncTimer != NULL) {
2,893!
1839
      TAOS_CHECK_RETURN(syncHbTimerStart(pSyncNode, pSyncTimer));
2,893✔
1840
    }
1841
  }
1842

1843
  return ret;
14,335✔
1844
}
1845

1846
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
37,641✔
1847
  int32_t code = 0;
37,641✔
1848

1849
#if 0
1850
  TAOS_CHECK_RETURN(atomic_add_fetch_64(&pSyncNode->heartbeatTimerLogicClockUser, 1));
1851
  bool stop = taosTmrStop(pSyncNode->pHeartbeatTimer);
1852
  sDebug("vgId:%d, stop heartbeat timer, stop:%d", pSyncNode->vgId, stop);
1853
  pSyncNode->pHeartbeatTimer = NULL;
1854
#endif
1855

1856
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
67,376✔
1857
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
29,734✔
1858
    if (pSyncTimer != NULL) {
29,734!
1859
      TAOS_CHECK_RETURN(syncHbTimerStop(pSyncNode, pSyncTimer));
29,734!
1860
    }
1861
  }
1862

1863
  return code;
37,642✔
1864
}
1865

1866
#ifdef BUILD_NO_CALL
1867
int32_t syncNodeRestartHeartbeatTimer(SSyncNode* pSyncNode) {
1868
  // TODO check return value
1869
  int32_t code = 0;
1870
  TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1871
  TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
1872
  return 0;
1873
}
1874
#endif
1875

1876
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pNode, SRpcMsg* pMsg) {
617,407✔
1877
  SEpSet* epSet = NULL;
617,407✔
1878
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
915,318✔
1879
    if (destRaftId->addr == pNode->peersId[i].addr) {
915,250✔
1880
      epSet = &pNode->peersEpset[i];
617,339✔
1881
      break;
617,339✔
1882
    }
1883
  }
1884

1885
  int32_t code = -1;
617,407✔
1886
  if (pNode->syncSendMSg != NULL && epSet != NULL) {
617,407!
1887
    syncUtilMsgHtoN(pMsg->pCont);
617,340✔
1888
    pMsg->info.noResp = 1;
617,337✔
1889
    code = pNode->syncSendMSg(epSet, pMsg);
617,337✔
1890
  }
1891

1892
  if (code < 0) {
617,409✔
1893
    sError("vgId:%d, failed to send sync msg since %s. epset:%p dnode:%d addr:0x%" PRIx64, pNode->vgId, tstrerror(code),
68!
1894
           epSet, DID(destRaftId), destRaftId->addr);
1895
    rpcFreeCont(pMsg->pCont);
68✔
1896
  }
1897

1898
  TAOS_RETURN(code);
617,409✔
1899
}
1900

1901
inline bool syncNodeInConfig(SSyncNode* pNode, const SSyncCfg* pCfg) {
2,665✔
1902
  bool b1 = false;
2,665✔
1903
  bool b2 = false;
2,665✔
1904

1905
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
3,111!
1906
    if (strcmp(pCfg->nodeInfo[i].nodeFqdn, pNode->myNodeInfo.nodeFqdn) == 0 &&
3,111!
1907
        pCfg->nodeInfo[i].nodePort == pNode->myNodeInfo.nodePort) {
3,111✔
1908
      b1 = true;
2,665✔
1909
      break;
2,665✔
1910
    }
1911
  }
1912

1913
  for (int32_t i = 0; i < pCfg->totalReplicaNum; ++i) {
3,111!
1914
    SRaftId raftId = {
3,111✔
1915
        .addr = SYNC_ADDR(&pCfg->nodeInfo[i]),
3,111✔
1916
        .vgId = pNode->vgId,
3,111✔
1917
    };
1918

1919
    if (syncUtilSameId(&raftId, &pNode->myRaftId)) {
3,111✔
1920
      b2 = true;
2,665✔
1921
      break;
2,665✔
1922
    }
1923
  }
1924

1925
  if (b1 != b2) {
2,665!
1926
    terrno = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1927
    return false;
×
1928
  }
1929
  return b1;
2,665✔
1930
}
1931

1932
static bool syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg) {
3,868✔
1933
  if (pOldCfg->totalReplicaNum != pNewCfg->totalReplicaNum) return true;
3,868✔
1934
  if (pOldCfg->myIndex != pNewCfg->myIndex) return true;
2,651✔
1935
  for (int32_t i = 0; i < pOldCfg->totalReplicaNum; ++i) {
6,405✔
1936
    const SNodeInfo* pOldInfo = &pOldCfg->nodeInfo[i];
4,544✔
1937
    const SNodeInfo* pNewInfo = &pNewCfg->nodeInfo[i];
4,544✔
1938
    if (strcmp(pOldInfo->nodeFqdn, pNewInfo->nodeFqdn) != 0) return true;
4,544!
1939
    if (pOldInfo->nodePort != pNewInfo->nodePort) return true;
4,544✔
1940
    if (pOldInfo->nodeRole != pNewInfo->nodeRole) return true;
4,542✔
1941
  }
1942

1943
  return false;
1,861✔
1944
}
1945

1946
int32_t syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* pNewConfig, SyncIndex lastConfigChangeIndex) {
2,129✔
1947
  int32_t  code = 0;
2,129✔
1948
  SSyncCfg oldConfig = pSyncNode->raftCfg.cfg;
2,129✔
1949
  if (!syncIsConfigChanged(&oldConfig, pNewConfig)) {
2,129✔
1950
    sInfo("vgId:1, sync not reconfig since not changed");
1,861✔
1951
    return 0;
1,861✔
1952
  }
1953

1954
  pSyncNode->raftCfg.cfg = *pNewConfig;
268✔
1955
  pSyncNode->raftCfg.lastConfigIndex = lastConfigChangeIndex;
268✔
1956

1957
  pSyncNode->configChangeNum++;
268✔
1958

1959
  bool IamInOld = syncNodeInConfig(pSyncNode, &oldConfig);
268✔
1960
  bool IamInNew = syncNodeInConfig(pSyncNode, pNewConfig);
268✔
1961

1962
  bool isDrop = false;
268✔
1963
  bool isAdd = false;
268✔
1964

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

1971
  if (!IamInOld && IamInNew) {
268!
1972
    isAdd = true;
×
1973
  } else {
1974
    isAdd = false;
268✔
1975
  }
1976

1977
  // log begin config change
1978
  sNInfo(pSyncNode, "begin do config change, from %d to %d, from %" PRId64 " to %" PRId64 ", replicas:%d",
268!
1979
         pSyncNode->vgId, oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum, oldConfig.lastIndex,
1980
         pNewConfig->lastIndex);
1981

1982
  if (IamInNew) {
268!
1983
    pSyncNode->raftCfg.isStandBy = 0;  // change isStandBy to normal
268✔
1984
  }
1985
  if (isDrop) {
268!
1986
    pSyncNode->raftCfg.isStandBy = 1;  // set standby
×
1987
  }
1988

1989
  // add last config index
1990
  SRaftCfg* pCfg = &pSyncNode->raftCfg;
268✔
1991
  if (pCfg->configIndexCount >= MAX_CONFIG_INDEX_COUNT) {
268!
1992
    sNError(pSyncNode, "failed to add cfg index:%d since out of range", pCfg->configIndexCount);
×
1993
    terrno = TSDB_CODE_OUT_OF_RANGE;
×
1994
    return -1;
×
1995
  }
1996

1997
  pCfg->configIndexArr[pCfg->configIndexCount] = lastConfigChangeIndex;
268✔
1998
  pCfg->configIndexCount++;
268✔
1999

2000
  if (IamInNew) {
268!
2001
    //-----------------------------------------
2002
    int32_t ret = 0;
268✔
2003

2004
    // save snapshot senders
2005
    SRaftId oldReplicasId[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
2006
    memcpy(oldReplicasId, pSyncNode->replicasId, sizeof(oldReplicasId));
268✔
2007
    SSyncSnapshotSender* oldSenders[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
2008
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
4,288✔
2009
      oldSenders[i] = pSyncNode->senders[i];
4,020✔
2010
      sSTrace(oldSenders[i], "snapshot sender save old");
4,020!
2011
    }
2012

2013
    // init internal
2014
    pSyncNode->myNodeInfo = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex];
268✔
2015
    if (syncUtilNodeInfo2RaftId(&pSyncNode->myNodeInfo, pSyncNode->vgId, &pSyncNode->myRaftId) == false) return terrno;
268!
2016

2017
    // init peersNum, peers, peersId
2018
    pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
268✔
2019
    int32_t j = 0;
268✔
2020
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
962✔
2021
      if (i != pSyncNode->raftCfg.cfg.myIndex) {
694✔
2022
        pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
426✔
2023
        syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
426✔
2024
        j++;
426✔
2025
      }
2026
    }
2027
    for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
694✔
2028
      if (syncUtilNodeInfo2RaftId(&pSyncNode->peersNodeInfo[i], pSyncNode->vgId, &pSyncNode->peersId[i]) == false)
426!
2029
        return terrno;
×
2030
    }
2031

2032
    // init replicaNum, replicasId
2033
    pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
268✔
2034
    pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
268✔
2035
    for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
962✔
2036
      if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
694!
2037
          false)
2038
        return terrno;
×
2039
    }
2040

2041
    // update quorum first
2042
    pSyncNode->quorum = syncUtilQuorum(pSyncNode->raftCfg.cfg.replicaNum);
268✔
2043

2044
    syncIndexMgrUpdate(pSyncNode->pNextIndex, pSyncNode);
268✔
2045
    syncIndexMgrUpdate(pSyncNode->pMatchIndex, pSyncNode);
268✔
2046
    voteGrantedUpdate(pSyncNode->pVotesGranted, pSyncNode);
268✔
2047
    votesRespondUpdate(pSyncNode->pVotesRespond, pSyncNode);
268✔
2048

2049
    // reset snapshot senders
2050

2051
    // clear new
2052
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
4,288✔
2053
      pSyncNode->senders[i] = NULL;
4,020✔
2054
    }
2055

2056
    // reset new
2057
    for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
962✔
2058
      // reset sender
2059
      bool reset = false;
694✔
2060
      for (int32_t j = 0; j < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++j) {
2,927✔
2061
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
2,805!
2062
          sNTrace(pSyncNode, "snapshot sender reset for:%" PRId64 ", newIndex:%d, dnode:%d, %p",
572!
2063
                  (pSyncNode->replicasId)[i].addr, i, DID(&pSyncNode->replicasId[i]), oldSenders[j]);
2064

2065
          pSyncNode->senders[i] = oldSenders[j];
572✔
2066
          oldSenders[j] = NULL;
572✔
2067
          reset = true;
572✔
2068

2069
          // reset replicaIndex
2070
          int32_t oldreplicaIndex = pSyncNode->senders[i]->replicaIndex;
572✔
2071
          pSyncNode->senders[i]->replicaIndex = i;
572✔
2072

2073
          sNTrace(pSyncNode, "snapshot sender udpate replicaIndex from %d to %d, dnode:%d, %p, reset:%d",
572!
2074
                  oldreplicaIndex, i, DID(&pSyncNode->replicasId[i]), pSyncNode->senders[i], reset);
2075

2076
          break;
572✔
2077
        }
2078
      }
2079
    }
2080

2081
    // create new
2082
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
4,288✔
2083
      if (pSyncNode->senders[i] == NULL) {
4,020✔
2084
        TAOS_CHECK_RETURN(snapshotSenderCreate(pSyncNode, i, &pSyncNode->senders[i]));
3,448!
2085
        if (pSyncNode->senders[i] == NULL) {
3,448!
2086
          // will be created later while send snapshot
2087
          sSError(pSyncNode->senders[i], "snapshot sender create failed while reconfig");
×
2088
        } else {
2089
          sSDebug(pSyncNode->senders[i], "snapshot sender create while reconfig, data:%p", pSyncNode->senders[i]);
3,448✔
2090
        }
2091
      } else {
2092
        sSDebug(pSyncNode->senders[i], "snapshot sender already exist, data:%p", pSyncNode->senders[i]);
572✔
2093
      }
2094
    }
2095

2096
    // free old
2097
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
4,288✔
2098
      if (oldSenders[i] != NULL) {
4,020✔
2099
        sSDebug(oldSenders[i], "snapshot sender destroy old, data:%p replica-index:%d", oldSenders[i], i);
3,448✔
2100
        snapshotSenderDestroy(oldSenders[i]);
3,448✔
2101
        oldSenders[i] = NULL;
3,448✔
2102
      }
2103
    }
2104

2105
    // persist cfg
2106
    TAOS_CHECK_RETURN(syncWriteCfgFile(pSyncNode));
268!
2107
  } else {
2108
    // persist cfg
2109
    TAOS_CHECK_RETURN(syncWriteCfgFile(pSyncNode));
×
2110
    sNInfo(pSyncNode, "do not config change from %d to %d", oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum);
×
2111
  }
2112

2113
_END:
×
2114
  // log end config change
2115
  sNInfo(pSyncNode, "end do config change, from %d to %d", oldConfig.totalReplicaNum, pNewConfig->totalReplicaNum);
268!
2116
  return 0;
268✔
2117
}
2118

2119
// raft state change --------------
2120
void syncNodeUpdateTermWithoutStepDown(SSyncNode* pSyncNode, SyncTerm term) {
158✔
2121
  if (term > raftStoreGetTerm(pSyncNode)) {
158!
2122
    raftStoreSetTerm(pSyncNode, term);
×
2123
  }
2124
}
158✔
2125

2126
void syncNodeStepDown(SSyncNode* pSyncNode, SyncTerm newTerm, SRaftId id) {
248,453✔
2127
  SyncTerm currentTerm = raftStoreGetTerm(pSyncNode);
248,453✔
2128
  if (currentTerm > newTerm) {
248,453!
2129
    sNTrace(pSyncNode, "step down, ignore, new-term:%" PRId64 ", current-term:%" PRId64, newTerm, currentTerm);
×
2130
    return;
×
2131
  }
2132

2133
  do {
2134
    sNTrace(pSyncNode, "step down, new-term:%" PRId64 ", current-term:%" PRId64, newTerm, currentTerm);
248,453!
2135
  } while (0);
2136

2137
  if (pSyncNode->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
248,453✔
2138
    (void)taosThreadMutexLock(&pSyncNode->arbTokenMutex);
1✔
2139
    syncUtilGenerateArbToken(pSyncNode->myNodeInfo.nodeId, pSyncNode->vgId, pSyncNode->arbToken);
1✔
2140
    sInfo("vgId:%d, step down as assigned leader, new arbToken:%s", pSyncNode->vgId, pSyncNode->arbToken);
1!
2141
    (void)taosThreadMutexUnlock(&pSyncNode->arbTokenMutex);
1✔
2142
  }
2143

2144
  if (currentTerm < newTerm) {
248,453✔
2145
    raftStoreSetTerm(pSyncNode, newTerm);
2,562✔
2146
    char tmpBuf[64];
2147
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
2,562✔
2148
    syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
2,562✔
2149
    raftStoreClearVote(pSyncNode);
2,562✔
2150
  } else {
2151
    if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
245,891✔
2152
      syncNodeBecomeFollower(pSyncNode, id, "step down");
4✔
2153
    }
2154
  }
2155
}
2156

2157
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }
5,989✔
2158

2159
void syncNodeBecomeFollower(SSyncNode* pSyncNode, SRaftId leaderId, const char* debugStr) {
5,989✔
2160
  int32_t code = 0;  // maybe clear leader cache
5,989✔
2161
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
5,989✔
2162
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
50✔
2163
    pSyncNode->leaderCacheEp.port = 0;
50✔
2164
    pSyncNode->leaderCacheEp.fqdn[0] = '\0';
50✔
2165
  }
2166

2167
  pSyncNode->hbSlowNum = 0;
5,989✔
2168

2169
  pSyncNode->leaderCache = leaderId;  // state change
5,989✔
2170

2171
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
19,454✔
2172
    if (syncUtilSameId(&pSyncNode->replicasId[i], &leaderId)) {
16,031✔
2173
      pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[i].nodePort;
2,566✔
2174
      strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
2,566✔
2175
      break;
2,566✔
2176
    }
2177
  }
2178
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
5,989✔
2179
  pSyncNode->roleTimeMs = taosGetTimestampMs();
5,989✔
2180
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
5,989!
2181
    sError("vgId:%d, failed to stop heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2182
    return;
×
2183
  }
2184

2185
  // trace log
2186
  sNTrace(pSyncNode, "become follower %s", debugStr);
5,989!
2187

2188
  // send rsp to client
2189
  syncNodeLeaderChangeRsp(pSyncNode);
5,989✔
2190

2191
  // call back
2192
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
5,989!
2193
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
5,989✔
2194
  }
2195

2196
  // min match index
2197
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
5,989✔
2198

2199
  // reset log buffer
2200
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
5,989!
2201
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2202
    return;
×
2203
  }
2204

2205
  // reset elect timer
2206
  syncNodeResetElectTimer(pSyncNode);
5,989✔
2207

2208
  sInfo("vgId:%d, become follower. %s", pSyncNode->vgId, debugStr);
5,989!
2209
}
2210

2211
void syncNodeBecomeLearner(SSyncNode* pSyncNode, const char* debugStr) {
270✔
2212
  pSyncNode->hbSlowNum = 0;
270✔
2213

2214
  // state change
2215
  pSyncNode->state = TAOS_SYNC_STATE_LEARNER;
270✔
2216
  pSyncNode->roleTimeMs = taosGetTimestampMs();
270✔
2217

2218
  // trace log
2219
  sNTrace(pSyncNode, "become learner %s", debugStr);
270!
2220

2221
  // call back
2222
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLearnerCb != NULL) {
270!
2223
    pSyncNode->pFsm->FpBecomeLearnerCb(pSyncNode->pFsm);
270✔
2224
  }
2225

2226
  // min match index
2227
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
270✔
2228

2229
  // reset log buffer
2230
  int32_t code = 0;
270✔
2231
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
270!
2232
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2233
    return;
×
2234
  };
2235
}
2236

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

2260
  // reset restoreFinish
2261
  pSyncNode->restoreFinish = false;
12,380✔
2262

2263
  // state change
2264
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
12,380✔
2265
  pSyncNode->roleTimeMs = taosGetTimestampMs();
12,380✔
2266

2267
  // set leader cache
2268
  pSyncNode->leaderCache = pSyncNode->myRaftId;
12,380✔
2269
  strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeFqdn,
12,380✔
2270
          TSDB_FQDN_LEN);
2271
  pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodePort;
12,380✔
2272

2273
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
27,222✔
2274
    SyncIndex lastIndex;
2275
    SyncTerm  lastTerm;
2276
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
14,842✔
2277
    if (code != 0) {
14,842!
2278
      sError("vgId:%d, failed to become leader since %s", pSyncNode->vgId, tstrerror(code));
×
2279
      return;
×
2280
    }
2281
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
14,842✔
2282
  }
2283

2284
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
27,222✔
2285
    // maybe overwrite myself, no harm
2286
    // just do it!
2287
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
14,842✔
2288
  }
2289

2290
  // init peer mgr
2291
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
12,380!
2292
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2293
    return;
×
2294
  }
2295

2296
#if 0
2297
  // update sender private term
2298
  SSyncSnapshotSender* pMySender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->myRaftId));
2299
  if (pMySender != NULL) {
2300
    for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
2301
      if (pSyncNode->senders[i]->privateTerm > pMySender->privateTerm) {
2302
        pMySender->privateTerm = pSyncNode->senders[i]->privateTerm;
2303
      }
2304
    }
2305
    (pMySender->privateTerm) += 100;
2306
  }
2307
#endif
2308

2309
  // close receiver
2310
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
12,380!
2311
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2312
  }
2313

2314
  // stop elect timer
2315
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
12,380!
2316
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
2317
    return;
×
2318
  }
2319

2320
  // start heartbeat timer
2321
  if ((code = syncNodeStartHeartbeatTimer(pSyncNode)) != 0) {
12,380!
2322
    sError("vgId:%d, failed to start heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2323
    return;
×
2324
  }
2325

2326
  // send heartbeat right now
2327
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
12,380!
2328
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2329
    return;
×
2330
  }
2331

2332
  // call back
2333
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
12,380!
2334
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
12,380✔
2335
  }
2336

2337
  // min match index
2338
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
12,380✔
2339

2340
  // reset log buffer
2341
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
12,380!
2342
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2343
    return;
×
2344
  }
2345

2346
  // trace log
2347
  sNInfo(pSyncNode, "become leader %s", debugStr);
12,380✔
2348
}
2349

2350
void syncNodeBecomeAssignedLeader(SSyncNode* pSyncNode) {
2✔
2351
  int32_t code = 0;
2✔
2352
  pSyncNode->becomeAssignedLeaderNum++;
2✔
2353
  pSyncNode->hbrSlowNum = 0;
2✔
2354

2355
  // reset restoreFinish
2356
  // pSyncNode->restoreFinish = false;
2357

2358
  // state change
2359
  pSyncNode->state = TAOS_SYNC_STATE_ASSIGNED_LEADER;
2✔
2360
  pSyncNode->roleTimeMs = taosGetTimestampMs();
2✔
2361

2362
  // set leader cache
2363
  pSyncNode->leaderCache = pSyncNode->myRaftId;
2✔
2364

2365
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
6✔
2366
    SyncIndex lastIndex;
2367
    SyncTerm  lastTerm;
2368
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
4✔
2369
    if (code != 0) {
4!
2370
      sError("vgId:%d, failed to become assigned leader since %s", pSyncNode->vgId, tstrerror(code));
×
2371
      return;
×
2372
    }
2373
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
4✔
2374
  }
2375

2376
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
6✔
2377
    // maybe overwrite myself, no harm
2378
    // just do it!
2379
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
4✔
2380
  }
2381

2382
  // init peer mgr
2383
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
2!
2384
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2385
    return;
×
2386
  }
2387

2388
  // close receiver
2389
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
2!
2390
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2391
  }
2392

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

2399
  // start heartbeat timer
2400
  if ((code = syncNodeStartHeartbeatTimer(pSyncNode)) != 0) {
2✔
2401
    sError("vgId:%d, failed to start heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
1!
2402
    return;
1✔
2403
  }
2404

2405
  // send heartbeat right now
2406
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
1!
2407
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2408
    return;
×
2409
  }
2410

2411
  // call back
2412
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeAssignedLeaderCb != NULL) {
1!
2413
    pSyncNode->pFsm->FpBecomeAssignedLeaderCb(pSyncNode->pFsm);
1✔
2414
  }
2415

2416
  // min match index
2417
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
1✔
2418

2419
  // reset log buffer
2420
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
1!
2421
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2422
    return;
×
2423
  }
2424

2425
  // trace log
2426
  sNInfo(pSyncNode, "become assigned leader");
1!
2427
}
2428

2429
void syncNodeCandidate2Leader(SSyncNode* pSyncNode) {
1,210✔
2430
  if (pSyncNode->state != TAOS_SYNC_STATE_CANDIDATE) {
1,210!
2431
    sError("vgId:%d, failed leader from candidate since node state is wrong:%d", pSyncNode->vgId, pSyncNode->state);
×
2432
    return;
×
2433
  }
2434
  bool granted = voteGrantedMajority(pSyncNode->pVotesGranted);
1,210✔
2435
  if (!granted) {
1,210!
2436
    sError("vgId:%d, not granted by majority.", pSyncNode->vgId);
×
2437
    return;
×
2438
  }
2439
  syncNodeBecomeLeader(pSyncNode, "candidate to leader");
1,210✔
2440

2441
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
1,210!
2442

2443
  int32_t ret = syncNodeAppendNoop(pSyncNode);
1,210✔
2444
  if (ret < 0) {
1,210!
2445
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, terrstr());
×
2446
  }
2447

2448
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,210✔
2449

2450
  sInfo("vgId:%d, become leader. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64, pSyncNode->vgId,
1,210!
2451
        raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2452
}
2453

2454
bool syncNodeIsMnode(SSyncNode* pSyncNode) { return (pSyncNode->vgId == 1); }
117,967✔
2455

2456
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
27,231✔
2457
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
435,682✔
2458
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
408,451✔
2459
    pSyncNode->peerStates[i].lastSendTime = 0;
408,451✔
2460
  }
2461

2462
  return 0;
27,231✔
2463
}
2464

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

2476
  sNTrace(pSyncNode, "follower to candidate");
1,365!
2477
}
2478

2479
int32_t syncNodeAssignedLeader2Leader(SSyncNode* pSyncNode) {
×
2480
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) return TSDB_CODE_SYN_INTERNAL_ERROR;
×
2481
  syncNodeBecomeLeader(pSyncNode, "assigned leader to leader");
×
2482

2483
  sNTrace(pSyncNode, "assigned leader to leader");
×
2484

2485
  int32_t ret = syncNodeAppendNoop(pSyncNode);
×
2486
  if (ret < 0) {
×
2487
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, tstrerror(ret));
×
2488
  }
2489

2490
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
×
2491
  sInfo("vgId:%d, become leader from assigned leader. term:%" PRId64 ", commit index:%" PRId64
×
2492
        "assigned commit index:%" PRId64 ", last index:%" PRId64,
2493
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, pSyncNode->assignedCommitIndex,
2494
        lastIndex);
2495
  return 0;
×
2496
}
2497

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

2512
  raftStoreVote(pSyncNode, pRaftId);
1,459✔
2513
}
2514

2515
// simulate get vote from outside
2516
void syncNodeVoteForSelf(SSyncNode* pSyncNode, SyncTerm currentTerm) {
1,459✔
2517
  syncNodeVoteForTerm(pSyncNode, currentTerm, &pSyncNode->myRaftId);
1,459✔
2518

2519
  SRpcMsg rpcMsg = {0};
1,459✔
2520
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
1,459✔
2521
  if (ret != 0) return;
1,459!
2522

2523
  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
1,459✔
2524
  pMsg->srcId = pSyncNode->myRaftId;
1,459✔
2525
  pMsg->destId = pSyncNode->myRaftId;
1,459✔
2526
  pMsg->term = currentTerm;
1,459✔
2527
  pMsg->voteGranted = true;
1,459✔
2528

2529
  voteGrantedVote(pSyncNode->pVotesGranted, pMsg);
1,459✔
2530
  votesRespondAdd(pSyncNode->pVotesRespond, pMsg);
1,459✔
2531
  rpcFreeCont(rpcMsg.pCont);
1,459✔
2532
}
2533

2534
// return if has a snapshot
2535
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
20,309✔
2536
  bool      ret = false;
20,309✔
2537
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
20,309✔
2538
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
20,309!
2539
    // TODO check return value
2540
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
20,309✔
2541
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
20,309✔
2542
      ret = true;
1,942✔
2543
    }
2544
  }
2545
  return ret;
20,309✔
2546
}
2547

2548
// return max(logLastIndex, snapshotLastIndex)
2549
// if no snapshot and log, return -1
2550
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
20,347✔
2551
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
20,347✔
2552
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
20,347!
2553
    // TODO check return value
2554
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
20,347✔
2555
  }
2556
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
20,347✔
2557

2558
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
20,347✔
2559
  return lastIndex;
20,347✔
2560
}
2561

2562
// return the last term of snapshot and log
2563
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
2564
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
20,309✔
2565
  SyncTerm lastTerm = 0;
20,309✔
2566
  if (syncNodeHasSnapshot(pSyncNode)) {
20,309✔
2567
    // has snapshot
2568
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
1,942✔
2569
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
1,942!
2570
      // TODO check return value
2571
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
1,942✔
2572
    }
2573

2574
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,942✔
2575
    if (logLastIndex > snapshot.lastApplyIndex) {
1,942✔
2576
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
902✔
2577
    } else {
2578
      lastTerm = snapshot.lastApplyTerm;
1,040✔
2579
    }
2580

2581
  } else {
2582
    // no snapshot
2583
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
18,367✔
2584
  }
2585

2586
  return lastTerm;
20,309✔
2587
}
2588

2589
// get last index and term along with snapshot
2590
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
17,739✔
2591
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
17,739✔
2592
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
17,739✔
2593
  return 0;
17,739✔
2594
}
2595

2596
#ifdef BUILD_NO_CALL
2597
// return append-entries first try index
2598
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
2599
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
2600
  return syncStartIndex;
2601
}
2602

2603
// if index > 0, return index - 1
2604
// else, return -1
2605
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
2606
  SyncIndex preIndex = index - 1;
2607
  if (preIndex < SYNC_INDEX_INVALID) {
2608
    preIndex = SYNC_INDEX_INVALID;
2609
  }
2610

2611
  return preIndex;
2612
}
2613

2614
// if index < 0, return SYNC_TERM_INVALID
2615
// if index == 0, return 0
2616
// if index > 0, return preTerm
2617
// if error, return SYNC_TERM_INVALID
2618
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
2619
  if (index < SYNC_INDEX_BEGIN) {
2620
    return SYNC_TERM_INVALID;
2621
  }
2622

2623
  if (index == SYNC_INDEX_BEGIN) {
2624
    return 0;
2625
  }
2626

2627
  SyncTerm  preTerm = 0;
2628
  SyncIndex preIndex = index - 1;
2629

2630
  SSyncRaftEntry* pPreEntry = NULL;
2631
  SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
2632
  LRUHandle*      h = taosLRUCacheLookup(pCache, &preIndex, sizeof(preIndex));
2633
  int32_t         code = 0;
2634
  if (h) {
2635
    pPreEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2636
    code = 0;
2637

2638
    pSyncNode->pLogStore->cacheHit++;
2639
    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);
2640

2641
  } else {
2642
    pSyncNode->pLogStore->cacheMiss++;
2643
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);
2644

2645
    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
2646
  }
2647

2648
  SSnapshot snapshot = {.data = NULL,
2649
                        .lastApplyIndex = SYNC_INDEX_INVALID,
2650
                        .lastApplyTerm = SYNC_TERM_INVALID,
2651
                        .lastConfigIndex = SYNC_INDEX_INVALID};
2652

2653
  if (code == 0) {
2654
    if (pPreEntry == NULL) return -1;
2655
    preTerm = pPreEntry->term;
2656

2657
    if (h) {
2658
      taosLRUCacheRelease(pCache, h, false);
2659
    } else {
2660
      syncEntryDestroy(pPreEntry);
2661
    }
2662

2663
    return preTerm;
2664
  } else {
2665
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2666
      // TODO check return value
2667
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2668
      if (snapshot.lastApplyIndex == preIndex) {
2669
        return snapshot.lastApplyTerm;
2670
      }
2671
    }
2672
  }
2673

2674
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
2675
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
2676
  return SYNC_TERM_INVALID;
2677
}
2678

2679
// get pre index and term of "index"
2680
int32_t syncNodeGetPreIndexTerm(SSyncNode* pSyncNode, SyncIndex index, SyncIndex* pPreIndex, SyncTerm* pPreTerm) {
2681
  *pPreIndex = syncNodeGetPreIndex(pSyncNode, index);
2682
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
2683
  return 0;
2684
}
2685
#endif
2686

2687
static void syncNodeEqPingTimer(void* param, void* tmrId) {
46,072✔
2688
  if (!syncIsInit()) return;
46,072!
2689

2690
  int64_t    rid = (int64_t)param;
46,072✔
2691
  SSyncNode* pNode = syncNodeAcquire(rid);
46,072✔
2692

2693
  if (pNode == NULL) return;
46,072!
2694

2695
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
46,072!
2696
    SRpcMsg rpcMsg = {0};
46,072✔
2697
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
46,072✔
2698
                                    pNode->pingTimerMS, pNode);
2699
    if (code != 0) {
46,072!
2700
      sError("failed to build ping msg");
×
2701
      rpcFreeCont(rpcMsg.pCont);
×
2702
      goto _out;
×
2703
    }
2704

2705
    // sTrace("enqueue ping msg");
2706
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
46,072✔
2707
    if (code != 0) {
46,072!
2708
      sError("failed to sync enqueue ping msg since %s", terrstr());
×
2709
      rpcFreeCont(rpcMsg.pCont);
×
2710
      goto _out;
×
2711
    }
2712

2713
  _out:
46,072✔
2714
    if (taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
46,072!
2715
                     &pNode->pPingTimer))
2716
      sError("failed to reset ping timer");
×
2717
  }
2718
  syncNodeRelease(pNode);
46,072✔
2719
}
2720

2721
static void syncNodeEqElectTimer(void* param, void* tmrId) {
1,464✔
2722
  if (!syncIsInit()) return;
1,468!
2723

2724
  int64_t    rid = (int64_t)param;
1,464✔
2725
  SSyncNode* pNode = syncNodeAcquire(rid);
1,464✔
2726

2727
  if (pNode == NULL) return;
1,464✔
2728

2729
  if (pNode->syncEqMsg == NULL) {
1,463!
2730
    syncNodeRelease(pNode);
×
2731
    return;
×
2732
  }
2733

2734
  int64_t tsNow = taosGetTimestampMs();
1,463✔
2735
  if (tsNow < pNode->electTimerParam.executeTime) {
1,463✔
2736
    syncNodeRelease(pNode);
3✔
2737
    return;
3✔
2738
  }
2739

2740
  SRpcMsg rpcMsg = {0};
1,460✔
2741
  int32_t code =
2742
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
1,460✔
2743

2744
  if (code != 0) {
1,460!
2745
    sError("failed to build elect msg");
×
2746
    syncNodeRelease(pNode);
×
2747
    return;
×
2748
  }
2749

2750
  SyncTimeout* pTimeout = rpcMsg.pCont;
1,460✔
2751
  sNTrace(pNode, "enqueue elect msg lc:%" PRId64, pTimeout->logicClock);
1,460!
2752

2753
  code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
1,460✔
2754
  if (code != 0) {
1,460!
2755
    sError("failed to sync enqueue elect msg since %s", terrstr());
×
2756
    rpcFreeCont(rpcMsg.pCont);
×
2757
    syncNodeRelease(pNode);
×
2758
    return;
×
2759
  }
2760

2761
  syncNodeRelease(pNode);
1,460✔
2762
}
2763

2764
#ifdef BUILD_NO_CALL
2765
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
2766
  if (!syncIsInit()) return;
2767

2768
  int64_t    rid = (int64_t)param;
2769
  SSyncNode* pNode = syncNodeAcquire(rid);
2770

2771
  if (pNode == NULL) return;
2772

2773
  if (pNode->totalReplicaNum > 1) {
2774
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
2775
      SRpcMsg rpcMsg = {0};
2776
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
2777
                                      pNode->heartbeatTimerMS, pNode);
2778

2779
      if (code != 0) {
2780
        sError("failed to build heartbeat msg");
2781
        goto _out;
2782
      }
2783

2784
      sTrace("vgId:%d, enqueue heartbeat timer", pNode->vgId);
2785
      code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
2786
      if (code != 0) {
2787
        sError("failed to enqueue heartbeat msg since %s", terrstr());
2788
        rpcFreeCont(rpcMsg.pCont);
2789
        goto _out;
2790
      }
2791

2792
    _out:
2793
      if (taosTmrReset(syncNodeEqHeartbeatTimer, pNode->heartbeatTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
2794
                       &pNode->pHeartbeatTimer) != 0)
2795
        return;
2796

2797
    } else {
2798
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
2799
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
2800
    }
2801
  }
2802
}
2803
#endif
2804

2805
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
44,488✔
2806
  int32_t code = 0;
44,488✔
2807
  int64_t hbDataRid = (int64_t)param;
44,488✔
2808
  int64_t tsNow = taosGetTimestampMs();
44,488✔
2809

2810
  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
44,488✔
2811
  if (pData == NULL) {
44,488!
2812
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
×
2813
    return;
×
2814
  }
2815

2816
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
44,488✔
2817
  if (pSyncNode == NULL) {
44,488✔
2818
    syncHbTimerDataRelease(pData);
3✔
2819
    sError("hb timer get pSyncNode NULL");
3!
2820
    return;
3✔
2821
  }
2822

2823
  SSyncTimer* pSyncTimer = pData->pTimer;
44,485✔
2824

2825
  if (!pSyncNode->isStart) {
44,485!
2826
    syncNodeRelease(pSyncNode);
×
2827
    syncHbTimerDataRelease(pData);
×
2828
    sError("vgId:%d, hb timer sync node already stop", pSyncNode->vgId);
×
2829
    return;
×
2830
  }
2831

2832
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
44,485!
2833
    syncNodeRelease(pSyncNode);
×
2834
    syncHbTimerDataRelease(pData);
×
2835
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
×
2836
    return;
×
2837
  }
2838

2839
  sTrace("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
44,485!
2840
         pData->destId.addr);
2841

2842
  if (pSyncNode->totalReplicaNum > 1) {
44,485✔
2843
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
44,481✔
2844
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
44,481✔
2845

2846
    if (timerLogicClock == msgLogicClock) {
44,481✔
2847
      if (tsNow > pData->execTime) {
44,476✔
2848
        pData->execTime += pSyncTimer->timerMS;
44,465✔
2849

2850
        SRpcMsg rpcMsg = {0};
44,465✔
2851
        if ((code = syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId)) != 0) {
44,465!
2852
          sError("vgId:%d, failed to build heartbeat msg since %s", pSyncNode->vgId, tstrerror(code));
×
2853
          syncNodeRelease(pSyncNode);
×
2854
          syncHbTimerDataRelease(pData);
×
2855
          return;
×
2856
        }
2857

2858
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);
44,465✔
2859

2860
        SyncHeartbeat* pSyncMsg = rpcMsg.pCont;
44,465✔
2861
        pSyncMsg->srcId = pSyncNode->myRaftId;
44,465✔
2862
        pSyncMsg->destId = pData->destId;
44,465✔
2863
        pSyncMsg->term = raftStoreGetTerm(pSyncNode);
44,465✔
2864
        pSyncMsg->commitIndex = pSyncNode->commitIndex;
44,465✔
2865
        pSyncMsg->minMatchIndex = pSyncNode->minMatchIndex;
44,465✔
2866
        pSyncMsg->privateTerm = 0;
44,465✔
2867
        pSyncMsg->timeStamp = tsNow;
44,465✔
2868

2869
        // update reset time
2870
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
44,465✔
2871
        pSyncTimer->timeStamp = tsNow;
44,465✔
2872

2873
        // send msg
2874
        TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
44,465✔
2875
        TRACE_SET_ROOTID(&(rpcMsg.info.traceId), tGenIdPI64());
44,465✔
2876
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime, &(rpcMsg.info.traceId));
44,465✔
2877
        int ret = syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
44,465✔
2878
        if (ret != 0) {
44,465✔
2879
          sError("vgId:%d, failed to send heartbeat since %s", pSyncNode->vgId, tstrerror(ret));
68!
2880
        }
2881
      }
2882

2883
      if (syncIsInit()) {
44,476!
2884
        sTrace("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
44,476!
2885
        bool stopped = taosTmrResetPriority(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS, (void*)hbDataRid,
44,476✔
2886
                                            syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
44,476✔
2887
        if (stopped) sError("vgId:%d, reset peer hb timer error, %s", pSyncNode->vgId, tstrerror(code));
44,476!
2888

2889
      } else {
2890
        sError("sync env is stop, reset peer hb timer error");
×
2891
      }
2892

2893
    } else {
2894
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64, pSyncNode->vgId,
5!
2895
             timerLogicClock, msgLogicClock);
2896
    }
2897
  }
2898

2899
  syncHbTimerDataRelease(pData);
44,485✔
2900
  syncNodeRelease(pSyncNode);
44,485✔
2901
}
2902

2903
#ifdef BUILD_NO_CALL
2904
static void deleteCacheEntry(const void* key, size_t keyLen, void* value, void* ud) {
2905
  (void)ud;
2906
  taosMemoryFree(value);
2907
}
2908

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

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

2921
  return code;
2922
}
2923
#endif
2924

2925
void syncBuildConfigFromReq(SAlterVnodeReplicaReq* pReq, SSyncCfg* cfg) {  // TODO SAlterVnodeReplicaReq name is proper?
×
2926
  cfg->replicaNum = 0;
×
2927
  cfg->totalReplicaNum = 0;
×
2928
  int32_t code = 0;
×
2929

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

2962
int32_t syncNodeCheckChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry) {
×
2963
  int32_t code = 0;
×
2964
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
2965
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
2966
  }
2967

2968
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
2969
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
2970

2971
  SAlterVnodeTypeReq req = {0};
×
2972
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
2973
    code = TSDB_CODE_INVALID_MSG;
×
2974
    TAOS_RETURN(code);
×
2975
  }
2976

2977
  SSyncCfg cfg = {0};
×
2978
  syncBuildConfigFromReq(&req, &cfg);
×
2979

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

2991
    if (!incfg) {
×
2992
      SyncTerm currentTerm = raftStoreGetTerm(ths);
×
2993
      SRaftId  id = EMPTY_RAFT_ID;
×
2994
      syncNodeStepDown(ths, currentTerm, id);
×
2995
      return 1;
×
2996
    }
2997
  }
2998
  return 0;
×
2999
}
3000

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

3008
  sInfo("vgId:%d, %s, myNodeInfo, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3009
        ths->myNodeInfo.clusterId, ths->myNodeInfo.nodeId, ths->myNodeInfo.nodeFqdn, ths->myNodeInfo.nodePort,
3010
        ths->myNodeInfo.nodeRole);
3011

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

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

3029
    sInfo("vgId:%d, %s, peersEpset%d, %s, inUse:%d", ths->vgId, str, i, buf, ths->peersEpset->inUse);
×
3030
  }
3031

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

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

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

3048
int32_t syncNodeRebuildPeerAndCfg(SSyncNode* ths, SSyncCfg* cfg) {
×
3049
  int32_t i = 0;
×
3050

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

3062
      syncUtilNodeInfo2EpSet(&ths->peersNodeInfo[i], &ths->peersEpset[i]);
×
3063

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

3069
      i++;
×
3070
    }
3071
  }
3072
  ths->peersNum = i;
×
3073

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

3094
  return 0;
×
3095
}
3096

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

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

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

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

3137
  // 2.rebuild MatchIndex, remove deleted one
3138
  SSyncIndexMgr* oldIndex = ths->pMatchIndex;
×
3139

3140
  ths->pMatchIndex = syncIndexMgrCreate(ths);
×
3141
  if (ths->pMatchIndex == NULL) {
×
3142
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3143
    if (terrno != 0) code = terrno;
×
3144
    TAOS_RETURN(code);
×
3145
  }
3146

3147
  syncIndexMgrCopyIfExist(ths->pMatchIndex, oldIndex, oldReplicasId);
×
3148

3149
  syncIndexMgrDestroy(oldIndex);
×
3150

3151
  // 3.rebuild NextIndex, remove deleted one
3152
  SSyncIndexMgr* oldNextIndex = ths->pNextIndex;
×
3153

3154
  ths->pNextIndex = syncIndexMgrCreate(ths);
×
3155
  if (ths->pNextIndex == NULL) {
×
3156
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3157
    if (terrno != 0) code = terrno;
×
3158
    TAOS_RETURN(code);
×
3159
  }
3160

3161
  syncIndexMgrCopyIfExist(ths->pNextIndex, oldNextIndex, oldReplicasId);
×
3162

3163
  syncIndexMgrDestroy(oldNextIndex);
×
3164

3165
  // 4.rebuild pVotesGranted, pVotesRespond, no need to keep old vote state, only rebuild
3166
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3167
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3168

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

3176
  SSyncLogReplMgr* oldLogReplMgrs = NULL;
×
3177
  int64_t          length = sizeof(SSyncLogReplMgr) * (TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA);
×
3178
  oldLogReplMgrs = taosMemoryMalloc(length);
×
3179
  if (NULL == oldLogReplMgrs) return terrno;
×
3180
  memset(oldLogReplMgrs, 0, length);
×
3181

3182
  for (int i = 0; i < oldtotalReplicaNum; i++) {
×
3183
    oldLogReplMgrs[i] = *(ths->logReplMgrs[i]);
×
3184
  }
3185

3186
  syncNodeLogReplDestroy(ths);
×
3187
  if ((code = syncNodeLogReplInit(ths)) != 0) {
×
3188
    taosMemoryFree(oldLogReplMgrs);
×
3189
    TAOS_RETURN(code);
×
3190
  }
3191

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

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

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

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

3217
      if (snapshotSenderIsStart(ths->senders[i])) {
×
3218
        snapshotSenderStop(ths->senders[i], false);
×
3219
      }
3220

3221
      snapshotSenderDestroy(ths->senders[i]);
×
3222
      ths->senders[i] = NULL;
×
3223
    }
3224
  }
3225

3226
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3227
    SSyncSnapshotSender* pSender = NULL;
×
3228
    int32_t              code = snapshotSenderCreate(ths, i, &pSender);
×
3229
    if (pSender == NULL) return terrno = code;
×
3230

3231
    ths->senders[i] = pSender;
×
3232
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
×
3233
  }
3234

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

3240
  // 7.rebuild synctimer
3241
  if ((code = syncNodeStopHeartbeatTimer(ths)) != 0) {
×
3242
    taosMemoryFree(oldLogReplMgrs);
×
3243
    TAOS_RETURN(code);
×
3244
  }
3245

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

3253
  if ((code = syncNodeStartHeartbeatTimer(ths)) != 0) {
×
3254
    taosMemoryFree(oldLogReplMgrs);
×
3255
    TAOS_RETURN(code);
×
3256
  }
3257

3258
  // 8.rebuild peerStates
3259
  SPeerState oldState[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA] = {0};
×
3260
  for (int i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; i++) {
×
3261
    oldState[i] = ths->peerStates[i];
×
3262
  }
3263

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

3272
  taosMemoryFree(oldLogReplMgrs);
×
3273

3274
  return 0;
×
3275
}
3276

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

3285
  // pMatchIndex, pNextIndex, only need to change replicaNum when 1->3
3286
  ths->pMatchIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3287
  ths->pNextIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3288

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

3294
  // pVotesGranted, pVotesRespond
3295
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3296
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3297

3298
  // logRepMgrs
3299
  // no need to change logRepMgrs when 1->3
3300
}
×
3301

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

3308
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3309
    memcpy(&ths->raftCfg.cfg.nodeInfo[i], &node, sizeof(SNodeInfo));
×
3310
  }
3311
}
×
3312

3313
int32_t syncNodeChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry, char* str) {
×
3314
  int32_t code = 0;
×
3315
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3316
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3317
  }
3318

3319
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3320
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3321

3322
  SAlterVnodeTypeReq req = {0};
×
3323
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3324
    code = TSDB_CODE_INVALID_MSG;
×
3325
    TAOS_RETURN(code);
×
3326
  }
3327

3328
  SSyncCfg cfg = {0};
×
3329
  syncBuildConfigFromReq(&req, &cfg);
×
3330

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

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

3369
  syncNodeLogConfigInfo(ths, &cfg, "before config change");
×
3370

3371
  int32_t oldTotalReplicaNum = ths->totalReplicaNum;
×
3372

3373
  if (cfg.totalReplicaNum == 1 || cfg.totalReplicaNum == 2) {  // remove replica
×
3374

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

3384
    if (incfg) {  // remove other
×
3385
      syncNodeResetPeerAndCfg(ths);
×
3386

3387
      // no need to change myNodeInfo
3388

3389
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3390
        TAOS_RETURN(code);
×
3391
      };
3392

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

3399
      syncNodeResetPeerAndCfg(ths);
×
3400

3401
      // change myNodeInfo
3402
      ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
3403

3404
      // change peer and cfg
3405
      ths->peersNum = 0;
×
3406
      memcpy(&ths->raftCfg.cfg.nodeInfo[0], &ths->myNodeInfo, sizeof(SNodeInfo));
×
3407
      ths->raftCfg.cfg.replicaNum = 0;
×
3408
      ths->raftCfg.cfg.totalReplicaNum = 1;
×
3409

3410
      // change other
3411
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3412
        TAOS_RETURN(code);
×
3413
      }
3414

3415
      // change state
3416
      ths->state = TAOS_SYNC_STATE_LEARNER;
×
3417
    }
3418

3419
    ths->restoreFinish = false;
×
3420
  } else {                            // add replica, or change replica type
3421
    if (ths->totalReplicaNum == 3) {  // change replica type
×
3422
      sInfo("vgId:%d, begin change replica type", ths->vgId);
×
3423

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

3434
      // change peer and cfg
3435
      syncNodeChangePeerAndCfgToVoter(ths, &cfg);
×
3436

3437
      // change other
3438
      syncNodeChangeToVoter(ths);
×
3439

3440
      // change state
3441
      if (ths->state == TAOS_SYNC_STATE_LEARNER) {
×
3442
        if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3443
          ths->state = TAOS_SYNC_STATE_FOLLOWER;
×
3444
        }
3445
      }
3446

3447
      ths->restoreFinish = false;
×
3448
    } else {  // add replica
3449
      sInfo("vgId:%d, begin add replica", ths->vgId);
×
3450

3451
      // no need to change myNodeInfo
3452

3453
      // change peer and cfg
3454
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3455
        TAOS_RETURN(code);
×
3456
      };
3457

3458
      // change other
3459
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3460
        TAOS_RETURN(code);
×
3461
      };
3462

3463
      // no need to change state
3464

3465
      if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
3466
        ths->restoreFinish = false;
×
3467
      }
3468
    }
3469
  }
3470

3471
  ths->quorum = syncUtilQuorum(ths->replicaNum);
×
3472

3473
  ths->raftCfg.lastConfigIndex = pEntry->index;
×
3474
  ths->raftCfg.cfg.lastIndex = pEntry->index;
×
3475
  ths->raftCfg.cfg.changeVersion = cfg.changeVersion;
×
3476

3477
  syncNodeLogConfigInfo(ths, &cfg, "after config change");
×
3478

3479
  if ((code = syncWriteCfgFile(ths)) != 0) {
×
3480
    sError("vgId:%d, failed to create sync cfg file", ths->vgId);
×
3481
    TAOS_RETURN(code);
×
3482
  };
3483

3484
  TAOS_RETURN(code);
×
3485
}
3486

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

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

3510
  code = 0;
2,045,856✔
3511
_out:;
2,045,856✔
3512
  // proceed match index, with replicating on needed
3513
  SyncIndex       matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL, "Append", pMsg);
2,045,856✔
3514
  const STraceId* trace = pEntry ? &pEntry->originRpcTraceId : NULL;
2,045,784!
3515

3516
  if (pEntry != NULL) {
2,045,784!
3517
    sGDebug(trace,
2,045,830!
3518
            "vgId:%d, index:%" PRId64 ", raft entry appended, msg:%p term:%" PRId64 " buf:[%" PRId64 " %" PRId64
3519
            " %" PRId64 ", %" PRId64 ")",
3520
            ths->vgId, pEntry->index, pMsg, pEntry->term, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3521
            ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex);
3522
  }
3523

3524
  if (code == 0 && ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,045,785✔
3525
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
4✔
3526
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
4!
3527

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

3536
  // multi replica
3537
  if (ths->replicaNum > 1) {
2,045,754✔
3538
    TAOS_RETURN(code);
115,830✔
3539
  }
3540

3541
  // single replica
3542
  SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, matchIndex);
1,929,924✔
3543
  sGTrace(trace, "vgId:%d, index:%" PRId64 ", raft entry update commit, msg:%p return index:%" PRId64, ths->vgId,
1,929,956!
3544
          matchIndex, pMsg, returnIndex);
3545

3546
  if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
3,859,963!
3547
      (code = syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, trace, "append-entry")) < 0) {
1,929,918✔
3548
    sGError(trace,
×
3549
            "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64 " return index:%" PRId64,
3550
            ths->vgId, matchIndex, pMsg, ths->commitIndex, returnIndex);
3551
  }
3552

3553
  TAOS_RETURN(code);
1,930,045✔
3554
}
3555

3556
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
2,035,168✔
3557
  if (pSyncNode->totalReplicaNum == 1) {
2,035,168✔
3558
    return false;
1,918,726✔
3559
  }
3560

3561
  int32_t toCount = 0;
116,442✔
3562
  int64_t tsNow = taosGetTimestampMs();
116,445✔
3563
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
349,429✔
3564
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
232,984✔
3565
      continue;
502✔
3566
    }
3567
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
232,482✔
3568
    if (recvTime == 0 || recvTime == -1) {
232,482!
3569
      continue;
×
3570
    }
3571

3572
    if (tsNow - recvTime > tsHeartbeatTimeout) {
232,482✔
3573
      toCount++;
6,265✔
3574
    }
3575
  }
3576

3577
  bool b = (toCount >= pSyncNode->quorum ? true : false);
116,445✔
3578

3579
  return b;
116,445✔
3580
}
3581

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

3594
bool syncNodeSnapshotRecving(SSyncNode* pSyncNode) {
×
3595
  if (pSyncNode == NULL) return false;
×
3596
  if (pSyncNode->pNewNodeReceiver == NULL) return false;
×
3597
  if (pSyncNode->pNewNodeReceiver->start) return true;
×
3598
  return false;
×
3599
}
3600

3601
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
12,382✔
3602
  int32_t   code = 0;
12,382✔
3603
  SyncIndex index = syncLogBufferGetEndIndex(ths->pLogBuf);
12,382✔
3604
  SyncTerm  term = raftStoreGetTerm(ths);
12,382✔
3605

3606
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
12,382✔
3607
  if (pEntry == NULL) {
12,382!
3608
    code = TSDB_CODE_OUT_OF_MEMORY;
×
3609
    TAOS_RETURN(code);
×
3610
  }
3611

3612
  code = syncNodeAppend(ths, pEntry, NULL);
12,382✔
3613
  TAOS_RETURN(code);
12,382✔
3614
}
3615

3616
#ifdef BUILD_NO_CALL
3617
static int32_t syncNodeAppendNoopOld(SSyncNode* ths) {
3618
  int32_t ret = 0;
3619

3620
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
3621
  SyncTerm        term = raftStoreGetTerm(ths);
3622
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
3623
  if (pEntry == NULL) return -1;
3624

3625
  LRUHandle* h = NULL;
3626

3627
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
3628
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry, false);
3629
    if (code != 0) {
3630
      sError("append noop error");
3631
      return -1;
3632
    }
3633

3634
    syncCacheEntry(ths->pLogStore, pEntry, &h);
3635
  }
3636

3637
  if (h) {
3638
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
3639
  } else {
3640
    syncEntryDestroy(pEntry);
3641
  }
3642

3643
  return ret;
3644
}
3645
#endif
3646

3647
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
42,363✔
3648
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
42,363✔
3649
  bool           resetElect = false;
42,363✔
3650

3651
  int64_t tsMs = taosGetTimestampMs();
42,363✔
3652

3653
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pNextIndex, &(pMsg->srcId));
42,363✔
3654
  syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);
42,363✔
3655
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
42,363✔
3656

3657
  int64_t netElapsed = tsMs - pMsg->timeStamp;
42,363✔
3658
  int64_t timeDiff = tsMs - lastRecvTime;
42,363✔
3659
  syncLogRecvHeartbeat(ths, pMsg, netElapsed, &pRpcMsg->info.traceId, timeDiff, pRpcMsg);
42,363✔
3660

3661
  if (!syncNodeInRaftGroup(ths, &pMsg->srcId)) {
42,363!
3662
    sWarn(
×
3663
        "vgId:%d, drop heartbeat msg from dnode:%d, because it come from another cluster:%d, differ from current "
3664
        "cluster:%d",
3665
        ths->vgId, DID(&(pMsg->srcId)), CID(&(pMsg->srcId)), CID(&(ths->myRaftId)));
3666
    return 0;
×
3667
  }
3668

3669
  SyncTerm currentTerm = raftStoreGetTerm(ths);
42,363✔
3670

3671
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
42,362✔
3672
    raftStoreSetTerm(ths, pMsg->term);
264✔
3673
    currentTerm = pMsg->term;
264✔
3674
  }
3675

3676
  int64_t tsMs2 = taosGetTimestampMs();
42,362✔
3677

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

3693
  if (pMsg->term == currentTerm &&
42,362✔
3694
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
42,189!
3695
    resetElect = true;
42,189✔
3696

3697
    ths->minMatchIndex = pMsg->minMatchIndex;
42,189✔
3698

3699
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
42,189✔
3700
      SRpcMsg rpcMsgLocalCmd = {0};
42,187✔
3701
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
42,187!
3702
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
42,188✔
3703

3704
      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
42,188✔
3705
      pSyncMsg->cmd =
42,188✔
3706
          (ths->state == TAOS_SYNC_STATE_LEARNER) ? SYNC_LOCAL_CMD_LEARNER_CMT : SYNC_LOCAL_CMD_FOLLOWER_CMT;
42,188✔
3707
      pSyncMsg->commitIndex = pMsg->commitIndex;
42,188✔
3708
      pSyncMsg->currentTerm = pMsg->term;
42,188✔
3709

3710
      if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
42,188!
3711
        int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
42,188✔
3712
        if (code != 0) {
42,188!
3713
          sError("vgId:%d, failed to enqueue sync-local-cmd msg(cmd=commit) from heartbeat since %s",
×
3714
                 ths->vgId, tstrerror(code));
3715
          rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3716
        } else {
3717
          sGTrace(&pRpcMsg->info.traceId,
42,188!
3718
                  "vgId:%d, enqueue sync-local-cmd msg(cmd=commit) from heartbeat, commit-index:%" PRId64
3719
                  ", term:%" PRId64,
3720
                  ths->vgId, pMsg->commitIndex, pMsg->term);
3721
        }
3722
      }
3723
    }
3724
  }
3725

3726
  if (pMsg->term >= currentTerm &&
42,363!
3727
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
42,363!
3728
    SRpcMsg rpcMsgLocalCmd = {0};
×
3729
    TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
×
3730
    rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
×
3731

3732
    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
×
3733
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
×
3734
    pSyncMsg->currentTerm = pMsg->term;
×
3735
    pSyncMsg->commitIndex = pMsg->commitIndex;
×
3736

3737
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
×
3738
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
×
3739
      if (code != 0) {
×
3740
        sError("vgId:%d, sync enqueue sync-local-cmd msg(cmd=step-down) error, code:%d", ths->vgId, code);
×
3741
        rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3742
      } else {
3743
        sTrace("vgId:%d, sync enqueue sync-local-cmd msg(cmd=step-down), new-term:%" PRId64, ths->vgId, pMsg->term);
×
3744
      }
3745
    }
3746
  }
3747

3748
  SRpcMsg rpcMsg = {0};
42,363✔
3749
  TAOS_CHECK_RETURN(syncBuildHeartbeatReply(&rpcMsg, ths->vgId));
42,363!
3750
  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
42,363✔
3751
  pMsgReply->destId = pMsg->srcId;
42,363✔
3752
  pMsgReply->srcId = ths->myRaftId;
42,363✔
3753
  pMsgReply->term = currentTerm;
42,363✔
3754
  pMsgReply->privateTerm = 8864;  // magic number
42,363✔
3755
  pMsgReply->startTime = ths->startTime;
42,363✔
3756
  pMsgReply->timeStamp = tsMs;
42,363✔
3757
  rpcMsg.info.traceId = pRpcMsg->info.traceId;
42,363✔
3758

3759
  // reply
3760
  int64_t tsMs3 = taosGetTimestampMs();
42,363✔
3761

3762
  int64_t processTime2 = tsMs3 - tsMs2;
42,363✔
3763
  TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
42,363✔
3764
  if (processTime2 > SYNC_HEARTBEAT_SLOW_MS) {
42,363!
3765
    sGError(&rpcMsg.info.traceId,
×
3766
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3767
            ", processTime:%" PRId64,
3768
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3769
  } else {
3770
    if(tsSyncLogHeartbeat){
42,363!
3771
      sGInfo(&rpcMsg.info.traceId,
×
3772
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3773
            ", processTime:%" PRId64,
3774
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3775
    }
3776
    else{
3777
      sGDebug(&rpcMsg.info.traceId,
42,363!
3778
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3779
            ", processTime:%" PRId64,
3780
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3781
    }
3782
  }
3783

3784
  TAOS_CHECK_RETURN(syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg));
42,363!
3785

3786
  if (resetElect) syncNodeResetElectTimer(ths);
42,363✔
3787
  return 0;
42,363✔
3788
}
3789

3790
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
41,162✔
3791
  int32_t code = 0;
41,162✔
3792

3793
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
41,162✔
3794
  SSyncLogReplMgr*    pMgr = syncNodeGetLogReplMgr(ths, &pMsg->srcId);
41,162✔
3795
  if (pMgr == NULL) {
41,162!
3796
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3797
    if (terrno != 0) code = terrno;
×
3798
    sError("vgId:%d, failed to get log repl mgr for the peer at addr 0x016%" PRIx64, ths->vgId, pMsg->srcId.addr);
×
3799
    TAOS_RETURN(code);
×
3800
  }
3801

3802
  int64_t tsMs = taosGetTimestampMs();
41,162✔
3803
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pMatchIndex, &pMsg->srcId);
41,162✔
3804
  syncLogRecvHeartbeatReply(ths, pMsg, tsMs - pMsg->timeStamp, &pRpcMsg->info.traceId, tsMs - lastRecvTime);
41,162✔
3805

3806
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
41,162✔
3807
  syncIndexMgrIncRecvCount(ths->pMatchIndex, &(pMsg->srcId));
41,162✔
3808

3809
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
41,162✔
3810
}
3811

3812
#ifdef BUILD_NO_CALL
3813
int32_t syncNodeOnHeartbeatReplyOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
3814
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
3815

3816
  int64_t tsMs = taosGetTimestampMs();
3817
  int64_t timeDiff = tsMs - pMsg->timeStamp;
3818
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff, &pRpcMsg->info.traceId, timeDiff);
3819

3820
  // update last reply time, make decision whether the other node is alive or not
3821
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
3822
  return 0;
3823
}
3824
#endif
3825

3826
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
42,188✔
3827
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
42,188✔
3828
  syncLogRecvLocalCmd(ths, pMsg, &pRpcMsg->info.traceId);
42,188✔
3829

3830
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
42,188!
3831
    SRaftId id = EMPTY_RAFT_ID;
×
3832
    syncNodeStepDown(ths, pMsg->currentTerm, id);
×
3833

3834
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT || pMsg->cmd == SYNC_LOCAL_CMD_LEARNER_CMT) {
84,376!
3835
    if (syncLogBufferIsEmpty(ths->pLogBuf)) {
42,188!
3836
      sError("vgId:%d, sync log buffer is empty", ths->vgId);
×
3837
      return 0;
×
3838
    }
3839
    SyncTerm matchTerm = syncLogBufferGetLastMatchTerm(ths->pLogBuf);
42,188✔
3840
    if (matchTerm < 0) {
42,188!
3841
      return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3842
    }
3843
    if (pMsg->currentTerm == matchTerm) {
42,188✔
3844
      SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, pMsg->commitIndex);
38,700✔
3845
      sTrace("vgId:%d, raft entry update commit, return index:%" PRId64, ths->vgId, returnIndex);
38,700!
3846
    }
3847
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
84,376!
3848
        syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, &pRpcMsg->info.traceId, "heartbeat") < 0) {
42,188✔
3849
      sError("vgId:%d, failed to commit raft log since %s. commit index:%" PRId64, ths->vgId, terrstr(),
×
3850
             ths->commitIndex);
3851
    }
3852
  } else {
3853
    sError("error local cmd");
×
3854
  }
3855

3856
  return 0;
42,188✔
3857
}
3858

3859
// TLA+ Spec
3860
// ClientRequest(i, v) ==
3861
//     /\ state[i] = Leader
3862
//     /\ LET entry == [term  |-> currentTerm[i],
3863
//                      value |-> v]
3864
//            newLog == Append(log[i], entry)
3865
//        IN  log' = [log EXCEPT ![i] = newLog]
3866
//     /\ UNCHANGED <<messages, serverVars, candidateVars,
3867
//                    leaderVars, commitIndex>>
3868
//
3869

3870
int32_t syncNodeOnClientRequest(SSyncNode* ths, SRpcMsg* pMsg, SyncIndex* pRetIndex) {
2,033,496✔
3871
  sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, process client request", ths->vgId, pMsg);
2,033,496!
3872
  int32_t code = 0;
2,033,497✔
3873

3874
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
2,033,497✔
3875
  SyncTerm        term = raftStoreGetTerm(ths);
2,033,499✔
3876
  SSyncRaftEntry* pEntry = NULL;
2,033,502✔
3877
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
2,033,502✔
3878
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
196,302✔
3879
  } else {
3880
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
1,837,200✔
3881
  }
3882

3883
  if (pEntry == NULL) {
2,033,484!
3884
    sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to process client request since %s", ths->vgId, pMsg,
×
3885
            terrstr());
3886
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3887
  }
3888

3889
  // 1->2, config change is add in write thread, and will continue in sync thread
3890
  // need save message for it
3891
  if (pMsg->msgType == TDMT_SYNC_CONFIG_CHANGE) {
2,033,484!
3892
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
×
3893
    uint64_t  seqNum = syncRespMgrAdd(ths->pSyncRespMgr, &stub);
×
3894
    pEntry->seqNum = seqNum;
×
3895
  }
3896

3897
  if (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,033,484!
3898
    if (pRetIndex) {
2,033,484✔
3899
      (*pRetIndex) = index;
1,837,183✔
3900
    }
3901

3902
    if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE) {
2,033,484!
3903
      int32_t code = syncNodeCheckChangeConfig(ths, pEntry);
×
3904
      if (code < 0) {
×
3905
        sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to check change config since %s", ths->vgId, pMsg,
×
3906
                terrstr());
3907
        syncEntryDestroy(pEntry);
×
3908
        pEntry = NULL;
×
3909
        TAOS_RETURN(code);
×
3910
      }
3911

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

3926
    code = syncNodeAppend(ths, pEntry, pMsg);
2,033,484✔
3927
    return code;
2,033,334✔
3928
  } else {
3929
    syncEntryDestroy(pEntry);
×
3930
    pEntry = NULL;
×
3931
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3932
  }
3933
}
3934

3935
const char* syncStr(ESyncState state) {
964,370✔
3936
  switch (state) {
964,370!
3937
    case TAOS_SYNC_STATE_FOLLOWER:
669,957✔
3938
      return "follower";
669,957✔
3939
    case TAOS_SYNC_STATE_CANDIDATE:
3,090✔
3940
      return "candidate";
3,090✔
3941
    case TAOS_SYNC_STATE_LEADER:
271,478✔
3942
      return "leader";
271,478✔
3943
    case TAOS_SYNC_STATE_ERROR:
×
3944
      return "error";
×
3945
    case TAOS_SYNC_STATE_OFFLINE:
5,720✔
3946
      return "offline";
5,720✔
3947
    case TAOS_SYNC_STATE_LEARNER:
14,108✔
3948
      return "learner";
14,108✔
3949
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
19✔
3950
      return "assigned leader";
19✔
3951
    default:
×
3952
      return "unknown";
×
3953
  }
3954
}
3955

3956
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
2,129✔
3957
  for (int32_t i = 0; i < pNewCfg->totalReplicaNum; ++i) {
2,358!
3958
    SRaftId raftId = {
2,358✔
3959
        .addr = SYNC_ADDR(&pNewCfg->nodeInfo[i]),
2,358✔
3960
        .vgId = ths->vgId,
2,358✔
3961
    };
3962

3963
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
2,358✔
3964
      pNewCfg->myIndex = i;
2,129✔
3965
      return 0;
2,129✔
3966
    }
3967
  }
3968

3969
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3970
}
3971

3972
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
2,035,164✔
3973
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
2,035,164!
3974
}
3975

3976
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
557,739✔
3977
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
1,099,860!
3978
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
1,099,860✔
3979
      return true;
557,739✔
3980
    }
3981
  }
3982
  return false;
×
3983
}
3984

3985
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
29,673✔
3986
  SSyncSnapshotSender* pSender = NULL;
29,673✔
3987
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
120,881✔
3988
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
91,208✔
3989
      pSender = (ths->senders)[i];
29,673✔
3990
    }
3991
  }
3992
  return pSender;
29,673✔
3993
}
3994

3995
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
32,629✔
3996
  SSyncTimer* pTimer = NULL;
32,629✔
3997
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
140,543✔
3998
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
107,913✔
3999
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
32,627✔
4000
    }
4001
  }
4002
  return pTimer;
32,630✔
4003
}
4004

4005
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
100,220✔
4006
  SPeerState* pState = NULL;
100,220✔
4007
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
352,036✔
4008
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
251,816✔
4009
      pState = &((ths->peerStates)[i]);
100,217✔
4010
    }
4011
  }
4012
  return pState;
100,220✔
4013
}
4014

4015
#ifdef BUILD_NO_CALL
4016
bool syncNodeNeedSendAppendEntries(SSyncNode* ths, const SRaftId* pDestId, const SyncAppendEntries* pMsg) {
4017
  SPeerState* pState = syncNodeGetPeerState(ths, pDestId);
4018
  if (pState == NULL) {
4019
    sError("vgId:%d, replica maybe dropped", ths->vgId);
4020
    return false;
4021
  }
4022

4023
  SyncIndex sendIndex = pMsg->prevLogIndex + 1;
4024
  int64_t   tsNow = taosGetTimestampMs();
4025

4026
  if (pState->lastSendIndex == sendIndex && tsNow - pState->lastSendTime < SYNC_APPEND_ENTRIES_TIMEOUT_MS) {
4027
    return false;
4028
  }
4029

4030
  return true;
4031
}
4032

4033
bool syncNodeCanChange(SSyncNode* pSyncNode) {
4034
  if (pSyncNode->changing) {
4035
    sError("sync cannot change");
4036
    return false;
4037
  }
4038

4039
  if ((pSyncNode->commitIndex >= SYNC_INDEX_BEGIN)) {
4040
    SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);
4041
    if (pSyncNode->commitIndex != lastIndex) {
4042
      sError("sync cannot change2");
4043
      return false;
4044
    }
4045
  }
4046

4047
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
4048
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
4049
    if (pSender != NULL && pSender->start) {
4050
      sError("sync cannot change3");
4051
      return false;
4052
    }
4053
  }
4054

4055
  return true;
4056
}
4057
#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