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

taosdata / TDengine / #4703

01 Sep 2025 11:36AM UTC coverage: 58.16% (-0.9%) from 59.056%
#4703

push

travis-ci

web-flow
Merge pull request #32834 from taosdata/docs/wangxu/simplify-get-started

refactor: simplify get started

133101 of 291897 branches covered (45.6%)

Branch coverage included in aggregate %.

201587 of 283568 relevant lines covered (71.09%)

5506801.45 hits per line

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

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

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

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

87
int32_t syncStart(int64_t rid) {
14,143✔
88
  int32_t    code = 0;
14,143✔
89
  int32_t    vgId = 0;
14,143✔
90
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
14,143✔
91
  if (pSyncNode == NULL) {
14,143!
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,143✔
98
  sInfo("vgId:%d, begin to start sync", pSyncNode->vgId);
14,143✔
99

100
  if ((code = syncNodeRestore(pSyncNode)) < 0) {
14,143!
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,143✔
105

106
  if ((code = syncNodeStart(pSyncNode)) < 0) {
14,143!
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,143✔
111

112
  syncNodeRelease(pSyncNode);
14,143✔
113

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

116
  TAOS_RETURN(code);
14,143✔
117

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

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

127
  if (pSyncNode == NULL) {
22,191!
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;
22,191✔
135

136
  syncNodeRelease(pSyncNode);
22,191✔
137

138
  return 0;
22,190✔
139
}
140

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

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

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

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

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

191
  if (!syncNodeCheckNewConfig(pSyncNode, pNewCfg)) {
1,790!
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));
1,790!
199

200
  if (syncNodeDoConfigChange(pSyncNode, pNewCfg, pNewCfg->lastIndex) != 0) {
1,790!
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) {
1,790!
207
    // TODO check return value
208
    TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1,602!
209

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

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

218
  syncNodeRelease(pSyncNode);
1,790✔
219
  TAOS_RETURN(code);
1,790✔
220
}
221

222
int32_t syncProcessMsg(int64_t rid, SRpcMsg* pMsg) {
930,020✔
223
  int32_t code = -1;
930,020✔
224
  if (!syncIsInit()) {
930,020!
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);
930,020✔
231
  if (pSyncNode == NULL) {
930,022✔
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) {
930,021!
238
    case TDMT_SYNC_HEARTBEAT:
60,965✔
239
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
60,965✔
240
      break;
60,965✔
241
    case TDMT_SYNC_HEARTBEAT_REPLY:
60,290✔
242
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
60,290✔
243
      break;
60,290✔
244
    case TDMT_SYNC_TIMEOUT:
59,525✔
245
      code = syncNodeOnTimeout(pSyncNode, pMsg);
59,525✔
246
      break;
59,515✔
247
    case TDMT_SYNC_TIMEOUT_ELECTION:
1,416✔
248
      code = syncNodeOnTimeout(pSyncNode, pMsg);
1,416✔
249
      break;
1,416✔
250
    case TDMT_SYNC_CLIENT_REQUEST:
189,691✔
251
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
189,691✔
252
      break;
189,691✔
253
    case TDMT_SYNC_REQUEST_VOTE:
2,538✔
254
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
2,538✔
255
      break;
2,538✔
256
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
2,480✔
257
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
2,480✔
258
      break;
2,480✔
259
    case TDMT_SYNC_APPEND_ENTRIES:
244,658✔
260
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
244,658✔
261
      break;
244,658✔
262
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
244,222✔
263
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
244,222✔
264
      break;
244,221✔
265
    case TDMT_SYNC_SNAPSHOT_SEND:
1,672✔
266
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
1,672✔
267
      break;
1,672✔
268
    case TDMT_SYNC_SNAPSHOT_RSP:
1,672✔
269
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
1,672✔
270
      break;
1,672✔
271
    case TDMT_SYNC_LOCAL_CMD:
60,872✔
272
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
60,872✔
273
      break;
60,872✔
274
    case TDMT_SYNC_FORCE_FOLLOWER:
18✔
275
      code = syncForceBecomeFollower(pSyncNode, pMsg);
18✔
276
      break;
18✔
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);
930,010✔
285
  if (code != 0) {
930,013✔
286
    sDebug("vgId:%d, failed to process sync msg:%p type:%s since %s", pSyncNode->vgId, pMsg, TMSG_INFO(pMsg->msgType),
22!
287
           tstrerror(code));
288
  }
289
  TAOS_RETURN(code);
930,013✔
290
}
291

292
int32_t syncLeaderTransfer(int64_t rid) {
14,143✔
293
  int32_t    code = 0;
14,143✔
294
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
14,143✔
295
  if (pSyncNode == NULL) {
14,143!
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,143✔
302
  syncNodeRelease(pSyncNode);
14,143✔
303
  return ret;
14,143✔
304
}
305

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

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

318
  return 0;
18✔
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) {
65,202✔
429
  SyncIndex minMatchIndex = SYNC_INDEX_INVALID;
65,202✔
430

431
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
194,941✔
432
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
129,739✔
433
    if (minMatchIndex == SYNC_INDEX_INVALID) {
129,739✔
434
      minMatchIndex = matchIndex;
68,860✔
435
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
60,879✔
436
      minMatchIndex = matchIndex;
1,070✔
437
    }
438
  }
439
  return minMatchIndex;
65,202✔
440
}
441

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

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

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

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

466
  int64_t logRetention = 0;
25,623✔
467

468
  if (syncNodeIsMnode(pSyncNode)) {
25,623✔
469
    // mnode
470
    logRetention = tsMndLogRetention;
3,527✔
471
  } else {
472
    // vnode
473
    if (pSyncNode->replicaNum > 1) {
22,095✔
474
      logRetention = SYNC_VNODE_LOG_RETENTION;
867✔
475
    }
476
  }
477

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

491
_DEL_WAL:
24,313✔
492

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

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

505
        code = walBeginSnapshot(pData->pWal, lastApplyIndex, logRetention);
25,622✔
506
        if (code == 0) {
25,621!
507
          sNTrace(pSyncNode, "wal snapshot begin, index:%" PRId64 ", last apply index:%" PRId64,
25,621✔
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,621✔
523
  TAOS_RETURN(code);
25,621✔
524
}
525

526
int32_t syncEndSnapshot(int64_t rid) {
25,718✔
527
  int32_t    code = 0;
25,718✔
528
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
25,718✔
529
  if (pSyncNode == NULL) {
25,718!
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,718✔
537
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
25,621✔
538
    code = walEndSnapshot(pData->pWal);
25,621✔
539
    if (code != 0) {
25,622!
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,622✔
545
      atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
25,622✔
546
    }
547
  }
548

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

553
bool syncNodeIsReadyForRead(SSyncNode* pSyncNode) {
2,797,211✔
554
  if (pSyncNode == NULL) {
2,797,211!
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,797,211✔
561
    terrno = TSDB_CODE_SYN_NOT_LEADER;
73,716✔
562
    return false;
73,716✔
563
  }
564

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

570
  return true;
2,723,149✔
571
}
572

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

580
  bool ready = syncNodeIsReadyForRead(pSyncNode);
2,530,813✔
581

582
  syncNodeRelease(pSyncNode);
2,530,766✔
583
  return ready;
2,530,496✔
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,143✔
611
  if (pSyncNode->peersNum == 0) {
14,143✔
612
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
10,341✔
613
    return 0;
10,341✔
614
  }
615

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

629
  return ret;
3,802✔
630
}
631

632
int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader) {
1,242✔
633
  if (pSyncNode->replicaNum == 1) {
1,242!
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,242!
639

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

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

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

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

656
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,252,615✔
657
  if (pSyncNode != NULL) {
1,253,403✔
658
    state.state = pSyncNode->state;
1,253,369✔
659
    state.roleTimeMs = pSyncNode->roleTimeMs;
1,253,369✔
660
    state.startTimeMs = pSyncNode->startTime;
1,253,369✔
661
    state.restored = pSyncNode->restoreFinish;
1,253,369✔
662
    if (pSyncNode->vgId != 1) {
1,253,369✔
663
      state.canRead = syncNodeIsReadyForRead(pSyncNode);
266,959✔
664
    } else {
665
      state.canRead = state.restored;
986,410✔
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,253,369✔
682
    syncNodeRelease(pSyncNode);
1,253,411✔
683
  }
684

685
  return state;
1,253,410✔
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) {
254,663✔
715
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
254,663✔
716
  if (pSyncNode != NULL) {
254,663!
717
    *syncCommitIndex = pSyncNode->commitIndex;
254,663✔
718
    syncNodeRelease(pSyncNode);
254,663✔
719
  }
720
}
254,663✔
721

722
int32_t syncGetArbToken(int64_t rid, char* outToken) {
45,590✔
723
  int32_t    code = 0;
45,590✔
724
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
45,590✔
725
  if (pSyncNode == NULL) {
45,590!
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);
45,590✔
732
  (void)taosThreadMutexLock(&pSyncNode->arbTokenMutex);
45,590✔
733
  tstrncpy(outToken, pSyncNode->arbToken, TSDB_ARB_TOKEN_SIZE);
45,590✔
734
  (void)taosThreadMutexUnlock(&pSyncNode->arbTokenMutex);
45,590✔
735

736
  syncNodeRelease(pSyncNode);
45,590✔
737
  TAOS_RETURN(code);
45,590✔
738
}
739

740
int32_t syncCheckSynced(int64_t rid) {
6✔
741
  int32_t    code = 0;
6✔
742
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
6✔
743
  if (pSyncNode == NULL) {
6!
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) {
6!
750
    code = TSDB_CODE_SYN_NOT_LEADER;
×
751
    syncNodeRelease(pSyncNode);
×
752
    TAOS_RETURN(code);
×
753
  }
754

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

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

766
int32_t syncUpdateArbTerm(int64_t rid, SyncTerm arbTerm) {
153✔
767
  int32_t    code = 0;
153✔
768
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
153✔
769
  if (pSyncNode == NULL) {
153!
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);
153✔
776
  syncNodeRelease(pSyncNode);
153✔
777
  TAOS_RETURN(code);
153✔
778
}
779

780
SyncIndex syncNodeGetSnapshotConfigIndex(SSyncNode* pSyncNode, SyncIndex snapshotLastApplyIndex) {
574,335✔
781
  if (pSyncNode->raftCfg.configIndexCount < 1) {
574,335!
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];
574,335✔
788

789
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
1,193,212✔
790
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
618,877✔
791
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
44,542✔
792
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
44,387✔
793
    }
794
  }
795
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
574,335✔
796
         lastIndex);
797

798
  return lastIndex;
574,335✔
799
}
800

801
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
178,868✔
802
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
308,760✔
803
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
213,747✔
804
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
213,731✔
805
      return pSyncNode->peersId[i];
83,855✔
806
    }
807
  }
