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

taosdata / TDengine / #4829

30 Oct 2025 09:25AM UTC coverage: 49.734% (-11.3%) from 61.071%
#4829

push

travis-ci

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

merge 3.0

123072 of 323930 branches covered (37.99%)

Branch coverage included in aggregate %.

7 of 25 new or added lines in 3 files covered. (28.0%)

35232 existing lines in 327 files now uncovered.

172062 of 269495 relevant lines covered (63.85%)

70709785.06 hits per line

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

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

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

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

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

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

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

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

114
  syncNodeRelease(pSyncNode);
851,549✔
115

116
  sInfo("vgId:%d, sync started", vgId);
851,549!
117

118
  TAOS_RETURN(code);
851,549✔
119

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

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

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

138
  syncNodeRelease(pSyncNode);
878,562✔
139

140
  return 0;
878,562✔
141
}
142

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

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

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

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

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

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

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

212
    for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
1,551,264✔
213
      TAOS_CHECK_RETURN(syncHbTimerInit(pSyncNode, &pSyncNode->peerHeartbeatTimerArr[i], pSyncNode->replicasId[i]));
1,454,310!
214
    }
215

216
    TAOS_CHECK_RETURN(syncNodeStartHeartbeatTimer(pSyncNode));
96,954!
217
    // syncNodeReplicate(pSyncNode);
218
  }
219

220
  syncNodeRelease(pSyncNode);
111,299✔
221
  TAOS_RETURN(code);
111,299✔
222
}
223

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

239
  switch (pMsg->msgType) {
50,793,878!
240
    case TDMT_SYNC_HEARTBEAT:
6,233,475✔
241
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
6,233,475✔
242
      break;
6,233,475✔
243
    case TDMT_SYNC_HEARTBEAT_REPLY:
6,140,813✔
244
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
6,140,813✔
245
      break;
6,140,813✔
246
    case TDMT_SYNC_TIMEOUT:
7,501,653✔
247
      code = syncNodeOnTimeout(pSyncNode, pMsg);
7,501,653✔
248
      break;
7,495,912✔
249
    case TDMT_SYNC_TIMEOUT_ELECTION:
111,861✔
250
      code = syncNodeOnTimeout(pSyncNode, pMsg);
111,861✔
251
      break;
111,861✔
252
    case TDMT_SYNC_CLIENT_REQUEST:
9,462,946✔
253
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
9,462,946✔
254
      break;
9,462,946✔
255
    case TDMT_SYNC_REQUEST_VOTE:
150,677✔
256
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
150,677✔
257
      break;
150,677✔
258
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
135,267✔
259
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
135,267✔
260
      break;
135,267✔
261
    case TDMT_SYNC_APPEND_ENTRIES:
7,465,105✔
262
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
7,465,105✔
263
      break;
7,465,105✔
264
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
7,449,621✔
265
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
7,449,621✔
266
      break;
7,449,621✔
267
    case TDMT_SYNC_SNAPSHOT_SEND:
5,058✔
268
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
5,058✔
269
      break;
5,058✔
270
    case TDMT_SYNC_SNAPSHOT_RSP:
5,058✔
271
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
5,058✔
272
      break;
5,058✔
273
    case TDMT_SYNC_LOCAL_CMD:
6,132,087✔
274
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
6,132,087✔
275
      break;
6,132,087✔
UNCOV
276
    case TDMT_SYNC_FORCE_FOLLOWER:
×
UNCOV
277
      code = syncForceBecomeFollower(pSyncNode, pMsg);
×
UNCOV
278
      break;
×
279
    case TDMT_SYNC_SET_ASSIGNED_LEADER:
257✔
280
      code = syncBecomeAssignedLeader(pSyncNode, pMsg);
257✔
UNCOV
281
      break;
×
282
    default:
×
283
      code = TSDB_CODE_MSG_NOT_PROCESSED;
×
284
  }
285

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

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

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

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

UNCOV
320
  return 0;
×
321
}
322

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

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

UNCOV
335
  if (ths->arbTerm > req.arbTerm) {
×
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

UNCOV
341
  ths->arbTerm = TMAX(req.arbTerm, ths->arbTerm);
×
342

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

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

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

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

UNCOV
371
  contLen = tSerializeSVArbSetAssignedLeaderRsp(NULL, 0, &rsp);
×
UNCOV
372
  if (contLen <= 0) {
×
373
    code = TSDB_CODE_OUT_OF_MEMORY;
×
374
    sError("vgId:%d, failed to serialize SVArbSetAssignedLeaderRsp", ths->vgId);
×
375
    goto _OVER;
×
376
  }
UNCOV
377
  pHead = rpcMallocCont(contLen);
×
UNCOV
378
  if (!pHead) {
×
379
    code = terrno;
×
380
    sError("vgId:%d, failed to malloc memory for SVArbSetAssignedLeaderRsp", ths->vgId);
×
381
    goto _OVER;
×
382
  }
UNCOV
383
  if (tSerializeSVArbSetAssignedLeaderRsp(pHead, contLen, &rsp) <= 0) {
×
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

UNCOV
390
  code = TSDB_CODE_SUCCESS;
×
391

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

UNCOV
400
  tmsgSendRsp(&rspMsg);
×
401

UNCOV
402
  tFreeSVArbSetAssignedLeaderReq(&req);
×
UNCOV
403
  TAOS_RETURN(code);
×
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) {
7,189,269✔
431
  SyncIndex minMatchIndex = SYNC_INDEX_INVALID;
7,189,269✔
432

433
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
21,483,399✔
434
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
14,294,130✔
435
    if (minMatchIndex == SYNC_INDEX_INVALID) {
14,294,130✔
436
      minMatchIndex = matchIndex;
7,702,352✔
437
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
6,591,778✔
438
      minMatchIndex = matchIndex;
72,386✔
439
    }
440
  }
441
  return minMatchIndex;
7,189,269✔
442
}
443

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

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

