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

taosdata / TDengine / #4747

21 Sep 2025 11:53PM UTC coverage: 58.002% (-1.1%) from 59.065%
#4747

push

travis-ci

web-flow
fix: refine python taos error log matching in checkAsan.sh (#33029)

* fix: refine python taos error log matching in checkAsan.sh

* fix: improve python taos error log matching in checkAsan.sh

133398 of 293157 branches covered (45.5%)

Branch coverage included in aggregate %.

201778 of 284713 relevant lines covered (70.87%)

5539418.83 hits per line

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

53.24
/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,258✔
64
  sInfo("vgId:%d, start to open sync", pSyncInfo->vgId);
14,258✔
65

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

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

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

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

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

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

114
  syncNodeRelease(pSyncNode);
14,264✔
115

116
  sInfo("vgId:%d, sync started", vgId);
14,264✔
117

118
  TAOS_RETURN(code);
14,264✔
119

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

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

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

136
  *cfg = pSyncNode->raftCfg.cfg;
22,383✔
137

138
  syncNodeRelease(pSyncNode);
22,383✔
139

140
  return 0;
22,382✔
141
}
142

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

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

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

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

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

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

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

200
  TAOS_CHECK_RETURN(syncNodeUpdateNewConfigIndex(pSyncNode, pNewCfg));
1,797!
201

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

208
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER || pSyncNode->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
1,797!
209
    // TODO check return value
210
    TAOS_CHECK_RETURN(syncNodeStopHeartbeatTimer(pSyncNode));
1,611!
211

212
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
25,776✔
213
      TAOS_CHECK_RETURN(syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]));
24,165!
214
    }
215

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

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

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

232
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
947,468✔
233
  if (pSyncNode == NULL) {
947,477✔
234
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
11✔
235
    if (terrno != 0) code = terrno;
11!
236
    TAOS_RETURN(code);
×
237
  }
238

239
  switch (pMsg->msgType) {
947,466!
240
    case TDMT_SYNC_HEARTBEAT:
68,280✔
241
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
68,280✔
242
      break;
68,280✔
243
    case TDMT_SYNC_HEARTBEAT_REPLY:
67,721✔
244
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
67,721✔
245
      break;
67,721✔
246
    case TDMT_SYNC_TIMEOUT:
63,990✔
247
      code = syncNodeOnTimeout(pSyncNode, pMsg);
63,990✔
248
      break;
63,987✔
249
    case TDMT_SYNC_TIMEOUT_ELECTION:
1,361✔
250
      code = syncNodeOnTimeout(pSyncNode, pMsg);
1,361✔
251
      break;
1,361✔
252
    case TDMT_SYNC_CLIENT_REQUEST:
188,687✔
253
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
188,687✔
254
      break;
188,687✔
255
    case TDMT_SYNC_REQUEST_VOTE:
2,465✔
256
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
2,465✔
257
      break;
2,465✔
258
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
2,461✔
259
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
2,461✔
260
      break;
2,461✔
261
    case TDMT_SYNC_APPEND_ENTRIES:
240,712✔
262
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
240,712✔
263
      break;
240,712✔
264
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
240,455✔
265
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
240,455✔
266
      break;
240,454✔
267
    case TDMT_SYNC_SNAPSHOT_SEND:
1,574✔
268
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
1,574✔
269
      break;
1,574✔
270
    case TDMT_SYNC_SNAPSHOT_RSP:
1,574✔
271
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
1,574✔
272
      break;
1,574✔
273
    case TDMT_SYNC_LOCAL_CMD:
68,163✔
274
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
68,163✔
275
      break;
68,163✔
276
    case TDMT_SYNC_FORCE_FOLLOWER:
18✔
277
      code = syncForceBecomeFollower(pSyncNode, pMsg);
18✔
278
      break;
18✔
279
    case TDMT_SYNC_SET_ASSIGNED_LEADER:
5✔
280
      code = syncBecomeAssignedLeader(pSyncNode, pMsg);
5✔
281
      break;
5✔
282
    default:
×
283
      code = TSDB_CODE_MSG_NOT_PROCESSED;
×
284
  }
285

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

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

303
  int32_t ret = syncNodeLeaderTransfer(pSyncNode);
14,264✔
304
  syncNodeRelease(pSyncNode);
14,264✔
305
  return ret;
14,264✔
306
}
307

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

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

320
  return 0;
18✔
321
}
322

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

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

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

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

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

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

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

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

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

390
  code = TSDB_CODE_SUCCESS;
2✔
391

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

400
  tmsgSendRsp(&rspMsg);
5✔
401

402
  tFreeSVArbSetAssignedLeaderReq(&req);
5✔
403
  TAOS_RETURN(code);
5✔
404
}
405

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

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

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

430
SyncIndex syncMinMatchIndex(SSyncNode* pSyncNode) {
72,320✔
431
  SyncIndex minMatchIndex = SYNC_INDEX_INVALID;
72,320✔
432

433
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
216,232✔
434
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
143,912✔
435
    if (minMatchIndex == SYNC_INDEX_INVALID) {
143,912✔
436
      minMatchIndex = matchIndex;
75,816✔
437
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
68,096✔
438
      minMatchIndex = matchIndex;
1,495✔
439
    }
440
  }
441
  return minMatchIndex;
72,320✔
442
}
443

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

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

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

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

468
  int64_t logRetention = 0;
25,848✔
469

470
  if (syncNodeIsMnode(pSyncNode)) {
25,848✔
471
    // mnode
472
    logRetention = tsMndLogRetention;
3,558✔
473
  } else {
474
    // vnode
475
    if (pSyncNode->replicaNum > 1) {
22,290✔
476
      logRetention = SYNC_VNODE_LOG_RETENTION;
870✔
477
    }
478
  }
479

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

493
_DEL_WAL:
24,532✔
494

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

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

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

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

524
  syncNodeRelease(pSyncNode);
25,846✔
525
  TAOS_RETURN(code);
25,846✔
526
}
527

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

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

551
  syncNodeRelease(pSyncNode);
25,941✔
552
  TAOS_RETURN(code);
25,941✔
553
}
554

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

562
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,883,011✔
563
    terrno = TSDB_CODE_SYN_NOT_LEADER;
77,479✔
564
    return false;
77,479✔
565
  }
566

567
  if (!pSyncNode->restoreFinish) {
2,805,532✔
568
    terrno = TSDB_CODE_SYN_RESTORING;
388✔
569
    return false;
388✔
570
  }
571

572
  return true;
2,805,144✔
573
}
574

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

582
  bool ready = syncNodeIsReadyForRead(pSyncNode);
2,597,431✔
583

584
  syncNodeRelease(pSyncNode);
2,597,454✔
585
  return ready;
2,597,363✔
586
}
587

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

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

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

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

612
int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode) {
14,264✔
613
  if (pSyncNode->peersNum == 0) {
14,264✔
614
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
10,470✔
615
    return 0;
10,470✔
616
  }
617

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

631
  return ret;
3,794✔
632
}
633

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

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

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

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

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

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

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

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

675
SSyncState syncGetState(int64_t rid) {
1,974,044✔
676
  SSyncState state = {.state = TAOS_SYNC_STATE_ERROR};
1,974,044✔
677

678
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,974,044✔
679
  if (pSyncNode != NULL) {
1,974,567✔
680
    state.state = pSyncNode->state;
1,974,205✔
681
    state.roleTimeMs = pSyncNode->roleTimeMs;
1,974,205✔
682
    state.startTimeMs = pSyncNode->startTime;
1,974,205✔
683
    state.restored = pSyncNode->restoreFinish;
1,974,205✔
684
    if (pSyncNode->vgId != 1) {
1,974,205✔
685
      state.canRead = syncNodeIsReadyForRead(pSyncNode);
286,079✔
686
    } else {
687
      state.canRead = state.restored;
1,688,126✔
688
    }
689
    /*
690
    double progress = 0;
691
    if(pSyncNode->pLogBuf->totalIndex > 0 && pSyncNode->pLogBuf->commitIndex > 0){
692
      progress = (double)pSyncNode->pLogBuf->commitIndex/(double)pSyncNode->pLogBuf->totalIndex;
693
      state.progress = (int32_t)(progress * 100);
694
    }
695
    else{
696
      state.progress = -1;
697
    }
698
    sDebug("vgId:%d, learner progress state, commitIndex:%" PRId64 " totalIndex:%" PRId64 ", "
699
            "progress:%lf, progress:%d",
700
          pSyncNode->vgId,
701
         pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->totalIndex, progress, state.progress);
702
    */
703
    state.term = raftStoreGetTerm(pSyncNode);
1,974,204✔
704
    syncNodeRelease(pSyncNode);
1,974,597✔
705
  }
706

707
  return state;
1,974,594✔
708
}
709

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

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

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

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

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

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

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

758
  syncNodeRelease(pSyncNode);
48,508✔
759
  TAOS_RETURN(code);
48,508✔
760
}
761

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

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

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

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

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

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

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

811
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
1,190,503✔
812
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
620,171✔
813
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
49,838✔
814
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
49,699✔
815
    }
816
  }
817
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
570,332✔
818
         lastIndex);
819

820
  return lastIndex;
570,333✔
821
}
822

823
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
181,290✔
824
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
308,243✔
825
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
209,787✔
826
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
209,783✔
827
      return pSyncNode->peersId[i];
82,834✔
828
    }
829
  }
830
  return EMPTY_RAFT_ID;
98,456✔
831
}
832

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

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

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

848
  if (offset < bufferSize) {
98,561✔
849
    snprintf(buffer + offset, bufferSize - offset, "]");
98,560✔
850
  }
851
}
852

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

856
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
98,561✔
857
  if (pSyncNode == NULL) return;
98,563!
858

859
  int index = -1;
98,563✔
860

861
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
98,563✔
862
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
863
  int j = 0;
98,563✔
864
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
281,550✔
865
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
182,985✔
866
    SEp* pEp = &pEpSet->eps[j];
181,295✔
867
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
181,295✔
868
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
181,295✔
869
    pEpSet->numOfEps++;
181,295✔
870
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
181,295✔
871
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
181,296✔
872
           pEp->port);
873
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
181,297✔
874
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
68,940✔
875
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
876
      index = j;
68,935✔
877
    }
878
    j++;
181,297✔
879
  }
880
  if (pEpSet->numOfEps > 0) {
98,565✔
881
    if (index != -1) {
98,561✔
882
      pEpSet->inUse = index;
68,939✔
883
    } else {
884
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
29,622!
885
          pSyncNode->myRaftId.vgId == pSyncNode->leaderCache.vgId) {
×
886
        pEpSet->inUse = pSyncNode->raftCfg.cfg.myIndex;
×
887
      } else {
888
        pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
29,622✔
889
      }
890
    }
891
    // pEpSet->inUse = 0;
892
  }
893
  epsetSort(pEpSet);
98,565✔
894

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

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

912
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak, seq);
1,942,595✔
913
  syncNodeRelease(pSyncNode);