808
  return EMPTY_RAFT_ID;
95,013✔
809
}
810

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

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

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

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

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

834
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
95,121✔
835
  if (pSyncNode == NULL) return;
95,125!
836

837
  int index = -1;
95,125✔
838

839
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
95,125✔
840
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
841
  int j = 0;
95,124✔
842
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
275,531✔
843
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
180,402✔
844
    SEp* pEp = &pEpSet->eps[j];
178,879✔
845
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
178,879✔
846
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
178,879✔
847
    pEpSet->numOfEps++;
178,879✔
848
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
178,879✔
849
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
178,883✔
850
           pEp->port);
851
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
178,884✔
852
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
65,281!
853
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
854
      index = j;
65,281✔
855
    }
856
    j++;
178,884✔
857
  }
858
  if (pEpSet->numOfEps > 0) {
95,129✔
859
    if (index != -1) {
95,120✔
860
      pEpSet->inUse = index;
65,280✔
861
    } else {
862
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
29,840!
863
          pSyncNode->myRaftId.vgId == pSyncNode->leaderCache.vgId) {
×
864
        pEpSet->inUse = pSyncNode->raftCfg.cfg.myIndex;
×
865
      } else {
866
        pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
29,840✔
867
      }
868
    }
869
    // pEpSet->inUse = 0;