458
  SyncIndex beginIndex = pSyncNode->pLogStore->syncLogBeginIndex(pSyncNode->pLogStore);
1,097,522✔
459
  SyncIndex endIndex = pSyncNode->pLogStore->syncLogEndIndex(pSyncNode->pLogStore);
1,097,824✔
460
  bool      isEmpty = pSyncNode->pLogStore->syncLogIsEmpty(pSyncNode->pLogStore);
1,097,515✔
461

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

468
  int64_t logRetention = 0;
1,096,960✔
469

470
  if (syncNodeIsMnode(pSyncNode)) {
1,096,960✔
471
    // mnode
472
    logRetention = tsMndLogRetention;
219,262✔
473
  } else {
474
    // vnode
475
    if (pSyncNode->replicaNum > 1) {
878,000✔
476
      logRetention = SYNC_VNODE_LOG_RETENTION;
29,063✔
477
    }
478
  }
479

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

493
_DEL_WAL:
1,041,482✔
494

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

503
      if (snapshottingIndex == SYNC_INDEX_INVALID) {
1,097,262!
504
        atomic_store_64(&pSyncNode->snapshottingIndex, lastApplyIndex);
1,097,262✔
505
        pSyncNode->snapshottingTime = taosGetTimestampMs();
1,097,137✔
506

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

528
int32_t syncEndSnapshot(int64_t rid) {
1,097,424✔
529
  int32_t    code = 0;
1,097,424✔
530
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
1,097,424✔
531
  if (pSyncNode == NULL) {
1,097,648!
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) {
1,097,648✔
539
    SSyncLogStoreData* pData = pSyncNode->pLogStore->data;
1,097,086✔
540
    code = walEndSnapshot(pData->pWal);
1,096,862✔
541
    if (code != 0) {
1,097,262!
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));
1,097,262!
547
      atomic_store_64(&pSyncNode->snapshottingIndex, SYNC_INDEX_INVALID);
1,097,262✔
548
    }
549
  }
550

551
  syncNodeRelease(pSyncNode);
1,097,824✔
552
  TAOS_RETURN(code);
1,097,824✔
553
}
554

555
bool syncNodeIsReadyForRead(SSyncNode* pSyncNode) {
156,703,825✔
556
  if (pSyncNode == NULL) {
156,703,825!
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) {
156,703,825!
563
    terrno = TSDB_CODE_SYN_NOT_LEADER;
6,484,777✔
564
    return false;
6,484,777✔
565
  }
566

567
  if (!pSyncNode->restoreFinish) {
150,227,362!
568
    terrno = TSDB_CODE_SYN_RESTORING;
26,104✔
569
    return false;
34,453✔
570
  }
571

572
  return true;
150,200,750✔
573
}
574

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

582
  bool ready = syncNodeIsReadyForRead(pSyncNode);
124,907,970✔
583

584
  syncNodeRelease(pSyncNode);
124,912,939✔
585
  return ready;
124,904,100✔
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) {
851,549✔
613
  if (pSyncNode->peersNum == 0) {
851,549✔
614
    sDebug("vgId:%d, only one replica, cannot leader transfer", pSyncNode->vgId);
613,620✔
615
    return 0;
613,620✔
616
  }
617

618
  int32_t ret = 0;
237,929✔
619
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER && pSyncNode->replicaNum > 1) {
237,929✔
620
    SNodeInfo newLeader = (pSyncNode->peersNodeInfo)[0];
85,483✔
621
    if (pSyncNode->peersNum == 2) {
85,483✔
622
      SyncIndex matchIndex0 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[0]));
80,739✔
623
      SyncIndex matchIndex1 = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[1]));
80,739✔
624
      if (matchIndex1 > matchIndex0) {
80,739✔
625
        newLeader = (pSyncNode->peersNodeInfo)[1];
900✔
626
      }
627
    }
628
    ret = syncNodeLeaderTransferTo(pSyncNode, newLeader);
85,483✔
629
  }
630

631
  return ret;
237,929✔
632
}
633

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

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

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

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

678
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
183,862,646✔
679
  if (pSyncNode != NULL) {
183,864,559!
680
    state.state = pSyncNode->state;
183,864,583✔
681
    state.roleTimeMs = pSyncNode->roleTimeMs;
183,864,583✔
682
    state.startTimeMs = pSyncNode->startTime;
183,862,162✔
683
    state.restored = pSyncNode->restoreFinish;
183,862,223!
684
    if (pSyncNode->vgId != 1) {
183,862,025✔
685
      state.canRead = syncNodeIsReadyForRead(pSyncNode);
31,804,920✔
686
    } else {
687
      state.canRead = state.restored;
152,057,574!
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);
183,860,353✔
704
    syncNodeRelease(pSyncNode);
183,864,442✔
705
  }
706

707
  return state;
