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

taosdata / TDengine / #4720

08 Sep 2025 08:43AM UTC coverage: 58.139% (-0.6%) from 58.762%
#4720

push

travis-ci

web-flow
Merge pull request #32881 from taosdata/enh/add-new-windows-ci

fix(ci): update workflow reference to use new Windows CI YAML

133181 of 292179 branches covered (45.58%)

Branch coverage included in aggregate %.

201691 of 283811 relevant lines covered (71.07%)

5442780.71 hits per line

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

52.93
/source/libs/sync/src/syncMain.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#define _DEFAULT_SOURCE
17
#include "sync.h"
18
#include "syncAppendEntries.h"
19
#include "syncAppendEntriesReply.h"
20
#include "syncCommit.h"
21
#include "syncElection.h"
22
#include "syncEnv.h"
23
#include "syncIndexMgr.h"
24
#include "syncInt.h"
25
#include "syncMessage.h"
26
#include "syncPipeline.h"
27
#include "syncRaftCfg.h"
28
#include "syncRaftLog.h"
29
#include "syncRaftStore.h"
30
#include "syncReplication.h"
31
#include "syncRequestVote.h"
32
#include "syncRequestVoteReply.h"
33
#include "syncRespMgr.h"
34
#include "syncSnapshot.h"
35
#include "syncTimeout.h"
36
#include "syncUtil.h"
37
#include "syncVoteMgr.h"
38
#include "tglobal.h"
39
#include "tmisce.h"
40
#include "tref.h"
41

42
static void    syncNodeEqPingTimer(void* param, void* tmrId);
43
static void    syncNodeEqElectTimer(void* param, void* tmrId);
44
static void    syncNodeEqHeartbeatTimer(void* param, void* tmrId);
45
static int32_t syncNodeAppendNoop(SSyncNode* ths);
46
static void    syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId);
47
static bool    syncIsConfigChanged(const SSyncCfg* pOldCfg, const SSyncCfg* pNewCfg);
48
static int32_t syncHbTimerInit(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer, SRaftId destId);
49
static int32_t syncHbTimerStart(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
50
static int32_t syncHbTimerStop(SSyncNode* pSyncNode, SSyncTimer* pSyncTimer);
51
static int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg);
52
static bool    syncNodeInConfig(SSyncNode* pSyncNode, const SSyncCfg* config);
53
static int32_t syncNodeDoConfigChange(SSyncNode* pSyncNode, SSyncCfg* newConfig, SyncIndex lastConfigChangeIndex);
54
static bool    syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg);
55

56
static bool    syncNodeCanChange(SSyncNode* pSyncNode);
57
static int32_t syncNodeLeaderTransfer(SSyncNode* pSyncNode);
58
static int32_t syncNodeLeaderTransferTo(SSyncNode* pSyncNode, SNodeInfo newLeader);
59
static int32_t syncDoLeaderTransfer(SSyncNode* ths, SRpcMsg* pRpcMsg, SSyncRaftEntry* pEntry);
60

61
static ESyncStrategy syncNodeStrategy(SSyncNode* pSyncNode);
62

63
int64_t syncOpen(SSyncInfo* pSyncInfo, int32_t vnodeVersion) {
14,334✔
64
  sInfo("vgId:%d, start to open sync", pSyncInfo->vgId);
14,334✔
65

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

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

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

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

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

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

114
  syncNodeRelease(pSyncNode);
14,338✔
115

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

118
  TAOS_RETURN(code);
14,338✔
119

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

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

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

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

138
  syncNodeRelease(pSyncNode);
22,437✔
139

140
  return 0;
22,437✔
141
}
142

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

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

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

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

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

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

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

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

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

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

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

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

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

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

239
  switch (pMsg->msgType) {
942,755!
240
    case TDMT_SYNC_HEARTBEAT:
63,097✔
241
      code = syncNodeOnHeartbeat(pSyncNode, pMsg);
63,097✔
242
      break;
63,097✔
243
    case TDMT_SYNC_HEARTBEAT_REPLY:
62,513✔
244
      code = syncNodeOnHeartbeatReply(pSyncNode, pMsg);
62,513✔
245
      break;
62,513✔
246
    case TDMT_SYNC_TIMEOUT:
61,218✔
247
      code = syncNodeOnTimeout(pSyncNode, pMsg);
61,218✔
248
      break;
61,211✔
249
    case TDMT_SYNC_TIMEOUT_ELECTION:
1,361✔
250
      code = syncNodeOnTimeout(pSyncNode, pMsg);
1,361✔
251
      break;
1,361✔
252
    case TDMT_SYNC_CLIENT_REQUEST:
191,385✔
253
      code = syncNodeOnClientRequest(pSyncNode, pMsg, NULL);
191,385✔
254
      break;
191,385✔
255
    case TDMT_SYNC_REQUEST_VOTE:
2,450✔
256
      code = syncNodeOnRequestVote(pSyncNode, pMsg);
2,450✔
257
      break;
2,450✔
258
    case TDMT_SYNC_REQUEST_VOTE_REPLY:
2,430✔
259
      code = syncNodeOnRequestVoteReply(pSyncNode, pMsg);
2,430✔
260
      break;
2,430✔
261
    case TDMT_SYNC_APPEND_ENTRIES:
246,538✔
262
      code = syncNodeOnAppendEntries(pSyncNode, pMsg);
246,538✔
263
      break;
246,536✔
264
    case TDMT_SYNC_APPEND_ENTRIES_REPLY:
245,514✔
265
      code = syncNodeOnAppendEntriesReply(pSyncNode, pMsg);
245,514✔
266
      break;
245,513✔
267
    case TDMT_SYNC_SNAPSHOT_SEND:
1,625✔
268
      code = syncNodeOnSnapshot(pSyncNode, pMsg);
1,625✔
269
      break;
1,625✔
270
    case TDMT_SYNC_SNAPSHOT_RSP:
1,625✔
271
      code = syncNodeOnSnapshotRsp(pSyncNode, pMsg);
1,625✔
272
      break;
1,625✔
273
    case TDMT_SYNC_LOCAL_CMD:
62,980✔
274
      code = syncNodeOnLocalCmd(pSyncNode, pMsg);
62,980✔
275
      break;
62,980✔
276
    case TDMT_SYNC_FORCE_FOLLOWER:
17✔
277
      code = syncForceBecomeFollower(pSyncNode, pMsg);
17✔
278
      break;
17✔
279
    case TDMT_SYNC_SET_ASSIGNED_LEADER:
2✔
280
      code = syncBecomeAssignedLeader(pSyncNode, pMsg);
2✔
281
      break;
2✔
282
    default:
×
283
      code = TSDB_CODE_MSG_NOT_PROCESSED;
×
284
  }
285

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

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

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

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

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

320
  return 0;
17✔
321
}
322

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

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

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

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

343
  if (!req.force) {
2✔
344
    if (strncmp(req.memberToken, ths->arbToken, TSDB_ARB_TOKEN_SIZE) != 0) {
1!
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

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

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

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

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

390
  code = TSDB_CODE_SUCCESS;
2✔
391

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

400
  tmsgSendRsp(&rspMsg);
2✔
401

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

433
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
201,314✔
434
    SyncIndex matchIndex = syncIndexMgrGetIndex(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
133,956✔
435
    if (minMatchIndex == SYNC_INDEX_INVALID) {
133,956✔
436
      minMatchIndex = matchIndex;
71,283✔
437
    } else if (matchIndex > 0 && matchIndex < minMatchIndex) {
62,673✔
438
      minMatchIndex = matchIndex;
1,204✔
439
    }
440
  }
441
  return minMatchIndex;
67,358✔
442
}
443

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

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

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

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

468
  int64_t logRetention = 0;
25,893✔
469

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

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

493
_DEL_WAL:
24,575✔
494

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

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

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

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

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

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

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

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

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

562
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
2,864,567✔
563
    terrno = TSDB_CODE_SYN_NOT_LEADER;
73,378✔
564
    return false;
73,378✔
565
  }
566

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

572
  return true;
2,790,808✔
573
}
574

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

582
  bool ready = syncNodeIsReadyForRead(pSyncNode);
2,590,244✔
583

584
  syncNodeRelease(pSyncNode);
2,590,409✔
585
  return ready;
2,589,967✔
586
}
587

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

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

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

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

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

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

631
  return ret;
3,821✔
632
}
633

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

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

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

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

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

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

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

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

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

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

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

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

758
  syncNodeRelease(pSyncNode);
46,995✔
759
  TAOS_RETURN(code);
46,995✔
760
}
761

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

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

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

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

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

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

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

811
  for (int32_t i = 0; i < pSyncNode->raftCfg.configIndexCount; ++i) {
1,205,251✔
812
    if ((pSyncNode->raftCfg.configIndexArr)[i] > lastIndex &&
624,858✔
813
        (pSyncNode->raftCfg.configIndexArr)[i] <= snapshotLastApplyIndex) {
44,466✔
814
      lastIndex = (pSyncNode->raftCfg.configIndexArr)[i];
44,307✔
815
    }
816
  }
817
  sTrace("vgId:%d, index:%" PRId64 ", get last snapshot config index:%" PRId64, pSyncNode->vgId, snapshotLastApplyIndex,
580,393✔
818
         lastIndex);
819

820
  return lastIndex;
580,393✔
821
}
822

823
static SRaftId syncGetRaftIdByEp(SSyncNode* pSyncNode, const SEp* pEp) {
174,361✔
824
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
296,525✔
825
    if (strcmp(pEp->fqdn, (pSyncNode->peersNodeInfo)[i].nodeFqdn) == 0 &&
201,575✔
826
        pEp->port == (pSyncNode->peersNodeInfo)[i].nodePort) {
201,556✔
827
      return pSyncNode->peersId[i];
79,411✔
828
    }
829
  }
830
  return EMPTY_RAFT_ID;
94,950✔
831
}
832

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

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

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

848
  if (offset < bufferSize) {
95,062!
849
    snprintf(buffer + offset, bufferSize - offset, "]");
95,064✔
850
  }
851
}
852

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

856
  SSyncNode* pSyncNode = syncNodeAcquire(rid);
95,066✔
857
  if (pSyncNode == NULL) return;
95,071!
858

859
  int index = -1;
95,071✔
860

861
  sDebug("vgId:%d, sync get retry epset, leaderCache:%" PRIx64 ", leaderCacheEp.fqdn:%s, leaderCacheEp.port:%d",
95,071✔
862
         pSyncNode->vgId, pSyncNode->leaderCache.addr, pSyncNode->leaderCacheEp.fqdn, pSyncNode->leaderCacheEp.port);
863
  int j = 0;