870
  }
871
  epsetSort(pEpSet);
95,129✔
872

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

880
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
1,908,819✔
881
  int32_t    code = 0;
1,908,819✔
882
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,908,819✔
883
  if (pSyncNode == NULL) {
1,908,829!
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);
1,908,829✔
891
  syncNodeRelease(pSyncNode);
1,908,658✔
892
  return ret;
1,908,753✔
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,709✔
915
  int32_t    code = 0;
4,709✔
916
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,709✔
917
  if (pSyncNode == NULL) {
4,709!
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,709✔
925
  if (pSyncNode->pLogBuf->totalIndex < 0 || pSyncNode->pLogBuf->commitIndex < 0 ||
4,709!
926
      pSyncNode->pLogBuf->totalIndex < pSyncNode->pLogBuf->commitIndex ||
939✔
927
      pSyncNode->pLogBuf->totalIndex - pSyncNode->pLogBuf->commitIndex > SYNC_LEARNER_CATCHUP) {
936✔
928
    sInfo("vgId:%d, Not catch up, wait one second, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64,
4,437!
929
          pSyncNode->vgId, pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex,
930
          pSyncNode->pLogBuf->matchIndex);
931
    isCatchUp = 0;
4,437✔
932
  } else {
933
    sInfo("vgId:%d, Catch up, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64, pSyncNode->vgId,
272!
934
          pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->matchIndex);
935
    isCatchUp = 1;
272✔
936
  }
937

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

942
ESyncRole syncGetRole(int64_t rid) {
4,709✔
943
  int32_t    code = 0;
4,709✔
944
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
4,709✔
945
  if (pSyncNode == NULL) {
4,709!
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,709✔
953

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

958
int64_t syncGetTerm(int64_t rid) {
18,085✔
959
  int32_t    code = 0;
18,085✔
960
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
18,085✔
961
  if (pSyncNode == NULL) {
18,085!
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);
18,085✔
969

970
  syncNodeRelease(pSyncNode);
18,085✔
971
  return term;
18,085✔
972
}
973

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

982
  if (!pSyncNode->restoreFinish) {
1,906,982✔
983
    code = TSDB_CODE_SYN_RESTORING;
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)) {
1,906,946!
991
    code = TSDB_CODE_SYN_PROPOSE_NOT_READY;
×
992
    sNError(pSyncNode, "failed to sync propose since heartbeat timeout, type:%s, last:%" PRId64 ", cmt:%" PRId64,
×
993
            TMSG_INFO(pMsg->msgType), syncNodeGetLastIndex(pSyncNode), pSyncNode->commitIndex);
994
    TAOS_RETURN(code);
×
995
  }
996

997
  // optimized one replica
998
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
1,906,946✔
999
    SyncIndex retIndex;
1000
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
1,715,679✔
1001
    if (code >= 0) {
1,715,492!
1002
      pMsg->info.conn.applyIndex = retIndex;
1,715,527✔
1003
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
1,715,527✔
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,715,655✔
1008
        sGDebug(&pMsg->info.traceId, "vgId:%d, index:%" PRId64 ", propose optimized msg type:%s", pSyncNode->vgId,
1,715,647!
1009
                retIndex, TMSG_INFO(pMsg->msgType));
1010
        return 1;
1,715,578✔
1011
      } else {
1012
        sGDebug(&pMsg->info.traceId,
8!
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};
191,275✔
1025
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
191,277✔
1026
    SRpcMsg   rpcMsg = {.info.traceId = pMsg->info.traceId};
191,277✔
1027
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
191,277✔
1028
    if (code != 0) {
191,277!
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,
191,277!
1035
            TMSG_INFO(pMsg->msgType));
1036
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
191,277✔
1037
    if (code != 0) {
191,276✔
1038
      sWarn("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
1,585!
1039
      TAOS_CHECK_RETURN(syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum));
1,586✔
1040
    }
1041

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1257
  // init peersNum, peers, peersId
1258
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
14,143✔
1259
  int32_t j = 0;
14,143✔
1260
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
35,834✔
1261
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
21,691✔
1262
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
7,548✔
1263
      pSyncNode->peersId[j] = pSyncNode->replicasId[i];
7,548✔
1264
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
7,548✔
1265
      j++;
7,548✔
1266
    }
1267
  }
1268

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

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

1282
  // init life cycle outside
1283

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

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

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

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

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

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

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

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

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

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

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

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

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

1424
  // restore state
1425
  pSyncNode->restoreFinish = false;
14,143✔
1426

1427
  // snapshot senders
1428
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
226,184✔
1429
    SSyncSnapshotSender* pSender = NULL;
212,043✔
1430
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
212,043✔
1431
    if (pSender == NULL) return NULL;
212,039!
1432

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

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

1443
  // is config changing
1444
  pSyncNode->changing = false;
14,143✔
1445

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

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

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

1464
  // start in syncNodeStart
1465
  // start raft
1466

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

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

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

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

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

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

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

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

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

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

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

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

1549
  TAOS_RETURN(code);
14,143✔
1550
}
1551

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

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

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

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

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

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

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

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

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

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

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

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

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