183,864,342✔
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) {
31,071,826✔
737
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
31,071,826✔
738
  if (pSyncNode != NULL) {
31,071,826!
739
    *syncCommitIndex = pSyncNode->commitIndex;
31,071,826✔
740
    syncNodeRelease(pSyncNode);
31,071,826✔
741
  }
742
}
31,071,826✔
743

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

758
  syncNodeRelease(pSyncNode);
5,328,104✔
759
  TAOS_RETURN(code);
5,328,104✔
760
}
761

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

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

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

UNCOV
784
  syncNodeRelease(pSyncNode);
×
UNCOV
785
  TAOS_RETURN(code);
×
786
}
787

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

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

811
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
36,711,877✔
812
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
19,011,298✔
813
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
1,309,190!
814
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
1,309,190✔
815
    }
816
  }
817
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
17,702,108!
818
         lastIndex);
819

820
  return lastIndex;
17,701,091✔
821
}
822

823
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
11,661,656✔
824
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
16,784,322✔
825
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
8,543,494!
826
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
8,544,617✔
827
      return pSyncNode->peersId[i];
3,421,730✔
828
    }
829
  }
830
  return EMPTY_RAFT_ID;
8,237,017✔
831
}
832

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

839
  size_t offset = 0;
8,244,398✔
840
  offset += snprintf(buffer + offset, bufferSize - offset, "EpSet: [");
8,244,398!
841

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

848
  if (offset < bufferSize) {
8,248,386✔
849
    snprintf(buffer + offset, bufferSize - offset, "]");
8,247,979!
850
  }
851
}
852

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

856
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
8,246,670✔
857
  if (pSyncNode == NULL) return;
8,248,194!
858

859
  int index = -1;
8,248,194✔
860

861
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
8,248,194✔
862
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
863
  int j = 0;
8,247,564✔
864
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
19,948,332✔
865
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
11,701,951✔
866
    SEp* pEp = &pEpSet->eps[j];
11,660,820✔
867
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
11,660,535!
868
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
11,661,087✔
869
    pEpSet->numOfEps++;
11,660,511✔
870
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
11,661,198✔
871
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
11,658,977✔
872
           pEp->port);
873
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
11,658,977✔
874
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
7,407,857!
875
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
876
      index = j;
7,407,885✔
877
    }
878
    j++;
11,660,767✔
879
  }
880
  if (pEpSet->numOfEps > 0) {
8,245,995!
881
    if (index != -1) {
8,247,200✔
882
      pEpSet->inUse = index;
7,408,726✔
883
    } else {
884
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
838,474!
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;
838,474!
889
      }
890
    }
891
    // pEpSet->inUse = 0;
892
  }
893
  epsetSort(pEpSet);
8,246,809✔
894

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

902
int32_t syncPropose(int64_t rid, SRpcMsg* pMsg, bool isWeak, int64_t* seq) {
163,974,682✔
903
  int32_t    code = 0;
163,974,682✔
904
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
163,974,682✔
905
  if (pSyncNode == NULL) {
163,975,528!
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);
163,975,528✔
913
  syncNodeRelease(pSyncNode);
163,962,805✔
914
  return ret;
163,966,847✔
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) {
127,263✔
937
  int32_t    code = 0;
127,263✔
938
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
127,263✔
939
  if (pSyncNode == NULL) {
127,263!
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;
127,263✔
947
  if (pSyncNode->pLogBuf->totalIndex < 0 || pSyncNode->pLogBuf->commitIndex < 0 ||
127,263!
948
      pSyncNode->pLogBuf->totalIndex < pSyncNode->pLogBuf->commitIndex ||
47,023!
949
      pSyncNode->pLogBuf->totalIndex - pSyncNode->pLogBuf->commitIndex > SYNC_LEARNER_CATCHUP) {
47,023✔
950
    sInfo("vgId:%d, Not catch up, wait one second, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64,
118,405!
951
          pSyncNode->vgId, pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex,
952
          pSyncNode->pLogBuf->matchIndex);
953
    isCatchUp = 0;
118,405✔
954
  } else {
955
    sInfo("vgId:%d, Catch up, totalIndex:%" PRId64 " commitIndex:%" PRId64 " matchIndex:%" PRId64, pSyncNode->vgId,
8,858!
956
          pSyncNode->pLogBuf->totalIndex, pSyncNode->pLogBuf->commitIndex, pSyncNode->pLogBuf->matchIndex);
957
    isCatchUp = 1;
8,858✔
958
  }
959

960
  syncNodeRelease(pSyncNode);
127,263✔
961
  return isCatchUp;
127,263✔
962
}
963

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

976
  syncNodeRelease(pSyncNode);
127,263✔
977
  return role;
127,263✔
978
}
979

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

992
  syncNodeRelease(pSyncNode);
2,119,514✔
993
  return term;
2,119,514✔
994
}
995

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

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

1011
  // heartbeat timeout
1012
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER && syncNodeHeartbeatReplyTimeout(pSyncNode)) {
164,040,708!
UNCOV
1013
    code = TSDB_CODE_SYN_PROPOSE_NOT_READY;
×
UNCOV
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);
UNCOV
1016
    TAOS_RETURN(code);
×
1017
  }
1018

1019
  // optimized one replica
1020
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
164,038,660✔
1021
    SyncIndex retIndex;