95,071✔
864
  for (int32_t i = 0; i < pSyncNode->raftCfg.cfg.totalReplicaNum; ++i) {
270,727✔
865
    if (pSyncNode->raftCfg.cfg.nodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) continue;
175,643✔
866
    SEp* pEp = &pEpSet->eps[j];
174,372✔
867
    tstrncpy(pEp->fqdn, pSyncNode->raftCfg.cfg.nodeInfo[i].nodeFqdn, TSDB_FQDN_LEN);
174,372✔
868
    pEp->port = (pSyncNode->raftCfg.cfg.nodeInfo)[i].nodePort;
174,372✔
869
    pEpSet->numOfEps++;
174,372✔
870
    SRaftId id = syncGetRaftIdByEp(pSyncNode, pEp);
174,372✔
871
    sDebug("vgId:%d, sync get retry epset, index:%d id:%" PRIx64 " %s:%d", pSyncNode->vgId, i, id.addr, pEp->fqdn,
174,379✔
872
           pEp->port);
873
    if (pEp->port == pSyncNode->leaderCacheEp.port &&
174,385✔
874
        strncmp(pEp->fqdn, pSyncNode->leaderCacheEp.fqdn, TSDB_FQDN_LEN) == 0 /*&&
65,578✔
875
        id.vgId == pSyncNode->leaderCache.vgId && id.addr != 0 && id.vgId != 0*/) {
876
      index = j;
65,574✔
877
    }
878
    j++;
174,385✔
879
  }
880
  if (pEpSet->numOfEps > 0) {
95,084✔
881
    if (index != -1) {
95,069✔
882
      pEpSet->inUse = index;
65,578✔
883
    } else {
884
      if (pSyncNode->myRaftId.addr == pSyncNode->leaderCache.addr &&
29,491!
885
          pSyncNode->myRaftId.vgId == pSyncNode->leaderCache.vgId) {
×
886
        pEpSet->inUse = pSyncNode->raftCfg.cfg.myIndex;
×
887
      } else {
888
        pEpSet->inUse = (pSyncNode->raftCfg.cfg.myIndex + 1) % pEpSet->numOfEps;
29,491✔
889
      }
890
    }
891
    // pEpSet->inUse = 0;
892
  }
893
  epsetSort(pEpSet);
95,084✔
894

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

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

912
  int32_t ret = syncNodePropose(pSyncNode, pMsg, isWeak, seq);
1,971,893✔
913
  syncNodeRelease(pSyncNode);
1,971,776✔
914
  return ret;
1,971,864✔
915
}
916

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

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

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

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

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

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

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

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

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

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

992
  syncNodeRelease(pSyncNode);
18,681✔
993
  return term;
18,681✔
994
}
995

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

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

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

1019
  // optimized one replica
1020
  if (syncNodeIsOptimizedOneReplica(pSyncNode, pMsg)) {
1,970,699✔
1021
    SyncIndex retIndex;
1022
    int32_t   code = syncNodeOnClientRequest(pSyncNode, pMsg, &retIndex);
1,777,746✔
1023
    if (code >= 0) {
1,777,629!
1024
      pMsg->info.conn.applyIndex = retIndex;
1,777,644✔
1025
      pMsg->info.conn.applyTerm = raftStoreGetTerm(pSyncNode);
1,777,644✔
1026

1027
      // after raft member change, need to handle 1->2 switching point
1028
      // at this point, need to switch entry handling thread
1029
      if (pSyncNode->replicaNum == 1) {
1,777,725✔
1030
        sGDebug(&pMsg->info.traceId, "vgId:%d, index:%" PRId64 ", propose optimized msg type:%s", pSyncNode->vgId,
1,777,720!
1031
                retIndex, TMSG_INFO(pMsg->msgType));
1032
        return 1;
1,777,673✔
1033
      } else {
1034
        sGDebug(&pMsg->info.traceId,
5!
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};
192,953✔
1047
    uint64_t  seqNum = syncRespMgrAdd(pSyncNode->pSyncRespMgr, &stub);
192,954✔
1048
    SRpcMsg   rpcMsg = {.info.traceId = pMsg->info.traceId};
192,954✔
1049
    int32_t   code = syncBuildClientRequest(&rpcMsg, pMsg, seqNum, isWeak, pSyncNode->vgId);
192,954✔
1050
    if (code != 0) {
192,954!
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,
192,954!
1057
            TMSG_INFO(pMsg->msgType));
1058
    code = (*pSyncNode->syncEqMsg)(pSyncNode->msgcb, &rpcMsg);
192,954✔
1059
    if (code != 0) {
192,954✔
1060
      sWarn("vgId:%d, failed to propose msg while enqueue since %s", pSyncNode->vgId, terrstr());
1,569!
1061
      TAOS_CHECK_RETURN(syncRespMgrDel(pSyncNode->pSyncRespMgr, seqNum));
1,569✔
1062
    }
1063

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1307
  // init life cycle outside
1308

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1452
  // snapshot senders
1453
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
229,302✔
1454
    SSyncSnapshotSender* pSender = NULL;
214,956✔
1455
    code = snapshotSenderCreate(pSyncNode, i, &pSender);
214,956✔
1456
    if (pSender == NULL) return NULL;
214,965!
1457

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1747
  raftStoreClose(pSyncNode);
14,337✔
1748

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

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

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

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

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

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

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

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

1807
  return code;
334,408✔
1808
}
1809

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

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

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

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

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

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

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

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

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

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

1867
  return ret;
13,517✔
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) {
36,142✔
1884
  int32_t code = 0;
36,142✔
1885

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

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

1900
  return code;
36,142✔
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) {
633,404✔
1916
  SEpSet* epSet = NULL;
633,404✔
1917
  for (int32_t i = 0; i < pNode->peersNum; ++i) {
950,295✔
1918
    if (destRaftId->addr == pNode->peersId[i].addr) {
950,209✔
1919
      epSet = &pNode->peersEpset[i];
633,318✔
1920
      break;
633,318✔
1921
    }
1922
  }
1923

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

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

1937
  TAOS_RETURN(code);
633,411✔
1938
}
1939

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

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

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

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

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

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

1982
  return false;
1,520✔
1983
}
1984

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

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

1996
  pSyncNode->configChangeNum++;
278✔
1997

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2088
    // reset snapshot senders
2089

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

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

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

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

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

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

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

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

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

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

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

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

2183
  if (currentTerm < newTerm) {
224,424✔
2184
    raftStoreSetTerm(pSyncNode, newTerm);
2,466✔
2185
    char tmpBuf[64];
2186
    snprintf(tmpBuf, sizeof(tmpBuf), "step down, update term to %" PRId64, newTerm);
2,466✔
2187
    syncNodeBecomeFollower(pSyncNode, id, tmpBuf);
2,466✔
2188
    raftStoreClearVote(pSyncNode);
2,466✔
2189
  } else {
2190
    if (pSyncNode->state != TAOS_SYNC_STATE_FOLLOWER) {
221,958✔
2191
      syncNodeBecomeFollower(pSyncNode, id, "step down");
5✔
2192
    }
2193
  }
2194
}
2195

2196
void syncNodeLeaderChangeRsp(SSyncNode* pSyncNode) { syncRespCleanRsp(pSyncNode->pSyncRespMgr); }
5,853✔
2197

2198
void syncNodeBecomeFollower(SSyncNode* pSyncNode, SRaftId leaderId, const char* debugStr) {
5,853✔
2199
  int32_t code = 0;  // maybe clear leader cache
5,853✔
2200
  if (pSyncNode->state == TAOS_SYNC_STATE_LEADER) {
5,853✔
2201
    pSyncNode->leaderCache = EMPTY_RAFT_ID;
30✔
2202
    pSyncNode->leaderCacheEp.port = 0;
30✔
2203
    pSyncNode->leaderCacheEp.fqdn[0] = '\0';
30✔
2204
  }
2205

2206
  pSyncNode->hbSlowNum = 0;
5,853✔
2207

2208
  pSyncNode->leaderCache = leaderId;  // state change
5,853✔
2209

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

2224
  // trace log
2225
  sNTrace(pSyncNode, "become follower %s", debugStr);
5,853!
2226

2227
  // send rsp to client
2228
  syncNodeLeaderChangeRsp(pSyncNode);
5,853✔
2229

2230
  // call back
2231
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeFollowerCb != NULL) {
5,853!
2232
    pSyncNode->pFsm->FpBecomeFollowerCb(pSyncNode->pFsm);
5,853✔
2233
  }
2234

2235
  // min match index
2236
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
5,853✔
2237

2238
  // reset log buffer
2239
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
5,853!
2240
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2241
    return;
×
2242
  }
2243

2244
  // reset elect timer
2245
  syncNodeResetElectTimer(pSyncNode);
5,853✔
2246

2247
  sInfo("vgId:%d, become follower. %s", pSyncNode->vgId, debugStr);
5,853!
2248
}
2249

2250
void syncNodeBecomeLearner(SSyncNode* pSyncNode, const char* debugStr) {
291✔
2251
  pSyncNode->hbSlowNum = 0;
291✔
2252

2253
  // state change
2254
  pSyncNode->state = TAOS_SYNC_STATE_LEARNER;
291✔
2255
  pSyncNode->roleTimeMs = taosGetTimestampMs();
291✔
2256

2257
  // trace log
2258
  sNTrace(pSyncNode, "become learner %s", debugStr);
291!
2259

2260
  // call back
2261
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLearnerCb != NULL) {
291!
2262
    pSyncNode->pFsm->FpBecomeLearnerCb(pSyncNode->pFsm);
291✔
2263
  }
2264

2265
  // min match index
2266
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
291✔
2267

2268
  // reset log buffer
2269
  int32_t code = 0;
291✔
2270
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
291!
2271
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2272
    return;
×
2273
  };
2274
}
2275

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

2299
  // reset restoreFinish
2300
  pSyncNode->restoreFinish = false;
11,902✔
2301

2302
  // state change
2303
  pSyncNode->state = TAOS_SYNC_STATE_LEADER;
11,902✔
2304
  pSyncNode->roleTimeMs = taosGetTimestampMs();
11,902✔
2305

2306
  // set leader cache
2307
  pSyncNode->leaderCache = pSyncNode->myRaftId;
11,902✔
2308
  strncpy(pSyncNode->leaderCacheEp.fqdn, pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodeFqdn,
11,902✔
2309
          TSDB_FQDN_LEN);
2310
  pSyncNode->leaderCacheEp.port = pSyncNode->raftCfg.cfg.nodeInfo[pSyncNode->raftCfg.cfg.myIndex].nodePort;
11,902✔
2311

2312
  for (int32_t i = 0; i < pSyncNode->pNextIndex->replicaNum; ++i) {
26,188✔
2313
    SyncIndex lastIndex;
2314
    SyncTerm  lastTerm;
2315
    int32_t   code = syncNodeGetLastIndexTerm(pSyncNode, &lastIndex, &lastTerm);
14,286✔
2316
    if (code != 0) {
14,286!
2317
      sError("vgId:%d, failed to become leader since %s", pSyncNode->vgId, tstrerror(code));
×
2318
      return;
×
2319
    }
2320
    pSyncNode->pNextIndex->index[i] = lastIndex + 1;
14,286✔
2321
  }
2322

2323
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
26,188✔
2324
    // maybe overwrite myself, no harm
2325
    // just do it!
2326
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
14,286✔
2327
  }
2328

2329
  // init peer mgr
2330
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
11,902!
2331
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2332
    return;
×
2333
  }
2334

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

2348
  // close receiver
2349
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
11,902!
2350
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2351
  }
2352

2353
  // stop elect timer
2354
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
11,902!
2355
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
2356
    return;
×
2357
  }
2358

2359
  // start heartbeat timer