1655
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }
2,899!
1656

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

1662
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
14,143✔
1663

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

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

1693
  (void)taosThreadMutexDestroy(&pSyncNode->arbTokenMutex);
14,143✔
1694

1695
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
226,242✔
1696
    if (pSyncNode->senders[i] != NULL) {
212,099!
1697
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", pSyncNode->vgId, pSyncNode->senders[i]);
212,099✔
1698

1699
      if (snapshotSenderIsStart(pSyncNode->senders[i])) {
212,099!
1700
        snapshotSenderStop(pSyncNode->senders[i], false);
×
1701
      }
1702

1703
      snapshotSenderDestroy(pSyncNode->senders[i]);
212,111✔
1704
      pSyncNode->senders[i] = NULL;
212,111✔
1705
    }
1706
  }
1707

1708
  if (pSyncNode->pNewNodeReceiver != NULL) {
14,143✔
1709
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
1,918!
1710
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1711
    }
1712

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

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

1722
  raftStoreClose(pSyncNode);
14,141✔
1723

1724
  taosMemoryFree(pSyncNode);
14,142!
1725
}
1726

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

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

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

1755
int32_t syncNodeStartElectTimer(SSyncNode* pSyncNode, int32_t ms) {
290,041✔
1756
  int32_t code = 0;
290,041✔
1757
  if (syncIsInit()) {
290,041!
1758
    pSyncNode->electTimerMS = ms;
290,040✔
1759

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

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

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

1782
  return code;
330,076✔
1783
}
1784

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

1792
void syncNodeResetElectTimer(SSyncNode* pSyncNode) {
290,037✔
1793
  int32_t code = 0;
290,037✔
1794
  int32_t electMS;
1795

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

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

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

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

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

1827
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
13,352✔
1828
  int32_t ret = 0;
13,352✔
1829

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

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

1842
  return ret;
13,352✔
1843
}
1844

1845
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
35,808✔
1846
  int32_t code = 0;
35,808✔
1847

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

1855
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
63,698✔
1856
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
27,889✔
1857
    if (pSyncTimer != NULL) {
27,890!
1858
      TAOS_CHECK_RETURN(syncHbTimerStop(pSyncNode, pSyncTimer));
27,890!
1859
    }
1860
  }