1,942,500✔
914
  return ret;
1,942,572✔
915
}
916

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

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

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

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

946
  int32_t isCatchUp = 0;
4,724✔
947
  if (pSyncNode->pLogBuf->totalIndex < 0 || pSyncNode->pLogBuf->commitIndex < 0 ||
4,724!
948
      pSyncNode->pLogBuf->totalIndex < pSyncNode->pLogBuf->commitIndex ||
814✔
949
      pSyncNode->pLogBuf->totalIndex - pSyncNode->pLogBuf->commitIndex > SYNC_LEARNER_CATCHUP) {
810✔
950
    sInfo("vgId:%d, Not catch up, wait one second, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64,
4,450!
951
          pSyncNode->vgId, pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex,
952
          pSyncNode->pLogBuf->matchIndex);
953
    isCatchUp = 0;
4,450✔
954
  } else {
955
    sInfo("vgId:%d, Catch up, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64, pSyncNode->vgId,
274!
956
          pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->matchIndex);
957
    isCatchUp = 1;
274✔
958
  }
959

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

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

974
  ESyncRole role = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole;
4,724✔
975

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

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

990
  int64_t term = raftStoreGetTerm(pSyncNode);
19,269✔
991

992
  syncNodeRelease(pSyncNode);
19,269✔
993
  return term;
19,269✔
994
}
995

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

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

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

1019
  // optimized one replica
1020
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
1,940,617✔
1021
    SyncIndex retIndex;
1022
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
1,750,374✔
1023
    if (code >= 0) {
1,750,262!
1024
      pMsg->info.conn.applyIndex = retIndex;
1,750,282✔
1025
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
1,750,282✔
1026

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1177
  memcpy(pSyncNode->path, pSyncInfo->path, sizeof(pSyncNode->path));
14,263✔
1178
  snprintf(pSyncNode->raftStorePath, sizeof(pSyncNode->raftStorePath), "%s%sraft_store.json", pSyncInfo->path,
14,263✔
1179
           TD_DIRSEP);
1180
  snprintf(pSyncNode->configPath, sizeof(pSyncNode->configPath), "%s%sraft_config.json", pSyncInfo->path, TD_DIRSEP);
14,263✔
1181

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

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

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

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

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

1254
  pSyncNode->pWal = pSyncInfo->pWal;
14,264✔
1255
  pSyncNode->msgcb = pSyncInfo->msgcb;
14,264✔
1256
  pSyncNode->syncSendMSg = pSyncInfo->syncSendMSg;
14,264✔
1257
  pSyncNode->syncEqMsg = pSyncInfo->syncEqMsg;
14,264✔
1258
  pSyncNode->syncEqCtrlMsg = pSyncInfo->syncEqCtrlMsg;
14,264✔
1259

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

1267
  // init replicaNum, replicasId
1268
  pSyncNode->replicaNum = pSyncNode->raftCfg.cfg.replicaNum;
14,263✔
1269
  pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
14,263✔
1270
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
36,038✔
1271
    if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
21,773!
1272
        false) {
1273
      sError("vgId:%d, failed to determine raft member id, replica:%d", pSyncNode->vgId, i);
×
1274
      goto _error;
×
1275
    }
1276
  }
1277

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

1282
  // init peersNum, peers, peersId
1283
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
14,265✔
1284
  int32_t j = 0;
14,265✔
1285
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
36,040✔
1286
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
21,775✔
1287
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
7,511✔
1288
      pSyncNode->peersId[j] = pSyncNode->replicasId[i];
7,511✔
1289
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
7,511✔
1290
      j++;
7,511✔
1291
    }
1292
  }
1293

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

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

1307
  // init life cycle outside
1308

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

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

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

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

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

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

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

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

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

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

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

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

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

1449
  // restore state
1450
  pSyncNode->restoreFinish = false;
14,263✔
1451

1452
  // snapshot senders
1453
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
228,081✔
1454
    SSyncSnapshotSender* pSender = NULL;
213,817✔
1455
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
213,817✔
1456
    if (pSender == NULL) return NULL;
213,825!
1457

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

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

1468
  // is config changing
1469
  pSyncNode->changing = false;
14,264✔
1470

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

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

1485
  //
1486
  // min match index
1487
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
14,264✔
1488

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

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

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

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

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

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

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

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

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

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

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

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

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

1574
  TAOS_RETURN(code);
14,264✔
1575
}
1576

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

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

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

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

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

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

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

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

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

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

1663
  // clean rsp
1664
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
14,263✔
1665
}
1666

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

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

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

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

1687
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
14,264✔
1688

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

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

1718
  (void)taosThreadMutexDestroy(&pSyncNode->arbTokenMutex);
14,263✔
1719

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

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

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

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

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

1743
  if (pSyncNode->pFsm != NULL) {
14,263!
1744
    taosMemoryFree(pSyncNode->pFsm);
14,263!
1745
  }
1746

1747
  raftStoreClose(pSyncNode);
14,264✔
1748

1749
  taosMemoryFree(pSyncNode);
14,263!
1750
}
1751

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

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

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

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

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

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

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

1807
  return code;
333,831✔
1808
}
1809

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

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

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

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

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

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

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

1852
int32_t syncNodeStartHeartbeatTimer(SSyncNode* pSyncNode) {
13,460✔
1853
  int32_t ret = 0;
13,460✔
1854

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

1860
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
16,296✔
1861
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
2,836✔
1862
    if (pSyncTimer != NULL) {
2,836!
1863
      TAOS_CHECK_RETURN(syncHbTimerStart(pSyncNode, pSyncTimer));
2,836!
1864
    }
1865
  }
1866

1867
  return ret;
13,460✔
1868
}
1869

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

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

1880
  return code;
×
1881
}
1882

1883
int32_t syncNodeStopHeartbeatTimer(SSyncNode* pSyncNode) {
35,983✔
1884
  int32_t code = 0;
35,983✔
1885

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

1893
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
63,619✔
1894
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
27,637✔
1895
    if (pSyncTimer != NULL) {
27,636!
1896
      TAOS_CHECK_RETURN(syncHbTimerStop(pSyncNode, pSyncTimer));
27,637!
1897
    }
1898
  }
1899

1900
  return code;
35,982✔
1901
}
1902

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

1912
  return 0;
×
1913
}
1914

1915
int32_t syncNodeSendMsgById(const SRaftId* destRaftId, SSyncNode* pNode, SRpcMsg* pMsg) {
632,159✔
1916
  SEpSet* epSet = NULL;
632,159✔
1917
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
973,019✔
1918
    if (destRaftId->addr == pNode->peersId[i].addr) {
972,854✔
1919
      epSet = &pNode->peersEpset[i];
631,994✔
1920
      break;
631,994✔
1921
    }
1922
  }
1923

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

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

1937
  TAOS_RETURN(code);
632,162✔
1938
}
1939

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

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

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

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

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

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

1982
  return false;
1,518✔
1983
}
1984

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

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

1996
  pSyncNode->configChangeNum++;
279✔
1997

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

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

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

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

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

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

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

2036
  pCfg->configIndexArr[pCfg->configIndexCount] = lastConfigChangeIndex;
279✔
2037
  pCfg->configIndexCount++;
279✔
2038

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

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

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

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

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

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

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

2088
    // reset snapshot senders
2089

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2229
  // trace log
2230
  sNTrace(pSyncNode, "become follower %s", debugStr);
5,844!
2231

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

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

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

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

2249
  // reset elect timer
2250
  syncNodeResetElectTimer(pSyncNode);
5,844✔
2251

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

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

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

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

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

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

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

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

2304
  // reset restoreFinish
2305
  pSyncNode->restoreFinish = false;
11,847✔
2306

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2500
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
26,113✔
2501
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
417,808✔
2502
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
391,695✔
2503
    pSyncNode->peerStates[i].lastSendTime = 0;
391,695✔
2504
  }
2505

2506
  return 0;
26,113✔
2507
}
2508

2509
void syncNodeFollower2Candidate(SSyncNode* pSyncNode) {
1,296✔
2510
  if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
1,296!
2511
    sError("vgId:%d, failed candidate from follower since node state is wrong:%d", pSyncNode->vgId, pSyncNode->state);
×
2512
    return;
×
2513
  }
2514
  pSyncNode->state = TAOS_SYNC_STATE_CANDIDATE;
1,296✔
2515
  pSyncNode->roleTimeMs = taosGetTimestampMs();
1,296✔
2516
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,296✔
2517
  sInfo("vgId:%d, become candidate from follower. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64,
1,296!
2518
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2519

2520
  sNTrace(pSyncNode, "follower to candidate");
1,296!
2521
}
2522

2523
int32_t syncNodeAssignedLeader2Leader(SSyncNode* pSyncNode) {
×
2524
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) return TSDB_CODE_SYN_INTERNAL_ERROR;
×
2525
  syncNodeBecomeLeader(pSyncNode, "assigned leader to leader");
×
2526

2527
  sNTrace(pSyncNode, "assigned leader to leader");
×
2528

2529
  int32_t ret = syncNodeAppendNoop(pSyncNode);
×
2530
  if (ret < 0) {
×
2531
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, tstrerror(ret));
×
2532
  }
2533

2534
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
×
2535
  sInfo("vgId:%d, become leader from assigned leader. term:%" PRId64 ", commit index:%" PRId64
×
2536
        "assigned commit index:%" PRId64 ", last index:%" PRId64,
2537
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, pSyncNode->assignedCommitIndex,
2538
        lastIndex);
2539
  return 0;
×
2540
}
2541

2542
// just called by syncNodeVoteForSelf
2543
void syncNodeVoteForTerm(SSyncNode* pSyncNode, SyncTerm term, SRaftId* pRaftId) {
1,360✔
2544
  SyncTerm storeTerm = raftStoreGetTerm(pSyncNode);
1,360✔
2545
  if (term != storeTerm) {
1,360!
2546
    sError("vgId:%d, failed to vote for term, term:%" PRId64 ", storeTerm:%" PRId64, pSyncNode->vgId, term, storeTerm);
×
2547
    return;
×
2548
  }
2549
  sTrace("vgId:%d, begin hasVoted", pSyncNode->vgId);
1,360!
2550
  bool voted = raftStoreHasVoted(pSyncNode);
1,360✔
2551
  if (voted) {
1,360!
2552
    sError("vgId:%d, failed to vote for term since not voted", pSyncNode->vgId);
×
2553
    return;
×
2554
  }
2555

2556
  raftStoreVote(pSyncNode, pRaftId);
1,360✔
2557
}
2558