2360
  if ((code = syncNodeStartHeartbeatTimer(pSyncNode)) != 0) {
11,902!
2361
    sError("vgId:%d, failed to start heartbeat timer since %s", pSyncNode->vgId, tstrerror(code));
×
2362
    return;
×
2363
  }
2364

2365
  // send heartbeat right now
2366
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
11,902!
2367
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2368
    return;
×
2369
  }
2370

2371
  // call back
2372
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeLeaderCb != NULL) {
11,902!
2373
    pSyncNode->pFsm->FpBecomeLeaderCb(pSyncNode->pFsm);
11,902✔
2374
  }
2375

2376
  // min match index
2377
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
11,902✔
2378

2379
  // reset log buffer
2380
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
11,902!
2381
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2382
    return;
×
2383
  }
2384

2385
  // trace log
2386
  sNInfo(pSyncNode, "become leader %s", debugStr);
11,902✔
2387
}
2388

2389
void syncNodeBecomeAssignedLeader(SSyncNode* pSyncNode) {
2✔
2390
  int32_t code = 0;
2✔
2391
  pSyncNode->becomeAssignedLeaderNum++;
2✔
2392
  pSyncNode->hbrSlowNum = 0;
2✔
2393

2394
  // reset restoreFinish
2395
  // pSyncNode->restoreFinish = false;
2396

2397
  // state change
2398
  pSyncNode->state = TAOS_SYNC_STATE_ASSIGNED_LEADER;
2✔
2399
  pSyncNode->roleTimeMs = taosGetTimestampMs();
2✔
2400

2401
  // set leader cache
2402
  pSyncNode->leaderCache = pSyncNode->myRaftId;
2✔
2403

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

2415
  for (int32_t i = 0; i < pSyncNode->pMatchIndex->replicaNum; ++i) {
6✔
2416
    // maybe overwrite myself, no harm
2417
    // just do it!
2418
    pSyncNode->pMatchIndex->index[i] = SYNC_INDEX_INVALID;
4✔
2419
  }
2420

2421
  // init peer mgr
2422
  if ((code = syncNodePeerStateInit(pSyncNode)) != 0) {
2!
2423
    sError("vgId:%d, failed to init peer state since %s", pSyncNode->vgId, tstrerror(code));
×
2424
    return;
×
2425
  }
2426

2427
  // close receiver
2428
  if (snapshotReceiverIsStart(pSyncNode->pNewNodeReceiver)) {
2!
2429
    snapshotReceiverStop(pSyncNode->pNewNodeReceiver);
×
2430
  }
2431

2432
  // stop elect timer
2433
  if ((code = syncNodeStopElectTimer(pSyncNode)) != 0) {
2!
2434
    sError("vgId:%d, failed to stop elect timer since %s", pSyncNode->vgId, tstrerror(code));
×
2435
    return;
×
2436
  }
2437

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

2444
  // send heartbeat right now
2445
  if ((code = syncNodeHeartbeatPeers(pSyncNode)) != 0) {
2!
2446
    sError("vgId:%d, failed to send heartbeat to peers since %s", pSyncNode->vgId, tstrerror(code));
×
2447
    return;
×
2448
  }
2449

2450
  // call back
2451
  if (pSyncNode->pFsm != NULL && pSyncNode->pFsm->FpBecomeAssignedLeaderCb != NULL) {
2!
2452
    pSyncNode->pFsm->FpBecomeAssignedLeaderCb(pSyncNode->pFsm);
2✔
2453
  }
2454

2455
  // min match index
2456
  pSyncNode->minMatchIndex = SYNC_INDEX_INVALID;
2✔
2457

2458
  // reset log buffer
2459
  if ((code = syncLogBufferReset(pSyncNode->pLogBuf, pSyncNode)) != 0) {
2!
2460
    sError("vgId:%d, failed to reset log buffer since %s", pSyncNode->vgId, tstrerror(code));
×
2461
    return;
×
2462
  }
2463

2464
  // trace log
2465
  sNInfo(pSyncNode, "become assigned leader");
2!
2466
}
2467

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

2480
  sNTrace(pSyncNode, "state change syncNodeCandidate2Leader");
1,220!
2481

2482
  int32_t ret = syncNodeAppendNoop(pSyncNode);
1,220✔
2483
  if (ret < 0) {
1,220!
2484
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, terrstr());
×
2485
  }
2486

2487
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
1,220✔
2488

2489
  sInfo("vgId:%d, become leader. term:%" PRId64 ", commit index:%" PRId64 ", last index:%" PRId64, pSyncNode->vgId,
1,220!
2490
        raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, lastIndex);
2491
}
2492

2493
bool syncNodeIsMnode(SSyncNode* pSyncNode) { return (pSyncNode->vgId == 1); }
148,516✔
2494

2495
int32_t syncNodePeerStateInit(SSyncNode* pSyncNode) {
26,240✔
2496
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
419,810✔
2497
    pSyncNode->peerStates[i].lastSendIndex = SYNC_INDEX_INVALID;
393,570✔
2498
    pSyncNode->peerStates[i].lastSendTime = 0;
393,570✔
2499
  }
2500

2501
  return 0;
26,240✔
2502
}
2503

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

2515
  sNTrace(pSyncNode, "follower to candidate");
1,307!
2516
}
2517

2518
int32_t syncNodeAssignedLeader2Leader(SSyncNode* pSyncNode) {
×
2519
  if (pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) return TSDB_CODE_SYN_INTERNAL_ERROR;
×
2520
  syncNodeBecomeLeader(pSyncNode, "assigned leader to leader");
×
2521

2522
  sNTrace(pSyncNode, "assigned leader to leader");
×
2523

2524
  int32_t ret = syncNodeAppendNoop(pSyncNode);
×
2525
  if (ret < 0) {
×
2526
    sError("vgId:%d, failed to append noop entry since %s", pSyncNode->vgId, tstrerror(ret));
×
2527
  }
2528

2529
  SyncIndex lastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
×
2530
  sInfo("vgId:%d, become leader from assigned leader. term:%" PRId64 ", commit index:%" PRId64
×
2531
        "assigned commit index:%" PRId64 ", last index:%" PRId64,
2532
        pSyncNode->vgId, raftStoreGetTerm(pSyncNode), pSyncNode->commitIndex, pSyncNode->assignedCommitIndex,
2533
        lastIndex);
2534
  return 0;
×
2535
}
2536

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

2551
  raftStoreVote(pSyncNode, pRaftId);
1,361✔
2552
}
2553

2554
// simulate get vote from outside
2555
void syncNodeVoteForSelf(SSyncNode* pSyncNode, SyncTerm currentTerm) {
1,361✔
2556
  syncNodeVoteForTerm(pSyncNode, currentTerm, &pSyncNode->myRaftId);
1,361✔
2557

2558
  SRpcMsg rpcMsg = {0};
1,361✔
2559
  int32_t ret = syncBuildRequestVoteReply(&rpcMsg, pSyncNode->vgId);
1,361✔
2560
  if (ret != 0) return;
1,361!
2561

2562
  SyncRequestVoteReply* pMsg = rpcMsg.pCont;
1,361✔
2563
  pMsg->srcId = pSyncNode->myRaftId;
1,361✔
2564
  pMsg->destId = pSyncNode->myRaftId;
1,361✔
2565
  pMsg->term = currentTerm;
1,361✔
2566
  pMsg->voteGranted = true;
1,361✔
2567

2568
  voteGrantedVote(pSyncNode->pVotesGranted, pMsg);
1,361✔
2569
  votesRespondAdd(pSyncNode->pVotesRespond, pMsg);
1,361✔
2570
  rpcFreeCont(rpcMsg.pCont);
1,361✔
2571
}
2572

2573
// return if has a snapshot
2574
bool syncNodeHasSnapshot(SSyncNode* pSyncNode) {
19,325✔
2575
  bool      ret = false;
19,325✔
2576
  SSnapshot snapshot = {.data = NULL, .lastApplyIndex = -1, .lastApplyTerm = 0, .lastConfigIndex = -1};
19,325✔
2577
  if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
19,325!
2578
    // TODO check return value
2579
    (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
19,325✔
2580
    if (snapshot.lastApplyIndex >= SYNC_INDEX_BEGIN) {
19,325✔
2581
      ret = true;
2,582✔
2582
    }
2583
  }
2584
  return ret;
19,325✔
2585
}
2586

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

2597
  SyncIndex lastIndex = logLastIndex > snapshot.lastApplyIndex ? logLastIndex : snapshot.lastApplyIndex;
19,379✔
2598
  return lastIndex;
19,379✔
2599
}
2600

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

2613
    SyncIndex logLastIndex = pSyncNode->pLogStore->syncLogLastIndex(pSyncNode->pLogStore);
2,582✔
2614
    if (logLastIndex > snapshot.lastApplyIndex) {
2,582✔
2615
      lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
1,495✔
2616
    } else {
2617
      lastTerm = snapshot.lastApplyTerm;
1,087✔
2618
    }
2619

2620
  } else {
2621
    // no snapshot
2622
    lastTerm = pSyncNode->pLogStore->syncLogLastTerm(pSyncNode->pLogStore);
16,743✔
2623
  }
2624

2625
  return lastTerm;
19,325✔
2626
}
2627

2628
// get last index and term along with snapshot
2629
int32_t syncNodeGetLastIndexTerm(SSyncNode* pSyncNode, SyncIndex* pLastIndex, SyncTerm* pLastTerm) {
16,875✔
2630
  *pLastIndex = syncNodeGetLastIndex(pSyncNode);
16,875✔
2631
  *pLastTerm = syncNodeGetLastTerm(pSyncNode);
16,875✔
2632
  return 0;
16,875✔
2633
}
2634

2635
#ifdef BUILD_NO_CALL
2636
// return append-entries first try index
2637
SyncIndex syncNodeSyncStartIndex(SSyncNode* pSyncNode) {
2638
  SyncIndex syncStartIndex = syncNodeGetLastIndex(pSyncNode) + 1;
2639
  return syncStartIndex;
2640
}
2641

2642
// if index > 0, return index - 1
2643
// else, return -1
2644
SyncIndex syncNodeGetPreIndex(SSyncNode* pSyncNode, SyncIndex index) {
2645
  SyncIndex preIndex = index - 1;
2646
  if (preIndex < SYNC_INDEX_INVALID) {
2647
    preIndex = SYNC_INDEX_INVALID;
2648
  }
2649

2650
  return preIndex;
2651
}
2652