154,493,288✔
1022
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
154,494,032✔
1023
    if (code >= 0) {
154,481,475!
1024
      pMsg->info.conn.applyIndex = retIndex;
154,481,475✔
1025
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
154,487,865✔
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) {
154,493,238!
1030
        sGDebug(&pMsg->info.traceId, "vgId:%d, index:%" PRId64 ", propose optimized msg type:%s", pSyncNode->vgId,
154,493,414!
1031
                retIndex, TMSG_INFO(pMsg->msgType));
1032
        return 1;
154,484,781✔
1033
      } else {
1034
        sGDebug(&pMsg->info.traceId,
×
1035
                "vgId:%d, index:%" PRId64 ", propose optimized msg, return to normal, type:%s, handle:%p",
1036
                pSyncNode->vgId, retIndex, TMSG_INFO(pMsg->msgType), pMsg->info.handle);
1037
        return 0;
×
1038
      }
1039
    } else {
1040
      code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
1041
      sError("vgId:%d, failed to propose optimized msg, index:%" PRId64 " type:%s", pSyncNode->vgId, retIndex,
×
1042
             TMSG_INFO(pMsg->msgType));
1043
      TAOS_RETURN(code);
×
1044
    }
1045
  } else {
1046
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
9,546,129✔
1047
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
9,545,907✔
1048
    SRpcMsg   rpcMsg = {.info.traceId = pMsg->info.traceId};
9,546,129✔
1049
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
9,546,129✔
1050
    if (code != 0) {
9,545,907!
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,
9,545,907!
1057
            TMSG_INFO(pMsg->msgType));
1058
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
9,545,907✔
1059
    if (code != 0) {
9,546,129✔
1060
      sWarn("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
83,183!
1061
      TAOS_CHECK_RETURN(syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum));
83,183!
1062
    }
1063

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

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

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

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

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

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

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

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

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

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

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

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

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

1195
    if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
676,200!
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) {
175,424!
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) {
175,424✔
1209
      if (pSyncInfo->syncCfg.totalReplicaNum > 0 && syncIsConfigChanged(&pSyncNode->raftCfg.cfg, &pSyncInfo->syncCfg)) {
51,182!
1210
        sInfo("vgId:%d, use sync config from input options and write to cfg file", pSyncNode->vgId);
21,539!
1211
        pSyncNode->raftCfg.cfg = pSyncInfo->syncCfg;
21,539✔
1212
        if ((code = syncWriteCfgFile(pSyncNode)) != 0) {
21,539!
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);
29,643!
1219
        pSyncInfo->syncCfg = pSyncNode->raftCfg.cfg;
29,643✔
1220
      }
1221
    } else {
1222
      sInfo("vgId:%d, skip save sync cfg file since request ver:%d <= file ver:%d", pSyncNode->vgId, vnodeVersion,
124,242!
1223
            pSyncInfo->syncCfg.changeVersion);
1224
    }
1225
  }
1226

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

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

1260
  // create raft log ring buffer
1261
  code = syncLogBufferCreate(&pSyncNode->pLogBuf);
851,624✔
1262
  if (pSyncNode->pLogBuf == NULL) {
851,624!
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;
851,624✔
1269
  pSyncNode->totalReplicaNum = pSyncNode->raftCfg.cfg.totalReplicaNum;
851,624✔
1270
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
2,156,302✔
1271
    if (syncUtilNodeInfo2RaftId(&pSyncNode->raftCfg.cfg.nodeInfo[i], pSyncNode->vgId, &pSyncNode->replicasId[i]) ==
1,304,678!
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];
851,624✔
1280
  pSyncNode->myRaftId = pSyncNode->replicasId[pSyncNode->raftCfg.cfg.myIndex];
851,624✔
1281

1282
  // init peersNum, peers, peersId
1283
  pSyncNode->peersNum = pSyncNode->raftCfg.cfg.totalReplicaNum - 1;
851,624✔
1284
  int32_t j = 0;
851,624✔
1285
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
2,156,302✔
1286
    if (i != pSyncNode->raftCfg.cfg.myIndex) {
1,304,678✔
1287
      pSyncNode->peersNodeInfo[j] = pSyncNode->raftCfg.cfg.nodeInfo[i];
453,067✔
1288
      pSyncNode->peersId[j] = pSyncNode->replicasId[i];
453,067✔
1289
      syncUtilNodeInfo2EpSet(&pSyncNode->peersNodeInfo[j], &pSyncNode->peersEpset[j]);
453,067✔
1290
      j++;
453,067✔
1291
    }
1292
  }
1293

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

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

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

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

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

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

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

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

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

1449
  // restore state
1450
  pSyncNode->restoreFinish = false;
851,624✔
1451

1452
  // snapshot senders
1453
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
13,624,820✔
1454
    SSyncSnapshotSender* pSender = NULL;
12,773,196✔
1455
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
12,773,196✔
1456
    if (pSender == NULL) return NULL;
12,773,596!
1457

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

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

1468
  // is config changing
1469
  pSyncNode->changing = false;
851,624✔
1470

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

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

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

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

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

1515
  sNInfo(pSyncNode, "sync node opened, node:%p electBaseLine:%d hbBaseLine:%d heartbeatTimeout:%d", pSyncNode,
851,624!
1516
         pSyncNode->electBaseLine, pSyncNode->hbBaseLine, tsHeartbeatTimeout);
1517
  return pSyncNode;