2559
// simulate get vote from outside
2560
void syncNodeVoteForSelf(SSyncNode* pSyncNode, SyncTerm currentTerm) {
1,360✔
2561
  syncNodeVoteForTerm(pSyncNode, currentTerm, &pSyncNode->myRaftId);
1,360✔
2562

2563
  SRpcMsg rpcMsg = {0};
1,360✔
2564
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
1,360✔
2565
  if (ret != 0) return;
1,360!
2566

2567
  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
1,360✔
2568
  pMsg->srcId = pSyncNode->myRaftId;
1,360✔
2569
  pMsg->destId = pSyncNode->myRaftId;
1,360✔
2570
  pMsg->term = currentTerm;
1,360✔
2571
  pMsg->voteGranted = true;
1,360✔
2572

2573
  voteGrantedVote(pSyncNode->pVotesGranted, pMsg);
1,360✔
2574
  votesRespondAdd(pSyncNode->pVotesRespond, pMsg);
1,360✔
2575
  rpcFreeCont(rpcMsg.pCont);
1,360✔
2576
}
2577

2578
// return if has a snapshot
2579
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
19,237✔
2580
  bool      ret = false;
19,237✔
2581
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
19,237✔
2582
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
19,237!
2583
    // TODO check return value
2584
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
19,237✔
2585
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
19,237✔
2586
      ret = true;
2,583✔
2587
    }
2588
  }
2589
  return ret;
19,237✔
2590
}
2591

2592
// return max(logLastIndex, snapshotLastIndex)
2593
// if no snapshot and log, return -1
2594
SyncIndex syncNodeGetLastIndex(const SSyncNode* pSyncNode) {
19,274✔
2595
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
19,274✔
2596
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
19,274!
2597
    // TODO check return value
2598
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
19,274✔
2599
  }
2600
  SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
19,274✔
2601

2602
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
19,274✔
2603
  return lastIndex;
19,274✔
2604
}
2605

2606
// return the last term of snapshot and log
2607
// if error, return SYNC_TERM_INVALID (by syncLogLastTerm)
2608
SyncTerm syncNodeGetLastTerm(SSyncNode* pSyncNode) {
19,237✔
2609
  SyncTerm lastTerm = 0;
19,237✔
2610
  if (syncNodeHasSnapshot(pSyncNode)) {
19,237✔
2611
    // has snapshot
2612
    SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
2,583✔
2613
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2,583!
2614
      // TODO check return value
2615
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2,583✔
2616
    }
2617

2618
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
2,583✔
2619
    if (logLastIndex > snapshot.lastApplyIndex) {
2,583✔
2620
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1,526✔
2621
    } else {
2622
      lastTerm = snapshot.lastApplyTerm;
1,057✔
2623
    }
2624

2625
  } else {
2626
    // no snapshot
2627
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
16,654✔
2628
  }
2629

2630
  return lastTerm;
19,237✔
2631
}
2632

2633
// get last index and term along with snapshot
2634
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
16,772✔
2635
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
16,772✔
2636
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
16,772✔
2637
  return 0;
16,772✔
2638
}
2639

2640
#ifdef BUILD_NO_CALL
2641
// return append-entries first try index
2642
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
2643
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
2644
  return syncStartIndex;
2645
}
2646

2647
// if index > 0, return index - 1
2648
// else, return -1
2649
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
2650
  SyncIndex preIndex = index - 1;
2651
  if (preIndex < SYNC_INDEX_INVALID) {
2652
    preIndex = SYNC_INDEX_INVALID;
2653
  }
2654

2655
  return preIndex;
2656
}
2657

2658
// if index < 0, return SYNC_TERM_INVALID
2659
// if index == 0, return 0
2660
// if index > 0, return preTerm
2661
// if error, return SYNC_TERM_INVALID
2662
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
2663
  if (index < SYNC_INDEX_BEGIN) {
2664
    return SYNC_TERM_INVALID;
2665
  }
2666

2667
  if (index == SYNC_INDEX_BEGIN) {
2668
    return 0;
2669
  }
2670

2671
  SyncTerm  preTerm = 0;
2672
  SyncIndex preIndex = index - 1;
2673

2674
  SSyncRaftEntry* pPreEntry = NULL;
2675
  SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
2676
  LRUHandle*      h = taosLRUCacheLookup(pCache, &preIndex, sizeof(preIndex));
2677
  int32_t         code = 0;
2678
  if (h) {
2679
    pPreEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2680
    code = 0;
2681

2682
    pSyncNode->pLogStore->cacheHit++;
2683
    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);
2684

2685
  } else {
2686
    pSyncNode->pLogStore->cacheMiss++;
2687
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);
2688

2689
    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
2690
  }
2691

2692
  SSnapshot snapshot = {.data = NULL,
2693
                        .lastApplyIndex = SYNC_INDEX_INVALID,
2694
                        .lastApplyTerm = SYNC_TERM_INVALID,
2695
                        .lastConfigIndex = SYNC_INDEX_INVALID};
2696

2697
  if (code == 0) {
2698
    if (pPreEntry == NULL) return -1;
2699
    preTerm = pPreEntry->term;
2700

2701
    if (h) {
2702
      taosLRUCacheRelease(pCache, h, false);
2703
    } else {
2704
      syncEntryDestroy(pPreEntry);
2705
    }
2706

2707
    return preTerm;
2708
  } else {
2709
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2710
      // TODO check return value
2711
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2712
      if (snapshot.lastApplyIndex == preIndex) {
2713
        return snapshot.lastApplyTerm;
2714
      }
2715
    }
2716
  }
2717

2718
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
2719
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
2720
  return SYNC_TERM_INVALID;
2721
}
2722

2723
// get pre index and term of "index"
2724
int32_t syncNodeGetPreIndexTerm(SSyncNode* pSyncNode, SyncIndex index, SyncIndex* pPreIndex, SyncTerm* pPreTerm) {
2725
  *pPreIndex = syncNodeGetPreIndex(pSyncNode, index);
2726
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
2727
  return 0;
2728
}
2729
#endif
2730

2731
static void syncNodeEqPingTimer(void* param, void* tmrId) {
64,007✔
2732
  if (!syncIsInit()) return;
64,007!
2733

2734
  int64_t    rid = (int64_t)param;
64,008✔
2735
  SSyncNode* pNode = syncNodeAcquire(rid);
64,008✔
2736

2737
  if (pNode == NULL) return;
64,008!
2738

2739
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
64,008!
2740
    SRpcMsg rpcMsg = {0};
64,008✔
2741
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
64,008✔
2742
                                    pNode->pingTimerMS, pNode);
2743
    if (code != 0) {
64,008!
2744
      sError("failed to build ping msg");
×
2745
      rpcFreeCont(rpcMsg.pCont);
×
2746
      goto _out;
×
2747
    }
2748

2749
    // sTrace("enqueue ping msg");
2750
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
64,008✔
2751
    if (code != 0) {
64,008!
2752
      sError("failed to sync enqueue ping msg since %s", terrstr());
×
2753
      rpcFreeCont(rpcMsg.pCont);
×
2754
      goto _out;
×
2755
    }
2756

2757
  _out:
64,008✔
2758
    if (taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
64,008!
2759
                     &pNode->pPingTimer))
2760
      sError("failed to reset ping timer");
×
2761
  }
2762
  syncNodeRelease(pNode);
64,008✔
2763
}
2764

2765
static void syncNodeEqElectTimer(void* param, void* tmrId) {
1,373✔
2766
  if (!syncIsInit()) return;
1,385!
2767

2768
  int64_t    rid = (int64_t)param;
1,373✔
2769
  SSyncNode* pNode = syncNodeAcquire(rid);
1,373✔
2770

2771
  if (pNode == NULL) return;
1,373✔
2772

2773
  if (pNode->syncEqMsg == NULL) {
1,365!
2774
    syncNodeRelease(pNode);
×
2775
    return;
×
2776
  }
2777

2778
  int64_t tsNow = taosGetTimestampMs();
1,365✔
2779
  if (tsNow < pNode->electTimerParam.executeTime) {
1,365✔
2780
    syncNodeRelease(pNode);
4✔
2781
    return;
4✔
2782
  }
2783

2784
  SRpcMsg rpcMsg = {0};
1,361✔
2785
  int32_t code =
2786
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
1,361✔
2787

2788
  if (code != 0) {
1,361!
2789
    sError("failed to build elect msg");
×
2790
    syncNodeRelease(pNode);
×
2791
    return;
×
2792
  }
2793

2794
  SyncTimeout* pTimeout = rpcMsg.pCont;
1,361✔
2795
  sNTrace(pNode, "enqueue elect msg lc:%" PRId64, pTimeout->logicClock);
1,361!
2796

2797
  code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
1,361✔
2798
  if (code != 0) {
1,361!
2799
    sError("failed to sync enqueue elect msg since %s", terrstr());
×
2800
    rpcFreeCont(rpcMsg.pCont);
×
2801
    syncNodeRelease(pNode);
×
2802
    return;
×
2803
  }
2804

2805
  syncNodeRelease(pNode);
1,361✔
2806
}
2807

2808
#ifdef BUILD_NO_CALL
2809
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
2810
  if (!syncIsInit()) return;
2811

2812
  int64_t    rid = (int64_t)param;
2813
  SSyncNode* pNode = syncNodeAcquire(rid);
2814

2815
  if (pNode == NULL) return;
2816

2817
  if (pNode->totalReplicaNum > 1) {
2818
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
2819
      SRpcMsg rpcMsg = {0};
2820
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
2821
                                      pNode->heartbeatTimerMS, pNode);
2822

2823
      if (code != 0) {
2824
        sError("failed to build heartbeat msg");
2825
        goto _out;
2826
      }
2827

2828
      sTrace("vgId:%d, enqueue heartbeat timer", pNode->vgId);
2829
      code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
2830
      if (code != 0) {
2831
        sError("failed to enqueue heartbeat msg since %s", terrstr());
2832
        rpcFreeCont(rpcMsg.pCont);
2833
        goto _out;
2834
      }
2835

2836
    _out:
2837
      if (taosTmrReset(syncNodeEqHeartbeatTimer, pNode->heartbeatTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
2838
                       &pNode->pHeartbeatTimer) != 0)
2839
        return;
2840

2841
    } else {
2842
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
2843
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
2844
    }
2845
  }
2846
}
2847
#endif
2848

2849
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
69,778✔
2850
  if (tsSyncLogHeartbeat) {
69,778!
2851
    sInfo("heartbeat timer start");
×
2852
  }
2853
  int32_t code = 0;
69,778✔
2854
  int64_t hbDataRid = (int64_t)param;
69,778✔
2855
  int64_t tsNow = taosGetTimestampMs();
69,778✔
2856

2857
  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
69,778✔
2858
  if (pData == NULL) {
69,778!
2859
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
×
2860
    return;
×
2861
  }
2862

2863
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
69,778✔
2864
  if (pSyncNode == NULL) {
69,778!
2865
    syncHbTimerDataRelease(pData);
×
2866
    sError("hb timer get pSyncNode NULL");
×
2867
    return;
×
2868
  }
2869

2870
  SSyncTimer* pSyncTimer = pData->pTimer;
69,778✔
2871

2872
  if (!pSyncNode->isStart) {
69,778!
2873
    syncNodeRelease(pSyncNode);
×
2874
    syncHbTimerDataRelease(pData);
×
2875
    sError("vgId:%d, hb timer sync node already stop", pSyncNode->vgId);
×
2876
    return;
×
2877
  }