2653
// if index < 0, return SYNC_TERM_INVALID
2654
// if index == 0, return 0
2655
// if index > 0, return preTerm
2656
// if error, return SYNC_TERM_INVALID
2657
SyncTerm syncNodeGetPreTerm(SSyncNode* pSyncNode, SyncIndex index) {
2658
  if (index < SYNC_INDEX_BEGIN) {
2659
    return SYNC_TERM_INVALID;
2660
  }
2661

2662
  if (index == SYNC_INDEX_BEGIN) {
2663
    return 0;
2664
  }
2665

2666
  SyncTerm  preTerm = 0;
2667
  SyncIndex preIndex = index - 1;
2668

2669
  SSyncRaftEntry* pPreEntry = NULL;
2670
  SLRUCache*      pCache = pSyncNode->pLogStore->pCache;
2671
  LRUHandle*      h = taosLRUCacheLookup(pCache, &preIndex, sizeof(preIndex));
2672
  int32_t         code = 0;
2673
  if (h) {
2674
    pPreEntry = (SSyncRaftEntry*)taosLRUCacheValue(pCache, h);
2675
    code = 0;
2676

2677
    pSyncNode->pLogStore->cacheHit++;
2678
    sNTrace(pSyncNode, "hit cache index:%" PRId64 ", bytes:%u, %p", preIndex, pPreEntry->bytes, pPreEntry);
2679

2680
  } else {
2681
    pSyncNode->pLogStore->cacheMiss++;
2682
    sNTrace(pSyncNode, "miss cache index:%" PRId64, preIndex);
2683

2684
    code = pSyncNode->pLogStore->syncLogGetEntry(pSyncNode->pLogStore, preIndex, &pPreEntry);
2685
  }
2686

2687
  SSnapshot snapshot = {.data = NULL,
2688
                        .lastApplyIndex = SYNC_INDEX_INVALID,
2689
                        .lastApplyTerm = SYNC_TERM_INVALID,
2690
                        .lastConfigIndex = SYNC_INDEX_INVALID};
2691

2692
  if (code == 0) {
2693
    if (pPreEntry == NULL) return -1;
2694
    preTerm = pPreEntry->term;
2695

2696
    if (h) {
2697
      taosLRUCacheRelease(pCache, h, false);
2698
    } else {
2699
      syncEntryDestroy(pPreEntry);
2700
    }
2701

2702
    return preTerm;
2703
  } else {
2704
    if (pSyncNode->pFsm->FpGetSnapshotInfo != NULL) {
2705
      // TODO check return value
2706
      (void)pSyncNode->pFsm->FpGetSnapshotInfo(pSyncNode->pFsm, &snapshot);
2707
      if (snapshot.lastApplyIndex == preIndex) {
2708
        return snapshot.lastApplyTerm;
2709
      }
2710
    }
2711
  }
2712

2713
  sNError(pSyncNode, "sync node get pre term error, index:%" PRId64 ", snap-index:%" PRId64 ", snap-term:%" PRId64,
2714
          index, snapshot.lastApplyIndex, snapshot.lastApplyTerm);
2715
  return SYNC_TERM_INVALID;
2716
}
2717

2718
// get pre index and term of "index"
2719
int32_t syncNodeGetPreIndexTerm(SSyncNode* pSyncNode, SyncIndex index, SyncIndex* pPreIndex, SyncTerm* pPreTerm) {
2720
  *pPreIndex = syncNodeGetPreIndex(pSyncNode, index);
2721
  *pPreTerm = syncNodeGetPreTerm(pSyncNode, index);
2722
  return 0;
2723
}
2724
#endif
2725

2726
static void syncNodeEqPingTimer(void* param, void* tmrId) {
61,225✔
2727
  if (!syncIsInit()) return;
61,225!
2728

2729
  int64_t    rid = (int64_t)param;
61,225✔
2730
  SSyncNode* pNode = syncNodeAcquire(rid);
61,225✔
2731

2732
  if (pNode == NULL) return;
61,225!
2733

2734
  if (atomic_load_64(&pNode->pingTimerLogicClockUser) <= atomic_load_64(&pNode->pingTimerLogicClock)) {
61,225!
2735
    SRpcMsg rpcMsg = {0};
61,225✔
2736
    int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_PING, atomic_load_64(&pNode->pingTimerLogicClock),
61,225✔
2737
                                    pNode->pingTimerMS, pNode);
2738
    if (code != 0) {
61,225!
2739
      sError("failed to build ping msg");
×
2740
      rpcFreeCont(rpcMsg.pCont);
×
2741
      goto _out;
×
2742
    }
2743

2744
    // sTrace("enqueue ping msg");
2745
    code = pNode->syncEqMsg(pNode->msgcb, &rpcMsg);
61,225✔
2746
    if (code != 0) {
61,225✔
2747
      sError("failed to sync enqueue ping msg since %s", terrstr());
1!
2748
      rpcFreeCont(rpcMsg.pCont);
1✔
2749
      goto _out;
1✔
2750
    }
2751

2752
  _out:
61,224✔
2753
    if (taosTmrReset(syncNodeEqPingTimer, pNode->pingTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
61,225!
2754
                     &pNode->pPingTimer))
2755
      sError("failed to reset ping timer");
×
2756
  }
2757
  syncNodeRelease(pNode);
61,225✔
2758
}
2759

2760
static void syncNodeEqElectTimer(void* param, void* tmrId) {
1,364✔
2761
  if (!syncIsInit()) return;
1,367!
2762

2763
  int64_t    rid = (int64_t)param;
1,364✔
2764
  SSyncNode* pNode = syncNodeAcquire(rid);
1,364✔
2765

2766
  if (pNode == NULL) return;
1,364✔
2767

2768
  if (pNode->syncEqMsg == NULL) {
1,363!
2769
    syncNodeRelease(pNode);
×
2770
    return;
×
2771
  }
2772

2773
  int64_t tsNow = taosGetTimestampMs();
1,363✔
2774
  if (tsNow < pNode->electTimerParam.executeTime) {
1,363✔
2775
    syncNodeRelease(pNode);
2✔
2776
    return;
2✔
2777
  }
2778

2779
  SRpcMsg rpcMsg = {0};
1,361✔
2780
  int32_t code =
2781
      syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_ELECTION, pNode->electTimerParam.logicClock, pNode->electTimerMS, pNode);
1,361✔
2782

2783
  if (code != 0) {
1,361!
2784
    sError("failed to build elect msg");
×
2785
    syncNodeRelease(pNode);
×
2786
    return;
×
2787
  }
2788

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

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

2800
  syncNodeRelease(pNode);
1,361✔
2801
}
2802

2803
#ifdef BUILD_NO_CALL
2804
static void syncNodeEqHeartbeatTimer(void* param, void* tmrId) {
2805
  if (!syncIsInit()) return;
2806

2807
  int64_t    rid = (int64_t)param;
2808
  SSyncNode* pNode = syncNodeAcquire(rid);
2809

2810
  if (pNode == NULL) return;
2811

2812
  if (pNode->totalReplicaNum > 1) {
2813
    if (atomic_load_64(&pNode->heartbeatTimerLogicClockUser) <= atomic_load_64(&pNode->heartbeatTimerLogicClock)) {
2814
      SRpcMsg rpcMsg = {0};
2815
      int32_t code = syncBuildTimeout(&rpcMsg, SYNC_TIMEOUT_HEARTBEAT, atomic_load_64(&pNode->heartbeatTimerLogicClock),
2816
                                      pNode->heartbeatTimerMS, pNode);
2817

2818
      if (code != 0) {
2819
        sError("failed to build heartbeat msg");
2820
        goto _out;
2821
      }
2822

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

2831
    _out:
2832
      if (taosTmrReset(syncNodeEqHeartbeatTimer, pNode->heartbeatTimerMS, (void*)pNode->rid, syncEnv()->pTimerManager,
2833
                       &pNode->pHeartbeatTimer) != 0)
2834
        return;
2835

2836
    } else {
2837
      sTrace("==syncNodeEqHeartbeatTimer== heartbeatTimerLogicClock:%" PRId64 ", heartbeatTimerLogicClockUser:%" PRId64,
2838
             pNode->heartbeatTimerLogicClock, pNode->heartbeatTimerLogicClockUser);
2839
    }
2840
  }
2841
}
2842
#endif
2843