1861

1862
  return code;
35,809✔
1863
}
1864

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

1875
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pNode, SRpcMsg* pMsg) {
625,494✔
1876
  SEpSet* epSet = NULL;
625,494✔
1877
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
944,774✔
1878
    if (destRaftId->addr == pNode->peersId[i].addr) {
944,670✔
1879
      epSet = &pNode->peersEpset[i];
625,390✔
1880
      break;
625,390✔
1881
    }
1882
  }
1883

1884
  int32_t code = -1;
625,494✔
1885
  if (pNode->syncSendMSg != NULL && epSet != NULL) {
625,494!
1886
    syncUtilMsgHtoN(pMsg->pCont);
625,392✔
1887
    pMsg->info.noResp = 1;
625,390✔
1888
    code = pNode->syncSendMSg(epSet, pMsg);
625,390✔
1889
  }
1890

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

1897
  TAOS_RETURN(code);
625,499✔
1898
}
1899

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

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

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

1918
    if (syncUtilSameId(&raftId, &pNode->myRaftId)) {
2,800✔
1919
      b2 = true;
2,350✔
1920
      break;
2,350✔
1921
    }
1922
  }
1923

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

1931
static bool syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg) {
3,320✔
1932
  if (pOldCfg->totalReplicaNum != pNewCfg->totalReplicaNum) return true;
3,320✔
1933
  if (pOldCfg->myIndex != pNewCfg->myIndex) return true;
2,232✔
1934
  for (int32_t i = 0; i < pOldCfg->totalReplicaNum; ++i) {
5,294✔
1935
    const SNodeInfo* pOldInfo = &pOldCfg->nodeInfo[i];
3,784✔
1936
    const SNodeInfo* pNewInfo = &pNewCfg->nodeInfo[i];
3,784✔
1937
    if (strcmp(pOldInfo->nodeFqdn, pNewInfo->nodeFqdn) != 0) return true;
3,784!
1938
    if (pOldInfo->nodePort != pNewInfo->nodePort) return true;
3,784!
1939
    if (pOldInfo->nodeRole != pNewInfo->nodeRole) return true;
3,784✔
1940
  }
1941

1942
  return false;
1,510✔
1943
}
1944

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

1953
  pSyncNode->raftCfg.cfg = *pNewConfig;
280✔
1954
  pSyncNode->raftCfg.lastConfigIndex = lastConfigChangeIndex;
280✔
1955

1956
  pSyncNode->configChangeNum++;
280✔
1957

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

1961
  bool isDrop = false;
280✔
1962
  bool isAdd = false;
280✔
1963

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

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

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

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

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

1996
  pCfg->configIndexArr[pCfg->configIndexCount] = lastConfigChangeIndex;