2878

2879
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
69,778!
2880
    syncNodeRelease(pSyncNode);
×
2881
    syncHbTimerDataRelease(pData);
×
2882
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
×
2883
    return;
×
2884
  }
2885

2886
  if (tsSyncLogHeartbeat) {
69,778!
2887
    sInfo("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
×
2888
          pData->destId.addr);
2889
  } else {
2890
    sTrace("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
69,778!
2891
           pData->destId.addr);
2892
  }
2893

2894
  if (pSyncNode->totalReplicaNum > 1) {
69,778✔
2895
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
69,776✔
2896
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
69,776✔
2897

2898
    if (timerLogicClock == msgLogicClock) {
69,776✔
2899
      if (tsNow > pData->execTime) {
69,774✔
2900
        pData->execTime += pSyncTimer->timerMS;
69,761✔
2901

2902
        SRpcMsg rpcMsg = {0};
69,761✔
2903
        if ((code = syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId)) != 0) {
69,761!
2904
          sError("vgId:%d, failed to build heartbeat msg since %s", pSyncNode->vgId, tstrerror(code));
×
2905
          syncNodeRelease(pSyncNode);
×
2906
          syncHbTimerDataRelease(pData);
×
2907
          return;
×
2908
        }
2909

2910
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);
69,761✔
2911

2912
        SyncHeartbeat* pSyncMsg = rpcMsg.pCont;
69,761✔
2913
        pSyncMsg->srcId = pSyncNode->myRaftId;
69,761✔
2914
        pSyncMsg->destId = pData->destId;
69,761✔
2915
        pSyncMsg->term = raftStoreGetTerm(pSyncNode);
69,761✔
2916
        pSyncMsg->commitIndex = pSyncNode->commitIndex;
69,761✔
2917
        pSyncMsg->minMatchIndex = pSyncNode->minMatchIndex;
69,761✔
2918
        pSyncMsg->privateTerm = 0;
69,761✔
2919
        pSyncMsg->timeStamp = tsNow;
69,761✔
2920

2921
        // update reset time
2922
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
69,761✔
2923
        pSyncTimer->timeStamp = tsNow;
69,761✔
2924

2925
        // send msg
2926
        TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
69,761✔
2927
        TRACE_SET_ROOTID(&(rpcMsg.info.traceId), tGenIdPI64());
69,761✔
2928
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime, &(rpcMsg.info.traceId));
69,761✔
2929
        int ret = syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
69,761✔
2930
        if (ret != 0) {
69,761✔
2931
          sError("vgId:%d, failed to send heartbeat since %s", pSyncNode->vgId, tstrerror(ret));
167!
2932
        }
2933
      }
2934

2935
      if (syncIsInit()) {
69,774!
2936
        if (tsSyncLogHeartbeat) {
69,774!
2937
          sInfo("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
×
2938
        } else {
2939
          sTrace("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
69,774!
2940
        }
2941
        bool stopped = taosTmrResetPriority(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS, (void*)hbDataRid,
69,774✔
2942
                                            syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
69,774✔
2943
        if (stopped) sError("vgId:%d, reset peer hb timer error, %s", pSyncNode->vgId, tstrerror(code));
69,774!
2944

2945
      } else {
2946
        sError("sync env is stop, reset peer hb timer error");
×
2947
      }
2948

2949
    } else {
2950
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64, pSyncNode->vgId,
2!
2951
             timerLogicClock, msgLogicClock);
2952
    }
2953

2954
    if (tsSyncLogHeartbeat) {
69,776!
2955
      sInfo("vgId:%d, finish send sync-heartbeat", pSyncNode->vgId);
×
2956
    }
2957
  }
2958

2959
  syncHbTimerDataRelease(pData);
69,778✔
2960
  syncNodeRelease(pSyncNode);
69,778✔
2961
  if (tsSyncLogHeartbeat) {
69,778!
2962
    sInfo("heartbeat timer stop");
×
2963
  }
2964
}
2965

2966
#ifdef BUILD_NO_CALL
2967
static void deleteCacheEntry(const void* key, size_t keyLen, void* value, void* ud) {
2968
  (void)ud;
2969
  taosMemoryFree(value);
2970
}
2971

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

2976
  int32_t   code = 0;
2977
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2978
  LRUStatus status = taosLRUCacheInsert(pLogStore->pCache, &pEntry->index, sizeof(pEntry->index), pEntry, entryLen,
2979
                                        deleteCacheEntry, h, TAOS_LRU_PRIORITY_LOW, NULL);
2980
  if (status != TAOS_LRU_STATUS_OK) {
2981
    code = -1;
2982
  }
2983

2984
  return code;
2985
}
2986
#endif
2987

2988
void syncBuildConfigFromReq(SAlterVnodeReplicaReq* pReq, SSyncCfg* cfg) {  // TODO SAlterVnodeReplicaReq name is proper?
×
2989
  cfg->replicaNum = 0;
×
2990
  cfg->totalReplicaNum = 0;
×
2991
  int32_t code = 0;
×
2992

2993
  for (int i = 0; i < pReq->replica; ++i) {
×
2994
    SNodeInfo* pNode = &cfg->nodeInfo[i];
×
2995
    pNode->nodeId = pReq->replicas[i].id;
×
2996
    pNode->nodePort = pReq->replicas[i].port;
×
2997
    tstrncpy(pNode->nodeFqdn, pReq->replicas[i].fqdn, sizeof(pNode->nodeFqdn));
×
2998
    pNode->nodeRole = TAOS_SYNC_ROLE_VOTER;
×
2999
    bool update = tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort);
×
3000
    sInfo("vgId:%d, replica:%d ep:%s:%u dnode:%d nodeRole:%d, update:%d", pReq->vgId, i, pNode->nodeFqdn,
×
3001
          pNode->nodePort, pNode->nodeId, pNode->nodeRole, update);
3002
    cfg->replicaNum++;
×
3003
  }
3004
  if (pReq->selfIndex != -1) {
×
3005
    cfg->myIndex = pReq->selfIndex;
×
3006
  }
3007
  for (int i = cfg->replicaNum; i < pReq->replica + pReq->learnerReplica; ++i) {
×
3008
    SNodeInfo* pNode = &cfg->nodeInfo[i];
×
3009
    pNode->nodeId = pReq->learnerReplicas[cfg->totalReplicaNum].id;
×
3010
    pNode->nodePort = pReq->learnerReplicas[cfg->totalReplicaNum].port;
×
3011
    pNode->nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
3012
    tstrncpy(pNode->nodeFqdn, pReq->learnerReplicas[cfg->totalReplicaNum].fqdn, sizeof(pNode->nodeFqdn));
×
3013
    bool update = tmsgUpdateDnodeInfo(&pNode->nodeId, &pNode->clusterId, pNode->nodeFqdn, &pNode->nodePort);
×
3014
    sInfo("vgId:%d, replica:%d ep:%s:%u dnode:%d nodeRole:%d, update:%d", pReq->vgId, i, pNode->nodeFqdn,
×
3015
          pNode->nodePort, pNode->nodeId, pNode->nodeRole, update);
3016
    cfg->totalReplicaNum++;
×
3017
  }
3018
  cfg->totalReplicaNum += pReq->replica;
×
3019
  if (pReq->learnerSelfIndex != -1) {
×
3020
    cfg->myIndex = pReq->replica + pReq->learnerSelfIndex;
×
3021
  }
3022
  cfg->changeVersion = pReq->changeVersion;
×
3023
}
×
3024

3025
int32_t syncNodeCheckChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry) {
×
3026
  int32_t code = 0;
×
3027
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3028
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3029
  }
3030

3031
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3032
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3033

3034
  SAlterVnodeTypeReq req = {0};
×
3035
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3036
    code = TSDB_CODE_INVALID_MSG;
×
3037
    TAOS_RETURN(code);
×
3038
  }
3039

3040
  SSyncCfg cfg = {0};
×
3041
  syncBuildConfigFromReq(&req, &cfg);
×
3042

3043
  if (cfg.totalReplicaNum >= 1 &&
×
3044
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
×
3045
    bool incfg = false;
×
3046
    for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3047
      if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3048
          ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3049
        incfg = true;
×
3050
        break;
×
3051
      }
3052
    }
3053

3054
    if (!incfg) {
×
3055
      SyncTerm currentTerm = raftStoreGetTerm(ths);
×
3056
      SRaftId  id = EMPTY_RAFT_ID;
×
3057
      syncNodeStepDown(ths, currentTerm, id, "changeConfig");
×
3058
      return 1;
×
3059
    }
3060
  }
3061
  return 0;
×
3062
}
3063

3064
void syncNodeLogConfigInfo(SSyncNode* ths, SSyncCfg* cfg, char* str) {
×
3065
  sInfo("vgId:%d, %s. SyncNode, replicaNum:%d, peersNum:%d, lastConfigIndex:%" PRId64
×
3066
        ", changeVersion:%d, "
3067
        "restoreFinish:%d",
3068
        ths->vgId, str, ths->replicaNum, ths->peersNum, ths->raftCfg.lastConfigIndex, ths->raftCfg.cfg.changeVersion,
3069
        ths->restoreFinish);
3070

3071
  sInfo("vgId:%d, %s, myNodeInfo, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3072
        ths->myNodeInfo.clusterId, ths->myNodeInfo.nodeId, ths->myNodeInfo.nodeFqdn, ths->myNodeInfo.nodePort,
3073
        ths->myNodeInfo.nodeRole);
3074

3075
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3076
    sInfo("vgId:%d, %s, peersNodeInfo%d, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3077
          i, ths->peersNodeInfo[i].clusterId, ths->peersNodeInfo[i].nodeId, ths->peersNodeInfo[i].nodeFqdn,
3078
          ths->peersNodeInfo[i].nodePort, ths->peersNodeInfo[i].nodeRole);
3079
  }
3080

3081
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3082
    char    buf[256];
3083
    int32_t len = 256;
×
3084
    int32_t n = 0;
×
3085
    n += tsnprintf(buf + n, len - n, "%s", "{");
×
3086
    for (int i = 0; i < ths->peersEpset->numOfEps; i++) {
×
3087
      n += tsnprintf(buf + n, len - n, "%s:%d%s", ths->peersEpset->eps[i].fqdn, ths->peersEpset->eps[i].port,
×
3088
                     (i + 1 < ths->peersEpset->numOfEps ? ", " : ""));
×
3089
    }
3090
    n += tsnprintf(buf + n, len - n, "%s", "}");
×
3091

3092
    sInfo("vgId:%d, %s, peersEpset%d, %s, inUse:%d", ths->vgId, str, i, buf, ths->peersEpset->inUse);
×
3093
  }
3094

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