2844
static void syncNodeEqPeerHeartbeatTimer(void* param, void* tmrId) {
64,809✔
2845
  if (tsSyncLogHeartbeat) {
64,809!
2846
    sInfo("heartbeat timer start");
×
2847
  }
2848
  int32_t code = 0;
64,809✔
2849
  int64_t hbDataRid = (int64_t)param;
64,809✔
2850
  int64_t tsNow = taosGetTimestampMs();
64,809✔
2851

2852
  SSyncHbTimerData* pData = syncHbTimerDataAcquire(hbDataRid);
64,809✔
2853
  if (pData == NULL) {
64,809✔
2854
    sError("hb timer get pData NULL, %" PRId64, hbDataRid);
1!
2855
    return;
1✔
2856
  }
2857

2858
  SSyncNode* pSyncNode = syncNodeAcquire(pData->syncNodeRid);
64,808✔
2859
  if (pSyncNode == NULL) {
64,808✔
2860
    syncHbTimerDataRelease(pData);
1✔
2861
    sError("hb timer get pSyncNode NULL");
1!
2862
    return;
1✔
2863
  }
2864

2865
  SSyncTimer* pSyncTimer = pData->pTimer;
64,807✔
2866

2867
  if (!pSyncNode->isStart) {
64,807!
2868
    syncNodeRelease(pSyncNode);
×
2869
    syncHbTimerDataRelease(pData);
×
2870
    sError("vgId:%d, hb timer sync node already stop", pSyncNode->vgId);
×
2871
    return;
×
2872
  }
2873

2874
  if (pSyncNode->state != TAOS_SYNC_STATE_LEADER && pSyncNode->state != TAOS_SYNC_STATE_ASSIGNED_LEADER) {
64,807!
2875
    syncNodeRelease(pSyncNode);
×
2876
    syncHbTimerDataRelease(pData);
×
2877
    sError("vgId:%d, hb timer sync node not leader", pSyncNode->vgId);
×
2878
    return;
×
2879
  }
2880

2881
  if (tsSyncLogHeartbeat) {
64,807!
2882
    sInfo("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
×
2883
          pData->destId.addr);
2884
  } else {
2885
    sTrace("vgId:%d, peer hb timer execution, rid:%" PRId64 " addr:0x%" PRIx64, pSyncNode->vgId, hbDataRid,
64,807!
2886
           pData->destId.addr);
2887
  }
2888

2889
  if (pSyncNode->totalReplicaNum > 1) {
64,807✔
2890
    int64_t timerLogicClock = atomic_load_64(&pSyncTimer->logicClock);
64,805✔
2891
    int64_t msgLogicClock = atomic_load_64(&pData->logicClock);
64,805✔
2892

2893
    if (timerLogicClock == msgLogicClock) {
64,805✔
2894
      if (tsNow > pData->execTime) {
64,802✔
2895
        pData->execTime += pSyncTimer->timerMS;
64,778✔
2896

2897
        SRpcMsg rpcMsg = {0};
64,778✔
2898
        if ((code = syncBuildHeartbeat(&rpcMsg, pSyncNode->vgId)) != 0) {
64,778!
2899
          sError("vgId:%d, failed to build heartbeat msg since %s", pSyncNode->vgId, tstrerror(code));
×
2900
          syncNodeRelease(pSyncNode);
×
2901
          syncHbTimerDataRelease(pData);
×
2902
          return;
×
2903
        }
2904

2905
        pSyncNode->minMatchIndex = syncMinMatchIndex(pSyncNode);
64,778✔
2906

2907
        SyncHeartbeat* pSyncMsg = rpcMsg.pCont;
64,778✔
2908
        pSyncMsg->srcId = pSyncNode->myRaftId;
64,778✔
2909
        pSyncMsg->destId = pData->destId;
64,778✔
2910
        pSyncMsg->term = raftStoreGetTerm(pSyncNode);
64,778✔
2911
        pSyncMsg->commitIndex = pSyncNode->commitIndex;
64,778✔
2912
        pSyncMsg->minMatchIndex = pSyncNode->minMatchIndex;
64,778✔
2913
        pSyncMsg->privateTerm = 0;
64,778✔
2914
        pSyncMsg->timeStamp = tsNow;
64,778✔
2915

2916
        // update reset time
2917
        int64_t timerElapsed = tsNow - pSyncTimer->timeStamp;
64,778✔
2918
        pSyncTimer->timeStamp = tsNow;
64,778✔
2919

2920
        // send msg
2921
        TRACE_SET_MSGID(&(rpcMsg.info.traceId), tGenIdPI64());
64,778✔
2922
        TRACE_SET_ROOTID(&(rpcMsg.info.traceId), tGenIdPI64());
64,778✔
2923
        syncLogSendHeartbeat(pSyncNode, pSyncMsg, false, timerElapsed, pData->execTime, &(rpcMsg.info.traceId));
64,778✔
2924
        int ret = syncNodeSendHeartbeat(pSyncNode, &pSyncMsg->destId, &rpcMsg);
64,778✔
2925
        if (ret != 0) {
64,778✔
2926
          sError("vgId:%d, failed to send heartbeat since %s", pSyncNode->vgId, tstrerror(ret));
93!
2927
        }
2928
      }
2929

2930
      if (syncIsInit()) {
64,802!
2931
        if (tsSyncLogHeartbeat) {
64,802!
2932
          sInfo("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
×
2933
        } else {
2934
          sTrace("vgId:%d, reset peer hb timer at %d", pSyncNode->vgId, pSyncTimer->timerMS);
64,802!
2935
        }
2936
        bool stopped = taosTmrResetPriority(syncNodeEqPeerHeartbeatTimer, pSyncTimer->timerMS, (void*)hbDataRid,
64,802✔
2937
                                            syncEnv()->pTimerManager, &pSyncTimer->pTimer, 2);
64,802✔
2938
        if (stopped) sError("vgId:%d, reset peer hb timer error, %s", pSyncNode->vgId, tstrerror(code));
64,802!
2939

2940
      } else {
2941
        sError("sync env is stop, reset peer hb timer error");
×
2942
      }
2943

2944
    } else {
2945
      sTrace("vgId:%d, do not send hb, timerLogicClock:%" PRId64 ", msgLogicClock:%" PRId64, pSyncNode->vgId,
3!
2946
             timerLogicClock, msgLogicClock);
2947
    }
2948

2949
    if (tsSyncLogHeartbeat) {
64,805!
2950
      sInfo("vgId:%d, finish send sync-heartbeat", pSyncNode->vgId);
×
2951
    }
2952
  }
2953

2954
  syncHbTimerDataRelease(pData);
64,807✔
2955
  syncNodeRelease(pSyncNode);
64,807✔
2956
  if (tsSyncLogHeartbeat) {
64,807!
2957
    sInfo("heartbeat timer stop");
×
2958
  }
2959
}
2960

2961
#ifdef BUILD_NO_CALL
2962
static void deleteCacheEntry(const void* key, size_t keyLen, void* value, void* ud) {
2963
  (void)ud;
2964
  taosMemoryFree(value);
2965
}
2966

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

2971
  int32_t   code = 0;
2972
  int32_t   entryLen = sizeof(*pEntry) + pEntry->dataLen;
2973
  LRUStatus status = taosLRUCacheInsert(pLogStore->pCache, &pEntry->index, sizeof(pEntry->index), pEntry, entryLen,
2974
                                        deleteCacheEntry, h, TAOS_LRU_PRIORITY_LOW, NULL);
2975
  if (status != TAOS_LRU_STATUS_OK) {
2976
    code = -1;
2977
  }
2978

2979
  return code;
2980
}
2981
#endif
2982

2983
void syncBuildConfigFromReq(SAlterVnodeReplicaReq* pReq, SSyncCfg* cfg) {  // TODO SAlterVnodeReplicaReq name is proper?
×
2984
  cfg->replicaNum = 0;
×
2985
  cfg->totalReplicaNum = 0;
×
2986
  int32_t code = 0;
×
2987

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

3020
int32_t syncNodeCheckChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry) {
×
3021
  int32_t code = 0;
×
3022
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3023
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3024
  }
3025

3026
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3027
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3028

3029
  SAlterVnodeTypeReq req = {0};
×
3030
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3031
    code = TSDB_CODE_INVALID_MSG;
×
3032
    TAOS_RETURN(code);
×
3033
  }
3034

3035
  SSyncCfg cfg = {0};
×
3036
  syncBuildConfigFromReq(&req, &cfg);
×
3037

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

3049
    if (!incfg) {
×
3050
      SyncTerm currentTerm = raftStoreGetTerm(ths);
×
3051
      SRaftId  id = EMPTY_RAFT_ID;
×
3052
      syncNodeStepDown(ths, currentTerm, id);
×
3053
      return 1;
×
3054
    }
3055
  }
3056
  return 0;
×
3057
}
3058

3059
void syncNodeLogConfigInfo(SSyncNode* ths, SSyncCfg* cfg, char* str) {
×
3060
  sInfo("vgId:%d, %s. SyncNode, replicaNum:%d, peersNum:%d, lastConfigIndex:%" PRId64
×
3061
        ", changeVersion:%d, "
3062
        "restoreFinish:%d",
3063
        ths->vgId, str, ths->replicaNum, ths->peersNum, ths->raftCfg.lastConfigIndex, ths->raftCfg.cfg.changeVersion,
3064
        ths->restoreFinish);
3065

3066
  sInfo("vgId:%d, %s, myNodeInfo, clusterId:0x%" PRIx64 ", nodeId:%d, Fqdn:%s, port:%d, role:%d", ths->vgId, str,
×
3067
        ths->myNodeInfo.clusterId, ths->myNodeInfo.nodeId, ths->myNodeInfo.nodeFqdn, ths->myNodeInfo.nodePort,
3068
        ths->myNodeInfo.nodeRole);
3069

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

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

3087
    sInfo("vgId:%d, %s, peersEpset%d, %s, inUse:%d", ths->vgId, str, i, buf, ths->peersEpset->inUse);
×
3088
  }
3089

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

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

3101
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3102
    sInfo("vgId:%d, %s, replicasId%d, addr:0x%" PRIx64, ths->vgId, str, i, ths->replicasId[i].addr);
×
3103
  }
3104
}
×
3105

3106
int32_t syncNodeRebuildPeerAndCfg(SSyncNode* ths, SSyncCfg* cfg) {
×
3107
  int32_t i = 0;
×
3108

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

3120
      syncUtilNodeInfo2EpSet(&ths->peersNodeInfo[i], &ths->peersEpset[i]);
×
3121

3122
      if (syncUtilNodeInfo2RaftId(&ths->peersNodeInfo[i], ths->vgId, &ths->peersId[i]) == false) {
×
3123
        sError("vgId:%d, failed to determine raft member id, peer:%d", ths->vgId, i);
×
3124
        return terrno;
×
3125
      }
3126

3127
      i++;
×
3128
    }
3129
  }
3130
  ths->peersNum = i;
×
3131

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

3152
  return 0;
×
3153
}
3154

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

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

3183
int32_t syncNodeRebuildAndCopyIfExist(SSyncNode* ths, int32_t oldtotalReplicaNum) {
×
3184
  int32_t code = 0;
×
3185
  // 1.rebuild replicasId, remove deleted one
3186
  SRaftId oldReplicasId[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA];
3187
  memcpy(oldReplicasId, ths->replicasId, sizeof(oldReplicasId));
×
3188

3189
  ths->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3190
  ths->totalReplicaNum = ths->raftCfg.cfg.totalReplicaNum;
×
3191
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3192
    if (syncUtilNodeInfo2RaftId(&ths->raftCfg.cfg.nodeInfo[i], ths->vgId, &ths->replicasId[i]) == false) return terrno;
×
3193
  }
3194

3195
  // 2.rebuild MatchIndex, remove deleted one
3196
  SSyncIndexMgr* oldIndex = ths->pMatchIndex;
×
3197

3198
  ths->pMatchIndex = syncIndexMgrCreate(ths);
×
3199
  if (ths->pMatchIndex == NULL) {
×
3200
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3201
    if (terrno != 0) code = terrno;
×
3202
    TAOS_RETURN(code);
×
3203
  }
3204

3205
  syncIndexMgrCopyIfExist(ths->pMatchIndex, oldIndex, oldReplicasId);
×
3206

3207
  syncIndexMgrDestroy(oldIndex);
×
3208

3209
  // 3.rebuild NextIndex, remove deleted one
3210
  SSyncIndexMgr* oldNextIndex = ths->pNextIndex;
×
3211

3212
  ths->pNextIndex = syncIndexMgrCreate(ths);
×
3213
  if (ths->pNextIndex == NULL) {
×
3214
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3215
    if (terrno != 0) code = terrno;
×
3216
    TAOS_RETURN(code);
×
3217
  }
3218

3219
  syncIndexMgrCopyIfExist(ths->pNextIndex, oldNextIndex, oldReplicasId);
×
3220

3221
  syncIndexMgrDestroy(oldNextIndex);
×
3222

3223
  // 4.rebuild pVotesGranted, pVotesRespond, no need to keep old vote state, only rebuild
3224
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3225
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3226

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

3234
  SSyncLogReplMgr* oldLogReplMgrs = NULL;
×
3235
  int64_t          length = sizeof(SSyncLogReplMgr) * (TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA);
×
3236
  oldLogReplMgrs = taosMemoryMalloc(length);
×
3237
  if (NULL == oldLogReplMgrs) return terrno;
×
3238
  memset(oldLogReplMgrs, 0, length);
×
3239

3240
  for (int i = 0; i < oldtotalReplicaNum; i++) {
×
3241
    oldLogReplMgrs[i] = *(ths->logReplMgrs[i]);
×
3242
  }
3243

3244
  syncNodeLogReplDestroy(ths);
×
3245
  if ((code = syncNodeLogReplInit(ths)) != 0) {
×
3246
    taosMemoryFree(oldLogReplMgrs);
×
3247
    TAOS_RETURN(code);
×
3248
  }
3249

3250
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3251
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3252
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3253
        *(ths->logReplMgrs[i]) = oldLogReplMgrs[j];
×
3254
        ths->logReplMgrs[i]->peerId = i;
×
3255
      }
3256
    }
3257
  }
3258

3259
  for (int i = 0; i < ths->totalReplicaNum; ++i) {
×
3260
    sDebug("vgId:%d, new logReplMgrs i:%d, peerId:%d, restoreed:%d, [%" PRId64 " %" PRId64 ", %" PRId64 ")", ths->vgId,
×
3261
           i, ths->logReplMgrs[i]->peerId, ths->logReplMgrs[i]->restored, ths->logReplMgrs[i]->startIndex,
3262
           ths->logReplMgrs[i]->matchIndex, ths->logReplMgrs[i]->endIndex);
3263
  }
3264

3265
  // 6.rebuild sender