280✔
1997
  pCfg->configIndexCount++;
280✔
1998

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

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

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

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

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

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

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

2048
    // reset snapshot senders
2049

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

2055
    // reset new
2056
    for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
1,018✔
2057
      // reset sender
2058
      bool reset = false;
738✔
2059
      for (int32_t j = 0; j < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++j) {
3,173✔
2060
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
3,039!
2061
          sNTrace(pSyncNode, "snapshot sender reset for:%" PRId64 ", newIndex:%d, dnode:%d, %p",
604!
2062
                  (pSyncNode->replicasId)[i].addr, i, DID(&pSyncNode->replicasId[i]), oldSenders[j]);
2063

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

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

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

2075
          break;
604✔
2076
        }
2077
      }
2078
    }
2079

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

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

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

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

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

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

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

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

2143
  if (currentTerm < newTerm) {
222,644✔
2144
    raftStoreSetTerm(pSyncNode, newTerm);
2,535✔
2145
    char tmpBuf[64];
2146
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
2,535✔
2147
    syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
2,535✔
2148
    raftStoreClearVote(pSyncNode);
2,535✔
2149
  } else {
2150
    if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
220,109✔
2151
      syncNodeBecomeFollower(pSyncNode, id, "step down");
7✔
2152
    }
2153
  }
2154
}
2155

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

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

2166
  pSyncNode->hbSlowNum = 0;
5,920✔
2167

2168
  pSyncNode->leaderCache = leaderId;  // state change
5,920✔
2169

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

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

2187
  // send rsp to client
2188
  syncNodeLeaderChangeRsp(pSyncNode);
5,920✔
2189

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

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

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

2204
  // reset elect timer
2205
  syncNodeResetElectTimer(pSyncNode);
5,919✔
2206

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

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

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

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

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

2225
  // min match index
2226
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
276✔
2227

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

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

2259
  // reset restoreFinish
2260
  pSyncNode->restoreFinish = false;
11,748✔
2261

2262
  // state change
2263
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
11,748✔
2264
  pSyncNode->roleTimeMs = taosGetTimestampMs();
11,748✔
2265

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

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

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

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

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

2308
  // close receiver
2309
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
11,748!
2310
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2311
  }
2312

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

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

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

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

2336
  // min match index
2337
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
11,748✔
2338

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

2345
  // trace log
2346
  sNInfo(pSyncNode, "become leader %s", debugStr);
11,748✔
2347
}
2348

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

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

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

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

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

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

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

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

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

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

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

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

2415
  // min match index
2416
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
2✔
2417

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

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

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

2440
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
1,241!
2441

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

2447
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,241✔
2448

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

2453
bool syncNodeIsMnode(SSyncNode* pSyncNode) { return (pSyncNode->vgId == 1); }
144,861✔
2454

2455
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
25,890✔
2456
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
414,285✔
2457
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
388,395✔
2458
    pSyncNode->peerStates[i].lastSendTime = 0;
388,395✔
2459
  }
2460

2461
  return 0;
25,890✔
2462
}
2463

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

2475
  sNTrace(pSyncNode, "follower to candidate");
1,356!
2476
}
2477

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

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

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

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

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

2511
  raftStoreVote(pSyncNode, pRaftId);
1,414✔
2512
}
2513

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

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

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

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

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

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

2557
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
19,446✔
2558
  return lastIndex;
19,446✔
2559
}
2560

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

2573
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
2,569✔
2574
    if (logLastIndex > snapshot.lastApplyIndex) {
2,569✔
2575
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1,487✔
2576
    } else {
2577
      lastTerm = snapshot.lastApplyTerm;
1,082✔
2578
    }
2579

2580
  } else {
2581
    // no snapshot
2582
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
16,841✔
2583
  }
2584

2585
  return lastTerm;
19,410✔
2586
}
2587

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

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

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

2610
  return preIndex;
2611
}
2612

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

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

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

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

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

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

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

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

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

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

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

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

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