3099
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3100
    sInfo("vgId:%d, %s, nodeInfo%d, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str, i,
×
3101
          ths->raftCfg.cfg.nodeInfo[i].clusterId, ths->raftCfg.cfg.nodeInfo[i].nodeId,
3102
          ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, ths->raftCfg.cfg.nodeInfo[i].nodePort,
3103
          ths->raftCfg.cfg.nodeInfo[i].nodeRole);
3104
  }
3105

3106
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3107
    sInfo("vgId:%d, %s, replicasId%d, addr:0x%" PRIx64, ths->vgId, str, i, ths->replicasId[i].addr);
×
3108
  }
3109
}
×
3110

3111
int32_t syncNodeRebuildPeerAndCfg(SSyncNode* ths, SSyncCfg* cfg) {
×
3112
  int32_t i = 0;
×
3113

3114
  // change peersNodeInfo
3115
  i = 0;
×
3116
  for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3117
    if (!(strcmp(ths->myNodeInfo.nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3118
          ths->myNodeInfo.nodePort == cfg->nodeInfo[j].nodePort)) {
×
3119
      ths->peersNodeInfo[i].nodeRole = cfg->nodeInfo[j].nodeRole;
×
3120
      ths->peersNodeInfo[i].clusterId = cfg->nodeInfo[j].clusterId;
×
3121
      tstrncpy(ths->peersNodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn, TSDB_FQDN_LEN);
×
3122
      ths->peersNodeInfo[i].nodeId = cfg->nodeInfo[j].nodeId;
×
3123
      ths->peersNodeInfo[i].nodePort = cfg->nodeInfo[j].nodePort;
×
3124

3125
      syncUtilNodeInfo2EpSet(&ths->peersNodeInfo[i], &ths->peersEpset[i]);
×
3126

3127
      if (syncUtilNodeInfo2RaftId(&ths->peersNodeInfo[i], ths->vgId, &ths->peersId[i]) == false) {
×
3128
        sError("vgId:%d, failed to determine raft member id, peer:%d", ths->vgId, i);
×
3129
        return terrno;
×
3130
      }
3131

3132
      i++;
×
3133
    }
3134
  }
3135
  ths->peersNum = i;
×
3136

3137
  // change cfg nodeInfo
3138
  ths->raftCfg.cfg.replicaNum = 0;
×
3139
  i = 0;
×
3140
  for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3141
    if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3142
      ths->raftCfg.cfg.replicaNum++;
×
3143
    }
3144
    ths->raftCfg.cfg.nodeInfo[i].nodeRole = cfg->nodeInfo[j].nodeRole;
×
3145
    ths->raftCfg.cfg.nodeInfo[i].clusterId = cfg->nodeInfo[j].clusterId;
×
3146
    tstrncpy(ths->raftCfg.cfg.nodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn, TSDB_FQDN_LEN);
×
3147
    ths->raftCfg.cfg.nodeInfo[i].nodeId = cfg->nodeInfo[j].nodeId;
×
3148
    ths->raftCfg.cfg.nodeInfo[i].nodePort = cfg->nodeInfo[j].nodePort;
×
3149
    if ((strcmp(ths->myNodeInfo.nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3150
         ths->myNodeInfo.nodePort == cfg->nodeInfo[j].nodePort)) {
×
3151
      ths->raftCfg.cfg.myIndex = i;
×
3152
    }
3153
    i++;
×
3154
  }
3155
  ths->raftCfg.cfg.totalReplicaNum = i;
×
3156

3157
  return 0;
×
3158
}
3159

3160
void syncNodeChangePeerAndCfgToVoter(SSyncNode* ths, SSyncCfg* cfg) {
×
3161
  // change peersNodeInfo
3162
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3163
    for (int32_t j = 0; j < cfg->totalReplicaNum; ++j) {
×
3164
      if (strcmp(ths->peersNodeInfo[i].nodeFqdn, cfg->nodeInfo[j].nodeFqdn) == 0 &&
×
3165
          ths->peersNodeInfo[i].nodePort == cfg->nodeInfo[j].nodePort) {
×
3166
        if (cfg->nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3167
          ths->peersNodeInfo[i].nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3168
        }
3169
      }
3170
    }
3171
  }
3172

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

3188
int32_t syncNodeRebuildAndCopyIfExist(SSyncNode* ths, int32_t oldtotalReplicaNum) {
×
3189
  int32_t code = 0;
×
3190
  // 1.rebuild replicasId, remove deleted one
3191
  SRaftId oldReplicasId[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
3192
  memcpy(oldReplicasId, ths->replicasId, sizeof(oldReplicasId));
×
3193

3194
  ths->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3195
  ths->totalReplicaNum = ths->raftCfg.cfg.totalReplicaNum;
×
3196
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3197
    if (syncUtilNodeInfo2RaftId(&ths->raftCfg.cfg.nodeInfo[i], ths->vgId, &ths->replicasId[i]) == false) return terrno;
×
3198
  }
3199

3200
  // 2.rebuild MatchIndex, remove deleted one
3201
  SSyncIndexMgr* oldIndex = ths->pMatchIndex;
×
3202

3203
  ths->pMatchIndex = syncIndexMgrCreate(ths);
×
3204
  if (ths->pMatchIndex == NULL) {
×
3205
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3206
    if (terrno != 0) code = terrno;
×
3207
    TAOS_RETURN(code);
×
3208
  }
3209

3210
  syncIndexMgrCopyIfExist(ths->pMatchIndex, oldIndex, oldReplicasId);
×
3211

3212
  syncIndexMgrDestroy(oldIndex);
×
3213

3214
  // 3.rebuild NextIndex, remove deleted one
3215
  SSyncIndexMgr* oldNextIndex = ths->pNextIndex;
×
3216

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

3224
  syncIndexMgrCopyIfExist(ths->pNextIndex, oldNextIndex, oldReplicasId);
×
3225

3226
  syncIndexMgrDestroy(oldNextIndex);
×
3227

3228
  // 4.rebuild pVotesGranted, pVotesRespond, no need to keep old vote state, only rebuild
3229
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3230
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3231

3232
  // 5.rebuild logReplMgr
3233
  for (int i = 0; i < oldtotalReplicaNum; ++i) {
×
3234
    sDebug("vgId:%d, old logReplMgrs i:%d, peerId:%d, restoreed:%d, [%" PRId64 " %" PRId64 ", %" PRId64 ")", ths->vgId,
×
3235
           i, ths->logReplMgrs[i]->peerId, ths->logReplMgrs[i]->restored, ths->logReplMgrs[i]->startIndex,
3236
           ths->logReplMgrs[i]->matchIndex, ths->logReplMgrs[i]->endIndex);
3237
  }
3238

3239
  SSyncLogReplMgr* oldLogReplMgrs = NULL;
×
3240
  int64_t          length = sizeof(SSyncLogReplMgr) * (TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA);
×
3241
  oldLogReplMgrs = taosMemoryMalloc(length);
×
3242
  if (NULL == oldLogReplMgrs) return terrno;
×
3243
  memset(oldLogReplMgrs, 0, length);
×
3244

3245
  for (int i = 0; i < oldtotalReplicaNum; i++) {
×
3246
    oldLogReplMgrs[i] = *(ths->logReplMgrs[i]);
×
3247
  }
3248

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

3255
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3256
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3257
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3258
        *(ths->logReplMgrs[i]) = oldLogReplMgrs[j];
×
3259
        ths->logReplMgrs[i]->peerId = i;
×
3260
      }
3261
    }
3262
  }
3263

3264
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3265
    sDebug("vgId:%d, new logReplMgrs i:%d, peerId:%d, restoreed:%d, [%" PRId64 " %" PRId64 ", %" PRId64 ")", ths->vgId,
×
3266
           i, ths->logReplMgrs[i]->peerId, ths->logReplMgrs[i]->restored, ths->logReplMgrs[i]->startIndex,
3267
           ths->logReplMgrs[i]->matchIndex, ths->logReplMgrs[i]->endIndex);
3268
  }
3269

3270
  // 6.rebuild sender
3271
  for (int i = 0; i < oldtotalReplicaNum; ++i) {
×
3272
    sDebug("vgId:%d, old sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3273
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3274
  }
3275

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

3280
      if (snapshotSenderIsStart(ths->senders[i])) {
×
3281
        snapshotSenderStop(ths->senders[i], false);
×
3282
      }
3283

3284
      snapshotSenderDestroy(ths->senders[i]);
×
3285
      ths->senders[i] = NULL;
×
3286
    }
3287
  }
3288

3289
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3290
    SSyncSnapshotSender* pSender = NULL;
×
3291
    int32_t              code = snapshotSenderCreate(ths, i, &pSender);
×
3292
    if (pSender == NULL) return terrno = code;
×
3293

3294
    ths->senders[i] = pSender;
×
3295
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
×
3296
  }
3297

3298
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3299
    sDebug("vgId:%d, new sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3300
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3301
  }
3302

3303
  // 7.rebuild synctimer
3304
  if ((code = syncNodeStopHeartbeatTimer(ths)) != 0) {
×
3305
    taosMemoryFree(oldLogReplMgrs);
×
3306
    TAOS_RETURN(code);
×
3307
  }
3308

3309
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3310
    if ((code = syncHbTimerInit(ths, &ths->peerHeartbeatTimerArr[i], ths->replicasId[i])) != 0) {
×
3311
      taosMemoryFree(oldLogReplMgrs);
×
3312
      TAOS_RETURN(code);
×
3313
    }
3314
  }
3315

3316
  if ((code = syncNodeStartHeartbeatTimer(ths)) != 0) {
×
3317
    taosMemoryFree(oldLogReplMgrs);
×
3318
    TAOS_RETURN(code);
×
3319
  }
3320

3321
  // 8.rebuild peerStates
3322
  SPeerState oldState[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA] = {0};
×
3323
  for (int i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; i++) {
×
3324
    oldState[i] = ths->peerStates[i];
×
3325
  }
3326

3327
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3328
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3329
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3330
        ths->peerStates[i] = oldState[j];
×
3331
      }
3332
    }
3333
  }
3334

3335
  taosMemoryFree(oldLogReplMgrs);
×
3336

3337
  return 0;
×
3338
}
3339

3340
void syncNodeChangeToVoter(SSyncNode* ths) {
×
3341
  // replicasId, only need to change replicaNum when 1->3
3342
  ths->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3343
  sDebug("vgId:%d, totalReplicaNum:%d", ths->vgId, ths->totalReplicaNum);
×
3344
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
×
3345
    sDebug("vgId:%d, i:%d, replicaId.addr:0x%" PRIx64, ths->vgId, i, ths->replicasId[i].addr);
×
3346
  }
3347

3348
  // pMatchIndex, pNextIndex, only need to change replicaNum when 1->3
3349
  ths->pMatchIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3350
  ths->pNextIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3351

3352
  sDebug("vgId:%d, pMatchIndex->totalReplicaNum:%d", ths->vgId, ths->pMatchIndex->totalReplicaNum);
×
3353
  for (int32_t i = 0; i < ths->pMatchIndex->totalReplicaNum; ++i) {
×
3354
    sDebug("vgId:%d, i:%d, match.index:%" PRId64, ths->vgId, i, ths->pMatchIndex->index[i]);
×
3355
  }