3266
  for (int i = 0; i < oldtotalReplicaNum; ++i) {
×
3267
    sDebug("vgId:%d, old sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3268
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3269
  }
3270

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

3275
      if (snapshotSenderIsStart(ths->senders[i])) {
×
3276
        snapshotSenderStop(ths->senders[i], false);
×
3277
      }
3278

3279
      snapshotSenderDestroy(ths->senders[i]);
×
3280
      ths->senders[i] = NULL;
×
3281
    }
3282
  }
3283

3284
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3285
    SSyncSnapshotSender* pSender = NULL;
×
3286
    int32_t              code = snapshotSenderCreate(ths, i, &pSender);
×
3287
    if (pSender == NULL) return terrno = code;
×
3288

3289
    ths->senders[i] = pSender;
×
3290
    sSDebug(pSender, "snapshot sender create while open sync node, data:%p", pSender);
×
3291
  }
3292

3293
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3294
    sDebug("vgId:%d, new sender i:%d, replicaIndex:%d, lastSendTime:%" PRId64, ths->vgId, i,
×
3295
           ths->senders[i]->replicaIndex, ths->senders[i]->lastSendTime)
3296
  }
3297

3298
  // 7.rebuild synctimer
3299
  if ((code = syncNodeStopHeartbeatTimer(ths)) != 0) {
×
3300
    taosMemoryFree(oldLogReplMgrs);
×
3301
    TAOS_RETURN(code);
×
3302
  }
3303

3304
  for (int32_t i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; ++i) {
×
3305
    if ((code = syncHbTimerInit(ths, &ths->peerHeartbeatTimerArr[i], ths->replicasId[i])) != 0) {
×
3306
      taosMemoryFree(oldLogReplMgrs);
×
3307
      TAOS_RETURN(code);
×
3308
    }
3309
  }
3310

3311
  if ((code = syncNodeStartHeartbeatTimer(ths)) != 0) {
×
3312
    taosMemoryFree(oldLogReplMgrs);
×
3313
    TAOS_RETURN(code);
×
3314
  }
3315

3316
  // 8.rebuild peerStates
3317
  SPeerState oldState[TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA] = {0};
×
3318
  for (int i = 0; i < TSDB_MAX_REPLICA + TSDB_MAX_LEARNER_REPLICA; i++) {
×
3319
    oldState[i] = ths->peerStates[i];
×
3320
  }
3321

3322
  for (int i = 0; i < ths->totalReplicaNum; i++) {
×
3323
    for (int j = 0; j < oldtotalReplicaNum; j++) {
×
3324
      if (syncUtilSameId(&ths->replicasId[i], &oldReplicasId[j])) {
×
3325
        ths->peerStates[i] = oldState[j];
×
3326
      }
3327
    }
3328
  }
3329

3330
  taosMemoryFree(oldLogReplMgrs);
×
3331

3332
  return 0;
×
3333
}
3334

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

3343
  // pMatchIndex, pNextIndex, only need to change replicaNum when 1->3
3344
  ths->pMatchIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3345
  ths->pNextIndex->replicaNum = ths->raftCfg.cfg.replicaNum;
×
3346

3347
  sDebug("vgId:%d, pMatchIndex->totalReplicaNum:%d", ths->vgId, ths->pMatchIndex->totalReplicaNum);
×
3348
  for (int32_t i = 0; i < ths->pMatchIndex->totalReplicaNum; ++i) {
×
3349
    sDebug("vgId:%d, i:%d, match.index:%" PRId64, ths->vgId, i, ths->pMatchIndex->index[i]);
×
3350
  }
3351

3352
  // pVotesGranted, pVotesRespond
3353
  voteGrantedUpdate(ths->pVotesGranted, ths);
×
3354
  votesRespondUpdate(ths->pVotesRespond, ths);
×
3355

3356
  // logRepMgrs
3357
  // no need to change logRepMgrs when 1->3
3358
}
×
3359

3360
void syncNodeResetPeerAndCfg(SSyncNode* ths) {
×
3361
  SNodeInfo node = {0};
×
3362
  for (int32_t i = 0; i < ths->peersNum; ++i) {
×
3363
    memcpy(&ths->peersNodeInfo[i], &node, sizeof(SNodeInfo));
×
3364
  }
3365

3366
  for (int32_t i = 0; i < ths->raftCfg.cfg.totalReplicaNum; ++i) {
×
3367
    memcpy(&ths->raftCfg.cfg.nodeInfo[i], &node, sizeof(SNodeInfo));
×
3368
  }
3369
}
×
3370

3371
int32_t syncNodeChangeConfig(SSyncNode* ths, SSyncRaftEntry* pEntry, char* str) {
×
3372
  int32_t code = 0;
×
3373
  if (pEntry->originalRpcType != TDMT_SYNC_CONFIG_CHANGE) {
×
3374
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3375
  }
3376

3377
  SMsgHead* head = (SMsgHead*)pEntry->data;
×
3378
  void*     pReq = POINTER_SHIFT(head, sizeof(SMsgHead));
×
3379

3380
  SAlterVnodeTypeReq req = {0};
×
3381
  if (tDeserializeSAlterVnodeReplicaReq(pReq, head->contLen, &req) != 0) {
×
3382
    code = TSDB_CODE_INVALID_MSG;
×
3383
    TAOS_RETURN(code);
×
3384
  }
3385

3386
  SSyncCfg cfg = {0};
×
3387
  syncBuildConfigFromReq(&req, &cfg);
×
3388

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

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

3427
  syncNodeLogConfigInfo(ths, &cfg, "before config change");
×
3428

3429
  int32_t oldTotalReplicaNum = ths->totalReplicaNum;
×
3430

3431
  if (cfg.totalReplicaNum == 1 || cfg.totalReplicaNum == 2) {  // remove replica
×
3432

3433
    bool incfg = false;
×
3434
    for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3435
      if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3436
          ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3437
        incfg = true;
×
3438
        break;
×
3439
      }
3440
    }
3441

3442
    if (incfg) {  // remove other
×
3443
      syncNodeResetPeerAndCfg(ths);
×
3444

3445
      // no need to change myNodeInfo
3446

3447
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3448
        TAOS_RETURN(code);
×
3449
      };
3450

3451
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3452
        TAOS_RETURN(code);
×
3453
      };
3454
    } else {  // remove myself
3455
      // no need to do anything actually, to change the following to reduce distruptive server chance
3456

3457
      syncNodeResetPeerAndCfg(ths);
×
3458

3459
      // change myNodeInfo
3460
      ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_LEARNER;
×
3461

3462
      // change peer and cfg
3463
      ths->peersNum = 0;
×
3464
      memcpy(&ths->raftCfg.cfg.nodeInfo[0], &ths->myNodeInfo, sizeof(SNodeInfo));
×
3465
      ths->raftCfg.cfg.replicaNum = 0;
×
3466
      ths->raftCfg.cfg.totalReplicaNum = 1;
×
3467

3468
      // change other
3469
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3470
        TAOS_RETURN(code);
×
3471
      }
3472

3473
      // change state
3474
      ths->state = TAOS_SYNC_STATE_LEARNER;
×
3475
    }
3476

3477
    ths->restoreFinish = false;
×
3478
  } else {                            // add replica, or change replica type
3479
    if (ths->totalReplicaNum == 3) {  // change replica type
×
3480
      sInfo("vgId:%d, begin change replica type", ths->vgId);
×
3481

3482
      // change myNodeInfo
3483
      for (int32_t j = 0; j < cfg.totalReplicaNum; ++j) {
×
3484
        if (strcmp(ths->myNodeInfo.nodeFqdn, cfg.nodeInfo[j].nodeFqdn) == 0 &&
×
3485
            ths->myNodeInfo.nodePort == cfg.nodeInfo[j].nodePort) {
×
3486
          if (cfg.nodeInfo[j].nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3487
            ths->myNodeInfo.nodeRole = TAOS_SYNC_ROLE_VOTER;
×
3488
          }
3489
        }
3490
      }
3491

3492
      // change peer and cfg
3493
      syncNodeChangePeerAndCfgToVoter(ths, &cfg);
×
3494

3495
      // change other
3496
      syncNodeChangeToVoter(ths);
×
3497

3498
      // change state
3499
      if (ths->state == TAOS_SYNC_STATE_LEARNER) {
×
3500
        if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_VOTER) {
×
3501
          ths->state = TAOS_SYNC_STATE_FOLLOWER;
×
3502
        }
3503
      }
3504

3505
      ths->restoreFinish = false;
×
3506
    } else {  // add replica
3507
      sInfo("vgId:%d, begin add replica", ths->vgId);
×
3508

3509
      // no need to change myNodeInfo
3510

3511
      // change peer and cfg
3512
      if ((code = syncNodeRebuildPeerAndCfg(ths, &cfg)) != 0) {
×
3513
        TAOS_RETURN(code);
×
3514
      };
3515

3516
      // change other
3517
      if ((code = syncNodeRebuildAndCopyIfExist(ths, oldTotalReplicaNum)) != 0) {
×
3518
        TAOS_RETURN(code);
×
3519
      };
3520

3521
      // no need to change state
3522

3523
      if (ths->myNodeInfo.nodeRole == TAOS_SYNC_ROLE_LEARNER) {
×
3524
        ths->restoreFinish = false;
×
3525
      }
3526
    }
3527
  }
3528

3529
  ths->quorum = syncUtilQuorum(ths->replicaNum);
×
3530

3531
  ths->raftCfg.lastConfigIndex = pEntry->index;
×
3532
  ths->raftCfg.cfg.lastIndex = pEntry->index;
×
3533
  ths->raftCfg.cfg.changeVersion = cfg.changeVersion;
×
3534

3535
  syncNodeLogConfigInfo(ths, &cfg, "after config change");
×
3536

3537
  if ((code = syncWriteCfgFile(ths)) != 0) {
×
3538
    sError("vgId:%d, failed to create sync cfg file", ths->vgId);
×
3539
    TAOS_RETURN(code);
×
3540
  };
3541

3542
  TAOS_RETURN(code);
×
3543
}
3544

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

3556
  // append to log buffer
3557
  if ((code = syncLogBufferAppend(ths->pLogBuf, ths, pEntry)) < 0) {
1,981,027✔
3558
    sError("vgId:%d, index:%" PRId64 ", failed to enqueue sync log buffer", ths->vgId, pEntry->index);
9!
3559
    int32_t ret = 0;
9✔
3560
    if ((ret = syncFsmExecute(ths, ths->pFsm, ths->state, raftStoreGetTerm(ths), pEntry, terrno, false)) != 0) {
9!
3561
      sError("vgId:%d, index:%" PRId64 ", failed to execute fsm since %s", ths->vgId, pEntry->index, tstrerror(ret));
×
3562
    }
3563
    syncEntryDestroy(pEntry);
×
3564
    pEntry = NULL;
×
3565
    goto _out;
×
3566
  }
3567

3568
  code = 0;
1,981,018✔
3569
_out:;
1,981,018✔
3570
  // proceed match index, with replicating on needed
3571
  SyncIndex       matchIndex = syncLogBufferProceed(ths->pLogBuf, ths, NULL, "Append", pMsg);
1,981,018✔
3572
  const STraceId* trace = pEntry ? &pEntry->originRpcTraceId : NULL;
1,980,965✔
3573