851,624✔
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) {
851,549✔
1542
  int32_t code = 0;
851,549✔
1543
  if (pSyncNode->pLogStore == NULL) {
851,549!
1544
    sError("vgId:%d, log store not created", pSyncNode->vgId);
×
1545
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
1546
  }
1547
  if (pSyncNode->pLogBuf == NULL) {
851,549!
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);
851,549✔
1553
  SyncIndex lastVer = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
851,549✔
1554
  SyncIndex commitIndex = pSyncNode->pLogStore->syncLogCommitIndex(pSyncNode->pLogStore);
851,549✔
1555
  SyncIndex endIndex = pSyncNode->pLogBuf->endIndex;
851,549✔
1556
  (void)taosThreadMutexUnlock(&pSyncNode->pLogBuf->mutex);
851,549✔
1557

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

1569
  if (pSyncNode->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
1,703,098!
1570
      (code = syncLogBufferCommit(pSyncNode->pLogBuf, pSyncNode, pSyncNode->commitIndex, NULL, "restore")) < 0) {
851,549✔
1571
    TAOS_RETURN(code);
×
1572
  }
1573

1574
  TAOS_RETURN(code);
851,549✔
1575
}
1576

1577
int32_t syncNodeStart(SSyncNode* pSyncNode) {
851,549✔
1578
  // start raft
1579
  sInfo("vgId:%d, begin to start sync node", pSyncNode->vgId);
851,549!
1580
  if (pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
851,549✔
1581
    syncNodeBecomeLearner(pSyncNode, "first start");
11,474✔
1582
  } else {
1583
    if (pSyncNode->replicaNum == 1) {
840,075✔
1584
      raftStoreNextTerm(pSyncNode);
620,858✔
1585
      syncNodeBecomeLeader(pSyncNode, "one replica start");
620,858✔
1586

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

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

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

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

1680
void syncHbTimerDataFree(SSyncHbTimerData* pData) { taosMemoryFree(pData); }
195,961!
1681

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

1687
  syncRespCleanRsp(pSyncNode->pSyncRespMgr);
851,549✔
1688

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

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

1718
  (void)taosThreadMutexDestroy(&pSyncNode->arbTokenMutex);
851,549✔
1719

1720
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
13,623,618✔
1721
    if (pSyncNode->senders[i] != NULL) {
12,772,069!
1722
      sDebug("vgId:%d, snapshot sender destroy while close, data:%p", pSyncNode->vgId, pSyncNode->senders[i]);
12,772,069✔
1723

1724
      if (snapshotSenderIsStart(pSyncNode->senders[i])) {
12,772,069!
UNCOV
1725
        snapshotSenderStop(pSyncNode->senders[i], false);
×
1726
      }
1727

1728
      snapshotSenderDestroy(pSyncNode->senders[i]);
12,772,449✔
1729
      pSyncNode->senders[i] = NULL;
12,772,069✔
1730
    }
1731
  }
1732

1733
  if (pSyncNode->pNewNodeReceiver != NULL) {
851,549✔
1734
    if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
126,468!
1735
      snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
1736
    }
1737

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

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

1747
  raftStoreClose(pSyncNode);
851,549✔
1748

1749
  taosMemoryFree(pSyncNode);
851,549!
1750
}
1751

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

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

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

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

1785
    int64_t execTime = taosGetTimestampMs() + ms;
13,537,384✔
1786
    atomic_store_64(&(pSyncNode->electTimerParam.executeTime), execTime);
13,537,384✔
1787
    atomic_store_64(&(pSyncNode->electTimerParam.logicClock), pSyncNode->electTimerLogicClock);
13,537,826✔
1788
    pSyncNode->electTimerParam.pSyncNode = pSyncNode;
13,537,622✔
1789
    pSyncNode->electTimerParam.pData = NULL;
13,536,841✔
1790

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

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

1807
  return code;
15,946,884✔
1808
}
1809

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

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

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

1827
  if ((code = syncNodeRestartElectTimer(pSyncNode, electMS)) != 0) {
13,537,826!
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,
13,537,826!
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) {
803,457✔
1853
  int32_t ret = 0;
803,457✔
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) {
999,418✔
1861
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
195,961✔
1862
    if (pSyncTimer != NULL) {
195,961!
1863
      TAOS_CHECK_RETURN(syncHbTimerStart(pSyncNode, pSyncTimer));
195,961!
1864
    }
1865
  }
1866

1867
  return ret;
802,631✔
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) {
2,186,515✔
1884
  int32_t code = 0;
2,186,515✔
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) {
3,903,527✔
1894
    SSyncTimer* pSyncTimer = syncNodeGetHbTimer(pSyncNode, &(pSyncNode->peersId[i]));
1,716,791✔
1895
    if (pSyncTimer != NULL) {
1,717,012!
1896
      TAOS_CHECK_RETURN(syncHbTimerStop(pSyncNode, pSyncTimer));
1,717,012!
1897
    }
1898
  }
1899

1900
  return code;
2,186,958✔
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) {
28,865,783✔
1916
  SEpSet* epSet = NULL;
28,865,783✔
1917
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
42,514,148✔
1918
    if (destRaftId->addr == pNode->peersId[i].addr) {
42,501,100✔
1919
      epSet = &pNode->peersEpset[i];
28,852,098✔
1920
      break;
28,852,731✔
1921
    }
1922
  }
1923

1924
  int32_t code = -1;
28,866,749✔
1925
  if (pNode->syncSendMSg != NULL && epSet != NULL) {
28,866,749✔
1926
    syncUtilMsgHtoN(pMsg->pCont);
28,852,673✔
1927
    pMsg->info.noResp = 1;
28,850,442✔
1928
    code = pNode->syncSendMSg(epSet, pMsg);
28,850,888✔
1929
  }