3356

3357
  // pVotesGranted, pVotesRespond
3358
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3359
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3360

3361
  // logRepMgrs
3362
  // no need to change logRepMgrs when 1->3
3363
}
×
3364

3365
void syncNodeResetPeerAndCfg(SSyncNode* ths) {
×
3366
  SNodeInfo node = {0};
×
3367
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3368
    memcpy(&ths->peersNodeInfo[i], &node, sizeof(SNodeInfo));
×
3369
  }
3370

3371
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3372
    memcpy(&ths->raftCfg.cfg.nodeInfo[i], &node, sizeof(SNodeInfo));
×
3373
  }
3374
}
×
3375

3376
int32_t syncNodeChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry, char* str) {
×
3377
  int32_t code = 0;
×
3378
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3379
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3380
  }
3381

3382
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3383
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3384

3385
  SAlterVnodeTypeReq req = {0};
×
3386
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3387
    code = TSDB_CODE_INVALID_MSG;
×
3388
    TAOS_RETURN(code);
×
3389
  }
3390

3391
  SSyncCfg cfg = {0};
×
3392
  syncBuildConfigFromReq(&req, &cfg);
×
3393

3394
  if (cfg.changeVersion <= ths->raftCfg.cfg.changeVersion) {
×
3395
    sInfo(
×
3396
        "vgId:%d, skip conf change entry since lower version. "
3397
        "this entry, index:%" PRId64 ", term:%" PRId64
3398
        ", totalReplicaNum:%d, changeVersion:%d; "
3399
        "current node, replicaNum:%d, peersNum:%d, lastConfigIndex:%" PRId64 ", changeVersion:%d",
3400
        ths->vgId, pEntry->index, pEntry->term, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum, ths->peersNum,
3401
        ths->raftCfg.lastConfigIndex, ths->raftCfg.cfg.changeVersion);
3402
    return 0;
×
3403
  }
3404

3405
  if (strcmp(str, "Commit") == 0) {
×
3406
    sInfo(
×
3407
        "vgId:%d, change config from %s. "
3408
        "this, i:%" PRId64
3409
        ", trNum:%d, vers:%d; "
3410
        "node, rNum:%d, pNum:%d, trNum:%d, "
3411
        "buffer: [%" PRId64 " %" PRId64 " %" PRId64 ", %" PRId64
3412
        "), "
3413
        "cond:(next i:%" PRId64 ", t:%" PRId64 " ==%s)",
3414
        ths->vgId, str, pEntry->index - 1, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum, ths->peersNum,
3415
        ths->totalReplicaNum, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex, ths->pLogBuf->matchIndex,
3416
        ths->pLogBuf->endIndex, pEntry->index, pEntry->term, TMSG_INFO(pEntry->originalRpcType));
3417
  } else {
3418
    sInfo(
×
3419
        "vgId:%d, change config from %s. "
3420
        "this, i:%" PRId64 ", t:%" PRId64
3421
        ", trNum:%d, vers:%d; "
3422
        "node, rNum:%d, pNum:%d, trNum:%d, "
3423
        "buffer: [%" PRId64 " %" PRId64 " %" PRId64 ", %" PRId64
3424
        "), "
3425
        "cond:(pre i:%" PRId64 "==ci:%" PRId64 ", bci:%" PRId64 ")",
3426
        ths->vgId, str, pEntry->index, pEntry->term, cfg.totalReplicaNum, cfg.changeVersion, ths->replicaNum,
3427
        ths->peersNum, ths->totalReplicaNum, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3428
        ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex, pEntry->index - 1, ths->commitIndex,
3429
        ths->pLogBuf->commitIndex);
3430
  }
3431

3432
  syncNodeLogConfigInfo(ths, &cfg, "before config change");
×
3433

3434
  int32_t oldTotalReplicaNum = ths->totalReplicaNum;
×
3435

3436
  if (cfg.totalReplicaNum == 1 || cfg.totalReplicaNum == 2) {  // remove replica
×
3437

3438
    bool incfg = false;
×
3439
    for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3440
      if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3441
          ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3442
        incfg = true;
×
3443
        break;
×
3444
      }
3445
    }
3446

3447
    if (incfg) {  // remove other
×
3448
      syncNodeResetPeerAndCfg(ths);
×
3449

3450
      // no need to change myNodeInfo
3451

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

3456
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3457
        TAOS_RETURN(code);
×
3458
      };
3459
    } else {  // remove myself
3460
      // no need to do anything actually, to change the following to reduce distruptive server chance
3461

3462
      syncNodeResetPeerAndCfg(ths);
×
3463

3464
      // change myNodeInfo
3465
      ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
3466

3467
      // change peer and cfg
3468
      ths->peersNum = 0;
×
3469
      memcpy(&ths->raftCfg.cfg.nodeInfo[0], &ths->myNodeInfo, sizeof(SNodeInfo));
×
3470
      ths->raftCfg.cfg.replicaNum = 0;
×
3471
      ths->raftCfg.cfg.totalReplicaNum = 1;
×
3472

3473
      // change other
3474
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3475
        TAOS_RETURN(code);
×
3476
      }
3477

3478
      // change state
3479
      ths->state = TAOS_SYNC_STATE_LEARNER;
×
3480
    }
3481

3482
    ths->restoreFinish = false;
×
3483
  } else {                            // add replica, or change replica type
3484
    if (ths->totalReplicaNum == 3) {  // change replica type
×
3485
      sInfo("vgId:%d, begin change replica type", ths->vgId);
×
3486

3487
      // change myNodeInfo
3488
      for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3489
        if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3490
            ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3491
          if (cfg.nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3492
            ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3493
          }
3494
        }
3495
      }
3496

3497
      // change peer and cfg
3498
      syncNodeChangePeerAndCfgToVoter(ths, &cfg);
×
3499

3500
      // change other
3501
      syncNodeChangeToVoter(ths);
×
3502

3503
      // change state
3504
      if (ths->state == TAOS_SYNC_STATE_LEARNER) {
×
3505
        if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3506
          ths->state = TAOS_SYNC_STATE_FOLLOWER;
×
3507
        }
3508
      }
3509

3510
      ths->restoreFinish = false;
×
3511
    } else {  // add replica
3512
      sInfo("vgId:%d, begin add replica", ths->vgId);
×
3513

3514
      // no need to change myNodeInfo
3515

3516
      // change peer and cfg
3517
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3518
        TAOS_RETURN(code);
×
3519
      };
3520

3521
      // change other
3522
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3523
        TAOS_RETURN(code);
×
3524
      };
3525

3526
      // no need to change state
3527

3528
      if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
3529
        ths->restoreFinish = false;
×
3530
      }
3531
    }
3532
  }
3533

3534
  ths->quorum = syncUtilQuorum(ths->replicaNum);
×
3535

3536
  ths->raftCfg.lastConfigIndex = pEntry->index;
×
3537
  ths->raftCfg.cfg.lastIndex = pEntry->index;
×
3538
  ths->raftCfg.cfg.changeVersion = cfg.changeVersion;
×
3539

3540
  syncNodeLogConfigInfo(ths, &cfg, "after config change");
×
3541

3542
  if ((code = syncWriteCfgFile(ths)) != 0) {
×
3543
    sError("vgId:%d, failed to create sync cfg file", ths->vgId);
×
3544
    TAOS_RETURN(code);
×
3545
  };
3546

3547
  TAOS_RETURN(code);
×
3548
}
3549

3550
int32_t syncNodeAppend(SSyncNode* ths, SSyncRaftEntry* pEntry, SRpcMsg* pMsg) {
1,950,894✔
3551
  int32_t code = -1;
1,950,894✔
3552
  if (pEntry->dataLen < sizeof(SMsgHead)) {
1,950,894!
3553
    code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
3554
    sError("vgId:%d, msg:%p, cannot append an invalid client request with no msg head, type:%s dataLen:%d", ths->vgId,
×
3555
           pMsg, TMSG_INFO(pEntry->originalRpcType), pEntry->dataLen);
3556
    syncEntryDestroy(pEntry);
×
3557
    pEntry = NULL;
×
3558
    goto _out;
×
3559
  }
3560

3561
  // append to log buffer
3562
  if ((code = syncLogBufferAppend(ths->pLogBuf, ths, pEntry)) < 0) {
1,950,894✔
3563
    sError("vgId:%d, index:%" PRId64 ", failed to enqueue sync log buffer", ths->vgId, pEntry->index);
17!
3564
    int32_t ret = 0;
17✔
3565
    if ((ret = syncFsmExecute(ths, ths->pFsm, ths->state, raftStoreGetTerm(ths), pEntry, terrno, false)) != 0) {
17!
3566
      sError("vgId:%d, index:%" PRId64 ", failed to execute fsm since %s", ths->vgId, pEntry->index, tstrerror(ret));
×
3567
    }
3568
    syncEntryDestroy(pEntry);
×
3569
    pEntry = NULL;
×
3570
    goto _out;
×
3571
  }
3572

3573
  code = 0;
1,950,884✔
3574
_out:;
1,950,884✔
3575
  // proceed match index, with replicating on needed
3576
  SyncIndex       matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL, "Append", pMsg);
1,950,884✔
3577
  const STraceId* trace = pEntry ? &pEntry->originRpcTraceId : NULL;
1,950,845!
3578

3579
  if (pEntry != NULL) {
1,950,845!
3580
    sGDebug(trace,
1,950,883!
3581
            "vgId:%d, index:%" PRId64 ", raft entry appended, msg:%p term:%" PRId64 " buf:[%" PRId64 " %" PRId64
3582
            " %" PRId64 ", %" PRId64 ")",
3583
            ths->vgId, pEntry->index, pMsg, pEntry->term, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3584
            ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex);
3585
  }
3586

3587
  if (code == 0 && ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
1,950,845!
3588
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
5✔
3589
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
5!
3590

3591
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
×
3592
        syncLogBufferCommit(ths->pLogBuf, ths, ths->assignedCommitIndex, trace, "append-entry") < 0) {
5✔
3593
      sGError(trace, "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64, ths->vgId, index,
×
3594
              pMsg, ths->commitIndex);
3595
      code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
3596
    }
3597
  }
3598

3599
  // multi replica
3600
  if (ths->replicaNum > 1) {
1,950,823✔
3601
    TAOS_RETURN(code);
99,272✔
3602
  }
3603

3604
  // single replica
3605
  SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, matchIndex);
1,851,551✔
3606
  sGTrace(trace, "vgId:%d, index:%" PRId64 ", raft entry update commit, msg:%p return index:%" PRId64, ths->vgId,
1,851,552!
3607
          matchIndex, pMsg, returnIndex);
3608

3609
  if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
3,703,154!
3610
      (code = syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, trace, "append-entry")) < 0) {
1,851,521✔
3611
    sGError(trace,
×
3612
            "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64 " return index:%" PRId64,
3613
            ths->vgId, matchIndex, pMsg, ths->commitIndex, returnIndex);
3614
  }