3574
  if (pEntry != NULL) {
1,980,965!
3575
    sGDebug(trace,
1,980,972!
3576
            "vgId:%d, index:%" PRId64 ", raft entry appended, msg:%p term:%" PRId64 " buf:[%" PRId64 " %" PRId64
3577
            " %" PRId64 ", %" PRId64 ")",
3578
            ths->vgId, pEntry->index, pMsg, pEntry->term, ths->pLogBuf->startIndex, ths->pLogBuf->commitIndex,
3579
            ths->pLogBuf->matchIndex, ths->pLogBuf->endIndex);
3580
  }
3581

3582
  if (code == 0 && ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
1,980,965!
3583
    int64_t index = syncNodeUpdateAssignedCommitIndex(ths, matchIndex);
7✔
3584
    sGTrace(trace, "vgId:%d, index:%" PRId64 ", update assigned commit, msg:%p", ths->vgId, index, pMsg);
7!
3585

3586
    if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
×
3587
        syncLogBufferCommit(ths->pLogBuf, ths, ths->assignedCommitIndex, trace, "append-entry") < 0) {
7✔
3588
      sGError(trace, "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64, ths->vgId, index,
×
3589
              pMsg, ths->commitIndex);
3590
      code = TSDB_CODE_SYN_INTERNAL_ERROR;
×
3591
    }
3592
  }
3593

3594
  // multi replica
3595
  if (ths->replicaNum > 1) {
1,980,947✔
3596
    TAOS_RETURN(code);
101,917✔
3597
  }
3598

3599
  // single replica
3600
  SyncIndex returnIndex = syncNodeUpdateCommitIndex(ths, matchIndex);
1,879,030✔
3601
  sGTrace(trace, "vgId:%d, index:%" PRId64 ", raft entry update commit, msg:%p return index:%" PRId64, ths->vgId,
1,879,027!
3602
          matchIndex, pMsg, returnIndex);
3603

3604
  if (ths->fsmState != SYNC_FSM_STATE_INCOMPLETE &&
3,758,091!
3605
      (code = syncLogBufferCommit(ths->pLogBuf, ths, ths->commitIndex, trace, "append-entry")) < 0) {
1,879,044✔
3606
    sGError(trace,
×
3607
            "vgId:%d, index:%" PRId64 ", failed to commit, msg:%p commit index:%" PRId64 " return index:%" PRId64,
3608
            ths->vgId, matchIndex, pMsg, ths->commitIndex, returnIndex);
3609
  }
3610

3611
  TAOS_RETURN(code);
1,879,047✔
3612
}
3613

3614
bool syncNodeHeartbeatReplyTimeout(SSyncNode* pSyncNode) {
1,970,690✔
3615
  if (pSyncNode->totalReplicaNum == 1) {
1,970,690✔
3616
    return false;
1,866,548✔
3617
  }
3618

3619
  int32_t toCount = 0;
104,142✔
3620
  int64_t tsNow = taosGetTimestampMs();
104,143✔
3621
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
309,761✔
3622
    if (pSyncNode->peersNodeInfo[i].nodeRole == TAOS_SYNC_ROLE_LEARNER) {
205,617✔
3623
      continue;
2,162✔
3624
    }
3625
    int64_t recvTime = syncIndexMgrGetRecvTime(pSyncNode->pMatchIndex, &(pSyncNode->peersId[i]));
203,455✔
3626
    if (recvTime == 0 || recvTime == -1) {
203,456!
3627
      continue;
×
3628
    }
3629

3630
    if (tsNow - recvTime > tsHeartbeatTimeout) {
203,456✔
3631
      toCount++;
695✔
3632
    }
3633
  }
3634

3635
  bool b = (toCount >= pSyncNode->quorum ? true : false);
104,144✔
3636

3637
  return b;
104,144✔
3638
}
3639

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

3652
bool syncNodeSnapshotRecving(SSyncNode* pSyncNode) {
×
3653
  if (pSyncNode == NULL) return false;
×
3654
  if (pSyncNode->pNewNodeReceiver == NULL) return false;
×
3655
  if (pSyncNode->pNewNodeReceiver->start) return true;
×
3656
  return false;
×
3657
}
3658

3659
static int32_t syncNodeAppendNoop(SSyncNode* ths) {
11,904✔
3660
  int32_t   code = 0;
11,904✔
3661
  SyncIndex index = syncLogBufferGetEndIndex(ths->pLogBuf);
11,904✔
3662
  SyncTerm  term = raftStoreGetTerm(ths);
11,904✔
3663

3664
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
11,904✔
3665
  if (pEntry == NULL) {
11,904!
3666
    code = TSDB_CODE_OUT_OF_MEMORY;
×
3667
    TAOS_RETURN(code);
×
3668
  }
3669

3670
  code = syncNodeAppend(ths, pEntry, NULL);
11,904✔
3671
  TAOS_RETURN(code);
11,904✔
3672
}
3673

3674
#ifdef BUILD_NO_CALL
3675
static int32_t syncNodeAppendNoopOld(SSyncNode* ths) {
3676
  int32_t ret = 0;
3677

3678
  SyncIndex       index = ths->pLogStore->syncLogWriteIndex(ths->pLogStore);
3679
  SyncTerm        term = raftStoreGetTerm(ths);
3680
  SSyncRaftEntry* pEntry = syncEntryBuildNoop(term, index, ths->vgId);
3681
  if (pEntry == NULL) return -1;
3682

3683
  LRUHandle* h = NULL;
3684

3685
  if (ths->state == TAOS_SYNC_STATE_LEADER) {
3686
    int32_t code = ths->pLogStore->syncLogAppendEntry(ths->pLogStore, pEntry, false);
3687
    if (code != 0) {
3688
      sError("append noop error");
3689
      return -1;
3690
    }
3691

3692
    syncCacheEntry(ths->pLogStore, pEntry, &h);
3693
  }
3694

3695
  if (h) {
3696
    taosLRUCacheRelease(ths->pLogStore->pCache, h, false);
3697
  } else {
3698
    syncEntryDestroy(pEntry);
3699
  }
3700

3701
  return ret;
3702
}
3703
#endif
3704

3705
int32_t syncNodeOnHeartbeat(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
63,097✔
3706
  SyncHeartbeat* pMsg = pRpcMsg->pCont;
63,097✔
3707
  bool           resetElect = false;
63,097✔
3708

3709
  int64_t tsMs = taosGetTimestampMs();
63,097✔
3710

3711
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pNextIndex, &(pMsg->srcId));
63,097✔
3712
  syncIndexMgrSetRecvTime(ths->pNextIndex, &(pMsg->srcId), tsMs);
63,096✔
3713
  syncIndexMgrIncRecvCount(ths->pNextIndex, &(pMsg->srcId));
63,096✔
3714

3715
  int64_t netElapsed = tsMs - pMsg->timeStamp;
63,096✔
3716
  int64_t timeDiff = tsMs - lastRecvTime;
63,096✔
3717
  syncLogRecvHeartbeat(ths, pMsg, netElapsed, &pRpcMsg->info.traceId, timeDiff, pRpcMsg);
63,096✔
3718

3719
  if (!syncNodeInRaftGroup(ths, &pMsg->srcId)) {
63,097!
3720
    sWarn(
×
3721
        "vgId:%d, drop heartbeat msg from dnode:%d, because it come from another cluster:%d, differ from current "
3722
        "cluster:%d",
3723
        ths->vgId, DID(&(pMsg->srcId)), CID(&(pMsg->srcId)), CID(&(ths->myRaftId)));
3724
    return 0;
×
3725
  }
3726

3727
  SyncTerm currentTerm = raftStoreGetTerm(ths);
63,097✔
3728

3729
  if (pMsg->term > currentTerm && ths->state == TAOS_SYNC_STATE_LEARNER) {
63,097✔
3730
    raftStoreSetTerm(ths, pMsg->term);
269✔
3731
    currentTerm = pMsg->term;
269✔
3732
  }
3733

3734
  int64_t tsMs2 = taosGetTimestampMs();
63,097✔
3735

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