1930

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

1937
  TAOS_RETURN(code);
28,867,541✔
1938
}
1939

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

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

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

1958
    if (syncUtilSameId(&raftId, &pNode->myRaftId)) {
186,479✔
1959
      b2 = true;
154,613✔
1960
      break;
154,613✔
1961
    }
1962
  }
1963

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

1971
static bool syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg) {
132,838✔
1972
  if (pOldCfg->totalReplicaNum != pNewCfg->totalReplicaNum) return true;
132,838✔
1973
  if (pOldCfg->myIndex != pNewCfg->myIndex) return true;
109,571✔
1974
  for (int32_t i = 0; i < pOldCfg->totalReplicaNum; ++i) {
238,124✔
1975
    const SNodeInfo* pOldInfo = &pOldCfg->nodeInfo[i];
148,482✔
1976
    const SNodeInfo* pNewInfo = &pNewCfg->nodeInfo[i];
148,482✔
1977
    if (strcmp(pOldInfo->nodeFqdn, pNewInfo->nodeFqdn) != 0) return true;
148,482!
1978
    if (pOldInfo->nodePort != pNewInfo->nodePort) return true;
148,482!
1979
    if (pOldInfo->nodeRole != pNewInfo->nodeRole) return true;
148,482✔
1980
  }
1981

1982
  return false;
89,642✔
1983
}
1984

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

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

1996
  pSyncNode->configChangeNum++;
21,657✔
1997

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

2001
  bool isDrop = false;
21,657✔
2002
  bool isAdd = false;
21,657✔
2003

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

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

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

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

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

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

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

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

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

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

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

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

2088
    // reset snapshot senders
2089

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

2095
    // reset new
2096
    for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
78,192✔
2097
      // reset sender
2098
      bool reset = false;
56,535✔
2099
      for (int32_t j = 0; j < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++j) {
242,050✔
2100
        if (syncUtilSameId(&(pSyncNode->replicasId)[i], &oldReplicasId[j]) && oldSenders[j] != NULL) {
231,781!
2101
          sNTrace(pSyncNode, "snapshot sender reset for:%" PRId64 ", newIndex:%d, dnode:%d, %p",
46,266!
2102
                  (pSyncNode->replicasId)[i].addr, i, DID(&pSyncNode->replicasId[i]), oldSenders[j]);
2103

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

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

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

2115
          break;
46,266✔
2116
        }
2117
      }
2118
    }
2119

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

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

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

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

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

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

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

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

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

2211
  pSyncNode->hbSlowNum = 0;
386,906✔
2212

2213
  pSyncNode->leaderCache = leaderId;  // state change
386,906✔
2214

2215
  for (int32_t i = 0; i < pSyncNode->totalReplicaNum; ++i) {
1,192,096✔
2216
    if (syncUtilSameId(&pSyncNode->replicasId[i], &leaderId)) {
973,100✔
2217
      pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[i].nodePort;
167,468✔
2218
      strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
167,468!
2219
      break;
167,468✔
2220
    }
2221
  }
2222
  pSyncNode->state = TAOS_SYNC_STATE_FOLLOWER;
386,464✔
2223
  pSyncNode->roleTimeMs = taosGetTimestampMs();
386,685✔
2224
  if ((code = syncNodeStopHeartbeatTimer(pSyncNode)) != 0) {
386,685!
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);
386,464!
2231

2232
  // send rsp to client
2233
  syncNodeLeaderChangeRsp(pSyncNode);
386,464✔
2234

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

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

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

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

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

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

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

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

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

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

2304
  // reset restoreFinish
2305
  pSyncNode->restoreFinish = false;
706,986✔
2306

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

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

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

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

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

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

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

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

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

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

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

2406
  // set leader cache
UNCOV
2407
  pSyncNode->leaderCache = pSyncNode->myRaftId;
×
2408

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

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

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

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

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

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

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

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

2460
  // min match index
UNCOV
2461
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
×
2462

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

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

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

2485
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
86,128!
2486

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

2492
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
86,128✔
2493

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

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

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

2514
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
1,557,595✔
2515
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
24,901,231✔
2516
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
23,343,421✔
2517
    pSyncNode->peerStates[i].lastSendTime = 0;
23,345,325✔
2518
  }
2519

2520
  return 0;
1,557,810✔
2521
}
2522

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

2534
  sNTrace(pSyncNode, "follower to candidate");
107,679!
2535
}
2536

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

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

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

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

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

2570
  raftStoreVote(pSyncNode, pRaftId);
110,662✔
2571
}
2572

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

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

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

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

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

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

2616
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
1,248,523✔
2617
  return lastIndex;
1,248,523✔
2618
}
2619

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

2632
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
124,246✔
2633
    if (logLastIndex > snapshot.lastApplyIndex) {
124,246✔
2634
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
56,782✔
2635
    } else {
2636
      lastTerm = snapshot.lastApplyTerm;
67,464✔
2637
    }
2638

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

2644
  return lastTerm;
1,247,097✔
2645
}
2646

2647
// get last index and term along with snapshot
2648
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
1,097,155✔
2649
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
1,097,155✔
2650
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
1,097,622✔
2651
  return 0;
1,096,139✔
2652
}
2653

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

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

2669
  return preIndex;
2670
}
2671

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

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

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

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

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

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

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

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

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

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

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

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

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