3615

3616
  TAOS_RETURN(code);
1,851,633✔
3617
}
3618

3619
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
1,940,605✔
3620
  if (pSyncNode->totalReplicaNum == 1) {
1,940,605✔
3621
    return false;
1,839,699✔
3622
  }
3623

3624
  int32_t toCount = 0;
100,906✔
3625
  int64_t tsNow = taosGetTimestampMs();
100,912✔
3626
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
300,989✔
3627
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
200,076✔
3628
      continue;
1,573✔
3629
    }
3630
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
198,503✔
3631
    if (recvTime == 0 || recvTime == -1) {
198,504!
3632
      continue;
×
3633
    }
3634

3635
    if (tsNow - recvTime > tsHeartbeatTimeout) {
198,504✔
3636
      toCount++;
567✔
3637
    }
3638
  }
3639

3640
  bool b = (toCount >= pSyncNode->quorum ? true : false);
100,913✔
3641

3642
  return b;
100,913✔
3643
}
3644

3645
bool syncNodeSnapshotSending(SSyncNode* pSyncNode) {
×
3646
  if (pSyncNode == NULL) return false;
×
3647
  bool b = false;
×
3648
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
×
3649
    if (pSyncNode->senders[i] != NULL && pSyncNode->senders[i]->start) {
×
3650
      b = true;
×
3651
      break;
×
3652
    }
3653
  }
3654
  return b;
×
3655
}
3656

3657
bool syncNodeSnapshotRecving(SSyncNode* pSyncNode) {
×
3658
  if (pSyncNode == NULL) return false;
×
3659
  if (pSyncNode->pNewNodeReceiver == NULL) return false;
×
3660
  if (pSyncNode->pNewNodeReceiver->start) return true;
×
3661
  return false;
×
3662
}
3663

3664
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
11,849✔
3665
  int32_t   code = 0;
11,849✔
3666
  SyncIndex index = syncLogBufferGetEndIndex(ths->pLogBuf);
11,849✔
3667
  SyncTerm  term = raftStoreGetTerm(ths);
11,849✔
3668

3669
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
11,849✔
3670
  if (pEntry == NULL) {
11,849!
3671
    code = TSDB_CODE_OUT_OF_MEMORY;
×
3672
    TAOS_RETURN(code);
×
3673
  }
3674

3675
  code = syncNodeAppend(ths, pEntry, NULL);
11,849✔
3676
  TAOS_RETURN(code);
11,849✔
3677
}
3678

3679
#ifdef BUILD_NO_CALL
3680
static int32_t syncNodeAppendNoopOld(SSyncNode* ths) {
3681
  int32_t ret = 0;
3682

3683
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
3684
  SyncTerm        term = raftStoreGetTerm(ths);
3685
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
3686
  if (pEntry == NULL) return -1;
3687

3688
  LRUHandle* h = NULL;
3689

3690
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
3691
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry, false);
3692
    if (code != 0) {
3693
      sError("append noop error");
3694
      return -1;
3695
    }
3696

3697
    syncCacheEntry(ths->pLogStore, pEntry, &h);
3698
  }
3699

3700
  if (h) {
3701
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
3702
  } else {
3703
    syncEntryDestroy(pEntry);
3704
  }
3705

3706
  return ret;
3707
}
3708
#endif
3709

3710
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
68,280✔
3711
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
68,280✔
3712
  bool           resetElect = false;
68,280✔
3713

3714
  int64_t tsMs = taosGetTimestampMs();
68,280✔
3715

3716
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pNextIndex, &(pMsg->srcId));
68,280✔
3717
  syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);
68,280✔
3718
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
68,280✔
3719

3720
  int64_t netElapsed = tsMs - pMsg->timeStamp;
68,280✔
3721
  int64_t timeDiff = tsMs - lastRecvTime;
68,280✔
3722
  syncLogRecvHeartbeat(ths, pMsg, netElapsed, &pRpcMsg->info.traceId, timeDiff, pRpcMsg);
68,280✔
3723

3724
  if (!syncNodeInRaftGroup(ths, &pMsg->srcId)) {
68,280!
3725
    sWarn(
×
3726
        "vgId:%d, drop heartbeat msg from dnode:%d, because it come from another cluster:%d, differ from current "
3727
        "cluster:%d",
3728
        ths->vgId, DID(&(pMsg->srcId)), CID(&(pMsg->srcId)), CID(&(ths->myRaftId)));
3729
    return 0;
×
3730
  }
3731

3732
  SyncTerm currentTerm = raftStoreGetTerm(ths);
68,280✔
3733

3734
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
68,280✔
3735
    raftStoreSetTerm(ths, pMsg->term);
279✔
3736
    currentTerm = pMsg->term;
279✔
3737
  }
3738

3739
  int64_t tsMs2 = taosGetTimestampMs();
68,280✔
3740

3741
  int64_t processTime = tsMs2 - tsMs;
68,280✔
3742
  if (processTime > SYNC_HEARTBEAT_SLOW_MS) {
68,280!
3743
    sGError(&pRpcMsg->info.traceId,
×
3744
            "vgId:%d, process sync-heartbeat msg from dnode:%d, commit-index:%" PRId64 ", cluster:%d msgTerm:%" PRId64
3745
            " currentTerm:%" PRId64 ", processTime:%" PRId64,
3746
            ths->vgId, DID(&(pMsg->srcId)), pMsg->commitIndex, CID(&(pMsg->srcId)), pMsg->term, currentTerm,
3747
            processTime);
3748
  } else {
3749
    sGDebug(&pRpcMsg->info.traceId,
68,280!
3750
            "vgId:%d, process sync-heartbeat msg from dnode:%d, commit-index:%" PRId64 ", cluster:%d msgTerm:%" PRId64
3751
            " currentTerm:%" PRId64 ", processTime:%" PRId64,
3752
            ths->vgId, DID(&(pMsg->srcId)), pMsg->commitIndex, CID(&(pMsg->srcId)), pMsg->term, currentTerm,
3753
            processTime);
3754
  }
3755

3756
  if (pMsg->term == currentTerm &&
68,280✔
3757
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
68,165!
3758
    resetElect = true;
68,165✔
3759

3760
    ths->minMatchIndex = pMsg->minMatchIndex;
68,165✔
3761

3762
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
68,165✔
3763
      SRpcMsg rpcMsgLocalCmd = {0};
68,160✔
3764
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
68,160!
3765
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
68,160✔
3766

3767
      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
68,160✔
3768
      pSyncMsg->cmd =
68,160✔
3769
          (ths->state == TAOS_SYNC_STATE_LEARNER) ? SYNC_LOCAL_CMD_LEARNER_CMT : SYNC_LOCAL_CMD_FOLLOWER_CMT;
68,160✔
3770
      pSyncMsg->commitIndex = pMsg->commitIndex;
68,160✔
3771
      pSyncMsg->currentTerm = pMsg->term;
68,160✔
3772

3773
      if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
68,160!
3774
        int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
68,160✔
3775
        if (code != 0) {
68,160!
3776
          sError("vgId:%d, failed to enqueue sync-local-cmd msg(cmd=commit) from heartbeat since %s",
×
3777
                 ths->vgId, tstrerror(code));
3778
          rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3779
        } else {
3780
          sGTrace(&pRpcMsg->info.traceId,
68,160!
3781
                  "vgId:%d, enqueue sync-local-cmd msg(cmd=commit) from heartbeat, commit-index:%" PRId64
3782
                  ", term:%" PRId64,
3783
                  ths->vgId, pMsg->commitIndex, pMsg->term);
3784
        }
3785
      }
3786
    }
3787
  }
3788

3789
  if (pMsg->term >= currentTerm &&
68,280✔
3790
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
68,277!
3791
    SRpcMsg rpcMsgLocalCmd = {0};
3✔
3792
    TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
3!
3793
    rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
3✔
3794

3795
    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
3✔
3796
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
3✔
3797
    pSyncMsg->currentTerm = pMsg->term;
3✔
3798
    pSyncMsg->commitIndex = pMsg->commitIndex;
3✔
3799

3800
    if (ths->syncEqMsg != NULL && ths->msgcb != NULL) {
3!
3801
      int32_t code = ths->syncEqMsg(ths->msgcb, &rpcMsgLocalCmd);
3✔
3802
      if (code != 0) {
3!
3803
        sError("vgId:%d, sync enqueue sync-local-cmd msg(cmd=step-down) error, code:%d", ths->vgId, code);
×
3804
        rpcFreeCont(rpcMsgLocalCmd.pCont);
×
3805
      } else {
3806
        sTrace("vgId:%d, sync enqueue sync-local-cmd msg(cmd=step-down), new-term:%" PRId64, ths->vgId, pMsg->term);
3!
3807
      }
3808
    }
3809
  }
3810

3811
  SRpcMsg rpcMsg = {0};
68,280✔
3812
  TAOS_CHECK_RETURN(syncBuildHeartbeatReply(&rpcMsg, ths->vgId));
68,280!
3813
  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
68,280✔
3814
  pMsgReply->destId = pMsg->srcId;
68,280✔
3815
  pMsgReply->srcId = ths->myRaftId;
68,280✔
3816
  pMsgReply->term = currentTerm;
68,280✔
3817
  pMsgReply->privateTerm = 8864;  // magic number
68,280✔
3818
  pMsgReply->startTime = ths->startTime;
68,280✔
3819
  pMsgReply->timeStamp = tsMs;
68,280✔
3820
  rpcMsg.info.traceId = pRpcMsg->info.traceId;
68,280✔
3821

3822
  // reply
3823
  int64_t tsMs3 = taosGetTimestampMs();
68,280✔
3824

3825
  int64_t processTime2 = tsMs3 - tsMs2;
68,280✔
3826
  TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
68,280✔
3827
  if (processTime2 > SYNC_HEARTBEAT_SLOW_MS) {
68,280!
3828
    sGError(&rpcMsg.info.traceId,
×
3829
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3830
            ", processTime:%" PRId64,
3831
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3832
  } else {
3833
    if(tsSyncLogHeartbeat){
68,280!
3834
      sGInfo(&rpcMsg.info.traceId,
×
3835
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3836
            ", processTime:%" PRId64,
3837
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3838
    }
3839
    else{
3840
      sGDebug(&rpcMsg.info.traceId,
68,280!
3841
            "vgId:%d, send sync-heartbeat-reply to dnode:%d term:%" PRId64 " timestamp:%" PRId64
3842
            ", processTime:%" PRId64,
3843
            ths->vgId, DID(&(pMsgReply->destId)), pMsgReply->term, pMsgReply->timeStamp, processTime2);
3844
    }
3845
  }
3846

3847
  TAOS_CHECK_RETURN(syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg));
68,280!
3848

3849
  if (resetElect) syncNodeResetElectTimer(ths);
68,280✔
3850
  return 0;
68,280✔
3851
}
3852

3853
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
67,721✔
3854
  int32_t code = 0;