2686
static void syncNodeEqPingTimer(void* param, void* tmrId) {
59,529✔
2687
  if (!syncIsInit()) return;
59,529!
2688

2689
  int64_t    rid = (int64_t)param;
59,529✔
2690
  SSyncNode* pNode = syncNodeAcquire(rid);
59,529✔
2691

2692
  if (pNode == NULL) return;
59,529!
2693

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

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

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

2720
static void syncNodeEqElectTimer(void* param, void* tmrId) {
1,421✔
2721
  if (!syncIsInit()) return;
1,426!
2722

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

2726
  if (pNode == NULL) return;
1,421✔
2727

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

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

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

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

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

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

2760
  syncNodeRelease(pNode);
1,416✔
2761
}
2762

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

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

2770
  if (pNode == NULL) return;
2771

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

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

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

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

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

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

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

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

2822
  SSyncTimer* pSyncTimer = pData->pTimer;
62,601✔
2823

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

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

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

2841
  if (pSyncNode->totalReplicaNum > 1) {
62,601✔
2842
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
62,599✔
2843
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
62,599✔
2844

2845
    if (timerLogicClock == msgLogicClock) {
62,599✔
2846
      if (tsNow > pData->execTime) {
62,597✔
2847
        pData->execTime += pSyncTimer->timerMS;
62,577✔
2848

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

2857
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);
62,577✔
2858

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

2868
        // update reset time
2869
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
62,577✔
2870
        pSyncTimer->timeStamp = tsNow;
62,577✔
2871

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

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

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

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

2898
  syncHbTimerDataRelease(pData);
62,601✔
2899
  syncNodeRelease(pSyncNode);
62,601✔
2900
}
2901

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

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

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

2920
  return code;
2921
}
2922
#endif
2923

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3093
  return 0;
×
3094
}
3095

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

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

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

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

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

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

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

3148
  syncIndexMgrDestroy(oldIndex);
×
3149

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

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

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

3162
  syncIndexMgrDestroy(oldNextIndex);
×
3163

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3271
  taosMemoryFree(oldLogReplMgrs);
×
3272

3273
  return 0;
×
3274
}
3275

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3370
  int32_t oldTotalReplicaNum = ths->totalReplicaNum;
×
3371

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

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

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

3386
      // no need to change myNodeInfo
3387

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

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

3398
      syncNodeResetPeerAndCfg(ths);
×
3399

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

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

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

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

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

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

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

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

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

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

3450
      // no need to change myNodeInfo
3451

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

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

3462
      // no need to change state
3463

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

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

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

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

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

3483
  TAOS_RETURN(code);
×
3484
}
3485

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

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

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

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

3523
  if (code == 0 && ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
1,917,024✔
3524
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
8✔
3525
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
8!
3526

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

3535
  // multi replica
3536
  if (ths->replicaNum > 1) {
1,916,963✔
3537
    TAOS_RETURN(code);
101,276✔
3538
  }
3539

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

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

3552
  TAOS_RETURN(code);
1,815,828✔
3553
}
3554

3555
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
1,906,936✔
3556
  if (pSyncNode->totalReplicaNum == 1) {
1,906,936✔
3557
    return false;
1,803,543✔
3558
  }
3559

3560
  int32_t toCount = 0;
103,393✔
3561
  int64_t tsNow = taosGetTimestampMs();
103,403✔
3562
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
307,935✔
3563
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
204,534✔
3564
      continue;
2,187✔
3565
    }
3566
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
202,347✔
3567
    if (recvTime == 0 || recvTime == -1) {
202,345!
3568
      continue;
×
3569
    }
3570

3571
    if (tsNow - recvTime > tsHeartbeatTimeout) {
202,345✔
3572
      toCount++;
795✔
3573
    }
3574
  }
3575

3576
  bool b = (toCount >= pSyncNode->quorum ? true : false);
103,401✔
3577

3578
  return b;
103,401✔
3579
}
3580

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

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

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

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

3611
  code = syncNodeAppend(ths, pEntry, NULL);
11,750✔
3612
  TAOS_RETURN(code);
11,750✔
3613
}
3614

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

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

3624
  LRUHandle* h = NULL;
3625

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

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

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

3642
  return ret;
3643
}
3644
#endif
3645

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

3650
  int64_t tsMs = taosGetTimestampMs();
60,965✔
3651

3652
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pNextIndex, &(pMsg->srcId));
60,965✔
3653
  syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);
60,965✔
3654
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
60,965✔
3655

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

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

3668
  SyncTerm currentTerm = raftStoreGetTerm(ths);
60,965✔
3669

3670
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
60,965✔
3671
    raftStoreSetTerm(ths, pMsg->term);
271✔
3672
    currentTerm = pMsg->term;
271✔
3673
  }
3674

3675
  int64_t tsMs2 = taosGetTimestampMs();
60,965✔
3676

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