2745
static void syncNodeEqPingTimer(void* param, void* tmrId) {
7,502,934✔
2746
  if (!syncIsInit()) return;
7,502,934!
2747

2748
  int64_t    rid = (int64_t)param;
7,503,149✔
2749
  SSyncNode* pNode = syncNodeAcquire(rid);
7,503,149✔
2750

2751
  if (pNode == NULL) return;
7,503,149!
2752

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

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

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

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

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

2785
  if (pNode == NULL) return;
112,827!
2786

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

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

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

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

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

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

2819
  syncNodeRelease(pNode);
111,861✔
2820
}
2821

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

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

2829
  if (pNode == NULL) return;
2830

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

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

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

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

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

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

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

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

2884
  SSyncTimer* pSyncTimer = pData->pTimer;
7,018,075✔
2885

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

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

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

2908
  if (pSyncNode->totalReplicaNum > 1) {
7,018,075✔
2909
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
7,017,776✔
2910
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
7,017,776✔
2911

2912
    if (timerLogicClock == msgLogicClock) {
7,017,776!
2913
      if (tsNow > pData->execTime) {
7,017,776✔
2914
        pData->execTime += pSyncTimer->timerMS;
7,014,874✔
2915

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

2924
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);
7,014,874✔
2925

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

2935
        // update reset time
2936
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
7,014,874✔
2937
        pSyncTimer->timeStamp = tsNow;
7,014,874✔
2938

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

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

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

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

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

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

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

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

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

2998
  return code;
2999
}
3000
#endif
3001

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3171
  return 0;
×
3172
}
3173

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

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

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

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

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

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

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

3226
  syncIndexMgrDestroy(oldIndex);
×
3227

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

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

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

3240
  syncIndexMgrDestroy(oldNextIndex);
×
3241

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3349
  taosMemoryFree(oldLogReplMgrs);
×
3350

3351
  return 0;
×
3352
}
3353

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3448
  int32_t oldTotalReplicaNum = ths->totalReplicaNum;
×
3449

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

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

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

3464
      // no need to change myNodeInfo
3465

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

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

3476
      syncNodeResetPeerAndCfg(ths);
×
3477

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

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

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

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

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

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

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

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

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

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

3528
      // no need to change myNodeInfo
3529

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

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

3540
      // no need to change state
3541

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

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

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

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

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

3561
  TAOS_RETURN(code);
×
3562
}
3563

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

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

3587
  code = 0;
164,660,061✔
3588
_out:;
164,660,061✔
3589
  // proceed match index, with replicating on needed
3590
  SyncIndex       matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL, "Append", pMsg);
164,660,061✔
3591
  const STraceId* trace = pEntry ? &pEntry->originRpcTraceId : NULL;
164,659,724!
3592

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

3601
  if (code == 0 && ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
164,653,906!
UNCOV
3602
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
×
UNCOV
3603
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
×
3604

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

3613
  // multi replica
3614
  if (ths->replicaNum > 1) {
164,659,999✔
3615
    TAOS_RETURN(code);
3,344,714✔
3616
  }
3617

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

3623
  if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
322,616,530!
3624
      (code = syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, trace, "append-entry")) < 0) {
161,314,685✔
3625
    sGError(trace,
×
3626
            "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64 " return index:%" PRId64,
3627
            ths->vgId, matchIndex, pMsg, ths->commitIndex, returnIndex);
3628
  }
3629

3630
  TAOS_RETURN(code);
161,303,959✔
3631
}
3632

3633
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
164,038,603✔
3634
  if (pSyncNode->totalReplicaNum == 1) {
164,038,603✔
3635
    return false;
160,686,287✔
3636
  }
3637

3638
  int32_t toCount = 0;
3,353,526✔
3639
  int64_t tsNow = taosGetTimestampMs();
3,353,526✔
3640
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
10,040,017✔
3641
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
6,686,935✔
3642
      continue;
21,720✔
3643
    }
3644
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
6,665,215✔
3645
    if (recvTime == 0 || recvTime == -1) {
6,664,771!
3646
      continue;
×
3647
    }
3648

3649
    if (tsNow - recvTime > tsHeartbeatTimeout) {
6,664,771✔
3650
      toCount++;
23,363✔
3651
    }
3652
  }
3653

3654
  bool b = (toCount >= pSyncNode->quorum ? true : false);
3,353,304✔
3655

3656
  return b;
3,353,526✔
3657
}
3658

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

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

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

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

3689
  code = syncNodeAppend(ths, pEntry, NULL);
706,986✔
3690
  TAOS_RETURN(code);
706,986✔
3691
}
3692

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

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

3702
  LRUHandle* h = NULL;
3703

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

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

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

3720
  return ret;
3721
}
3722
#endif
3723

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

3728
  int64_t tsMs = taosGetTimestampMs();
6,232,659✔
3729

3730
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pNextIndex, &(pMsg->srcId));
6,232,659✔
3731
  syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);
6,233,067✔
3732
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
6,233,271✔
3733

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

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

3746
  SyncTerm currentTerm = raftStoreGetTerm(ths);
6,232,648✔
3747

3748
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
6,233,056✔
3749
    raftStoreSetTerm(ths, pMsg->term);
9,499✔
3750
    currentTerm = pMsg->term;
9,499✔
3751
  }
3752

3753
  int64_t tsMs2 = taosGetTimestampMs();
6,233,475✔
3754

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