67,721✔
3855

3856
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
67,721✔
3857
  SSyncLogReplMgr*    pMgr = syncNodeGetLogReplMgr(ths, &pMsg->srcId);
67,721✔
3858
  if (pMgr == NULL) {
67,721!
3859
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3860
    if (terrno != 0) code = terrno;
×
3861
    sError("vgId:%d, failed to get log repl mgr for the peer at addr 0x016%" PRIx64, ths->vgId, pMsg->srcId.addr);
×
3862
    TAOS_RETURN(code);
×
3863
  }
3864

3865
  int64_t tsMs = taosGetTimestampMs();
67,721✔
3866
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pMatchIndex, &pMsg->srcId);
67,721✔
3867
  syncLogRecvHeartbeatReply(ths, pMsg, tsMs - pMsg->timeStamp, &pRpcMsg->info.traceId, tsMs - lastRecvTime);
67,721✔
3868

3869
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
67,721✔
3870
  syncIndexMgrIncRecvCount(ths->pMatchIndex, &(pMsg->srcId));
67,721✔
3871

3872
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
67,720✔
3873
}
3874

3875
#ifdef BUILD_NO_CALL
3876
int32_t syncNodeOnHeartbeatReplyOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
3877
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
3878

3879
  int64_t tsMs = taosGetTimestampMs();
3880
  int64_t timeDiff = tsMs - pMsg->timeStamp;
3881
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff, &pRpcMsg->info.traceId, timeDiff);
3882

3883
  // update last reply time, make decision whether the other node is alive or not
3884
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
3885
  return 0;
3886
}
3887
#endif
3888

3889
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
68,163✔
3890
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
68,163✔
3891
  syncLogRecvLocalCmd(ths, pMsg, &pRpcMsg->info.traceId);
68,163✔
3892

3893
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
68,163✔
3894
    SRaftId id = EMPTY_RAFT_ID;
3✔
3895
    syncNodeStepDown(ths, pMsg->currentTerm, id, "localCmd");
3✔
3896

3897
  } else if (pMsg->cmd == SYNC_LOCAL_CMD_FOLLOWER_CMT || pMsg->cmd == SYNC_LOCAL_CMD_LEARNER_CMT) {
136,320!
3898
    if (syncLogBufferIsEmpty(ths->pLogBuf)) {
68,160!
3899
      sError("vgId:%d, sync log buffer is empty", ths->vgId);
×
3900
      return 0;
×
3901
    }
3902
    SyncTerm matchTerm = syncLogBufferGetLastMatchTerm(ths->pLogBuf);
68,160✔
3903
    if (matchTerm < 0) {
68,160!
3904
      return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3905
    }
3906
    if (pMsg->currentTerm == matchTerm) {
68,160✔
3907
      SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, pMsg->commitIndex);
64,288✔
3908
      sTrace("vgId:%d, raft entry update commit, return index:%" PRId64, ths->vgId, returnIndex);
64,288!
3909
    }
3910
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
136,320!
3911
        syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, &pRpcMsg->info.traceId, "heartbeat") < 0) {
68,160✔
3912
      sError("vgId:%d, failed to commit raft log since %s. commit index:%" PRId64, ths->vgId, terrstr(),
×
3913
             ths->commitIndex);
3914
    }
3915
  } else {
3916
    sError("error local cmd");
×
3917
  }
3918

3919
  return 0;
68,163✔
3920
}
3921

3922
// TLA+ Spec
3923
// ClientRequest(i, v) ==
3924
//     /\ state[i] = Leader
3925
//     /\ LET entry == [term  |-> currentTerm[i],
3926
//                      value |-> v]
3927
//            newLog == Append(log[i], entry)
3928
//        IN  log' = [log EXCEPT ![i] = newLog]
3929
//     /\ UNCHANGED <<messages, serverVars, candidateVars,
3930
//                    leaderVars, commitIndex>>
3931
//
3932

3933
int32_t syncNodeOnClientRequest(SSyncNode* ths, SRpcMsg* pMsg, SyncIndex* pRetIndex) {
1,939,054✔
3934
  sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, process client request", ths->vgId, pMsg);
1,939,054!
3935
  int32_t code = 0;
1,939,054✔
3936

3937
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
1,939,054✔
3938
  SyncTerm        term = raftStoreGetTerm(ths);
1,939,057✔
3939
  SSyncRaftEntry* pEntry = NULL;
1,939,063✔
3940
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
1,939,063✔
3941
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
188,687✔
3942
  } else {
3943
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
1,750,376✔
3944
  }
3945

3946
  if (pEntry == NULL) {
1,939,050!
3947
    sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to process client request since %s", ths->vgId, pMsg,
×
3948
            terrstr());
3949
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3950
  }
3951

3952
  // 1->2, config change is add in write thread, and will continue in sync thread
3953
  // need save message for it
3954
  if (pMsg->msgType == TDMT_SYNC_CONFIG_CHANGE) {
1,939,050!
3955
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
×
3956
    uint64_t  seqNum = syncRespMgrAdd(ths->pSyncRespMgr, &stub);
×
3957
    pEntry->seqNum = seqNum;
×
3958
  }
3959

3960
  if (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
1,939,050!
3961
    if (pRetIndex) {
1,939,050✔
3962
      (*pRetIndex) = index;
1,750,363✔
3963
    }
3964

3965
    if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE) {
1,939,050!
3966
      int32_t code = syncNodeCheckChangeConfig(ths, pEntry);
×
3967
      if (code < 0) {
×
3968
        sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to check change config since %s", ths->vgId, pMsg,
×
3969
                terrstr());
3970
        syncEntryDestroy(pEntry);
×
3971
        pEntry = NULL;
×
3972
        TAOS_RETURN(code);
×
3973
      }
3974

3975
      if (code > 0) {
×
3976
        SRpcMsg rsp = {.code = pMsg->code, .info = pMsg->info};
×
3977
        int32_t num = syncRespMgrGetAndDel(ths->pSyncRespMgr, pEntry->seqNum, &rsp.info);
×
3978
        sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, get response stub for config change, seqNum:%" PRIu64 " num:%d",
×
3979
                ths->vgId, pMsg, pEntry->seqNum, num);
3980
        if (rsp.info.handle != NULL) {
×
3981
          tmsgSendRsp(&rsp);
×
3982
        }
3983
        syncEntryDestroy(pEntry);
×
3984
        pEntry = NULL;
×
3985
        TAOS_RETURN(code);
×
3986
      }
3987
    }
3988

3989
    code = syncNodeAppend(ths, pEntry, pMsg);
1,939,050✔
3990
    return code;
1,938,946✔
3991
  } else {
3992
    syncEntryDestroy(pEntry);
×
3993
    pEntry = NULL;
×
3994
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3995
  }
3996
}
3997

3998
const char* syncStr(ESyncState state) {
707,536✔
3999
  switch (state) {
707,536!
4000
    case TAOS_SYNC_STATE_FOLLOWER:
380,230✔
4001
      return "follower";
380,230✔
4002
    case TAOS_SYNC_STATE_CANDIDATE:
2,609✔
4003
      return "candidate";
2,609✔
4004
    case TAOS_SYNC_STATE_LEADER:
289,662✔
4005
      return "leader";
289,662✔
4006
    case TAOS_SYNC_STATE_ERROR:
×
4007
      return "error";
×
4008
    case TAOS_SYNC_STATE_OFFLINE:
5,453✔
4009
      return "offline";
5,453✔
4010
    case TAOS_SYNC_STATE_LEARNER:
29,562✔
4011
      return "learner";
29,562✔
4012
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
19✔
4013
      return "assigned leader";
19✔
4014
    default:
1✔
4015
      return "unknown";
1✔
4016
  }
4017
}
4018

4019
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
1,797✔
4020
  for (int32_t i = 0; i < pNewCfg->totalReplicaNum; ++i) {
2,038!
4021
    SRaftId raftId = {
2,038✔
4022
        .addr = SYNC_ADDR(&pNewCfg->nodeInfo[i]),
2,038✔
4023
        .vgId = ths->vgId,
2,038✔
4024
    };
4025

4026
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
2,038✔
4027
      pNewCfg->myIndex = i;
1,797✔
4028
      return 0;
1,797✔
4029
    }
4030
  }
4031

4032
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4033
}
4034

4035
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
1,940,607✔
4036
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
1,940,607!
4037
}
4038

4039
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
557,521✔
4040
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
1,133,313!
4041
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
1,133,314✔
4042
      return true;
557,520✔
4043
    }
4044
  }
4045
  return false;
×
4046
}
4047

4048
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
43,536✔
4049
  SSyncSnapshotSender* pSender = NULL;
43,536✔
4050
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
174,234✔
4051
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
130,697✔
4052
      pSender = (ths->senders)[i];
43,537✔
4053
    }
4054
  }
4055
  return pSender;
43,537✔
4056
}
4057

4058
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
30,473✔
4059
  SSyncTimer* pTimer = NULL;
30,473✔
4060
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
126,999✔
4061
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
96,525✔
4062
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
30,472✔
4063
    }
4064
  }
4065
  return pTimer;
30,474✔
4066
}
4067

4068
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
3,398✔
4069
  SPeerState* pState = NULL;
3,398✔
4070
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
11,481✔
4071
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
8,083✔
4072
      pState = &((ths->peerStates)[i]);
3,398✔
4073
    }
4074
  }
4075
  return pState;
3,398✔
4076
}
4077

4078
#ifdef BUILD_NO_CALL
4079
bool syncNodeNeedSendAppendEntries(SSyncNode* ths, const SRaftId* pDestId, const SyncAppendEntries* pMsg) {
4080
  SPeerState* pState = syncNodeGetPeerState(ths, pDestId);
4081
  if (pState == NULL) {
4082
    sError("vgId:%d, replica maybe dropped", ths->vgId);
4083
    return false;
4084
  }
4085

4086
  SyncIndex sendIndex = pMsg->prevLogIndex + 1;
4087
  int64_t   tsNow = taosGetTimestampMs();
4088

4089
  if (pState->lastSendIndex == sendIndex && tsNow - pState->lastSendTime < SYNC_APPEND_ENTRIES_TIMEOUT_MS) {
4090
    return false;
4091
  }
4092

4093
  return true;
4094
}
4095

4096
bool syncNodeCanChange(SSyncNode* pSyncNode) {
4097
  if (pSyncNode->changing) {
4098
    sError("sync cannot change");
4099
    return false;
4100
  }
4101

4102
  if ((pSyncNode->commitIndex >= SYNC_INDEX_BEGIN)) {
4103
    SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);
4104
    if (pSyncNode->commitIndex != lastIndex) {
4105
      sError("sync cannot change2");
4106
      return false;
4107
    }
4108
  }
4109

4110
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
4111
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
4112
    if (pSender != NULL && pSender->start) {
4113
      sError("sync cannot change3");
4114
      return false;
4115
    }
4116
  }
4117

4118
  return true;
4119
}
4120
#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