3692
  if (pMsg->term == currentTerm &&
60,965✔
3693
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
60,877!
3694
    resetElect = true;
60,877✔
3695

3696
    ths->minMatchIndex = pMsg->minMatchIndex;
60,877✔
3697

3698
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
60,877✔
3699
      SRpcMsg rpcMsgLocalCmd = {0};
60,872✔
3700
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
60,872!
3701
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
60,872✔
3702

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

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

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

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

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

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

3758
  // reply
3759
  int64_t tsMs3 = taosGetTimestampMs();
60,965✔
3760

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

3783
  TAOS_CHECK_RETURN(syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg));
60,965!
3784

3785
  if (resetElect) syncNodeResetElectTimer(ths);
60,965✔
3786
  return 0;
60,965✔
3787
}
3788

3789
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
60,290✔
3790
  int32_t code = 0;
60,290✔
3791

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

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

3805
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
60,290✔
3806
  syncIndexMgrIncRecvCount(ths->pMatchIndex, &(pMsg->srcId));
60,290✔
3807

3808
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
60,290✔
3809
}
3810

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

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

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

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

3829
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
60,872!
3830
    SRaftId id = EMPTY_RAFT_ID;
×
3831
    syncNodeStepDown(ths, pMsg->currentTerm, id);
×
3832

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

3855
  return 0;
60,872✔
3856
}
3857

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

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

3873
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
1,905,361✔
3874
  SyncTerm        term = raftStoreGetTerm(ths);
1,905,372✔
3875
  SSyncRaftEntry* pEntry = NULL;
1,905,369✔
3876
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
1,905,369✔
3877
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
189,691✔
3878
  } else {
3879
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
1,715,678✔
3880
  }
3881

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

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

3896
  if (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
1,905,348!
3897
    if (pRetIndex) {
1,905,348✔
3898
      (*pRetIndex) = index;
1,715,660✔
3899
    }
3900

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

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

3925
    code = syncNodeAppend(ths, pEntry, pMsg);
1,905,348✔
3926
    return code;
1,905,180✔
3927
  } else {
3928
    syncEntryDestroy(pEntry);
×
3929
    pEntry = NULL;
×
3930
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3931
  }
3932
}
3933

3934
const char* syncStr(ESyncState state) {
710,217✔
3935
  switch (state) {
710,217!
3936
    case TAOS_SYNC_STATE_FOLLOWER:
384,300✔
3937
      return "follower";
384,300✔
3938
    case TAOS_SYNC_STATE_CANDIDATE:
2,622✔
3939
      return "candidate";
2,622✔
3940
    case TAOS_SYNC_STATE_LEADER:
287,548✔
3941
      return "leader";
287,548✔
3942
    case TAOS_SYNC_STATE_ERROR:
×
3943
      return "error";
×
3944
    case TAOS_SYNC_STATE_OFFLINE:
5,718✔
3945
      return "offline";
5,718✔
3946
    case TAOS_SYNC_STATE_LEARNER:
30,014✔
3947
      return "learner";
30,014✔
3948
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
22✔
3949
      return "assigned leader";
22✔
3950
    default:
×
3951
      return "unknown";
×
3952
  }
3953
}
3954

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

3962
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
2,032✔
3963
      pNewCfg->myIndex = i;
1,790✔
3964
      return 0;
1,790✔
3965
    }
3966
  }
3967

3968
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3969
}
3970

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

3975
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
558,207✔
3976
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
1,115,274✔
3977
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
1,115,273✔
3978
      return true;
558,207✔
3979
    }
3980
  }
3981
  return false;
1✔
3982
}
3983

3984
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
40,914✔
3985
  SSyncSnapshotSender* pSender = NULL;
40,914✔
3986
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
163,872✔
3987
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
122,958✔
3988
      pSender = (ths->senders)[i];
40,914✔
3989
    }
3990
  }
3991
  return pSender;
40,914✔
3992
}
3993

3994
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
30,791✔
3995
  SSyncTimer* pTimer = NULL;
30,791✔
3996
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
128,353✔
3997
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
97,563✔
3998
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
30,792✔
3999
    }
4000
  }
4001
  return pTimer;
30,790✔
4002
}
4003

4004
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
3,366✔
4005
  SPeerState* pState = NULL;
3,366✔
4006
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
11,562✔
4007
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
8,196✔
4008
      pState = &((ths->peerStates)[i]);
3,366✔
4009
    }
4010
  }
4011
  return pState;
3,366✔
4012
}
4013

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

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

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

4029
  return true;
4030
}
4031

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

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

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

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