3751
  if (pMsg->term == currentTerm &&
63,097✔
3752
      (ths->state != TAOS_SYNC_STATE_LEADER && ths->state != TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
62,983!
3753
    resetElect = true;
62,983✔
3754

3755
    ths->minMatchIndex = pMsg->minMatchIndex;
62,983✔
3756

3757
    if (ths->state == TAOS_SYNC_STATE_FOLLOWER || ths->state == TAOS_SYNC_STATE_LEARNER) {
62,983✔
3758
      SRpcMsg rpcMsgLocalCmd = {0};
62,980✔
3759
      TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
62,980!
3760
      rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
62,980✔
3761

3762
      SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
62,980✔
3763
      pSyncMsg->cmd =
62,980✔
3764
          (ths->state == TAOS_SYNC_STATE_LEARNER) ? SYNC_LOCAL_CMD_LEARNER_CMT : SYNC_LOCAL_CMD_FOLLOWER_CMT;
62,980✔
3765
      pSyncMsg->commitIndex = pMsg->commitIndex;
62,980✔
3766
      pSyncMsg->currentTerm = pMsg->term;
62,980✔
3767

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

3784
  if (pMsg->term >= currentTerm &&
63,097!
3785
      (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER)) {
63,097!
3786
    SRpcMsg rpcMsgLocalCmd = {0};
×
3787
    TAOS_CHECK_RETURN(syncBuildLocalCmd(&rpcMsgLocalCmd, ths->vgId));
×
3788
    rpcMsgLocalCmd.info.traceId = pRpcMsg->info.traceId;
×
3789

3790
    SyncLocalCmd* pSyncMsg = rpcMsgLocalCmd.pCont;
×
3791
    pSyncMsg->cmd = SYNC_LOCAL_CMD_STEP_DOWN;
×
3792
    pSyncMsg->currentTerm = pMsg->term;
×
3793
    pSyncMsg->commitIndex = pMsg->commitIndex;
×
3794

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

3806
  SRpcMsg rpcMsg = {0};
63,097✔
3807
  TAOS_CHECK_RETURN(syncBuildHeartbeatReply(&rpcMsg, ths->vgId));
63,097!
3808
  SyncHeartbeatReply* pMsgReply = rpcMsg.pCont;
63,097✔
3809
  pMsgReply->destId = pMsg->srcId;
63,097✔
3810
  pMsgReply->srcId = ths->myRaftId;
63,097✔
3811
  pMsgReply->term = currentTerm;
63,097✔
3812
  pMsgReply->privateTerm = 8864;  // magic number
63,097✔
3813
  pMsgReply->startTime = ths->startTime;
63,097✔
3814
  pMsgReply->timeStamp = tsMs;
63,097✔
3815
  rpcMsg.info.traceId = pRpcMsg->info.traceId;
63,097✔
3816

3817
  // reply
3818
  int64_t tsMs3 = taosGetTimestampMs();
63,097✔
3819

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

3842
  TAOS_CHECK_RETURN(syncNodeSendMsgById(&pMsgReply->destId, ths, &rpcMsg));
63,097!
3843

3844
  if (resetElect) syncNodeResetElectTimer(ths);
63,097✔
3845
  return 0;
63,097✔
3846
}
3847

3848
int32_t syncNodeOnHeartbeatReply(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
62,513✔
3849
  int32_t code = 0;
62,513✔
3850

3851
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
62,513✔
3852
  SSyncLogReplMgr*    pMgr = syncNodeGetLogReplMgr(ths, &pMsg->srcId);
62,513✔
3853
  if (pMgr == NULL) {
62,513!
3854
    code = TSDB_CODE_SYN_RETURN_VALUE_NULL;
×
3855
    if (terrno != 0) code = terrno;
×
3856
    sError("vgId:%d, failed to get log repl mgr for the peer at addr 0x016%" PRIx64, ths->vgId, pMsg->srcId.addr);
×
3857
    TAOS_RETURN(code);
×
3858
  }
3859

3860
  int64_t tsMs = taosGetTimestampMs();
62,513✔
3861
  int64_t lastRecvTime = syncIndexMgrGetRecvTime(ths->pMatchIndex, &pMsg->srcId);
62,513✔
3862
  syncLogRecvHeartbeatReply(ths, pMsg, tsMs - pMsg->timeStamp, &pRpcMsg->info.traceId, tsMs - lastRecvTime);
62,513✔
3863

3864
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
62,513✔
3865
  syncIndexMgrIncRecvCount(ths->pMatchIndex, &(pMsg->srcId));
62,513✔
3866

3867
  return syncLogReplProcessHeartbeatReply(pMgr, ths, pMsg);
62,513✔
3868
}
3869

3870
#ifdef BUILD_NO_CALL
3871
int32_t syncNodeOnHeartbeatReplyOld(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
3872
  SyncHeartbeatReply* pMsg = pRpcMsg->pCont;
3873

3874
  int64_t tsMs = taosGetTimestampMs();
3875
  int64_t timeDiff = tsMs - pMsg->timeStamp;
3876
  syncLogRecvHeartbeatReply(ths, pMsg, timeDiff, &pRpcMsg->info.traceId, timeDiff);
3877

3878
  // update last reply time, make decision whether the other node is alive or not
3879
  syncIndexMgrSetRecvTime(ths->pMatchIndex, &pMsg->srcId, tsMs);
3880
  return 0;
3881
}
3882
#endif
3883

3884
int32_t syncNodeOnLocalCmd(SSyncNode* ths, const SRpcMsg* pRpcMsg) {
62,980✔
3885
  SyncLocalCmd* pMsg = pRpcMsg->pCont;
62,980✔
3886
  syncLogRecvLocalCmd(ths, pMsg, &pRpcMsg->info.traceId);
62,980✔
3887

3888
  if (pMsg->cmd == SYNC_LOCAL_CMD_STEP_DOWN) {
62,980!
3889
    SRaftId id = EMPTY_RAFT_ID;
×
3890
    syncNodeStepDown(ths, pMsg->currentTerm, id);
×
3891

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

3914
  return 0;
62,980✔
3915
}
3916

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

3928
int32_t syncNodeOnClientRequest(SSyncNode* ths, SRpcMsg* pMsg, SyncIndex* pRetIndex) {
1,969,128✔
3929
  sGDebug(&pMsg->info.traceId, "vgId:%d, msg:%p, process client request", ths->vgId, pMsg);
1,969,128!
3930
  int32_t code = 0;
1,969,128✔
3931

3932
  SyncIndex       index = syncLogBufferGetEndIndex(ths->pLogBuf);
1,969,128✔
3933
  SyncTerm        term = raftStoreGetTerm(ths);
1,969,136✔
3934
  SSyncRaftEntry* pEntry = NULL;
1,969,136✔
3935
  if (pMsg->msgType == TDMT_SYNC_CLIENT_REQUEST) {
1,969,136✔
3936
    pEntry = syncEntryBuildFromClientRequest(pMsg->pCont, term, index, &pMsg->info.traceId);
191,385✔
3937
  } else {
3938
    pEntry = syncEntryBuildFromRpcMsg(pMsg, term, index);
1,777,751✔
3939
  }
3940

3941
  if (pEntry == NULL) {
1,969,125!
3942
    sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to process client request since %s", ths->vgId, pMsg,
×
3943
            terrstr());
3944
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3945
  }
3946

3947
  // 1->2, config change is add in write thread, and will continue in sync thread
3948
  // need save message for it
3949
  if (pMsg->msgType == TDMT_SYNC_CONFIG_CHANGE) {
1,969,125!
3950
    SRespStub stub = {.createTime = taosGetTimestampMs(), .rpcMsg = *pMsg};
×
3951
    uint64_t  seqNum = syncRespMgrAdd(ths->pSyncRespMgr, &stub);
×
3952
    pEntry->seqNum = seqNum;
×
3953
  }
3954

3955
  if (ths->state == TAOS_SYNC_STATE_LEADER || ths->state == TAOS_SYNC_STATE_ASSIGNED_LEADER) {
1,969,125!
3956
    if (pRetIndex) {
1,969,125✔
3957
      (*pRetIndex) = index;
1,777,740✔
3958
    }
3959

3960
    if (pEntry->originalRpcType == TDMT_SYNC_CONFIG_CHANGE) {
1,969,125!
3961
      int32_t code = syncNodeCheckChangeConfig(ths, pEntry);
×
3962
      if (code < 0) {
×
3963
        sGError(&pMsg->info.traceId, "vgId:%d, msg:%p, failed to check change config since %s", ths->vgId, pMsg,
×
3964
                terrstr());
3965
        syncEntryDestroy(pEntry);
×
3966
        pEntry = NULL;
×
3967
        TAOS_RETURN(code);
×
3968
      }
3969

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

3984
    code = syncNodeAppend(ths, pEntry, pMsg);
1,969,125✔
3985
    return code;
1,969,012✔
3986
  } else {
3987
    syncEntryDestroy(pEntry);
×
3988
    pEntry = NULL;
×
3989
    return TSDB_CODE_SYN_INTERNAL_ERROR;
×
3990
  }
3991
}
3992

3993
const char* syncStr(ESyncState state) {
714,770✔
3994
  switch (state) {
714,770!
3995
    case TAOS_SYNC_STATE_FOLLOWER:
383,972✔
3996
      return "follower";
383,972✔
3997
    case TAOS_SYNC_STATE_CANDIDATE:
2,436✔
3998
      return "candidate";
2,436✔
3999
    case TAOS_SYNC_STATE_LEADER:
292,826✔
4000
      return "leader";
292,826✔
4001
    case TAOS_SYNC_STATE_ERROR:
×
4002
      return "error";
×
4003
    case TAOS_SYNC_STATE_OFFLINE:
5,547✔
4004
      return "offline";
5,547✔
4005
    case TAOS_SYNC_STATE_LEARNER:
29,977✔
4006
      return "learner";
29,977✔
4007
    case TAOS_SYNC_STATE_ASSIGNED_LEADER:
21✔
4008
      return "assigned leader";
21✔
4009
    default:
×
4010
      return "unknown";
×
4011
  }
4012
}
4013

4014
int32_t syncNodeUpdateNewConfigIndex(SSyncNode* ths, SSyncCfg* pNewCfg) {
1,798✔
4015
  for (int32_t i = 0; i < pNewCfg->totalReplicaNum; ++i) {
2,035!
4016
    SRaftId raftId = {
2,035✔
4017
        .addr = SYNC_ADDR(&pNewCfg->nodeInfo[i]),
2,035✔
4018
        .vgId = ths->vgId,
2,035✔
4019
    };
4020

4021
    if (syncUtilSameId(&(ths->myRaftId), &raftId)) {
2,035✔
4022
      pNewCfg->myIndex = i;
1,798✔
4023
      return 0;
1,798✔
4024
    }
4025
  }
4026

4027
  return TSDB_CODE_SYN_INTERNAL_ERROR;
×
4028
}
4029

4030
bool syncNodeIsOptimizedOneReplica(SSyncNode* ths, SRpcMsg* pMsg) {
1,970,693✔
4031
  return (ths->replicaNum == 1 && syncUtilUserCommit(pMsg->msgType) && ths->vgId != 1);
1,970,693!
4032
}
4033

4034
bool syncNodeInRaftGroup(SSyncNode* ths, SRaftId* pRaftId) {
563,279✔
4035
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
1,120,041!
4036
    if (syncUtilSameId(&((ths->replicasId)[i]), pRaftId)) {
1,120,042✔
4037
      return true;
563,278✔
4038
    }
4039
  }
4040
  return false;
×
4041
}
4042

4043
SSyncSnapshotSender* syncNodeGetSnapshotSender(SSyncNode* ths, SRaftId* pDestId) {
40,675✔
4044
  SSyncSnapshotSender* pSender = NULL;
40,675✔
4045
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
162,855✔
4046
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
122,181✔
4047
      pSender = (ths->senders)[i];
40,674✔
4048
    }
4049
  }
4050
  return pSender;
40,674✔
4051
}
4052

4053
SSyncTimer* syncNodeGetHbTimer(SSyncNode* ths, SRaftId* pDestId) {
30,657✔
4054
  SSyncTimer* pTimer = NULL;
30,657✔
4055
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
127,767✔
4056
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
97,110✔
4057
      pTimer = &((ths->peerHeartbeatTimerArr)[i]);
30,657✔
4058
    }
4059
  }
4060
  return pTimer;
30,657✔
4061
}
4062

4063
SPeerState* syncNodeGetPeerState(SSyncNode* ths, const SRaftId* pDestId) {
3,330✔
4064
  SPeerState* pState = NULL;
3,330✔
4065
  for (int32_t i = 0; i < ths->totalReplicaNum; ++i) {
11,418✔
4066
    if (syncUtilSameId(pDestId, &((ths->replicasId)[i]))) {
8,088✔
4067
      pState = &((ths->peerStates)[i]);
3,330✔
4068
    }
4069
  }
4070
  return pState;
3,330✔
4071
}
4072

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

4081
  SyncIndex sendIndex = pMsg->prevLogIndex + 1;
4082
  int64_t   tsNow = taosGetTimestampMs();
4083

4084
  if (pState->lastSendIndex == sendIndex && tsNow - pState->lastSendTime < SYNC_APPEND_ENTRIES_TIMEOUT_MS) {
4085
    return false;
4086
  }
4087

4088
  return true;
4089
}
4090

4091
bool syncNodeCanChange(SSyncNode* pSyncNode) {
4092
  if (pSyncNode->changing) {
4093
    sError("sync cannot change");
4094
    return false;
4095
  }
4096

4097
  if ((pSyncNode->commitIndex >= SYNC_INDEX_BEGIN)) {
4098
    SyncIndex lastIndex = syncNodeGetLastIndex(pSyncNode);
4099
    if (pSyncNode->commitIndex != lastIndex) {
4100
      sError("sync cannot change2");
4101
      return false;
4102
    }
4103
  }
4104

4105
  for (int32_t i = 0; i < pSyncNode->peersNum; ++i) {
4106
    SSyncSnapshotSender* pSender = syncNodeGetSnapshotSender(pSyncNode, &(pSyncNode->peersId)[i]);
4107
    if (pSender != NULL && pSender->start) {
4108
      sError("sync cannot change3");
4109
      return false;
4110
    }
4111
  }
4112

4113
  return true;
4114
}
4115
#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

© 2025 Coveralls, Inc