3770
  if (pMsg->term == currentTerm &&
6,233,475✔
3771
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
6,134,422!
3772
    resetElect = true;
6,134,422✔
3773

3774
    ths->minMatchIndex = pMsg->minMatchIndex;
6,134,422✔
3775

3776
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
6,134,626✔
3777
      SRpcMsg rpcMsgLocalCmd = {0};
6,131,260✔
3778
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
6,131,464!
3779
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
6,131,035✔
3780

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

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

3803
  if (pMsg->term >= currentTerm &&
6,234,280✔
3804
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
6,233,083!
3805
    SRpcMsg rpcMsgLocalCmd = {0};
×
3806
    TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
×
3807
    rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
×
3808

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

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

3825
  SRpcMsg rpcMsg = {0};
6,233,475✔
3826
  TAOS_CHECK_RETURN(syncBuildHeartbeatReply(&rpcMsg, ths->vgId));
6,232,691!
3827
  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
6,232,439✔
3828
  pMsgReply->destId = pMsg->srcId;
6,232,439✔
3829
  pMsgReply->srcId = ths->myRaftId;
6,233,298✔
3830
  pMsgReply->term = currentTerm;
6,233,121✔
3831
  pMsgReply->privateTerm = 8864;  // magic number
6,232,681✔
3832
  pMsgReply->startTime = ths->startTime;
6,233,083✔
3833
  pMsgReply->timeStamp = tsMs;
6,232,824✔
3834
  rpcMsg.info.traceId = pRpcMsg->info.traceId;
6,232,227✔
3835

3836
  // reply
3837
  int64_t tsMs3 = taosGetTimestampMs();
6,232,040✔
3838

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

3861
  TAOS_CHECK_RETURN(syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg));
6,233,271!
3862

3863
  if (resetElect) syncNodeResetElectTimer(ths);
6,233,475✔
3864
  return 0;
6,233,475✔
3865
}
3866

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

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

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

3883
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
6,140,813✔
3884
  syncIndexMgrIncRecvCount(ths->pMatchIndex, &(pMsg->srcId));
6,140,813✔
3885

3886
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
6,140,813✔
3887
}
3888

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

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

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

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

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

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

3933
  return 0;
6,131,866✔
3934
}
3935

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

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

3951
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
163,955,575✔
3952
  SyncTerm        term = raftStoreGetTerm(ths);
163,957,171✔
3953
  SSyncRaftEntry* pEntry = NULL;
163,958,021✔
3954
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
163,958,021✔
3955
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
9,462,946✔
3956
  } else {
3957
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
154,491,587✔
3958
  }
3959

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

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

3974
  if (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
163,955,264!
3975
    if (pRetIndex) {
163,956,268✔
3976
      (*pRetIndex) = index;
154,492,614✔
3977
    }
3978

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

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

4003
    code = syncNodeAppend(ths, pEntry, pMsg);
163,956,416✔
4004
    return code;
163,947,016✔
4005
  } else {
4006
    syncEntryDestroy(pEntry);
×
4007
    pEntry = NULL;
×
4008
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4009
  }
4010
}
4011

4012
const char* syncStr(ESyncState state) {
25,070,573✔
4013
  switch (state) {
25,070,573!
4014
    case TAOS_SYNC_STATE_FOLLOWER:
10,583,110✔
4015
      return "follower";
10,583,110✔
4016
    case TAOS_SYNC_STATE_CANDIDATE:
258,453✔
4017
      return "candidate";
258,453✔
4018
    case TAOS_SYNC_STATE_LEADER:
13,155,091✔
4019
      return "leader";
13,155,091✔
4020
    case TAOS_SYNC_STATE_ERROR:
×
4021
      return "error";
×
4022
    case TAOS_SYNC_STATE_OFFLINE:
351,162✔
4023
      return "offline";
351,162✔
4024
    case TAOS_SYNC_STATE_LEARNER:
723,186✔
4025
      return "learner";
723,186✔
UNCOV
4026
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
×
UNCOV
4027
      return "assigned leader";
×
UNCOV
4028
    default:
×
UNCOV
4029
      return "unknown";
×
4030
  }
4031
}
4032

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

4040
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
129,187✔
4041
      pNewCfg->myIndex = i;
111,299✔
4042
      return 0;
111,299✔
4043
    }
4044
  }
4045

4046
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4047
}
4048

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

4053
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
21,444,261✔
4054
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
41,597,006!
4055
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
41,596,598✔
4056
      return true;
21,443,649✔
4057
    }
4058
  }
4059
  return false;
×
4060
}
4061

4062
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
3,973,850✔
4063
  SSyncSnapshotSender* pSender = NULL;
3,973,850✔
4064
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
15,884,147✔
4065
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
11,913,092✔
4066
      pSender = (ths->senders)[i];
3,973,646✔
4067
    }
4068
  }
4069
  return pSender;
3,973,628✔
4070
}
4071

4072
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
1,912,530✔
4073
  SSyncTimer* pTimer = NULL;
1,912,530✔
4074
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
7,637,509✔
4075
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
5,725,423✔
4076
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
1,912,973✔
4077
    }
4078
  }
4079
  return pTimer;
1,912,973✔
4080
}
4081

4082
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
57,180✔
4083
  SPeerState* pState = NULL;
57,180✔
4084
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
143,865✔
4085
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
86,685✔
4086
      pState = &((ths->peerStates)[i]);
57,180✔
4087
    }
4088
  }
4089
  return pState;
57,180✔
4090
}
4091

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

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

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

4107
  return true;
4108
}
4109

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

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

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

4132
  return true;
4133
}
4134
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc