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

taosdata / TDengine / #3610

12 Feb 2025 09:54AM UTC coverage: 54.713% (-8.4%) from 63.066%
#3610

push

travis-ci

web-flow
Merge pull request #29745 from taosdata/fix/TD33664-3.0

fix: --version show information check for 3.0

120957 of 286549 branches covered (42.21%)

Branch coverage included in aggregate %.

190849 of 283342 relevant lines covered (67.36%)

4969786.97 hits per line

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

56.12
/source/dnode/mnode/impl/src/mndStream.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
#include "audit.h"
17
#include "mndDb.h"
18
#include "mndPrivilege.h"
19
#include "mndScheduler.h"
20
#include "mndShow.h"
21
#include "mndStb.h"
22
#include "mndStream.h"
23
#include "mndTrans.h"
24
#include "osMemory.h"
25
#include "parser.h"
26
#include "taoserror.h"
27
#include "tmisce.h"
28
#include "tname.h"
29

30
#define MND_STREAM_MAX_NUM 60
31

32
typedef struct {
33
  int8_t placeHolder;  // // to fix windows compile error, define place holder
34
} SMStreamNodeCheckMsg;
35

36
static int32_t  mndNodeCheckSentinel = 0;
37
SStreamExecInfo execInfo;
38

39
static int32_t mndStreamActionInsert(SSdb *pSdb, SStreamObj *pStream);
40
static int32_t mndStreamActionDelete(SSdb *pSdb, SStreamObj *pStream);
41
static int32_t mndStreamActionUpdate(SSdb *pSdb, SStreamObj *pOldStream, SStreamObj *pNewStream);
42
static int32_t mndProcessCreateStreamReq(SRpcMsg *pReq);
43
static int32_t mndProcessDropStreamReq(SRpcMsg *pReq);
44

45
static int32_t mndProcessCreateStreamReqFromMNode(SRpcMsg *pReq);
46
static int32_t mndProcessDropStreamReqFromMNode(SRpcMsg *pReq);
47

48
static int32_t mndProcessStreamCheckpoint(SRpcMsg *pReq);
49
static int32_t mndRetrieveStream(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows);
50
static void    mndCancelGetNextStream(SMnode *pMnode, void *pIter);
51
static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows);
52
static void    mndCancelGetNextStreamTask(SMnode *pMnode, void *pIter);
53
static int32_t mndProcessPauseStreamReq(SRpcMsg *pReq);
54
static int32_t mndProcessResumeStreamReq(SRpcMsg *pReq);
55
static int32_t mndProcessResetStreamReq(SRpcMsg *pReq);
56
static int32_t mndBuildStreamCheckpointSourceReq(void **pBuf, int32_t *pLen, int32_t nodeId, int64_t checkpointId,
57
                                                 int64_t streamId, int32_t taskId, int32_t transId, int8_t mndTrigger);
58
static int32_t mndProcessNodeCheck(SRpcMsg *pReq);
59
static int32_t mndProcessNodeCheckReq(SRpcMsg *pMsg);
60
static int32_t refreshNodeListFromExistedStreams(SMnode *pMnode, SArray *pNodeList);
61
static int32_t mndProcessStreamReqCheckpoint(SRpcMsg *pReq);
62
static int32_t mndProcessCheckpointReport(SRpcMsg *pReq);
63
static int32_t mndProcessConsensusInTmr(SRpcMsg *pMsg);
64
static void    doSendQuickRsp(SRpcHandleInfo *pInfo, int32_t msgSize, int32_t vgId, int32_t code);
65
static int32_t mndProcessDropOrphanTaskReq(SRpcMsg *pReq);
66
static void    saveTaskAndNodeInfoIntoBuf(SStreamObj *pStream, SStreamExecInfo *pExecNode);
67

68
static void     addAllStreamTasksIntoBuf(SMnode *pMnode, SStreamExecInfo *pExecInfo);
69
static SSdbRow *mndStreamActionDecode(SSdbRaw *pRaw);
70

71
SSdbRaw       *mndStreamSeqActionEncode(SStreamObj *pStream);
72
SSdbRow       *mndStreamSeqActionDecode(SSdbRaw *pRaw);
73
static int32_t mndStreamSeqActionInsert(SSdb *pSdb, SStreamSeq *pStream);
74
static int32_t mndStreamSeqActionDelete(SSdb *pSdb, SStreamSeq *pStream);
75
static int32_t mndStreamSeqActionUpdate(SSdb *pSdb, SStreamSeq *pOldStream, SStreamSeq *pNewStream);
76

77
int32_t mndInitStream(SMnode *pMnode) {
1,081✔
78
  SSdbTable table = {
1,081✔
79
      .sdbType = SDB_STREAM,
80
      .keyType = SDB_KEY_BINARY,
81
      .encodeFp = (SdbEncodeFp)mndStreamActionEncode,
82
      .decodeFp = (SdbDecodeFp)mndStreamActionDecode,
83
      .insertFp = (SdbInsertFp)mndStreamActionInsert,
84
      .updateFp = (SdbUpdateFp)mndStreamActionUpdate,
85
      .deleteFp = (SdbDeleteFp)mndStreamActionDelete,
86
  };
87
  SSdbTable tableSeq = {
1,081✔
88
      .sdbType = SDB_STREAM_SEQ,
89
      .keyType = SDB_KEY_BINARY,
90
      .encodeFp = (SdbEncodeFp)mndStreamSeqActionEncode,
91
      .decodeFp = (SdbDecodeFp)mndStreamSeqActionDecode,
92
      .insertFp = (SdbInsertFp)mndStreamSeqActionInsert,
93
      .updateFp = (SdbUpdateFp)mndStreamSeqActionUpdate,
94
      .deleteFp = (SdbDeleteFp)mndStreamSeqActionDelete,
95
  };
96

97
  mndSetMsgHandle(pMnode, TDMT_MND_CREATE_STREAM, mndProcessCreateStreamReq);
1,081✔
98
  mndSetMsgHandle(pMnode, TDMT_MND_DROP_STREAM, mndProcessDropStreamReq);
1,081✔
99
  mndSetMsgHandle(pMnode, TDMT_MND_NODECHECK_TIMER, mndProcessNodeCheck);
1,081✔
100

101
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DEPLOY_RSP, mndTransProcessRsp);
1,081✔
102
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DROP_RSP, mndTransProcessRsp);
1,081✔
103
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_PAUSE_RSP, mndTransProcessRsp);
1,081✔
104
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_RESUME_RSP, mndTransProcessRsp);
1,081✔
105
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_STOP_RSP, mndTransProcessRsp);
1,081✔
106
  mndSetMsgHandle(pMnode, TDMT_VND_STREAM_TASK_UPDATE_RSP, mndTransProcessRsp);
1,081✔
107
  mndSetMsgHandle(pMnode, TDMT_VND_STREAM_TASK_RESET_RSP, mndTransProcessRsp);
1,081✔
108
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_UPDATE_CHKPT_RSP, mndTransProcessRsp);
1,081✔
109
  mndSetMsgHandle(pMnode, TDMT_STREAM_CONSEN_CHKPT_RSP, mndTransProcessRsp);
1,081✔
110

111
  // for msgs inside mnode
112
  // TODO change the name
113
  mndSetMsgHandle(pMnode, TDMT_STREAM_CREATE, mndProcessCreateStreamReqFromMNode);
1,081✔
114
  mndSetMsgHandle(pMnode, TDMT_STREAM_CREATE_RSP, mndTransProcessRsp);
1,081✔
115
  mndSetMsgHandle(pMnode, TDMT_STREAM_DROP, mndProcessDropStreamReqFromMNode);
1,081✔
116
  mndSetMsgHandle(pMnode, TDMT_STREAM_DROP_RSP, mndTransProcessRsp);
1,081✔
117

118
  mndSetMsgHandle(pMnode, TDMT_VND_STREAM_CHECK_POINT_SOURCE_RSP, mndTransProcessRsp);
1,081✔
119
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_BEGIN_CHECKPOINT, mndProcessStreamCheckpoint);
1,081✔
120
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_DROP_ORPHANTASKS, mndProcessDropOrphanTaskReq);
1,081✔
121
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_TASK_RESET, mndProcessResetStatusReq);
1,081✔
122
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_REQ_CHKPT, mndProcessStreamReqCheckpoint);
1,081✔
123
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_CHKPT_REPORT, mndProcessCheckpointReport);
1,081✔
124
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_UPDATE_CHKPT_EVT, mndScanCheckpointReportInfo);
1,081✔
125
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_REPORT_CHECKPOINT, mndTransProcessRsp);
1,081✔
126
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_HEARTBEAT, mndProcessStreamHb);
1,081✔
127
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_NODECHANGE_CHECK, mndProcessNodeCheckReq);
1,081✔
128
  mndSetMsgHandle(pMnode, TDMT_MND_STREAM_CONSEN_TIMER, mndProcessConsensusInTmr);
1,081✔
129

130
  mndSetMsgHandle(pMnode, TDMT_MND_PAUSE_STREAM, mndProcessPauseStreamReq);
1,081✔
131
  mndSetMsgHandle(pMnode, TDMT_MND_RESUME_STREAM, mndProcessResumeStreamReq);
1,081✔
132
  mndSetMsgHandle(pMnode, TDMT_MND_RESET_STREAM, mndProcessResetStreamReq);
1,081✔
133

134
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_STREAMS, mndRetrieveStream);
1,081✔
135
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_STREAMS, mndCancelGetNextStream);
1,081✔
136
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_STREAM_TASKS, mndRetrieveStreamTask);
1,081✔
137
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_STREAM_TASKS, mndCancelGetNextStreamTask);
1,081✔
138

139
  int32_t code = mndInitExecInfo();
1,081✔
140
  if (code) {
1,081!
141
    return code;
×
142
  }
143

144
  code = sdbSetTable(pMnode->pSdb, table);
1,081✔
145
  if (code) {
1,081!
146
    return code;
×
147
  }
148

149
  code = sdbSetTable(pMnode->pSdb, tableSeq);
1,081✔
150
  return code;
1,081✔
151
}
152

153
void mndCleanupStream(SMnode *pMnode) {
1,080✔
154
  taosArrayDestroy(execInfo.pTaskList);
1,080✔
155
  taosArrayDestroy(execInfo.pNodeList);
1,080✔
156
  taosArrayDestroy(execInfo.pKilledChkptTrans);
1,080✔
157
  taosHashCleanup(execInfo.pTaskMap);
1,080✔
158
  taosHashCleanup(execInfo.transMgmt.pDBTrans);
1,080✔
159
  taosHashCleanup(execInfo.pTransferStateStreams);
1,080✔
160
  taosHashCleanup(execInfo.pChkptStreams);
1,080✔
161
  taosHashCleanup(execInfo.pStreamConsensus);
1,080✔
162
  (void)taosThreadMutexDestroy(&execInfo.lock);
1,080✔
163
  mDebug("mnd stream exec info cleanup");
1,080✔
164
}
1,080✔
165

166
SSdbRow *mndStreamActionDecode(SSdbRaw *pRaw) {
2,623✔
167
  int32_t     code = 0;
2,623✔
168
  int32_t     lino = 0;
2,623✔
169
  SSdbRow    *pRow = NULL;
2,623✔
170
  SStreamObj *pStream = NULL;
2,623✔
171
  void       *buf = NULL;
2,623✔
172
  int8_t      sver = 0;
2,623✔
173
  int32_t     tlen;
174
  int32_t     dataPos = 0;
2,623✔
175

176
  code = sdbGetRawSoftVer(pRaw, &sver);
2,623✔
177
  TSDB_CHECK_CODE(code, lino, _over);
2,623!
178

179
  if (sver < 1 || sver > MND_STREAM_VER_NUMBER) {
2,623!
180
    mError("stream read invalid ver, data ver: %d, curr ver: %d", sver, MND_STREAM_VER_NUMBER);
×
181
    goto _over;
×
182
  }
183

184
  pRow = sdbAllocRow(sizeof(SStreamObj));
2,623✔
185
  TSDB_CHECK_NULL(pRow, code, lino, _over, terrno);
2,623!
186

187
  pStream = sdbGetRowObj(pRow);
2,623✔
188
  TSDB_CHECK_NULL(pStream, code, lino, _over, terrno);
2,623!
189

190
  SDB_GET_INT32(pRaw, dataPos, &tlen, _over);
2,623!
191

192
  buf = taosMemoryMalloc(tlen + 1);
2,623!
193
  TSDB_CHECK_NULL(buf, code, lino, _over, terrno);
2,623!
194

195
  SDB_GET_BINARY(pRaw, dataPos, buf, tlen, _over);
2,623!
196

197
  SDecoder decoder;
198
  tDecoderInit(&decoder, buf, tlen + 1);
2,623✔
199
  code = tDecodeSStreamObj(&decoder, pStream, sver);
2,623✔
200
  tDecoderClear(&decoder);
2,623✔
201

202
  if (code < 0) {
2,623!
203
    tFreeStreamObj(pStream);
×
204
  }
205

206
_over:
2,623✔
207
  taosMemoryFreeClear(buf);
2,623!
208

209
  if (code != TSDB_CODE_SUCCESS) {
2,623!
210
    char *p = (pStream == NULL) ? "null" : pStream->name;
×
211
    mError("stream:%s, failed to decode from raw:%p since %s at:%d", p, pRaw, tstrerror(code), lino);
×
212
    taosMemoryFreeClear(pRow);
×
213

214
    terrno = code;
×
215
    return NULL;
×
216
  } else {
217
    mTrace("stream:%s, decode from raw:%p, row:%p, checkpoint:%" PRId64, pStream->name, pRaw, pStream,
2,623✔
218
           pStream->checkpointId);
219

220
    terrno = 0;
2,623✔
221
    return pRow;
2,623✔
222
  }
223
}
224

225
static int32_t mndStreamActionInsert(SSdb *pSdb, SStreamObj *pStream) {
684✔
226
  mTrace("stream:%s, perform insert action", pStream->name);
684✔
227
  return 0;
684✔
228
}
229

230
static int32_t mndStreamActionDelete(SSdb *pSdb, SStreamObj *pStream) {
2,623✔
231
  mTrace("stream:%s, perform delete action", pStream->name);
2,623✔
232
  taosWLockLatch(&pStream->lock);
2,623✔
233
  tFreeStreamObj(pStream);
2,623✔
234
  taosWUnLockLatch(&pStream->lock);
2,623✔
235
  return 0;
2,623✔
236
}
237

238
static int32_t mndStreamActionUpdate(SSdb *pSdb, SStreamObj *pOldStream, SStreamObj *pNewStream) {
1,320✔
239
  mTrace("stream:%s, perform update action", pOldStream->name);
1,320✔
240
  (void)atomic_exchange_32(&pOldStream->version, pNewStream->version);
1,320✔
241

242
  taosWLockLatch(&pOldStream->lock);
1,320✔
243

244
  pOldStream->status = pNewStream->status;
1,320✔
245
  pOldStream->updateTime = pNewStream->updateTime;
1,320✔
246
  pOldStream->checkpointId = pNewStream->checkpointId;
1,320✔
247
  pOldStream->checkpointFreq = pNewStream->checkpointFreq;
1,320✔
248

249
  taosWUnLockLatch(&pOldStream->lock);
1,320✔
250
  return 0;
1,320✔
251
}
252

253
int32_t mndAcquireStream(SMnode *pMnode, char *streamName, SStreamObj **pStream) {
4,710✔
254
  int32_t code = 0;
4,710✔
255
  SSdb   *pSdb = pMnode->pSdb;
4,710✔
256
  (*pStream) = sdbAcquire(pSdb, SDB_STREAM, streamName);
4,710✔
257
  if ((*pStream) == NULL && terrno == TSDB_CODE_SDB_OBJ_NOT_THERE) {
4,710!
258
    code = TSDB_CODE_MND_STREAM_NOT_EXIST;
1,491✔
259
  }
260
  return code;
4,710✔
261
}
262

263
void mndReleaseStream(SMnode *pMnode, SStreamObj *pStream) {
8,298✔
264
  SSdb *pSdb = pMnode->pSdb;
8,298✔
265
  sdbRelease(pSdb, pStream);
8,298✔
266
}
8,298✔
267

268
SSdbRaw *mndStreamSeqActionEncode(SStreamObj *pStream) { return NULL; }
×
269
SSdbRow *mndStreamSeqActionDecode(SSdbRaw *pRaw) { return NULL; }
×
270
int32_t  mndStreamSeqActionInsert(SSdb *pSdb, SStreamSeq *pStream) { return 0; }
×
271
int32_t  mndStreamSeqActionDelete(SSdb *pSdb, SStreamSeq *pStream) { return 0; }
×
272
int32_t  mndStreamSeqActionUpdate(SSdb *pSdb, SStreamSeq *pOldStream, SStreamSeq *pNewStream) { return 0; }
×
273

274
static int32_t mndCheckCreateStreamReq(SCMCreateStreamReq *pCreate) {
668✔
275
  if (pCreate->name[0] == 0 || pCreate->sql == NULL || pCreate->sql[0] == 0 || pCreate->sourceDB[0] == 0 ||
668!
276
      pCreate->targetStbFullName[0] == 0) {
668!
277
    return TSDB_CODE_MND_INVALID_STREAM_OPTION;
×
278
  }
279
  return TSDB_CODE_SUCCESS;
668✔
280
}
281

282
static int32_t createSchemaByFields(const SArray *pFields, SSchemaWrapper *pWrapper) {
668✔
283
  pWrapper->nCols = taosArrayGetSize(pFields);
668✔
284
  pWrapper->pSchema = taosMemoryCalloc(pWrapper->nCols, sizeof(SSchema));
668!
285
  if (NULL == pWrapper->pSchema) {
668!
286
    return terrno;
×
287
  }
288

289
  int32_t index = 0;
668✔
290
  for (int32_t i = 0; i < pWrapper->nCols; i++) {
49,188✔
291
    SField *pField = (SField *)taosArrayGet(pFields, i);
48,520✔
292
    if (pField == NULL) {
48,520!
293
      return terrno;
×
294
    }
295

296
    if (TSDB_DATA_TYPE_NULL == pField->type) {
48,520!
297
      pWrapper->pSchema[index].type = TSDB_DATA_TYPE_VARCHAR;
×
298
      pWrapper->pSchema[index].bytes = VARSTR_HEADER_SIZE;
×
299
    } else {
300
      pWrapper->pSchema[index].type = pField->type;
48,520✔
301
      pWrapper->pSchema[index].bytes = pField->bytes;
48,520✔
302
    }
303
    pWrapper->pSchema[index].colId = index + 1;
48,520✔
304
    tstrncpy(pWrapper->pSchema[index].name, pField->name, sizeof(pWrapper->pSchema[index].name));
48,520✔
305
    pWrapper->pSchema[index].flags = pField->flags;
48,520✔
306
    index += 1;
48,520✔
307
  }
308

309
  return TSDB_CODE_SUCCESS;
668✔
310
}
311

312
static bool hasDestPrimaryKey(SSchemaWrapper *pWrapper) {
668✔
313
  if (pWrapper->nCols < 2) {
668!
314
    return false;
×
315
  }
316
  for (int32_t i = 1; i < pWrapper->nCols; i++) {
48,520✔
317
    if (pWrapper->pSchema[i].flags & COL_IS_KEY) {
47,852!
318
      return true;
×
319
    }
320
  }
321
  return false;
668✔
322
}
323

324
static int32_t mndBuildStreamObjFromCreateReq(SMnode *pMnode, SStreamObj *pObj, SCMCreateStreamReq *pCreate) {
668✔
325
  SNode      *pAst = NULL;
668✔
326
  SQueryPlan *pPlan = NULL;
668✔
327
  int32_t     code = 0;
668✔
328

329
  mInfo("stream:%s to create", pCreate->name);
668!
330
  memcpy(pObj->name, pCreate->name, TSDB_STREAM_FNAME_LEN);
668✔
331
  pObj->createTime = taosGetTimestampMs();
668✔
332
  pObj->updateTime = pObj->createTime;
668✔
333
  pObj->version = 1;
668✔
334

335
  if (pCreate->smaId > 0) {
668✔
336
    pObj->subTableWithoutMd5 = 1;
259✔
337
  }
338

339
  pObj->smaId = pCreate->smaId;
668✔
340
  pObj->indexForMultiAggBalance = -1;
668✔
341

342
  pObj->uid = mndGenerateUid(pObj->name, strlen(pObj->name));
668✔
343

344
  char p[TSDB_STREAM_FNAME_LEN + 32] = {0};
668✔
345
  snprintf(p, tListLen(p), "%s_%s", pObj->name, "fillhistory");
668✔
346

347
  pObj->hTaskUid = mndGenerateUid(pObj->name, strlen(pObj->name));
668✔
348
  pObj->status = 0;
668✔
349

350
  pObj->conf.igExpired = pCreate->igExpired;
668✔
351
  pObj->conf.trigger = pCreate->triggerType;
668✔
352
  pObj->conf.triggerParam = pCreate->maxDelay;
668✔
353
  pObj->conf.watermark = pCreate->watermark;
668✔
354
  pObj->conf.fillHistory = pCreate->fillHistory;
668✔
355
  pObj->deleteMark = pCreate->deleteMark;
668✔
356
  pObj->igCheckUpdate = pCreate->igUpdate;
668✔
357

358
  memcpy(pObj->sourceDb, pCreate->sourceDB, TSDB_DB_FNAME_LEN);
668✔
359
  SDbObj *pSourceDb = mndAcquireDb(pMnode, pCreate->sourceDB);
668✔
360
  if (pSourceDb == NULL) {
668!
361
    code = terrno;
×
362
    mInfo("stream:%s failed to create, source db %s not exist since %s", pCreate->name, pObj->sourceDb,
×
363
          tstrerror(code));
364
    goto FAIL;
×
365
  }
366

367
  pObj->sourceDbUid = pSourceDb->uid;
668✔
368
  mndReleaseDb(pMnode, pSourceDb);
668✔
369

370
  memcpy(pObj->targetSTbName, pCreate->targetStbFullName, TSDB_TABLE_FNAME_LEN);
668✔
371

372
  SDbObj *pTargetDb = mndAcquireDbByStb(pMnode, pObj->targetSTbName);
668✔
373
  if (pTargetDb == NULL) {
668!
374
    code = terrno;
×
375
    mError("stream:%s failed to create, target db %s not exist since %s", pCreate->name, pObj->targetDb,
×
376
           tstrerror(code));
377
    goto FAIL;
×
378
  }
379

380
  tstrncpy(pObj->targetDb, pTargetDb->name, TSDB_DB_FNAME_LEN);
668✔
381

382
  if (pCreate->createStb == STREAM_CREATE_STABLE_TRUE) {
668✔
383
    pObj->targetStbUid = mndGenerateUid(pObj->targetSTbName, TSDB_TABLE_FNAME_LEN);
663✔
384
  } else {
385
    pObj->targetStbUid = pCreate->targetStbUid;
5✔
386
  }
387
  pObj->targetDbUid = pTargetDb->uid;
668✔
388
  mndReleaseDb(pMnode, pTargetDb);
668✔
389

390
  pObj->sql = pCreate->sql;
668✔
391
  pObj->ast = pCreate->ast;
668✔
392

393
  pCreate->sql = NULL;
668✔
394
  pCreate->ast = NULL;
668✔
395

396
  // deserialize ast
397
  if ((code = nodesStringToNode(pObj->ast, &pAst)) < 0) {
668!
398
    goto FAIL;
×
399
  }
400

401
  // create output schema
402
  if ((code = createSchemaByFields(pCreate->pCols, &pObj->outputSchema)) != TSDB_CODE_SUCCESS) {
668!
403
    goto FAIL;
×
404
  }
405

406
  int32_t numOfNULL = taosArrayGetSize(pCreate->fillNullCols);
668✔
407
  if (numOfNULL > 0) {
668!
408
    pObj->outputSchema.nCols += numOfNULL;
×
409
    SSchema *pFullSchema = taosMemoryCalloc(pObj->outputSchema.nCols, sizeof(SSchema));
×
410
    if (!pFullSchema) {
×
411
      code = terrno;
×
412
      goto FAIL;
×
413
    }
414

415
    int32_t nullIndex = 0;
×
416
    int32_t dataIndex = 0;
×
417
    for (int32_t i = 0; i < pObj->outputSchema.nCols; i++) {
×
418
      if (nullIndex >= numOfNULL) {
×
419
        pFullSchema[i].bytes = pObj->outputSchema.pSchema[dataIndex].bytes;
×
420
        pFullSchema[i].colId = i + 1;  // pObj->outputSchema.pSchema[dataIndex].colId;
×
421
        pFullSchema[i].flags = pObj->outputSchema.pSchema[dataIndex].flags;
×
422
        tstrncpy(pFullSchema[i].name, pObj->outputSchema.pSchema[dataIndex].name, sizeof(pFullSchema[i].name));
×
423
        pFullSchema[i].type = pObj->outputSchema.pSchema[dataIndex].type;
×
424
        dataIndex++;
×
425
      } else {
426
        SColLocation *pos = NULL;
×
427
        if (nullIndex < taosArrayGetSize(pCreate->fillNullCols)) {
×
428
          pos = taosArrayGet(pCreate->fillNullCols, nullIndex);
×
429
        }
430

431
        if (pos == NULL) {
×
432
          mError("invalid null column index, %d", nullIndex);
×
433
          continue;
×
434
        }
435

436
        if (i < pos->slotId) {
×
437
          pFullSchema[i].bytes = pObj->outputSchema.pSchema[dataIndex].bytes;
×
438
          pFullSchema[i].colId = i + 1;  // pObj->outputSchema.pSchema[dataIndex].colId;
×
439
          pFullSchema[i].flags = pObj->outputSchema.pSchema[dataIndex].flags;
×
440
          tstrncpy(pFullSchema[i].name, pObj->outputSchema.pSchema[dataIndex].name, sizeof(pFullSchema[i].name));
×
441
          pFullSchema[i].type = pObj->outputSchema.pSchema[dataIndex].type;
×
442
          dataIndex++;
×
443
        } else {
444
          pFullSchema[i].bytes = 0;
×
445
          pFullSchema[i].colId = pos->colId;
×
446
          pFullSchema[i].flags = COL_SET_NULL;
×
447
          memset(pFullSchema[i].name, 0, TSDB_COL_NAME_LEN);
×
448
          pFullSchema[i].type = pos->type;
×
449
          nullIndex++;
×
450
        }
451
      }
452
    }
453

454
    taosMemoryFree(pObj->outputSchema.pSchema);
×
455
    pObj->outputSchema.pSchema = pFullSchema;
×
456
  }
457

458
  SPlanContext cxt = {
668✔
459
      .pAstRoot = pAst,
460
      .topicQuery = false,
461
      .streamQuery = true,
462
      .triggerType =
463
          (pObj->conf.trigger == STREAM_TRIGGER_MAX_DELAY) ? STREAM_TRIGGER_WINDOW_CLOSE : pObj->conf.trigger,
668✔
464
      .watermark = pObj->conf.watermark,
668✔
465
      .igExpired = pObj->conf.igExpired,
668✔
466
      .deleteMark = pObj->deleteMark,
668✔
467
      .igCheckUpdate = pObj->igCheckUpdate,
668✔
468
      .destHasPrimaryKey = hasDestPrimaryKey(&pObj->outputSchema),
668✔
469
  };
470

471
  // using ast and param to build physical plan
472
  if ((code = qCreateQueryPlan(&cxt, &pPlan, NULL)) < 0) {
668!
473
    goto FAIL;
×
474
  }
475

476
  // save physcial plan
477
  if ((code = nodesNodeToString((SNode *)pPlan, false, &pObj->physicalPlan, NULL)) != 0) {
668!
478
    goto FAIL;
×
479
  }
480

481
  pObj->tagSchema.nCols = pCreate->numOfTags;
668✔
482
  if (pCreate->numOfTags) {
668✔
483
    pObj->tagSchema.pSchema = taosMemoryCalloc(pCreate->numOfTags, sizeof(SSchema));
261!
484
    if (pObj->tagSchema.pSchema == NULL) {
261!
485
      code = terrno;
×
486
      goto FAIL;
×
487
    }
488
  }
489

490
  /*A(pCreate->numOfTags == taosArrayGetSize(pCreate->pTags));*/
491
  for (int32_t i = 0; i < pCreate->numOfTags; i++) {
2,235✔
492
    SField *pField = taosArrayGet(pCreate->pTags, i);
1,567✔
493
    if (pField == NULL) {
1,567!
494
      continue;
×
495
    }
496

497
    pObj->tagSchema.pSchema[i].colId = pObj->outputSchema.nCols + i + 1;
1,567✔
498
    pObj->tagSchema.pSchema[i].bytes = pField->bytes;
1,567✔
499
    pObj->tagSchema.pSchema[i].flags = pField->flags;
1,567✔
500
    pObj->tagSchema.pSchema[i].type = pField->type;
1,567✔
501
    memcpy(pObj->tagSchema.pSchema[i].name, pField->name, TSDB_COL_NAME_LEN);
1,567✔
502
  }
503

504
FAIL:
668✔
505
  if (pAst != NULL) nodesDestroyNode(pAst);
668!
506
  if (pPlan != NULL) qDestroyQueryPlan(pPlan);
668!
507
  return code;
668✔
508
}
509

510
int32_t mndPersistTaskDeployReq(STrans *pTrans, SStreamTask *pTask) {
6,426✔
511
  SEncoder encoder;
512
  tEncoderInit(&encoder, NULL, 0);
6,426✔
513

514
  if (pTask->ver < SSTREAM_TASK_SUBTABLE_CHANGED_VER) {
6,426!
515
    pTask->ver = SSTREAM_TASK_VER;
×
516
  }
517

518
  int32_t code = tEncodeStreamTask(&encoder, pTask);
6,426✔
519
  if (code == -1) {
6,426!
520
    tEncoderClear(&encoder);
×
521
    return TSDB_CODE_INVALID_MSG;
×
522
  }
523

524
  int32_t size = encoder.pos;
6,426✔
525
  int32_t tlen = sizeof(SMsgHead) + size;
6,426✔
526
  tEncoderClear(&encoder);
6,426✔
527

528
  void *buf = taosMemoryCalloc(1, tlen);
6,426!
529
  if (buf == NULL) {
6,426!
530
    return terrno;
×
531
  }
532

533
  ((SMsgHead *)buf)->vgId = htonl(pTask->info.nodeId);
6,426✔
534

535
  void *abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
6,426✔
536
  tEncoderInit(&encoder, abuf, size);
6,426✔
537
  code = tEncodeStreamTask(&encoder, pTask);
6,426✔
538
  tEncoderClear(&encoder);
6,426✔
539

540
  if (code != 0) {
6,426!
541
    mError("failed to encode stream task, code:%s", tstrerror(code));
×
542
    taosMemoryFree(buf);
×
543
    return code;
×
544
  }
545

546
  code = setTransAction(pTrans, buf, tlen, TDMT_STREAM_TASK_DEPLOY, &pTask->info.epSet, 0,
6,426✔
547
                        TSDB_CODE_VND_INVALID_VGROUP_ID);
548
  if (code) {
6,426!
549
    taosMemoryFree(buf);
×
550
  }
551

552
  return code;
6,426✔
553
}
554

555
int32_t mndPersistStreamTasks(STrans *pTrans, SStreamObj *pStream) {
676✔
556
  SStreamTaskIter *pIter = NULL;
676✔
557
  int32_t          code = createStreamTaskIter(pStream, &pIter);
676✔
558
  if (code) {
676!
559
    mError("failed to create task iter for stream:%s", pStream->name);
×
560
    return code;
×
561
  }
562

563
  while (streamTaskIterNextTask(pIter)) {
4,346✔
564
    SStreamTask *pTask = NULL;
3,670✔
565
    code = streamTaskIterGetCurrent(pIter, &pTask);
3,670✔
566
    if (code) {
3,670!
567
      destroyStreamTaskIter(pIter);
×
568
      return code;
×
569
    }
570

571
    code = mndPersistTaskDeployReq(pTrans, pTask);
3,670✔
572
    if (code) {
3,670!
573
      destroyStreamTaskIter(pIter);
×
574
      return code;
×
575
    }
576
  }
577

578
  destroyStreamTaskIter(pIter);
676✔
579

580
  // persistent stream task for already stored ts data
581
  if (pStream->conf.fillHistory) {
676✔
582
    int32_t level = taosArrayGetSize(pStream->pHTasksList);
465✔
583

584
    for (int32_t i = 0; i < level; i++) {
1,409✔
585
      SArray *pLevel = taosArrayGetP(pStream->pHTasksList, i);
944✔
586

587
      int32_t numOfTasks = taosArrayGetSize(pLevel);
944✔
588
      for (int32_t j = 0; j < numOfTasks; j++) {
3,700✔
589
        SStreamTask *pTask = taosArrayGetP(pLevel, j);
2,756✔
590
        code = mndPersistTaskDeployReq(pTrans, pTask);
2,756✔
591
        if (code) {
2,756!
592
          return code;
×
593
        }
594
      }
595
    }
596
  }
597

598
  return code;
676✔
599
}
600

601
int32_t mndPersistStream(STrans *pTrans, SStreamObj *pStream) {
676✔
602
  int32_t code = 0;
676✔
603
  if ((code = mndPersistStreamTasks(pTrans, pStream)) < 0) {
676!
604
    return code;
×
605
  }
606

607
  return mndPersistTransLog(pStream, pTrans, SDB_STATUS_READY);
676✔
608
}
609

610
static int32_t mndCreateStbForStream(SMnode *pMnode, STrans *pTrans, const SStreamObj *pStream, const char *user) {
663✔
611
  SStbObj *pStb = NULL;
663✔
612
  SDbObj  *pDb = NULL;
663✔
613
  int32_t  code = 0;
663✔
614
  int32_t  lino = 0;
663✔
615

616
  SMCreateStbReq createReq = {0};
663✔
617
  tstrncpy(createReq.name, pStream->targetSTbName, TSDB_TABLE_FNAME_LEN);
663✔
618
  createReq.numOfColumns = pStream->outputSchema.nCols;
663✔
619
  createReq.numOfTags = 1;  // group id
663✔
620
  createReq.pColumns = taosArrayInit_s(sizeof(SFieldWithOptions), createReq.numOfColumns);
663✔
621
  TSDB_CHECK_NULL(createReq.pColumns, code, lino, _OVER, terrno);
663!
622

623
  // build fields
624
  for (int32_t i = 0; i < createReq.numOfColumns; i++) {
49,113✔
625
    SFieldWithOptions *pField = taosArrayGet(createReq.pColumns, i);
48,450✔
626
    TSDB_CHECK_NULL(pField, code, lino, _OVER, terrno);
48,450!
627

628
    tstrncpy(pField->name, pStream->outputSchema.pSchema[i].name, TSDB_COL_NAME_LEN);
48,450✔
629
    pField->flags = pStream->outputSchema.pSchema[i].flags;
48,450✔
630
    pField->type = pStream->outputSchema.pSchema[i].type;
48,450✔
631
    pField->bytes = pStream->outputSchema.pSchema[i].bytes;
48,450✔
632
    pField->compress = createDefaultColCmprByType(pField->type);
48,450✔
633
  }
634

635
  if (pStream->tagSchema.nCols == 0) {
663✔
636
    createReq.numOfTags = 1;
402✔
637
    createReq.pTags = taosArrayInit_s(sizeof(SField), 1);
402✔
638
    TSDB_CHECK_NULL(createReq.pTags, code, lino, _OVER, terrno);
402!
639

640
    // build tags
641
    SField *pField = taosArrayGet(createReq.pTags, 0);
402✔
642
    TSDB_CHECK_NULL(pField, code, lino, _OVER, terrno);
402!
643

644
    tstrncpy(pField->name, "group_id", sizeof(pField->name));
402✔
645
    pField->type = TSDB_DATA_TYPE_UBIGINT;
402✔
646
    pField->flags = 0;
402✔
647
    pField->bytes = 8;
402✔
648
  } else {
649
    createReq.numOfTags = pStream->tagSchema.nCols;
261✔
650
    createReq.pTags = taosArrayInit_s(sizeof(SField), createReq.numOfTags);
261✔
651
    TSDB_CHECK_NULL(createReq.pTags, code, lino, _OVER, terrno);
261!
652

653
    for (int32_t i = 0; i < createReq.numOfTags; i++) {
1,828✔
654
      SField *pField = taosArrayGet(createReq.pTags, i);
1,567✔
655
      if (pField == NULL) {
1,567!
656
        continue;
×
657
      }
658

659
      pField->bytes = pStream->tagSchema.pSchema[i].bytes;
1,567✔
660
      pField->flags = pStream->tagSchema.pSchema[i].flags;
1,567✔
661
      pField->type = pStream->tagSchema.pSchema[i].type;
1,567✔
662
      tstrncpy(pField->name, pStream->tagSchema.pSchema[i].name, TSDB_COL_NAME_LEN);
1,567✔
663
    }
664
  }
665

666
  if ((code = mndCheckCreateStbReq(&createReq)) != 0) {
663!
667
    goto _OVER;
×
668
  }
669

670
  pStb = mndAcquireStb(pMnode, createReq.name);
663✔
671
  if (pStb != NULL) {
663!
672
    code = TSDB_CODE_MND_STB_ALREADY_EXIST;
×
673
    goto _OVER;
×
674
  }
675

676
  pDb = mndAcquireDbByStb(pMnode, createReq.name);
663✔
677
  if (pDb == NULL) {
663!
678
    code = TSDB_CODE_MND_DB_NOT_SELECTED;
×
679
    goto _OVER;
×
680
  }
681

682
  int32_t numOfStbs = -1;
663✔
683
  if (mndGetNumOfStbs(pMnode, pDb->name, &numOfStbs) != 0) {
663!
684
    goto _OVER;
×
685
  }
686

687
  if (pDb->cfg.numOfStables == 1 && numOfStbs != 0) {
663!
688
    code = TSDB_CODE_MND_SINGLE_STB_MODE_DB;
×
689
    goto _OVER;
×
690
  }
691

692
  SStbObj stbObj = {0};
663✔
693

694
  if (mndBuildStbFromReq(pMnode, &stbObj, &createReq, pDb) != 0) {
663!
695
    goto _OVER;
×
696
  }
697

698
  stbObj.uid = pStream->targetStbUid;
663✔
699

700
  if (mndAddStbToTrans(pMnode, pTrans, pDb, &stbObj) < 0) {
663!
701
    mndFreeStb(&stbObj);
×
702
    goto _OVER;
×
703
  }
704

705
  tFreeSMCreateStbReq(&createReq);
663✔
706
  mndFreeStb(&stbObj);
663✔
707
  mndReleaseStb(pMnode, pStb);
663✔
708
  mndReleaseDb(pMnode, pDb);
663✔
709
  mDebug("stream:%s create dst stable:%s, cols:%d", pStream->name, pStream->targetSTbName, pStream->outputSchema.nCols);
663!
710
  return code;
663✔
711

712
_OVER:
×
713
  tFreeSMCreateStbReq(&createReq);
×
714
  mndReleaseStb(pMnode, pStb);
×
715
  mndReleaseDb(pMnode, pDb);
×
716

717
  mDebug("stream:%s failed to create dst stable:%s, line:%d code:%s", pStream->name, pStream->targetSTbName, lino,
×
718
         tstrerror(code));
719
  return code;
×
720
}
721

722
// 1. stream number check
723
// 2. target stable can not be target table of other existed streams.
724
static int32_t doStreamCheck(SMnode *pMnode, SStreamObj *pStreamObj) {
668✔
725
  int32_t     numOfStream = 0;
668✔
726
  SStreamObj *pStream = NULL;
668✔
727
  void       *pIter = NULL;
668✔
728

729
  while ((pIter = sdbFetch(pMnode->pSdb, SDB_STREAM, pIter, (void **)&pStream)) != NULL) {
1,166✔
730
    if (pStream->sourceDbUid == pStreamObj->sourceDbUid) {
498✔
731
      ++numOfStream;
485✔
732
    }
733

734
    sdbRelease(pMnode->pSdb, pStream);
498✔
735

736
    if (numOfStream > MND_STREAM_MAX_NUM) {
498!
737
      mError("too many streams, no more than %d for each database, failed to create stream:%s", MND_STREAM_MAX_NUM,
×
738
             pStreamObj->name);
739
      sdbCancelFetch(pMnode->pSdb, pIter);
×
740
      return TSDB_CODE_MND_TOO_MANY_STREAMS;
×
741
    }
742

743
    if (pStream->targetStbUid == pStreamObj->targetStbUid) {
498!
744
      mError("Cannot write the same stable as other stream:%s, failed to create stream:%s", pStream->name,
×
745
             pStreamObj->name);
746
      sdbCancelFetch(pMnode->pSdb, pIter);
×
747
      return TSDB_CODE_MND_INVALID_TARGET_TABLE;
×
748
    }
749
  }
750

751
  return TSDB_CODE_SUCCESS;
668✔
752
}
753

754
static void *notifyAddrDup(void *p) { return taosStrdup((char *)p); }
×
755

756
static int32_t addStreamTaskNotifyInfo(const SCMCreateStreamReq *createReq, const SStreamObj *pStream,
×
757
                                       SStreamTask *pTask) {
758
  int32_t code = TSDB_CODE_SUCCESS;
×
759
  int32_t lino = 0;
×
760

761
  TSDB_CHECK_NULL(createReq, code, lino, _end, TSDB_CODE_INVALID_PARA);
×
762
  TSDB_CHECK_NULL(pTask, code, lino, _end, TSDB_CODE_INVALID_PARA);
×
763

764
  pTask->notifyInfo.pNotifyAddrUrls = taosArrayDup(createReq->pNotifyAddrUrls, notifyAddrDup);
×
765
  TSDB_CHECK_NULL(pTask->notifyInfo.pNotifyAddrUrls, code, lino, _end, terrno);
×
766
  pTask->notifyInfo.notifyEventTypes = createReq->notifyEventTypes;
×
767
  pTask->notifyInfo.notifyErrorHandle = createReq->notifyErrorHandle;
×
768
  pTask->notifyInfo.streamName = taosStrdup(createReq->name);
×
769
  TSDB_CHECK_NULL(pTask->notifyInfo.streamName, code, lino, _end, terrno);
×
770
  pTask->notifyInfo.stbFullName = taosStrdup(createReq->targetStbFullName);
×
771
  TSDB_CHECK_NULL(pTask->notifyInfo.stbFullName, code, lino, _end, terrno);
×
772
  pTask->notifyInfo.pSchemaWrapper = tCloneSSchemaWrapper(&pStream->outputSchema);
×
773
  TSDB_CHECK_NULL(pTask->notifyInfo.pSchemaWrapper, code, lino, _end, terrno);
×
774

775
_end:
×
776
  if (code != TSDB_CODE_SUCCESS) {
×
777
    mError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
778
  }
779
  return code;
×
780
}
781

782
static int32_t addStreamNotifyInfo(SCMCreateStreamReq *createReq, SStreamObj *pStream) {
668✔
783
  int32_t code = TSDB_CODE_SUCCESS;
668✔
784
  int32_t lino = 0;
668✔
785
  int32_t level = 0;
668✔
786
  int32_t nTasks = 0;
668✔
787
  SArray *pLevel = NULL;
668✔
788

789
  TSDB_CHECK_NULL(createReq, code, lino, _end, TSDB_CODE_INVALID_PARA);
668!
790
  TSDB_CHECK_NULL(pStream, code, lino, _end, TSDB_CODE_INVALID_PARA);
668!
791

792
  if (taosArrayGetSize(createReq->pNotifyAddrUrls) == 0) {
668!
793
    goto _end;
668✔
794
  }
795

796
  level = taosArrayGetSize(pStream->tasks);
×
797
  for (int32_t i = 0; i < level; ++i) {
×
798
    pLevel = taosArrayGetP(pStream->tasks, i);
×
799
    nTasks = taosArrayGetSize(pLevel);
×
800
    for (int32_t j = 0; j < nTasks; ++j) {
×
801
      code = addStreamTaskNotifyInfo(createReq, pStream, taosArrayGetP(pLevel, j));
×
802
      TSDB_CHECK_CODE(code, lino, _end);
×
803
    }
804
  }
805

806
  if (pStream->conf.fillHistory && createReq->notifyHistory) {
×
807
    level = taosArrayGetSize(pStream->pHTasksList);
×
808
    for (int32_t i = 0; i < level; ++i) {
×
809
      pLevel = taosArrayGetP(pStream->pHTasksList, i);
×
810
      nTasks = taosArrayGetSize(pLevel);
×
811
      for (int32_t j = 0; j < nTasks; ++j) {
×
812
        code = addStreamTaskNotifyInfo(createReq, pStream, taosArrayGetP(pLevel, j));
×
813
        TSDB_CHECK_CODE(code, lino, _end);
×
814
      }
815
    }
816
  }
817

818
_end:
×
819
  if (code != TSDB_CODE_SUCCESS) {
668!
820
    mError("%s for stream %s failed at line %d since %s", __func__, pStream->name, lino, tstrerror(code));
×
821
  }
822
  return code;
668✔
823
}
824

825
static int32_t mndProcessCreateStreamReq(SRpcMsg *pReq) {
668✔
826
  SMnode     *pMnode = pReq->info.node;
668✔
827
  SStreamObj *pStream = NULL;
668✔
828
  SStreamObj  streamObj = {0};
668✔
829
  char       *sql = NULL;
668✔
830
  int32_t     sqlLen = 0;
668✔
831
  const char *pMsg = "create stream tasks on dnodes";
668✔
832
  int32_t     code = TSDB_CODE_SUCCESS;
668✔
833
  int32_t     lino = 0;
668✔
834
  STrans     *pTrans = NULL;
668✔
835

836
  SCMCreateStreamReq createReq = {0};
668✔
837
  code = tDeserializeSCMCreateStreamReq(pReq->pCont, pReq->contLen, &createReq);
668✔
838
  TSDB_CHECK_CODE(code, lino, _OVER);
668!
839

840
#ifdef WINDOWS
841
  code = TSDB_CODE_MND_INVALID_PLATFORM;
842
  goto _OVER;
843
#endif
844

845
  mInfo("stream:%s, start to create stream, sql:%s", createReq.name, createReq.sql);
668!
846
  if ((code = mndCheckCreateStreamReq(&createReq)) != 0) {
668!
847
    mError("stream:%s, failed to create since %s", createReq.name, tstrerror(code));
×
848
    goto _OVER;
×
849
  }
850

851
  code = mndAcquireStream(pMnode, createReq.name, &pStream);
668✔
852
  if (pStream != NULL && code == 0) {
668!
853
    if (createReq.igExists) {
×
854
      mInfo("stream:%s, already exist, ignore exist is set", createReq.name);
×
855
      mndReleaseStream(pMnode, pStream);
×
856
      tFreeSCMCreateStreamReq(&createReq);
×
857
      return code;
×
858
    } else {
859
      code = TSDB_CODE_MND_STREAM_ALREADY_EXIST;
×
860
      goto _OVER;
×
861
    }
862
  } else if (code != TSDB_CODE_MND_STREAM_NOT_EXIST) {
668!
863
    goto _OVER;
×
864
  }
865

866
  if ((code = grantCheck(TSDB_GRANT_STREAMS)) < 0) {
668!
867
    goto _OVER;
×
868
  }
869

870
  if (createReq.sql != NULL) {
668!
871
    sql = taosStrdup(createReq.sql);
668!
872
    TSDB_CHECK_NULL(sql, code, lino, _OVER, terrno);
668!
873
  }
874

875
  // check for the taskEp update trans
876
  if (isNodeUpdateTransActive()) {
668!
877
    mError("stream:%s failed to create stream, node update trans is active", createReq.name);
×
878
    code = TSDB_CODE_STREAM_TASK_IVLD_STATUS;
×
879
    goto _OVER;
×
880
  }
881

882
  SDbObj *pSourceDb = mndAcquireDb(pMnode, createReq.sourceDB);
668✔
883
  if (pSourceDb == NULL) {
668!
884
    code = terrno;
×
885
    mInfo("stream:%s failed to create, acquire source db %s failed, code:%s", createReq.name, createReq.sourceDB,
×
886
          tstrerror(code));
887
    goto _OVER;
×
888
  }
889

890
  code = mndCheckForSnode(pMnode, pSourceDb);
668✔
891
  mndReleaseDb(pMnode, pSourceDb);
668✔
892
  if (code != 0) {
668!
893
    goto _OVER;
×
894
  }
895

896
  // build stream obj from request
897
  if ((code = mndBuildStreamObjFromCreateReq(pMnode, &streamObj, &createReq)) < 0) {
668!
898
    mError("stream:%s, failed to create since %s", createReq.name, tstrerror(code));
×
899
    goto _OVER;
×
900
  }
901

902
  code = doStreamCheck(pMnode, &streamObj);
668✔
903
  TSDB_CHECK_CODE(code, lino, _OVER);
668!
904

905
  code = doCreateTrans(pMnode, &streamObj, pReq, TRN_CONFLICT_DB, MND_STREAM_CREATE_NAME, pMsg, &pTrans);
668✔
906
  if (pTrans == NULL || code) {
668!
907
    goto _OVER;
×
908
  }
909

910
  // create stb for stream
911
  if (createReq.createStb == STREAM_CREATE_STABLE_TRUE) {
668✔
912
    if ((code = mndCreateStbForStream(pMnode, pTrans, &streamObj, pReq->info.conn.user)) < 0) {
663!
913
      mError("trans:%d, failed to create stb for stream %s since %s", pTrans->id, createReq.name, tstrerror(code));
×
914
      mndTransDrop(pTrans);
×
915
      goto _OVER;
×
916
    }
917
  } else {
918
    mDebug("stream:%s no need create stable", createReq.name);
5!
919
  }
920

921
  // schedule stream task for stream obj
922
  code = mndScheduleStream(pMnode, &streamObj, createReq.lastTs, createReq.pVgroupVerList);
668✔
923
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
668!
924
    mError("stream:%s, failed to schedule since %s", createReq.name, tstrerror(code));
×
925
    mndTransDrop(pTrans);
×
926
    goto _OVER;
×
927
  }
928

929
  // add notify info into all stream tasks
930
  code = addStreamNotifyInfo(&createReq, &streamObj);
668✔
931
  if (code != TSDB_CODE_SUCCESS) {
668!
932
    mError("stream:%s failed to add stream notify info since %s", createReq.name, tstrerror(code));
×
933
    mndTransDrop(pTrans);
×
934
    goto _OVER;
×
935
  }
936

937
  // add stream to trans
938
  code = mndPersistStream(pTrans, &streamObj);
668✔
939
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
668!
940
    mError("stream:%s, failed to persist since %s", createReq.name, tstrerror(code));
×
941
    mndTransDrop(pTrans);
×
942
    goto _OVER;
×
943
  }
944

945
  if ((code = mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_READ_DB, streamObj.sourceDb)) != 0) {
668!
946
    mndTransDrop(pTrans);
×
947
    goto _OVER;
×
948
  }
949

950
  if ((code = mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, streamObj.targetDb)) != 0) {
668!
951
    mndTransDrop(pTrans);
×
952
    goto _OVER;
×
953
  }
954

955
  // add into buffer firstly
956
  // to make sure when the hb from vnode arrived, the newly created tasks have been in the task map already.
957
  streamMutexLock(&execInfo.lock);
668✔
958
  mDebug("stream stream:%s start to register tasks into task nodeList and set initial checkpointId", createReq.name);
668!
959
  saveTaskAndNodeInfoIntoBuf(&streamObj, &execInfo);
668✔
960
  streamMutexUnlock(&execInfo.lock);
668✔
961

962
  // execute creation
963
  code = mndTransPrepare(pMnode, pTrans);
668✔
964
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
668!
965
    mError("trans:%d, failed to prepare since %s", pTrans->id, tstrerror(code));
×
966
    mndTransDrop(pTrans);
×
967
    goto _OVER;
×
968
  }
969

970
  mndTransDrop(pTrans);
668✔
971

972
  SName dbname = {0};
668✔
973
  code = tNameFromString(&dbname, createReq.sourceDB, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);
668✔
974
  if (code) {
668!
975
    mError("invalid source dbname:%s in create stream, code:%s", createReq.sourceDB, tstrerror(code));
×
976
    goto _OVER;
×
977
  }
978

979
  SName name = {0};
668✔
980
  code = tNameFromString(&name, createReq.name, T_NAME_ACCT | T_NAME_TABLE);
668✔
981
  if (code) {
668!
982
    mError("invalid stream name:%s in create strem, code:%s", createReq.name, tstrerror(code));
×
983
    goto _OVER;
×
984
  }
985

986
  // reuse this function for stream
987
  if (sql != NULL && sqlLen > 0) {
668!
988
    auditRecord(pReq, pMnode->clusterId, "createStream", dbname.dbname, name.dbname, sql, sqlLen);
×
989
  } else {
990
    char detail[1000] = {0};
668✔
991
    snprintf(detail, tListLen(detail), "dbname:%s, stream name:%s", dbname.dbname, name.dbname);
668✔
992
    auditRecord(pReq, pMnode->clusterId, "createStream", dbname.dbname, name.dbname, detail, strlen(detail));
668✔
993
  }
994

995
_OVER:
668✔
996
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
668!
997
    mError("stream:%s, failed to create at line:%d since %s", createReq.name, lino, tstrerror(code));
×
998
  } else {
999
    mDebug("stream:%s create stream completed", createReq.name);
668!
1000
    code = TSDB_CODE_ACTION_IN_PROGRESS;
668✔
1001
  }
1002

1003
  mndReleaseStream(pMnode, pStream);
668✔
1004
  tFreeSCMCreateStreamReq(&createReq);
668✔
1005
  tFreeStreamObj(&streamObj);
668✔
1006

1007
  if (sql != NULL) {
668!
1008
    taosMemoryFreeClear(sql);
668!
1009
  }
1010

1011
  return code;
668✔
1012
}
1013

1014
static int32_t mndProcessRestartStreamReq(SRpcMsg *pReq) {
×
1015
  SMnode          *pMnode = pReq->info.node;
×
1016
  SStreamObj      *pStream = NULL;
×
1017
  int32_t          code = 0;
×
1018
  SMPauseStreamReq pauseReq = {0};
×
1019

1020
  if (tDeserializeSMPauseStreamReq(pReq->pCont, pReq->contLen, &pauseReq) < 0) {
×
1021
    return TSDB_CODE_INVALID_MSG;
×
1022
  }
1023

1024
  code = mndAcquireStream(pMnode, pauseReq.name, &pStream);
×
1025
  if (pStream == NULL || code != 0) {
×
1026
    if (pauseReq.igNotExists) {
×
1027
      mInfo("stream:%s, not exist, not restart stream", pauseReq.name);
×
1028
      return 0;
×
1029
    } else {
1030
      mError("stream:%s not exist, failed to restart stream", pauseReq.name);
×
1031
      TAOS_RETURN(TSDB_CODE_MND_STREAM_NOT_EXIST);
×
1032
    }
1033
  }
1034

1035
  mInfo("stream:%s,%" PRId64 " start to restart stream", pauseReq.name, pStream->uid);
×
1036
  if ((code = mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pStream->targetDb)) != 0) {
×
1037
    sdbRelease(pMnode->pSdb, pStream);
×
1038
    return code;
×
1039
  }
1040

1041
  // check if it is conflict with other trans in both sourceDb and targetDb.
1042
  code = mndStreamTransConflictCheck(pMnode, pStream->uid, MND_STREAM_RESTART_NAME, true);
×
1043
  if (code) {
×
1044
    sdbRelease(pMnode->pSdb, pStream);
×
1045
    return code;
×
1046
  }
1047

1048
  bool updated = mndStreamNodeIsUpdated(pMnode);
×
1049
  if (updated) {
×
1050
    mError("tasks are not ready for restart, node update detected");
×
1051
    sdbRelease(pMnode->pSdb, pStream);
×
1052
    TAOS_RETURN(TSDB_CODE_STREAM_TASK_IVLD_STATUS);
×
1053
  }
1054

1055
  STrans *pTrans = NULL;
×
1056
  code = doCreateTrans(pMnode, pStream, pReq, TRN_CONFLICT_NOTHING, MND_STREAM_RESTART_NAME, "restart the stream",
×
1057
                       &pTrans);
1058
  if (pTrans == NULL || code) {
×
1059
    mError("stream:%s failed to pause stream since %s", pauseReq.name, tstrerror(code));
×
1060
    sdbRelease(pMnode->pSdb, pStream);
×
1061
    return code;
×
1062
  }
1063

1064
  code = mndStreamRegisterTrans(pTrans, MND_STREAM_RESTART_NAME, pStream->uid);
×
1065
  if (code) {
×
1066
    sdbRelease(pMnode->pSdb, pStream);
×
1067
    mndTransDrop(pTrans);
×
1068
    return code;
×
1069
  }
1070

1071
  // if nodeUpdate happened, not send pause trans
1072
  code = mndStreamSetRestartAction(pMnode, pTrans, pStream);
×
1073
  if (code) {
×
1074
    mError("stream:%s, failed to restart task since %s", pauseReq.name, tstrerror(code));
×
1075
    sdbRelease(pMnode->pSdb, pStream);
×
1076
    mndTransDrop(pTrans);
×
1077
    return code;
×
1078
  }
1079

1080
  code = mndTransPrepare(pMnode, pTrans);
×
1081
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
×
1082
    mError("trans:%d, failed to prepare restart stream trans since %s", pTrans->id, tstrerror(code));
×
1083
    sdbRelease(pMnode->pSdb, pStream);
×
1084
    mndTransDrop(pTrans);
×
1085
    return code;
×
1086
  }
1087

1088
  sdbRelease(pMnode->pSdb, pStream);
×
1089
  mndTransDrop(pTrans);
×
1090

1091
  return TSDB_CODE_ACTION_IN_PROGRESS;
×
1092
}
1093

1094
int64_t mndStreamGenChkptId(SMnode *pMnode, bool lock) {
427✔
1095
  SStreamObj *pStream = NULL;
427✔
1096
  void       *pIter = NULL;
427✔
1097
  SSdb       *pSdb = pMnode->pSdb;
427✔
1098
  int64_t     maxChkptId = 0;
427✔
1099

1100
  while (1) {
1101
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
1,269✔
1102
    if (pIter == NULL) break;
1,269✔
1103

1104
    maxChkptId = TMAX(maxChkptId, pStream->checkpointId);
842✔
1105
    mDebug("stream:%p, %s id:0x%" PRIx64 " checkpoint %" PRId64 "", pStream, pStream->name, pStream->uid,
842!
1106
           pStream->checkpointId);
1107
    sdbRelease(pSdb, pStream);
842✔
1108
  }
1109

1110
  {  // check the max checkpoint id from all vnodes.
1111
    int64_t maxCheckpointId = -1;
427✔
1112
    if (lock) {
427✔
1113
      streamMutexLock(&execInfo.lock);
2✔
1114
    }
1115

1116
    for (int32_t i = 0; i < taosArrayGetSize(execInfo.pTaskList); ++i) {
5,277✔
1117
      STaskId          *p = taosArrayGet(execInfo.pTaskList, i);
4,850✔
1118
      STaskStatusEntry *pEntry = taosHashGet(execInfo.pTaskMap, p, sizeof(*p));
4,850✔
1119
      if (p == NULL || pEntry == NULL) {
4,850!
1120
        continue;
×
1121
      }
1122

1123
      if (pEntry->checkpointInfo.failed) {
4,850!
1124
        continue;
×
1125
      }
1126

1127
      if (maxCheckpointId < pEntry->checkpointInfo.latestId) {
4,850✔
1128
        maxCheckpointId = pEntry->checkpointInfo.latestId;
468✔
1129
      }
1130
    }
1131

1132
    if (lock) {
427✔
1133
      streamMutexUnlock(&execInfo.lock);
2✔
1134
    }
1135

1136
    if (maxCheckpointId > maxChkptId) {
427!
1137
      mDebug("max checkpointId in mnode:%" PRId64 ", smaller than max checkpointId in vnode:%" PRId64, maxChkptId,
×
1138
             maxCheckpointId);
1139
      maxChkptId = maxCheckpointId;
×
1140
    }
1141
  }
1142

1143
  mDebug("generate new checkpointId:%" PRId64, maxChkptId + 1);
427!
1144
  return maxChkptId + 1;
427✔
1145
}
1146

1147
static int32_t mndProcessStreamCheckpointTrans(SMnode *pMnode, SStreamObj *pStream, int64_t checkpointId,
427✔
1148
                                               int8_t mndTrigger, bool lock) {
1149
  int32_t code = TSDB_CODE_SUCCESS;
427✔
1150
  bool    conflict = false;
427✔
1151
  int64_t ts = taosGetTimestampMs();
427✔
1152
  STrans *pTrans = NULL;
427✔
1153

1154
  if (mndTrigger == 1 && (ts - pStream->checkpointFreq < tsStreamCheckpointInterval * 1000)) {
427!
1155
    return code;
×
1156
  }
1157

1158
  code = mndStreamTransConflictCheck(pMnode, pStream->uid, MND_STREAM_CHECKPOINT_NAME, lock);
427✔
1159
  if (code) {
427✔
1160
    mWarn("checkpoint conflict with other trans in %s, code:%s ignore the checkpoint for stream:%s %" PRIx64,
15!
1161
          pStream->sourceDb, tstrerror(code), pStream->name, pStream->uid);
1162
    goto _ERR;
15✔
1163
  }
1164

1165
  code = doCreateTrans(pMnode, pStream, NULL, TRN_CONFLICT_NOTHING, MND_STREAM_CHECKPOINT_NAME,
412✔
1166
                       "gen checkpoint for stream", &pTrans);
1167
  if (code) {
412!
1168
    mError("failed to checkpoint of stream name%s, checkpointId: %" PRId64 ", reason:%s", pStream->name, checkpointId,
×
1169
           tstrerror(code));
1170
    goto _ERR;
×
1171
  }
1172

1173
  code = mndStreamRegisterTrans(pTrans, MND_STREAM_CHECKPOINT_NAME, pStream->uid);
412✔
1174
  if (code) {
412!
1175
    mError("failed to register checkpoint trans for stream:%s, checkpointId:%" PRId64, pStream->name, checkpointId);
×
1176
    goto _ERR;
×
1177
  }
1178

1179
  mDebug("start to trigger checkpoint for stream:%s, checkpoint: %" PRId64 "", pStream->name, checkpointId);
412!
1180

1181
  taosWLockLatch(&pStream->lock);
412✔
1182
  pStream->currentTick = 1;
412✔
1183

1184
  // 1. redo action: broadcast checkpoint source msg for all source vg
1185
  int32_t totalLevel = taosArrayGetSize(pStream->tasks);
412✔
1186
  for (int32_t i = 0; i < totalLevel; i++) {
1,246✔
1187
    SArray      *pLevel = taosArrayGetP(pStream->tasks, i);
834✔
1188
    SStreamTask *p = taosArrayGetP(pLevel, 0);
834✔
1189

1190
    if (p->info.taskLevel == TASK_LEVEL__SOURCE) {
834✔
1191
      int32_t sz = taosArrayGetSize(pLevel);
412✔
1192
      for (int32_t j = 0; j < sz; j++) {
1,678✔
1193
        SStreamTask *pTask = taosArrayGetP(pLevel, j);
1,266✔
1194
        code = mndStreamSetCheckpointAction(pMnode, pTrans, pTask, checkpointId, mndTrigger);
1,266✔
1195

1196
        if (code != TSDB_CODE_SUCCESS) {
1,266!
1197
          taosWUnLockLatch(&pStream->lock);
×
1198
          goto _ERR;
×
1199
        }
1200
      }
1201
    }
1202
  }
1203

1204
  // 2. reset tick
1205
  pStream->checkpointId = checkpointId;
412✔
1206
  pStream->checkpointFreq = taosGetTimestampMs();
412✔
1207
  pStream->currentTick = 0;
412✔
1208

1209
  // 3. commit log: stream checkpoint info
1210
  pStream->version = pStream->version + 1;
412✔
1211
  taosWUnLockLatch(&pStream->lock);
412✔
1212

1213
  if ((code = mndPersistTransLog(pStream, pTrans, SDB_STATUS_READY)) != TSDB_CODE_SUCCESS) {
412!
1214
    goto _ERR;
×
1215
  }
1216

1217
  code = mndTransPrepare(pMnode, pTrans);
412✔
1218
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
412!
1219
    mError("failed to prepare checkpoint trans since %s", tstrerror(code));
×
1220
  } else {
1221
    code = TSDB_CODE_ACTION_IN_PROGRESS;
412✔
1222
  }
1223

1224
_ERR:
427✔
1225
  mndTransDrop(pTrans);
427✔
1226
  return code;
427✔
1227
}
1228

1229
int32_t extractStreamNodeList(SMnode *pMnode) {
1,435✔
1230
  if (taosArrayGetSize(execInfo.pNodeList) == 0) {
1,435✔
1231
    int32_t code = refreshNodeListFromExistedStreams(pMnode, execInfo.pNodeList);
712✔
1232
    if (code) {
712!
1233
      mError("Failed to extract node list from stream, code:%s", tstrerror(code));
×
1234
      return code;
×
1235
    }
1236
  }
1237

1238
  return taosArrayGetSize(execInfo.pNodeList);
1,435✔
1239
}
1240

1241
static int32_t mndCheckTaskAndNodeStatus(SMnode *pMnode) {
943✔
1242
  bool ready = true;
943✔
1243
  if (mndStreamNodeIsUpdated(pMnode)) {
943✔
1244
    TAOS_RETURN(TSDB_CODE_STREAM_TASK_IVLD_STATUS);
10✔
1245
  }
1246

1247
  streamMutexLock(&execInfo.lock);
933✔
1248
  if (taosArrayGetSize(execInfo.pNodeList) == 0) {
933✔
1249
    mDebug("stream task node change checking done, no vgroups exist, do nothing");
712✔
1250
    if (taosArrayGetSize(execInfo.pTaskList) != 0) {
712!
1251
      streamMutexUnlock(&execInfo.lock);
×
1252
      mError("stream task node change checking done, no vgroups exist, but task list is not empty");
×
1253
      return TSDB_CODE_FAILED;
×
1254
    }
1255
  }
1256

1257
  for (int32_t i = 0; i < taosArrayGetSize(execInfo.pTaskList); ++i) {
1,963✔
1258
    STaskId *p = taosArrayGet(execInfo.pTaskList, i);
1,150✔
1259
    if (p == NULL) {
1,150!
1260
      continue;
×
1261
    }
1262

1263
    STaskStatusEntry *pEntry = taosHashGet(execInfo.pTaskMap, p, sizeof(*p));
1,150✔
1264
    if (pEntry == NULL) {
1,150!
1265
      continue;
×
1266
    }
1267

1268
    if (pEntry->status != TASK_STATUS__READY) {
1,150✔
1269
      mDebug("s-task:0x%" PRIx64 "-0x%x (nodeId:%d) status:%s, checkpoint not issued", pEntry->id.streamId,
96!
1270
             (int32_t)pEntry->id.taskId, pEntry->nodeId, streamTaskGetStatusStr(pEntry->status));
1271
      ready = false;
96✔
1272
      break;
96✔
1273
    }
1274

1275
    if (pEntry->hTaskId != 0) {
1,054✔
1276
      mDebug("s-task:0x%" PRIx64 "-0x%x (nodeId:%d) status:%s related fill-history task:0x%" PRIx64
24!
1277
             " exists, checkpoint not issued",
1278
             pEntry->id.streamId, (int32_t)pEntry->id.taskId, pEntry->nodeId, streamTaskGetStatusStr(pEntry->status),
1279
             pEntry->hTaskId);
1280
      ready = false;
24✔
1281
      break;
24✔
1282
    }
1283
  }
1284

1285
  streamMutexUnlock(&execInfo.lock);
933✔
1286
  return ready ? 0 : -1;
933✔
1287
}
1288

1289
int64_t getStreamTaskLastReadyState(SArray *pTaskList, int64_t streamId) {
92✔
1290
  int64_t ts = -1;
92✔
1291
  int32_t taskId = -1;
92✔
1292

1293
  for (int32_t i = 0; i < taosArrayGetSize(pTaskList); ++i) {
968✔
1294
    STaskId          *p = taosArrayGet(pTaskList, i);
876✔
1295
    STaskStatusEntry *pEntry = taosHashGet(execInfo.pTaskMap, p, sizeof(*p));
876✔
1296
    if (p == NULL || pEntry == NULL || pEntry->id.streamId != streamId) {
876!
1297
      continue;
502✔
1298
    }
1299

1300
    if (pEntry->status == TASK_STATUS__READY && ts < pEntry->startTime) {
374!
1301
      ts = pEntry->startTime;
248✔
1302
      taskId = pEntry->id.taskId;
248✔
1303
    }
1304
  }
1305

1306
  mDebug("stream:0x%" PRIx64 " last ready ts:%" PRId64 " s-task:0x%x", streamId, ts, taskId);
92!
1307
  return ts;
92✔
1308
}
1309

1310
typedef struct {
1311
  int64_t streamId;
1312
  int64_t duration;
1313
} SCheckpointInterval;
1314

1315
static int32_t streamWaitComparFn(const void *p1, const void *p2) {
×
1316
  const SCheckpointInterval *pInt1 = p1;
×
1317
  const SCheckpointInterval *pInt2 = p2;
×
1318
  if (pInt1->duration == pInt2->duration) {
×
1319
    return 0;
×
1320
  }
1321

1322
  return pInt1->duration > pInt2->duration ? -1 : 1;
×
1323
}
1324

1325
// all tasks of this stream should be ready, otherwise do nothing
1326
static bool isStreamReadyHelp(int64_t now, SStreamObj* pStream) {
92✔
1327
  bool ready = false;
92✔
1328

1329
  streamMutexLock(&execInfo.lock);
92✔
1330

1331
  int64_t lastReadyTs = getStreamTaskLastReadyState(execInfo.pTaskList, pStream->uid);
92✔
1332
  if ((lastReadyTs == -1) || ((lastReadyTs != -1) && ((now - lastReadyTs) < tsStreamCheckpointInterval * 1000))) {
92!
1333
    if (lastReadyTs != -1) {
90✔
1334
      mInfo("not start checkpoint, stream:0x%"PRIx64" last ready ts:%"PRId64" ready duration:%"PRId64" less than threshold",
84!
1335
            pStream->uid, lastReadyTs, now - lastReadyTs);
1336
    } else {
1337
      mInfo("not start checkpoint, stream:0x%"PRIx64" not ready now", pStream->uid);
6!
1338
    }
1339

1340
    ready = false;
90✔
1341
  } else {
1342
    ready = true;
2✔
1343
  }
1344

1345
  streamMutexUnlock(&execInfo.lock);
92✔
1346
  return ready;
92✔
1347
}
1348

1349
static int32_t mndProcessStreamCheckpoint(SRpcMsg *pReq) {
943✔
1350
  SMnode     *pMnode = pReq->info.node;
943✔
1351
  SSdb       *pSdb = pMnode->pSdb;
943✔
1352
  void       *pIter = NULL;
943✔
1353
  SStreamObj *pStream = NULL;
943✔
1354
  int32_t     code = 0;
943✔
1355
  int32_t     numOfCheckpointTrans = 0;
943✔
1356

1357
  if ((code = mndCheckTaskAndNodeStatus(pMnode)) != 0) {
943✔
1358
    TAOS_RETURN(TSDB_CODE_STREAM_TASK_IVLD_STATUS);
130✔
1359
  }
1360

1361
  SArray *pList = taosArrayInit(4, sizeof(SCheckpointInterval));
813✔
1362
  if (pList == NULL) {
813!
1363
    return terrno;
×
1364
  }
1365

1366
  int64_t now = taosGetTimestampMs();
813✔
1367

1368
  while ((pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream)) != NULL) {
944✔
1369
    int64_t duration = now - pStream->checkpointFreq;
131✔
1370
    if (duration < tsStreamCheckpointInterval * 1000) {
131✔
1371
      sdbRelease(pSdb, pStream);
39✔
1372
      continue;
129✔
1373
    }
1374

1375
    bool ready = isStreamReadyHelp(now, pStream);
92✔
1376
    if (!ready) {
92✔
1377
      sdbRelease(pSdb, pStream);
90✔
1378
      continue;
90✔
1379
    }
1380

1381
    SCheckpointInterval in = {.streamId = pStream->uid, .duration = duration};
2✔
1382
    void               *p = taosArrayPush(pList, &in);
2✔
1383
    if (p) {
2!
1384
      int32_t currentSize = taosArrayGetSize(pList);
2✔
1385
      mDebug("stream:%s (uid:0x%" PRIx64 ") total %d stream(s) beyond chkpt interval threshold: %ds(%" PRId64
2!
1386
             "s), concurrently launch threshold:%d",
1387
             pStream->name, pStream->uid, currentSize, tsStreamCheckpointInterval, duration / 1000,
1388
             tsMaxConcurrentCheckpoint);
1389
    } else {
1390
      mError("failed to record the checkpoint interval info, stream:0x%" PRIx64, pStream->uid);
×
1391
    }
1392
    sdbRelease(pSdb, pStream);
2✔
1393
  }
1394

1395
  int32_t size = taosArrayGetSize(pList);
813✔
1396
  if (size == 0) {
813✔
1397
    taosArrayDestroy(pList);
811✔
1398
    return code;
811✔
1399
  }
1400

1401
  taosArraySort(pList, streamWaitComparFn);
2✔
1402
  code = mndStreamClearFinishedTrans(pMnode, &numOfCheckpointTrans);
2✔
1403
  if (code) {
2!
1404
    mError("failed to clear finish trans, code:%s", tstrerror(code));
×
1405
    taosArrayDestroy(pList);
×
1406
    return code;
×
1407
  }
1408

1409
  int32_t numOfQual = taosArrayGetSize(pList);
2✔
1410
  if (numOfCheckpointTrans > tsMaxConcurrentCheckpoint) {
2!
1411
    mDebug(
×
1412
        "%d stream(s) checkpoint interval longer than %ds, ongoing checkpoint trans:%d reach maximum allowed:%d, new "
1413
        "checkpoint trans are not allowed, wait for 30s",
1414
        numOfQual, tsStreamCheckpointInterval, numOfCheckpointTrans, tsMaxConcurrentCheckpoint);
1415
    taosArrayDestroy(pList);
×
1416
    return code;
×
1417
  }
1418

1419
  int32_t capacity = tsMaxConcurrentCheckpoint - numOfCheckpointTrans;
2✔
1420
  mDebug(
2!
1421
      "%d stream(s) checkpoint interval longer than %ds, %d ongoing checkpoint trans, %d new checkpoint trans allowed, "
1422
      "concurrent trans threshold:%d",
1423
      numOfQual, tsStreamCheckpointInterval, numOfCheckpointTrans, capacity, tsMaxConcurrentCheckpoint);
1424

1425
  int32_t started = 0;
2✔
1426
  int64_t checkpointId = mndStreamGenChkptId(pMnode, true);
2✔
1427

1428
  for (int32_t i = 0; i < numOfQual; ++i) {
2!
1429
    SCheckpointInterval *pCheckpointInfo = taosArrayGet(pList, i);
2✔
1430
    if (pCheckpointInfo == NULL) {
2!
1431
      continue;
×
1432
    }
1433

1434
    SStreamObj *p = NULL;
2✔
1435
    code = mndGetStreamObj(pMnode, pCheckpointInfo->streamId, &p);
2✔
1436
    if (p != NULL && code == 0) {
2!
1437
      code = mndProcessStreamCheckpointTrans(pMnode, p, checkpointId, 1, true);
2✔
1438
      sdbRelease(pSdb, p);
2✔
1439

1440
      if (code == 0 || code == TSDB_CODE_ACTION_IN_PROGRESS) {
2!
1441
        started += 1;
2✔
1442

1443
        if (started >= capacity) {
2!
1444
          mDebug("already start %d new checkpoint trans, current active checkpoint trans:%d", started,
2!
1445
                 (started + numOfCheckpointTrans));
1446
          break;
2✔
1447
        }
1448
      } else {
1449
        mError("failed to start checkpoint trans, code:%s", tstrerror(code));
×
1450
      }
1451
    }
1452
  }
1453

1454
  taosArrayDestroy(pList);
2✔
1455
  return code;
2✔
1456
}
1457

1458
static int32_t mndProcessDropStreamReq(SRpcMsg *pReq) {
583✔
1459
  SMnode     *pMnode = pReq->info.node;
583✔
1460
  SStreamObj *pStream = NULL;
583✔
1461
  int32_t     code = 0;
583✔
1462

1463
  SMDropStreamReq dropReq = {0};
583✔
1464
  if (tDeserializeSMDropStreamReq(pReq->pCont, pReq->contLen, &dropReq) < 0) {
583!
1465
    mError("invalid drop stream msg recv, discarded");
×
1466
    code = TSDB_CODE_INVALID_MSG;
×
1467
    TAOS_RETURN(code);
×
1468
  }
1469

1470
  mDebug("recv drop stream:%s msg", dropReq.name);
583!
1471

1472
  code = mndAcquireStream(pMnode, dropReq.name, &pStream);
583✔
1473
  if (pStream == NULL || code != 0) {
583!
1474
    if (dropReq.igNotExists) {
10!
1475
      mInfo("stream:%s not exist, ignore not exist is set, drop stream exec done with success", dropReq.name);
×
1476
      sdbRelease(pMnode->pSdb, pStream);
×
1477
      tFreeMDropStreamReq(&dropReq);
×
1478
      return 0;
×
1479
    } else {
1480
      mError("stream:%s not exist failed to drop it", dropReq.name);
10!
1481
      tFreeMDropStreamReq(&dropReq);
10✔
1482
      TAOS_RETURN(TSDB_CODE_MND_STREAM_NOT_EXIST);
10✔
1483
    }
1484
  }
1485

1486
  if (pStream->smaId != 0) {
573✔
1487
    mDebug("stream:%s, uid:0x%" PRIx64 " try to drop sma related stream", dropReq.name, pStream->uid);
220!
1488

1489
    void    *pIter = NULL;
220✔
1490
    SSmaObj *pSma = NULL;
220✔
1491
    pIter = sdbFetch(pMnode->pSdb, SDB_SMA, pIter, (void **)&pSma);
220✔
1492
    while (pIter) {
364✔
1493
      if (pSma && pSma->uid == pStream->smaId) {
149!
1494
        sdbRelease(pMnode->pSdb, pSma);
5✔
1495
        sdbRelease(pMnode->pSdb, pStream);
5✔
1496

1497
        sdbCancelFetch(pMnode->pSdb, pIter);
5✔
1498
        tFreeMDropStreamReq(&dropReq);
5✔
1499
        code = TSDB_CODE_TSMA_MUST_BE_DROPPED;
5✔
1500

1501
        mError("try to drop sma-related stream:%s, uid:0x%" PRIx64 " code:%s only allowed to be dropped along with sma",
5!
1502
               dropReq.name, pStream->uid, tstrerror(terrno));
1503
        TAOS_RETURN(code);
5✔
1504
      }
1505

1506
      if (pSma) {
144!
1507
        sdbRelease(pMnode->pSdb, pSma);
144✔
1508
      }
1509

1510
      pIter = sdbFetch(pMnode->pSdb, SDB_SMA, pIter, (void **)&pSma);
144✔
1511
    }
1512
  }
1513

1514
  if (mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pStream->targetDb) != 0) {
568!
1515
    sdbRelease(pMnode->pSdb, pStream);
×
1516
    tFreeMDropStreamReq(&dropReq);
×
1517
    return -1;
×
1518
  }
1519

1520
  // check if it is conflict with other trans in both sourceDb and targetDb.
1521
  code = mndStreamTransConflictCheck(pMnode, pStream->uid, MND_STREAM_DROP_NAME, true);
568✔
1522
  if (code) {
568✔
1523
    sdbRelease(pMnode->pSdb, pStream);
1✔
1524
    tFreeMDropStreamReq(&dropReq);
1✔
1525
    return code;
1✔
1526
  }
1527

1528
  STrans *pTrans = NULL;
567✔
1529
  code = doCreateTrans(pMnode, pStream, pReq, TRN_CONFLICT_NOTHING, MND_STREAM_DROP_NAME, "drop stream", &pTrans);
567✔
1530
  if (pTrans == NULL || code) {
567!
1531
    mError("stream:%s uid:0x%" PRIx64 " failed to drop since %s", dropReq.name, pStream->uid, tstrerror(code));
×
1532
    sdbRelease(pMnode->pSdb, pStream);
×
1533
    tFreeMDropStreamReq(&dropReq);
×
1534
    TAOS_RETURN(code);
×
1535
  }
1536

1537
  code = mndStreamRegisterTrans(pTrans, MND_STREAM_DROP_NAME, pStream->uid);
567✔
1538
  if (code) {
567!
1539
    mError("failed to register drop stream trans, code:%s", tstrerror(code));
×
1540
    sdbRelease(pMnode->pSdb, pStream);
×
1541
    mndTransDrop(pTrans);
×
1542
    tFreeMDropStreamReq(&dropReq);
×
1543
    TAOS_RETURN(code);
×
1544
  }
1545

1546
  // drop all tasks
1547
  code = mndStreamSetDropAction(pMnode, pTrans, pStream);
567✔
1548
  if (code) {
567!
1549
    mError("stream:%s uid:0x%" PRIx64 " failed to drop task since %s", dropReq.name, pStream->uid, tstrerror(code));
×
1550
    sdbRelease(pMnode->pSdb, pStream);
×
1551
    mndTransDrop(pTrans);
×
1552
    tFreeMDropStreamReq(&dropReq);
×
1553
    TAOS_RETURN(code);
×
1554
  }
1555

1556
  // drop stream
1557
  code = mndPersistTransLog(pStream, pTrans, SDB_STATUS_DROPPED);
567✔
1558
  if (code) {
567!
1559
    sdbRelease(pMnode->pSdb, pStream);
×
1560
    mndTransDrop(pTrans);
×
1561
    tFreeMDropStreamReq(&dropReq);
×
1562
    TAOS_RETURN(code);
×
1563
  }
1564

1565
  code = mndTransPrepare(pMnode, pTrans);
567✔
1566
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
567!
1567
    mError("trans:%d, failed to prepare drop stream trans since %s", pTrans->id, tstrerror(code));
×
1568
    sdbRelease(pMnode->pSdb, pStream);
×
1569
    mndTransDrop(pTrans);
×
1570
    tFreeMDropStreamReq(&dropReq);
×
1571
    TAOS_RETURN(code);
×
1572
  }
1573

1574
  // kill the related checkpoint trans
1575
  int32_t transId = mndStreamGetRelTrans(pMnode, pStream->uid);
567✔
1576
  if (transId != 0) {
567!
1577
    mDebug("drop active transId:%d due to stream:%s uid:0x%" PRIx64 " dropped", transId, pStream->name, pStream->uid);
×
1578
    mndKillTransImpl(pMnode, transId, pStream->sourceDb);
×
1579
  }
1580

1581
  mDebug("stream:%s uid:0x%" PRIx64 " transId:%d start to drop related task when dropping stream", dropReq.name,
567!
1582
         pStream->uid, transId);
1583

1584
  removeStreamTasksInBuf(pStream, &execInfo);
567✔
1585

1586
  SName name = {0};
567✔
1587
  code = tNameFromString(&name, dropReq.name, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);
567✔
1588
  auditRecord(pReq, pMnode->clusterId, "dropStream", "", name.dbname, dropReq.sql, dropReq.sqlLen);
567✔
1589

1590
  sdbRelease(pMnode->pSdb, pStream);
567✔
1591
  mndTransDrop(pTrans);
567✔
1592
  tFreeMDropStreamReq(&dropReq);
567✔
1593

1594
  if (code == 0) {
567✔
1595
    return TSDB_CODE_ACTION_IN_PROGRESS;
557✔
1596
  } else {
1597
    TAOS_RETURN(code);
10✔
1598
  }
1599
}
1600

1601
int32_t mndDropStreamByDb(SMnode *pMnode, STrans *pTrans, SDbObj *pDb) {
973✔
1602
  SSdb   *pSdb = pMnode->pSdb;
973✔
1603
  void   *pIter = NULL;
973✔
1604
  int32_t code = 0;
973✔
1605

1606
  while (1) {
60✔
1607
    SStreamObj *pStream = NULL;
1,033✔
1608
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
1,033✔
1609
    if (pIter == NULL) break;
1,033✔
1610

1611
    if (pStream->sourceDbUid == pDb->uid || pStream->targetDbUid == pDb->uid) {
60!
1612
      if (pStream->sourceDbUid != pStream->targetDbUid) {
46!
1613
        sdbRelease(pSdb, pStream);
×
1614
        sdbCancelFetch(pSdb, pIter);
×
1615
        mError("db:%s, failed to drop stream:%s since sourceDbUid:%" PRId64 " not match with targetDbUid:%" PRId64,
×
1616
               pDb->name, pStream->name, pStream->sourceDbUid, pStream->targetDbUid);
1617
        TAOS_RETURN(TSDB_CODE_MND_STREAM_MUST_BE_DELETED);
×
1618
      } else {
1619
        // kill the related checkpoint trans
1620
        int32_t transId = mndStreamGetRelTrans(pMnode, pStream->uid);
46✔
1621
        if (transId != 0) {
46✔
1622
          mDebug("drop active related transId:%d due to stream:%s dropped", transId, pStream->name);
1!
1623
          mndKillTransImpl(pMnode, transId, pStream->sourceDb);
1✔
1624
        }
1625

1626
        // drop the stream obj in execInfo
1627
        removeStreamTasksInBuf(pStream, &execInfo);
46✔
1628

1629
        code = mndPersistTransLog(pStream, pTrans, SDB_STATUS_DROPPED);
46✔
1630
        if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
46!
1631
          sdbRelease(pSdb, pStream);
×
1632
          sdbCancelFetch(pSdb, pIter);
×
1633
          return code;
×
1634
        }
1635
      }
1636
    }
1637

1638
    sdbRelease(pSdb, pStream);
60✔
1639
  }
1640

1641
  return 0;
973✔
1642
}
1643

1644
static int32_t mndRetrieveStream(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
120✔
1645
  SMnode     *pMnode = pReq->info.node;
120✔
1646
  SSdb       *pSdb = pMnode->pSdb;
120✔
1647
  int32_t     numOfRows = 0;
120✔
1648
  SStreamObj *pStream = NULL;
120✔
1649
  int32_t     code = 0;
120✔
1650

1651
  while (numOfRows < rows) {
350!
1652
    pShow->pIter = sdbFetch(pSdb, SDB_STREAM, pShow->pIter, (void **)&pStream);
350✔
1653
    if (pShow->pIter == NULL) break;
350✔
1654

1655
    code = setStreamAttrInResBlock(pStream, pBlock, numOfRows);
230✔
1656
    if (code == 0) {
230!
1657
      numOfRows++;
230✔
1658
    }
1659
    sdbRelease(pSdb, pStream);
230✔
1660
  }
1661

1662
  pShow->numOfRows += numOfRows;
120✔
1663
  return numOfRows;
120✔
1664
}
1665

1666
static void mndCancelGetNextStream(SMnode *pMnode, void *pIter) {
×
1667
  SSdb *pSdb = pMnode->pSdb;
×
1668
  sdbCancelFetchByType(pSdb, pIter, SDB_STREAM);
×
1669
}
×
1670

1671
static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rowsCapacity) {
498✔
1672
  SMnode     *pMnode = pReq->info.node;
498✔
1673
  SSdb       *pSdb = pMnode->pSdb;
498✔
1674
  int32_t     numOfRows = 0;
498✔
1675
  SStreamObj *pStream = NULL;
498✔
1676
  int32_t     code = 0;
498✔
1677

1678
  streamMutexLock(&execInfo.lock);
498✔
1679
  mndInitStreamExecInfo(pMnode, &execInfo);
498✔
1680
  streamMutexUnlock(&execInfo.lock);
498✔
1681

1682
  while (numOfRows < rowsCapacity) {
1,120!
1683
    pShow->pIter = sdbFetch(pSdb, SDB_STREAM, pShow->pIter, (void **)&pStream);
1,120✔
1684
    if (pShow->pIter == NULL) {
1,120✔
1685
      break;
498✔
1686
    }
1687

1688
    // lock
1689
    taosRLockLatch(&pStream->lock);
622✔
1690

1691
    int32_t count = mndGetNumOfStreamTasks(pStream);
622✔
1692
    if (numOfRows + count > rowsCapacity) {
622!
1693
      code = blockDataEnsureCapacity(pBlock, numOfRows + count);
×
1694
      if (code) {
×
1695
        mError("failed to prepare the result block buffer, quit return value");
×
1696
        taosRUnLockLatch(&pStream->lock);
×
1697
        sdbRelease(pSdb, pStream);
×
1698
        continue;
×
1699
      }
1700
    }
1701

1702
    int32_t precision = TSDB_TIME_PRECISION_MILLI;
622✔
1703
    SDbObj *pSourceDb = mndAcquireDb(pMnode, pStream->sourceDb);
622✔
1704
    if (pSourceDb != NULL) {
622!
1705
      precision = pSourceDb->cfg.precision;
622✔
1706
      mndReleaseDb(pMnode, pSourceDb);
622✔
1707
    }
1708

1709
    // add row for each task
1710
    SStreamTaskIter *pIter = NULL;
622✔
1711
    code = createStreamTaskIter(pStream, &pIter);
622✔
1712
    if (code) {
622!
1713
      taosRUnLockLatch(&pStream->lock);
×
1714
      sdbRelease(pSdb, pStream);
×
1715
      mError("failed to create task iter for stream:%s", pStream->name);
×
1716
      continue;
×
1717
    }
1718

1719
    while (streamTaskIterNextTask(pIter)) {
4,622✔
1720
      SStreamTask *pTask = NULL;
4,000✔
1721
      code = streamTaskIterGetCurrent(pIter, &pTask);
4,000✔
1722
      if (code) {
4,000!
1723
        destroyStreamTaskIter(pIter);
×
1724
        break;
×
1725
      }
1726

1727
      code = setTaskAttrInResBlock(pStream, pTask, pBlock, numOfRows, precision);
4,000✔
1728
      if (code == TSDB_CODE_SUCCESS) {
4,000!
1729
        numOfRows++;
4,000✔
1730
      }
1731
    }
1732

1733
    pBlock->info.rows = numOfRows;
622✔
1734

1735
    destroyStreamTaskIter(pIter);
622✔
1736
    taosRUnLockLatch(&pStream->lock);
622✔
1737

1738
    sdbRelease(pSdb, pStream);
622✔
1739
  }
1740

1741
  pShow->numOfRows += numOfRows;
498✔
1742
  return numOfRows;
498✔
1743
}
1744

1745
static void mndCancelGetNextStreamTask(SMnode *pMnode, void *pIter) {
×
1746
  SSdb *pSdb = pMnode->pSdb;
×
1747
  sdbCancelFetchByType(pSdb, pIter, SDB_STREAM);
×
1748
}
×
1749

1750
static int32_t mndProcessPauseStreamReq(SRpcMsg *pReq) {
511✔
1751
  SMnode     *pMnode = pReq->info.node;
511✔
1752
  SStreamObj *pStream = NULL;
511✔
1753
  int32_t     code = 0;
511✔
1754

1755
  SMPauseStreamReq pauseReq = {0};
511✔
1756
  if (tDeserializeSMPauseStreamReq(pReq->pCont, pReq->contLen, &pauseReq) < 0) {
511!
1757
    TAOS_RETURN(TSDB_CODE_INVALID_MSG);
×
1758
  }
1759

1760
  code = mndAcquireStream(pMnode, pauseReq.name, &pStream);
511✔
1761
  if (pStream == NULL || code != 0) {
511!
1762
    if (pauseReq.igNotExists) {
294✔
1763
      mInfo("stream:%s, not exist, not pause stream", pauseReq.name);
126!
1764
      return 0;
126✔
1765
    } else {
1766
      mError("stream:%s not exist, failed to pause stream", pauseReq.name);
168!
1767
      TAOS_RETURN(TSDB_CODE_MND_STREAM_NOT_EXIST);
168✔
1768
    }
1769
  }
1770

1771
  mInfo("stream:%s,%" PRId64 " start to pause stream", pauseReq.name, pStream->uid);
217!
1772

1773
  if ((code = mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pStream->targetDb)) != 0) {
217!
1774
    sdbRelease(pMnode->pSdb, pStream);
×
1775
    return code;
×
1776
  }
1777

1778
  // check if it is conflict with other trans in both sourceDb and targetDb.
1779
  code = mndStreamTransConflictCheck(pMnode, pStream->uid, MND_STREAM_PAUSE_NAME, true);
217✔
1780
  if (code) {
217!
1781
    sdbRelease(pMnode->pSdb, pStream);
×
1782
    TAOS_RETURN(code);
×
1783
  }
1784

1785
  bool updated = mndStreamNodeIsUpdated(pMnode);
217✔
1786
  if (updated) {
217!
1787
    mError("tasks are not ready for pause, node update detected");
×
1788
    sdbRelease(pMnode->pSdb, pStream);
×
1789
    TAOS_RETURN(TSDB_CODE_STREAM_TASK_IVLD_STATUS);
×
1790
  }
1791

1792
  {  // check for tasks, if tasks are not ready, not allowed to pause
1793
    bool found = false;
217✔
1794
    bool readyToPause = true;
217✔
1795
    streamMutexLock(&execInfo.lock);
217✔
1796

1797
    for (int32_t i = 0; i < taosArrayGetSize(execInfo.pTaskList); ++i) {
2,746✔
1798
      STaskId *p = taosArrayGet(execInfo.pTaskList, i);
2,529✔
1799
      if (p == NULL) {
2,529!
1800
        continue;
×
1801
      }
1802

1803
      STaskStatusEntry *pEntry = taosHashGet(execInfo.pTaskMap, p, sizeof(*p));
2,529✔
1804
      if (pEntry == NULL) {
2,529!
1805
        continue;
×
1806
      }
1807

1808
      if (pEntry->id.streamId != pStream->uid) {
2,529✔
1809
        continue;
1,616✔
1810
      }
1811

1812
      if (pEntry->status == TASK_STATUS__UNINIT || pEntry->status == TASK_STATUS__CK) {
913!
1813
        mError("stream:%s uid:0x%" PRIx64 " vgId:%d task:0x%" PRIx64 " status:%s, not ready for pause", pStream->name,
117!
1814
               pStream->uid, pEntry->nodeId, pEntry->id.taskId, streamTaskGetStatusStr(pEntry->status));
1815
        readyToPause = false;
117✔
1816
      }
1817

1818
      found = true;
913✔
1819
    }
1820

1821
    streamMutexUnlock(&execInfo.lock);
217✔
1822
    if (!found) {
217!
1823
      mError("stream:%s task not report status yet, not ready for pause", pauseReq.name);
×
1824
      sdbRelease(pMnode->pSdb, pStream);
×
1825
      TAOS_RETURN(TSDB_CODE_STREAM_TASK_IVLD_STATUS);
×
1826
    }
1827

1828
    if (!readyToPause) {
217✔
1829
      mError("stream:%s task not ready for pause yet", pauseReq.name);
34!
1830
      sdbRelease(pMnode->pSdb, pStream);
34✔
1831
      TAOS_RETURN(TSDB_CODE_STREAM_TASK_IVLD_STATUS);
34✔
1832
    }
1833
  }
1834

1835
  STrans *pTrans = NULL;
183✔
1836
  code = doCreateTrans(pMnode, pStream, pReq, TRN_CONFLICT_NOTHING, MND_STREAM_PAUSE_NAME, "pause the stream", &pTrans);
183✔
1837
  if (pTrans == NULL || code) {
183!
1838
    mError("stream:%s failed to pause stream since %s", pauseReq.name, tstrerror(code));
×
1839
    sdbRelease(pMnode->pSdb, pStream);
×
1840
    return code;
×
1841
  }
1842

1843
  code = mndStreamRegisterTrans(pTrans, MND_STREAM_PAUSE_NAME, pStream->uid);
183✔
1844
  if (code) {
183!
1845
    sdbRelease(pMnode->pSdb, pStream);
×
1846
    mndTransDrop(pTrans);
×
1847
    return code;
×
1848
  }
1849

1850
  // if nodeUpdate happened, not send pause trans
1851
  code = mndStreamSetPauseAction(pMnode, pTrans, pStream);
183✔
1852
  if (code) {
183!
1853
    mError("stream:%s, failed to pause task since %s", pauseReq.name, tstrerror(code));
×
1854
    sdbRelease(pMnode->pSdb, pStream);
×
1855
    mndTransDrop(pTrans);
×
1856
    return code;
×
1857
  }
1858

1859
  // pause stream
1860
  taosWLockLatch(&pStream->lock);
183✔
1861
  code = mndPersistTransLog(pStream, pTrans, SDB_STATUS_READY);
183✔
1862
  if (code) {
183!
1863
    taosWUnLockLatch(&pStream->lock);
×
1864
    sdbRelease(pMnode->pSdb, pStream);
×
1865
    mndTransDrop(pTrans);
×
1866
    return code;
×
1867
  }
1868

1869
  taosWUnLockLatch(&pStream->lock);
183✔
1870

1871
  code = mndTransPrepare(pMnode, pTrans);
183✔
1872
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
183!
1873
    mError("trans:%d, failed to prepare pause stream trans since %s", pTrans->id, tstrerror(code));
×
1874
    sdbRelease(pMnode->pSdb, pStream);
×
1875
    mndTransDrop(pTrans);
×
1876
    return code;
×
1877
  }
1878

1879
  sdbRelease(pMnode->pSdb, pStream);
183✔
1880
  mndTransDrop(pTrans);
183✔
1881

1882
  return TSDB_CODE_ACTION_IN_PROGRESS;
183✔
1883
}
1884

1885
static int32_t mndProcessResumeStreamReq(SRpcMsg *pReq) {
603✔
1886
  SMnode     *pMnode = pReq->info.node;
603✔
1887
  SStreamObj *pStream = NULL;
603✔
1888
  int32_t     code = 0;
603✔
1889

1890
  if ((code = grantCheckExpire(TSDB_GRANT_STREAMS)) < 0) {
603!
1891
    return code;
×
1892
  }
1893

1894
  SMResumeStreamReq resumeReq = {0};
603✔
1895
  if (tDeserializeSMResumeStreamReq(pReq->pCont, pReq->contLen, &resumeReq) < 0) {
603!
1896
    TAOS_RETURN(TSDB_CODE_INVALID_MSG);
×
1897
  }
1898

1899
  code = mndAcquireStream(pMnode, resumeReq.name, &pStream);
603✔
1900
  if (pStream == NULL || code != 0) {
603!
1901
    if (resumeReq.igNotExists) {
252!
1902
      mInfo("stream:%s not exist, not resume stream", resumeReq.name);
252!
1903
      sdbRelease(pMnode->pSdb, pStream);
252✔
1904
      return 0;
252✔
1905
    } else {
1906
      mError("stream:%s not exist, failed to resume stream", resumeReq.name);
×
1907
      TAOS_RETURN(TSDB_CODE_MND_STREAM_NOT_EXIST);
×
1908
    }
1909
  }
1910

1911
  mInfo("stream:%s,%" PRId64 " start to resume stream from pause", resumeReq.name, pStream->uid);
351!
1912
  if (mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pStream->targetDb) != 0) {
351!
1913
    sdbRelease(pMnode->pSdb, pStream);
×
1914
    return -1;
×
1915
  }
1916

1917
  // check if it is conflict with other trans in both sourceDb and targetDb.
1918
  code = mndStreamTransConflictCheck(pMnode, pStream->uid, MND_STREAM_RESUME_NAME, true);
351✔
1919
  if (code) {
351!
1920
    sdbRelease(pMnode->pSdb, pStream);
×
1921
    return code;
×
1922
  }
1923

1924
  STrans *pTrans = NULL;
351✔
1925
  code =
1926
      doCreateTrans(pMnode, pStream, pReq, TRN_CONFLICT_NOTHING, MND_STREAM_RESUME_NAME, "resume the stream", &pTrans);
351✔
1927
  if (pTrans == NULL || code) {
351!
1928
    mError("stream:%s, failed to resume stream since %s", resumeReq.name, tstrerror(code));
×
1929
    sdbRelease(pMnode->pSdb, pStream);
×
1930
    return code;
×
1931
  }
1932

1933
  code = mndStreamRegisterTrans(pTrans, MND_STREAM_RESUME_NAME, pStream->uid);
351✔
1934
  if (code) {
351!
1935
    sdbRelease(pMnode->pSdb, pStream);
×
1936
    mndTransDrop(pTrans);
×
1937
    return code;
×
1938
  }
1939

1940
  // set the resume action
1941
  code = mndStreamSetResumeAction(pTrans, pMnode, pStream, resumeReq.igUntreated);
351✔
1942
  if (code) {
351!
1943
    mError("stream:%s, failed to drop task since %s", resumeReq.name, tstrerror(code));
×
1944
    sdbRelease(pMnode->pSdb, pStream);
×
1945
    mndTransDrop(pTrans);
×
1946
    return code;
×
1947
  }
1948

1949
  // resume stream
1950
  taosWLockLatch(&pStream->lock);
351✔
1951
  pStream->status = STREAM_STATUS__NORMAL;
351✔
1952
  if (mndPersistTransLog(pStream, pTrans, SDB_STATUS_READY) < 0) {
351!
1953
    taosWUnLockLatch(&pStream->lock);
×
1954

1955
    sdbRelease(pMnode->pSdb, pStream);
×
1956
    mndTransDrop(pTrans);
×
1957
    return code;
×
1958
  }
1959

1960
  taosWUnLockLatch(&pStream->lock);
351✔
1961
  code = mndTransPrepare(pMnode, pTrans);
351✔
1962
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
351!
1963
    mError("trans:%d, failed to prepare pause stream trans since %s", pTrans->id, tstrerror(code));
×
1964
    sdbRelease(pMnode->pSdb, pStream);
×
1965
    mndTransDrop(pTrans);
×
1966
    return code;
×
1967
  }
1968

1969
  sdbRelease(pMnode->pSdb, pStream);
351✔
1970
  mndTransDrop(pTrans);
351✔
1971

1972
  return TSDB_CODE_ACTION_IN_PROGRESS;
351✔
1973
}
1974

1975
static int32_t mndProcessResetStreamReq(SRpcMsg *pReq) {
×
1976
  SMnode     *pMnode = pReq->info.node;
×
1977
  SStreamObj *pStream = NULL;
×
1978
  int32_t     code = 0;
×
1979

1980
  if ((code = grantCheckExpire(TSDB_GRANT_STREAMS)) < 0) {
×
1981
    return code;
×
1982
  }
1983

1984
  SMResetStreamReq resetReq = {0};
×
1985
  if (tDeserializeSMResetStreamReq(pReq->pCont, pReq->contLen, &resetReq) < 0) {
×
1986
    TAOS_RETURN(TSDB_CODE_INVALID_MSG);
×
1987
  }
1988

1989
  mDebug("recv reset stream req, stream:%s", resetReq.name);
×
1990

1991
  code = mndAcquireStream(pMnode, resetReq.name, &pStream);
×
1992
  if (pStream == NULL || code != 0) {
×
1993
    if (resetReq.igNotExists) {
×
1994
      mInfo("stream:%s, not exist, not pause stream", resetReq.name);
×
1995
      return 0;
×
1996
    } else {
1997
      mError("stream:%s not exist, failed to pause stream", resetReq.name);
×
1998
      TAOS_RETURN(TSDB_CODE_MND_STREAM_NOT_EXIST);
×
1999
    }
2000
  }
2001

2002
  //todo(liao hao jun)
2003
  return TSDB_CODE_ACTION_IN_PROGRESS;
×
2004
}
2005

2006
static int32_t mndProcessVgroupChange(SMnode *pMnode, SVgroupChangeInfo *pChangeInfo, bool includeAllNodes) {
3✔
2007
  SSdb       *pSdb = pMnode->pSdb;
3✔
2008
  SStreamObj *pStream = NULL;
3✔
2009
  void       *pIter = NULL;
3✔
2010
  STrans     *pTrans = NULL;
3✔
2011
  int32_t     code = 0;
3✔
2012

2013
  // conflict check for nodeUpdate trans, here we randomly chose one stream to add into the trans pool
2014
  while (1) {
2015
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
6✔
2016
    if (pIter == NULL) {
6✔
2017
      break;
3✔
2018
    }
2019

2020
    code = mndStreamTransConflictCheck(pMnode, pStream->uid, MND_STREAM_TASK_UPDATE_NAME, false);
3✔
2021
    sdbRelease(pSdb, pStream);
3✔
2022

2023
    if (code) {
3!
2024
      mError("nodeUpdate conflict with other trans, current nodeUpdate ignored, code:%s", tstrerror(code));
×
2025
      sdbCancelFetch(pSdb, pIter);
×
2026
      return code;
×
2027
    }
2028
  }
2029

2030
  while (1) {
2031
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
6✔
2032
    if (pIter == NULL) {
6✔
2033
      break;
3✔
2034
    }
2035

2036
    // here create only one trans
2037
    if (pTrans == NULL) {
3!
2038
      code = doCreateTrans(pMnode, pStream, NULL, TRN_CONFLICT_NOTHING, MND_STREAM_TASK_UPDATE_NAME,
3✔
2039
                           "update task epsets", &pTrans);
2040
      if (pTrans == NULL || code) {
3!
2041
        sdbRelease(pSdb, pStream);
×
2042
        sdbCancelFetch(pSdb, pIter);
×
2043
        return terrno = code;
×
2044
      }
2045
    }
2046

2047
    if (!includeAllNodes) {
3!
2048
      void *p1 = taosHashGet(pChangeInfo->pDBMap, pStream->targetDb, strlen(pStream->targetDb));
3✔
2049
      void *p2 = taosHashGet(pChangeInfo->pDBMap, pStream->sourceDb, strlen(pStream->sourceDb));
3✔
2050
      if (p1 == NULL && p2 == NULL) {
3!
2051
        mDebug("stream:0x%" PRIx64 " %s not involved nodeUpdate, ignore", pStream->uid, pStream->name);
×
2052
        sdbRelease(pSdb, pStream);
×
2053
        continue;
×
2054
      }
2055
    }
2056

2057
    mDebug("stream:0x%" PRIx64 " %s involved node changed, create update trans, transId:%d", pStream->uid,
3!
2058
           pStream->name, pTrans->id);
2059

2060
    // NOTE: for each stream, we register one trans entry for task update
2061
    code = mndStreamRegisterTrans(pTrans, MND_STREAM_TASK_UPDATE_NAME, pStream->uid);
3✔
2062
    if (code) {
3!
2063
      mError("failed to register trans, transId:%d, and continue", pTrans->id);
×
2064
    }
2065

2066
    code = mndStreamSetUpdateEpsetAction(pMnode, pStream, pChangeInfo, pTrans);
3✔
2067

2068
    // todo: not continue, drop all and retry again
2069
    if (code != TSDB_CODE_SUCCESS) {
3!
2070
      mError("stream:0x%" PRIx64 " build nodeUpdate trans failed, ignore and continue, code:%s", pStream->uid,
×
2071
             tstrerror(code));
2072
      sdbRelease(pSdb, pStream);
×
2073
      continue;
×
2074
    }
2075

2076
    code = mndPersistTransLog(pStream, pTrans, SDB_STATUS_READY);
3✔
2077
    sdbRelease(pSdb, pStream);
3✔
2078

2079
    if (code != TSDB_CODE_SUCCESS) {
3!
2080
      sdbCancelFetch(pSdb, pIter);
×
2081
      return code;
×
2082
    }
2083
  }
2084

2085
  // no need to build the trans to handle the vgroup update
2086
  if (pTrans == NULL) {
3!
2087
    return 0;
×
2088
  }
2089

2090
  code = mndTransPrepare(pMnode, pTrans);
3✔
2091
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
3!
2092
    mError("trans:%d, failed to prepare update stream trans since %s", pTrans->id, tstrerror(code));
×
2093
    sdbRelease(pMnode->pSdb, pStream);
×
2094
    mndTransDrop(pTrans);
×
2095
    return code;
×
2096
  }
2097

2098
  sdbRelease(pMnode->pSdb, pStream);
3✔
2099
  mndTransDrop(pTrans);
3✔
2100
  return code;
3✔
2101
}
2102

2103
static int32_t refreshNodeListFromExistedStreams(SMnode *pMnode, SArray *pNodeList) {
715✔
2104
  SSdb       *pSdb = pMnode->pSdb;
715✔
2105
  SStreamObj *pStream = NULL;
715✔
2106
  void       *pIter = NULL;
715✔
2107
  int32_t     code = 0;
715✔
2108

2109
  mDebug("start to refresh node list by existed streams");
715✔
2110

2111
  SHashObj *pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false, HASH_NO_LOCK);
715✔
2112
  if (pHash == NULL) {
715!
2113
    return terrno;
×
2114
  }
2115

2116
  while (1) {
3✔
2117
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
718✔
2118
    if (pIter == NULL) {
718✔
2119
      break;
715✔
2120
    }
2121

2122
    taosWLockLatch(&pStream->lock);
3✔
2123

2124
    SStreamTaskIter *pTaskIter = NULL;
3✔
2125
    code = createStreamTaskIter(pStream, &pTaskIter);
3✔
2126
    if (code) {
3!
2127
      taosWUnLockLatch(&pStream->lock);
×
2128
      sdbRelease(pSdb, pStream);
×
2129
      mError("failed to create task iter for stream:%s", pStream->name);
×
2130
      continue;
×
2131
    }
2132

2133
    while (streamTaskIterNextTask(pTaskIter)) {
24✔
2134
      SStreamTask *pTask = NULL;
21✔
2135
      code = streamTaskIterGetCurrent(pTaskIter, &pTask);
21✔
2136
      if (code) {
21!
2137
        break;
×
2138
      }
2139

2140
      SNodeEntry entry = {.hbTimestamp = -1, .nodeId = pTask->info.nodeId, .lastHbMsgId = -1};
21✔
2141
      epsetAssign(&entry.epset, &pTask->info.epSet);
21✔
2142
      int32_t ret = taosHashPut(pHash, &entry.nodeId, sizeof(entry.nodeId), &entry, sizeof(entry));
21✔
2143
      if (ret != 0 && ret != TSDB_CODE_DUP_KEY) {
21!
2144
        mError("failed to put entry into hash map, nodeId:%d, code:%s", entry.nodeId, tstrerror(code));
×
2145
      }
2146
    }
2147

2148
    destroyStreamTaskIter(pTaskIter);
3✔
2149
    taosWUnLockLatch(&pStream->lock);
3✔
2150

2151
    sdbRelease(pSdb, pStream);
3✔
2152
  }
2153

2154
  taosArrayClear(pNodeList);
715✔
2155

2156
  // convert to list
2157
  pIter = NULL;
715✔
2158
  while ((pIter = taosHashIterate(pHash, pIter)) != NULL) {
727✔
2159
    SNodeEntry *pEntry = (SNodeEntry *)pIter;
12✔
2160

2161
    void *p = taosArrayPush(pNodeList, pEntry);
12✔
2162
    if (p == NULL) {
12!
2163
      mError("failed to put entry into node list, nodeId:%d, code: out of memory", pEntry->nodeId);
×
2164
      if (code == 0) {
×
2165
        code = terrno;
×
2166
      }
2167
      continue;
×
2168
    }
2169

2170
    char    buf[256] = {0};
12✔
2171
    int32_t ret = epsetToStr(&pEntry->epset, buf, tListLen(buf));  // ignore this error since it is only for log file
12✔
2172
    if (ret != 0) {                                                // print error and continue
12!
2173
      mError("failed to convert epset to str, code:%s", tstrerror(ret));
×
2174
    }
2175

2176
    mDebug("extract nodeInfo from stream obj, nodeId:%d, %s", pEntry->nodeId, buf);
12!
2177
  }
2178

2179
  taosHashCleanup(pHash);
715✔
2180

2181
  mDebug("numOfNodes:%d for stream after extract nodeInfo from stream", (int32_t)taosArrayGetSize(pNodeList));
715✔
2182
  return code;
715✔
2183
}
2184

2185
static void addAllDbsIntoHashmap(SHashObj *pDBMap, SSdb *pSdb) {
×
2186
  void   *pIter = NULL;
×
2187
  int32_t code = 0;
×
2188
  while (1) {
×
2189
    SVgObj *pVgroup = NULL;
×
2190
    pIter = sdbFetch(pSdb, SDB_VGROUP, pIter, (void **)&pVgroup);
×
2191
    if (pIter == NULL) {
×
2192
      break;
×
2193
    }
2194

2195
    code = taosHashPut(pDBMap, pVgroup->dbName, strlen(pVgroup->dbName), NULL, 0);
×
2196
    sdbRelease(pSdb, pVgroup);
×
2197

2198
    if (code == 0) {
×
2199
      int32_t size = taosHashGetSize(pDBMap);
×
2200
      mDebug("add Db:%s into Dbs list (total:%d) for kill checkpoint trans", pVgroup->dbName, size);
×
2201
    }
2202
  }
2203
}
×
2204

2205
// this function runs by only one thread, so it is not multi-thread safe
2206
static int32_t mndProcessNodeCheckReq(SRpcMsg *pMsg) {
275✔
2207
  int32_t code = 0;
275✔
2208
  bool    allReady = true;
275✔
2209
  SArray *pNodeSnapshot = NULL;
275✔
2210
  SMnode *pMnode = pMsg->info.node;
275✔
2211
  int64_t ts = taosGetTimestampSec();
275✔
2212
  bool    updateAllVgroups = false;
275✔
2213

2214
  int32_t old = atomic_val_compare_exchange_32(&mndNodeCheckSentinel, 0, 1);
275✔
2215
  if (old != 0) {
275!
2216
    mDebug("still in checking node change");
×
2217
    return 0;
×
2218
  }
2219

2220
  mDebug("start to do node changing check");
275!
2221

2222
  streamMutexLock(&execInfo.lock);
275✔
2223
  int32_t numOfNodes = extractStreamNodeList(pMnode);
275✔
2224
  streamMutexUnlock(&execInfo.lock);
275✔
2225

2226
  if (numOfNodes == 0) {
275!
2227
    mDebug("end to do stream task(s) node change checking, no stream tasks exist, do nothing");
×
2228
    execInfo.ts = ts;
×
2229
    atomic_store_32(&mndNodeCheckSentinel, 0);
×
2230
    return 0;
×
2231
  }
2232

2233
  code = mndTakeVgroupSnapshot(pMnode, &allReady, &pNodeSnapshot);
275✔
2234
  if (code) {
275!
2235
    mError("failed to take the vgroup snapshot, ignore it and continue");
×
2236
  }
2237

2238
  if (!allReady) {
275✔
2239
    taosArrayDestroy(pNodeSnapshot);
9✔
2240
    atomic_store_32(&mndNodeCheckSentinel, 0);
9✔
2241
    mWarn("not all vnodes are ready, ignore the exec nodeUpdate check");
9!
2242
    return 0;
9✔
2243
  }
2244

2245
  streamMutexLock(&execInfo.lock);
266✔
2246

2247
  code = removeExpiredNodeEntryAndTaskInBuf(pNodeSnapshot);
266✔
2248
  if (code) {
266!
2249
    goto _end;
×
2250
  }
2251

2252
  SVgroupChangeInfo changeInfo = {0};
266✔
2253
  code = mndFindChangedNodeInfo(pMnode, execInfo.pNodeList, pNodeSnapshot, &changeInfo);
266✔
2254
  if (code) {
266!
2255
    goto _end;
×
2256
  }
2257

2258
  {
2259
    if (execInfo.role == NODE_ROLE_LEADER && execInfo.switchFromFollower) {
266!
2260
      mInfo("rollback all stream due to mnode leader/follower switch by using nodeUpdate trans");
×
2261
      updateAllVgroups = true;
×
2262
      execInfo.switchFromFollower = false;  // reset the flag
×
2263
      addAllDbsIntoHashmap(changeInfo.pDBMap, pMnode->pSdb);
×
2264
    }
2265
  }
2266

2267
  if (taosArrayGetSize(changeInfo.pUpdateNodeList) > 0 || updateAllVgroups) {
266!
2268
    // kill current active checkpoint transaction, since the transaction is vnode wide.
2269
    killAllCheckpointTrans(pMnode, &changeInfo);
3✔
2270
    code = mndProcessVgroupChange(pMnode, &changeInfo, updateAllVgroups);
3✔
2271

2272
    // keep the new vnode snapshot if success
2273
    if (code == TSDB_CODE_SUCCESS || code == TSDB_CODE_ACTION_IN_PROGRESS) {
3!
2274
      code = refreshNodeListFromExistedStreams(pMnode, execInfo.pNodeList);
3✔
2275
      if (code) {
3!
2276
        mError("failed to extract node list from stream, code:%s", tstrerror(code));
×
2277
        goto _end;
×
2278
      }
2279

2280
      execInfo.ts = ts;
3✔
2281
      mDebug("create trans successfully, update cached node list, numOfNodes:%d",
3!
2282
             (int)taosArrayGetSize(execInfo.pNodeList));
2283
    } else {
2284
      mError("unexpected code during create nodeUpdate trans, code:%s", tstrerror(code));
×
2285
    }
2286
  } else {
2287
    mDebug("no update found in nodeList");
263!
2288
  }
2289

2290
  mndDestroyVgroupChangeInfo(&changeInfo);
266✔
2291

2292
_end:
266✔
2293
  streamMutexUnlock(&execInfo.lock);
266✔
2294
  taosArrayDestroy(pNodeSnapshot);
266✔
2295

2296
  mDebug("end to do stream task node change checking");
266!
2297
  atomic_store_32(&mndNodeCheckSentinel, 0);
266✔
2298
  return 0;
266✔
2299
}
2300

2301
static int32_t mndProcessNodeCheck(SRpcMsg *pReq) {
1,597✔
2302
  SMnode *pMnode = pReq->info.node;
1,597✔
2303
  SSdb   *pSdb = pMnode->pSdb;
1,597✔
2304
  if (sdbGetSize(pSdb, SDB_STREAM) <= 0) {
1,597✔
2305
    return 0;
1,322✔
2306
  }
2307

2308
  int32_t               size = sizeof(SMStreamNodeCheckMsg);
275✔
2309
  SMStreamNodeCheckMsg *pMsg = rpcMallocCont(size);
275✔
2310
  if (pMsg == NULL) {
275!
2311
    return terrno;
×
2312
  }
2313

2314
  SRpcMsg rpcMsg = {.msgType = TDMT_MND_STREAM_NODECHANGE_CHECK, .pCont = pMsg, .contLen = size};
275✔
2315
  return tmsgPutToQueue(&pMnode->msgCb, WRITE_QUEUE, &rpcMsg);
275✔
2316
}
2317

2318
void saveTaskAndNodeInfoIntoBuf(SStreamObj *pStream, SStreamExecInfo *pExecNode) {
720✔
2319
  SStreamTaskIter *pIter = NULL;
720✔
2320
  int32_t          code = createStreamTaskIter(pStream, &pIter);
720✔
2321
  if (code) {
720!
2322
    mError("failed to create task iter for stream:%s", pStream->name);
×
2323
    return;
×
2324
  }
2325

2326
  while (streamTaskIterNextTask(pIter)) {
4,614✔
2327
    SStreamTask *pTask = NULL;
3,894✔
2328
    code = streamTaskIterGetCurrent(pIter, &pTask);
3,894✔
2329
    if (code) {
3,894!
2330
      break;
×
2331
    }
2332

2333
    STaskId id = {.streamId = pTask->id.streamId, .taskId = pTask->id.taskId};
3,894✔
2334
    void   *p = taosHashGet(pExecNode->pTaskMap, &id, sizeof(id));
3,894✔
2335
    if (p == NULL) {
3,894✔
2336
      STaskStatusEntry entry = {0};
3,654✔
2337
      streamTaskStatusInit(&entry, pTask);
3,654✔
2338

2339
      code = taosHashPut(pExecNode->pTaskMap, &id, sizeof(id), &entry, sizeof(entry));
3,654✔
2340
      if (code == 0) {
3,654!
2341
        void   *px = taosArrayPush(pExecNode->pTaskList, &id);
3,654✔
2342
        int32_t num = (int32_t)taosArrayGetSize(pExecNode->pTaskList);
3,654✔
2343
        if (px) {
3,654!
2344
          mInfo("s-task:0x%x add into task buffer, total:%d", (int32_t)entry.id.taskId, num);
3,654!
2345
        } else {
2346
          mError("s-task:0x%x failed to add into task buffer, total:%d", (int32_t)entry.id.taskId, num);
×
2347
        }
2348
      } else {
2349
        mError("s-task:0x%x failed to add into task map, since out of memory", (int32_t)entry.id.taskId);
×
2350
      }
2351

2352
      // add the new vgroups if not added yet
2353
      bool exist = false;
3,654✔
2354
      for (int32_t j = 0; j < taosArrayGetSize(pExecNode->pNodeList); ++j) {
14,107✔
2355
        SNodeEntry *pEntry = taosArrayGet(pExecNode->pNodeList, j);
13,667✔
2356
        if ((pEntry != NULL) && (pEntry->nodeId == pTask->info.nodeId)) {
13,667!
2357
          exist = true;
3,214✔
2358
          break;
3,214✔
2359
        }
2360
      }
2361

2362
      if (!exist) {
3,654✔
2363
        SNodeEntry nodeEntry = {.hbTimestamp = -1, .nodeId = pTask->info.nodeId, .lastHbMsgId = -1};
440✔
2364
        epsetAssign(&nodeEntry.epset, &pTask->info.epSet);
440✔
2365

2366
        void *px = taosArrayPush(pExecNode->pNodeList, &nodeEntry);
440✔
2367
        if (px) {
440!
2368
          mInfo("vgId:%d added into nodeList, total:%d", nodeEntry.nodeId, (int)taosArrayGetSize(pExecNode->pNodeList));
440!
2369
        } else {
2370
          mError("vgId:%d failed to add into nodeList, total:%d", nodeEntry.nodeId,
×
2371
                 (int)taosArrayGetSize(pExecNode->pNodeList))
2372
        }
2373
      }
2374
    }
2375
  }
2376

2377
  destroyStreamTaskIter(pIter);
720✔
2378
}
2379

2380
static void doAddTaskId(SArray *pList, int32_t taskId, int64_t uid, int32_t numOfTotal) {
2,619✔
2381
  int32_t num = taosArrayGetSize(pList);
2,619✔
2382
  for (int32_t i = 0; i < num; ++i) {
10,242✔
2383
    int32_t *pId = taosArrayGet(pList, i);
7,625✔
2384
    if (pId == NULL) {
7,625!
2385
      continue;
×
2386
    }
2387

2388
    if (taskId == *pId) {
7,625✔
2389
      return;
2✔
2390
    }
2391
  }
2392

2393
  int32_t numOfTasks = taosArrayGetSize(pList);
2,617✔
2394
  void   *p = taosArrayPush(pList, &taskId);
2,617✔
2395
  if (p) {
2,617!
2396
    mDebug("stream:0x%" PRIx64 " receive %d reqs for checkpoint, remain:%d", uid, numOfTasks, numOfTotal - numOfTasks);
2,617!
2397
  } else {
2398
    mError("stream:0x%" PRIx64 " receive %d reqs for checkpoint, failed to added into task list, since out of memory",
×
2399
           uid, numOfTasks);
2400
  }
2401
}
2402

2403
int32_t mndProcessStreamReqCheckpoint(SRpcMsg *pReq) {
2,619✔
2404
  SMnode                  *pMnode = pReq->info.node;
2,619✔
2405
  SStreamTaskCheckpointReq req = {0};
2,619✔
2406

2407
  SDecoder decoder = {0};
2,619✔
2408
  tDecoderInit(&decoder, pReq->pCont, pReq->contLen);
2,619✔
2409

2410
  if (tDecodeStreamTaskCheckpointReq(&decoder, &req)) {
2,619!
2411
    tDecoderClear(&decoder);
×
2412
    mError("invalid task checkpoint req msg received");
×
2413
    return TSDB_CODE_INVALID_MSG;
×
2414
  }
2415
  tDecoderClear(&decoder);
2,619✔
2416

2417
  mDebug("receive stream task checkpoint req msg, vgId:%d, s-task:0x%x", req.nodeId, req.taskId);
2,619!
2418

2419
  // register to the stream task done map, if all tasks has sent this kinds of message, start the checkpoint trans.
2420
  streamMutexLock(&execInfo.lock);
2,619✔
2421

2422
  SStreamObj *pStream = NULL;
2,619✔
2423
  int32_t     code = mndGetStreamObj(pMnode, req.streamId, &pStream);
2,619✔
2424
  if (pStream == NULL || code != 0) {
2,619!
2425
    mWarn("failed to find the stream:0x%" PRIx64 ", not handle the checkpoint req, try to acquire in buf",
×
2426
          req.streamId);
2427

2428
    // not in meta-store yet, try to acquire the task in exec buffer
2429
    // the checkpoint req arrives too soon before the completion of the create stream trans.
2430
    STaskId id = {.streamId = req.streamId, .taskId = req.taskId};
×
2431
    void   *p = taosHashGet(execInfo.pTaskMap, &id, sizeof(id));
×
2432
    if (p == NULL) {
×
2433
      mError("failed to find the stream:0x%" PRIx64 " in buf, not handle the checkpoint req", req.streamId);
×
2434
      streamMutexUnlock(&execInfo.lock);
×
2435
      return TSDB_CODE_MND_STREAM_NOT_EXIST;
×
2436
    } else {
2437
      mDebug("s-task:0x%" PRIx64 "-0x%x in buf not in mnode/meta, create stream trans may not complete yet",
×
2438
             req.streamId, req.taskId);
2439
    }
2440
  }
2441

2442
  int32_t numOfTasks = (pStream == NULL) ? 0 : mndGetNumOfStreamTasks(pStream);
2,619!
2443

2444
  SArray **pReqTaskList = (SArray **)taosHashGet(execInfo.pTransferStateStreams, &req.streamId, sizeof(req.streamId));
2,619✔
2445
  if (pReqTaskList == NULL) {
2,619✔
2446
    SArray *pList = taosArrayInit(4, sizeof(int32_t));
448✔
2447
    doAddTaskId(pList, req.taskId, req.streamId, numOfTasks);
448✔
2448
    code = taosHashPut(execInfo.pTransferStateStreams, &req.streamId, sizeof(int64_t), &pList, sizeof(void *));
448✔
2449
    if (code) {
448!
2450
      mError("failed to put into transfer state stream map, code: out of memory");
×
2451
    }
2452
    pReqTaskList = (SArray **)taosHashGet(execInfo.pTransferStateStreams, &req.streamId, sizeof(req.streamId));
448✔
2453
  } else {
2454
    doAddTaskId(*pReqTaskList, req.taskId, req.streamId, numOfTasks);
2,171✔
2455
  }
2456

2457
  int32_t total = taosArrayGetSize(*pReqTaskList);
2,619✔
2458
  if (total == numOfTasks) {  // all tasks have sent the reqs
2,619✔
2459
    int64_t checkpointId = mndStreamGenChkptId(pMnode, false);
425✔
2460
    mInfo("stream:0x%" PRIx64 " all tasks req checkpoint, start checkpointId:%" PRId64, req.streamId, checkpointId);
425!
2461

2462
    if (pStream != NULL) {  // TODO:handle error
425!
2463
      code = mndProcessStreamCheckpointTrans(pMnode, pStream, checkpointId, 0, false);
425✔
2464
      if (code) {
425!
2465
        mError("failed to create checkpoint trans, code:%s", tstrerror(code));
425!
2466
      }
2467
    } else {
2468
      // todo: wait for the create stream trans completed, and launch the checkpoint trans
2469
      // SStreamObj *pStream = mndGetStreamObj(pMnode, req.streamId);
2470
      // sleep(500ms)
2471
    }
2472

2473
    // remove this entry
2474
    (void) taosHashRemove(execInfo.pTransferStateStreams, &req.streamId, sizeof(int64_t));
425✔
2475

2476
    int32_t numOfStreams = taosHashGetSize(execInfo.pTransferStateStreams);
425✔
2477
    mDebug("stream:0x%" PRIx64 " removed, remain streams:%d fill-history not completed", req.streamId, numOfStreams);
425!
2478
  }
2479

2480
  if (pStream != NULL) {
2,619!
2481
    mndReleaseStream(pMnode, pStream);
2,619✔
2482
  }
2483

2484
  streamMutexUnlock(&execInfo.lock);
2,619✔
2485

2486
  {
2487
    SRpcMsg rsp = {.code = 0, .info = pReq->info, .contLen = sizeof(SMStreamReqCheckpointRsp)};
2,619✔
2488
    rsp.pCont = rpcMallocCont(rsp.contLen);
2,619✔
2489
    if (rsp.pCont == NULL) {
2,619!
2490
      return terrno;
×
2491
    }
2492

2493
    SMsgHead *pHead = rsp.pCont;
2,619✔
2494
    pHead->vgId = htonl(req.nodeId);
2,619✔
2495

2496
    tmsgSendRsp(&rsp);
2,619✔
2497
    pReq->info.handle = NULL;  // disable auto rsp
2,619✔
2498
  }
2499

2500
  return 0;
2,619✔
2501
}
2502

2503
// valid the info according to the HbMsg
2504
static bool validateChkptReport(const SCheckpointReport *pReport, int64_t reportChkptId) {
2,524✔
2505
  STaskId           id = {.streamId = pReport->streamId, .taskId = pReport->taskId};
2,524✔
2506
  STaskStatusEntry *pTaskEntry = taosHashGet(execInfo.pTaskMap, &id, sizeof(id));
2,524✔
2507
  if (pTaskEntry == NULL) {
2,524✔
2508
    mError("invalid checkpoint-report msg from task:0x%x, discard", pReport->taskId);
71!
2509
    return false;
71✔
2510
  }
2511

2512
  if (pTaskEntry->checkpointInfo.latestId >= pReport->checkpointId) {
2,453!
2513
    mError("s-task:0x%x invalid checkpoint-report msg, checkpointId:%" PRId64 " saved checkpointId:%" PRId64 " discard",
×
2514
           pReport->taskId, pReport->checkpointId, pTaskEntry->checkpointInfo.activeId);
2515
    return false;
×
2516
  }
2517

2518
  // now the task in checkpoint procedure
2519
  if ((pTaskEntry->checkpointInfo.activeId != 0) && (pTaskEntry->checkpointInfo.activeId > pReport->checkpointId)) {
2,453!
2520
    mError("s-task:0x%x invalid checkpoint-report msg, checkpointId:%" PRId64 " active checkpointId:%" PRId64
×
2521
           " discard",
2522
           pReport->taskId, pReport->checkpointId, pTaskEntry->checkpointInfo.activeId);
2523
    return false;
×
2524
  }
2525

2526
  if (reportChkptId >= pReport->checkpointId) {
2,453!
2527
    mError("s-task:0x%x expired checkpoint-report msg, checkpointId:%" PRId64 " already update checkpointId:%" PRId64
×
2528
           " discard",
2529
           pReport->taskId, pReport->checkpointId, reportChkptId);
2530
    return false;
×
2531
  }
2532

2533
  return true;
2,453✔
2534
}
2535

2536
static void doAddReportStreamTask(SArray *pList, int64_t reportedChkptId, const SCheckpointReport *pReport) {
2,524✔
2537
  bool valid = validateChkptReport(pReport, reportedChkptId);
2,524✔
2538
  if (!valid) {
2,524✔
2539
    return;
71✔
2540
  }
2541

2542
  for (int32_t i = 0; i < taosArrayGetSize(pList); ++i) {
9,810✔
2543
    STaskChkptInfo *p = taosArrayGet(pList, i);
7,357✔
2544
    if (p == NULL) {
7,357!
2545
      continue;
×
2546
    }
2547

2548
    if (p->taskId == pReport->taskId) {
7,357!
2549
      if (p->checkpointId > pReport->checkpointId) {
×
2550
        mError("s-task:0x%x invalid checkpoint-report msg, existed:%" PRId64 " req checkpointId:%" PRId64 ", discard",
×
2551
               pReport->taskId, p->checkpointId, pReport->checkpointId);
2552
      } else if (p->checkpointId < pReport->checkpointId) {  // expired checkpoint-report msg, update it
×
2553
        mInfo("s-task:0x%x expired checkpoint-report info in checkpoint-report list update from %" PRId64 "->%" PRId64,
×
2554
               pReport->taskId, p->checkpointId, pReport->checkpointId);
2555

2556
        // update the checkpoint report info
2557
        p->checkpointId = pReport->checkpointId;
×
2558
        p->ts = pReport->checkpointTs;
×
2559
        p->version = pReport->checkpointVer;
×
2560
        p->transId = pReport->transId;
×
2561
        p->dropHTask = pReport->dropHTask;
×
2562
      } else {
2563
        mWarn("taskId:0x%x already in checkpoint-report list", pReport->taskId);
×
2564
      }
2565
      return;
×
2566
    }
2567
  }
2568

2569
  STaskChkptInfo info = {
2,453✔
2570
      .streamId = pReport->streamId,
2,453✔
2571
      .taskId = pReport->taskId,
2,453✔
2572
      .transId = pReport->transId,
2,453✔
2573
      .dropHTask = pReport->dropHTask,
2,453✔
2574
      .version = pReport->checkpointVer,
2,453✔
2575
      .ts = pReport->checkpointTs,
2,453✔
2576
      .checkpointId = pReport->checkpointId,
2,453✔
2577
      .nodeId = pReport->nodeId,
2,453✔
2578
  };
2579

2580
  void *p = taosArrayPush(pList, &info);
2,453✔
2581
  if (p == NULL) {
2,453!
2582
    mError("failed to put into task list, taskId:0x%x", pReport->taskId);
×
2583
  } else {
2584
    int32_t size = taosArrayGetSize(pList);
2,453✔
2585
    mDebug("stream:0x%" PRIx64 " taskId:0x%x checkpoint-report recv, %d tasks has send checkpoint-report",
2,453!
2586
           pReport->streamId, pReport->taskId, size);
2587
  }
2588
}
2589

2590
int32_t mndProcessCheckpointReport(SRpcMsg *pReq) {
2,524✔
2591
  SMnode           *pMnode = pReq->info.node;
2,524✔
2592
  SCheckpointReport req = {0};
2,524✔
2593

2594
  SDecoder decoder = {0};
2,524✔
2595
  tDecoderInit(&decoder, pReq->pCont, pReq->contLen);
2,524✔
2596

2597
  if (tDecodeStreamTaskChkptReport(&decoder, &req)) {
2,524!
2598
    tDecoderClear(&decoder);
×
2599
    mError("invalid task checkpoint-report msg received");
×
2600
    return TSDB_CODE_INVALID_MSG;
×
2601
  }
2602
  tDecoderClear(&decoder);
2,524✔
2603

2604
  streamMutexLock(&execInfo.lock);
2,524✔
2605
  mndInitStreamExecInfo(pMnode, &execInfo);
2,524✔
2606
  streamMutexUnlock(&execInfo.lock);
2,524✔
2607

2608
  mDebug("receive stream task checkpoint-report msg, vgId:%d, s-task:0x%x, checkpointId:%" PRId64
2,524!
2609
         " checkpointVer:%" PRId64 " transId:%d",
2610
         req.nodeId, req.taskId, req.checkpointId, req.checkpointVer, req.transId);
2611

2612
  // register to the stream task done map, if all tasks has sent these kinds of message, start the checkpoint trans.
2613
  streamMutexLock(&execInfo.lock);
2,524✔
2614

2615
  SStreamObj *pStream = NULL;
2,524✔
2616
  int32_t     code = mndGetStreamObj(pMnode, req.streamId, &pStream);
2,524✔
2617
  if (pStream == NULL || code != 0) {
2,524!
2618
    mWarn("failed to find the stream:0x%" PRIx64 ", not handle checkpoint-report, try to acquire in buf", req.streamId);
×
2619

2620
    // not in meta-store yet, try to acquire the task in exec buffer
2621
    // the checkpoint req arrives too soon before the completion of the creation of stream trans.
2622
    STaskId id = {.streamId = req.streamId, .taskId = req.taskId};
×
2623
    void   *p = taosHashGet(execInfo.pTaskMap, &id, sizeof(id));
×
2624
    if (p == NULL) {
×
2625
      mError("failed to find the stream:0x%" PRIx64 " in buf, not handle the checkpoint-report", req.streamId);
×
2626
      streamMutexUnlock(&execInfo.lock);
×
2627
      return TSDB_CODE_MND_STREAM_NOT_EXIST;
×
2628
    } else {
2629
      mDebug("s-task:0x%" PRIx64 "-0x%x in buf not in mnode/meta, create stream trans may not complete yet",
×
2630
             req.streamId, req.taskId);
2631
    }
2632
  }
2633

2634
  int32_t numOfTasks = (pStream == NULL) ? 0 : mndGetNumOfStreamTasks(pStream);
2,524!
2635

2636
  SChkptReportInfo *pInfo =
2637
      (SChkptReportInfo *)taosHashGet(execInfo.pChkptStreams, &req.streamId, sizeof(req.streamId));
2,524✔
2638
  if (pInfo == NULL) {
2,524✔
2639
    SChkptReportInfo info = {.pTaskList = taosArrayInit(4, sizeof(STaskChkptInfo)), .streamId = req.streamId};
424✔
2640
    if (info.pTaskList != NULL) {
424!
2641
      doAddReportStreamTask(info.pTaskList, info.reportChkpt, &req);
424✔
2642
      code = taosHashPut(execInfo.pChkptStreams, &req.streamId, sizeof(req.streamId), &info, sizeof(info));
424✔
2643
      if (code) {
424!
2644
        mError("stream:0x%" PRIx64 " failed to put into checkpoint stream", req.streamId);
×
2645
      }
2646

2647
      pInfo = (SChkptReportInfo *)taosHashGet(execInfo.pChkptStreams, &req.streamId, sizeof(req.streamId));
424✔
2648
    }
2649
  } else {
2650
    doAddReportStreamTask(pInfo->pTaskList, pInfo->reportChkpt, &req);
2,100✔
2651
  }
2652

2653
  int32_t total = taosArrayGetSize(pInfo->pTaskList);
2,524✔
2654
  if (total == numOfTasks) {  // all tasks have sent the reqs
2,524✔
2655
    mInfo("stream:0x%" PRIx64 " %s all %d tasks send checkpoint-report, checkpoint meta-info for checkpointId:%" PRId64
383!
2656
          " will be issued soon",
2657
          req.streamId, pStream->name, total, req.checkpointId);
2658
  }
2659

2660
  if (pStream != NULL) {
2,524!
2661
    mndReleaseStream(pMnode, pStream);
2,524✔
2662
  }
2663

2664
  streamMutexUnlock(&execInfo.lock);
2,524✔
2665

2666
  doSendQuickRsp(&pReq->info, sizeof(SMStreamUpdateChkptRsp), req.nodeId, TSDB_CODE_SUCCESS);
2,524✔
2667
  return code;
2,524✔
2668
}
2669

2670
static int64_t getConsensusId(int64_t streamId, int32_t numOfTasks, int32_t *pExistedTasks, bool *pAllSame) {
20✔
2671
  int32_t num = 0;
20✔
2672
  int64_t chkId = INT64_MAX;
20✔
2673
  *pExistedTasks = 0;
20✔
2674
  *pAllSame = true;
20✔
2675

2676
  for (int32_t i = 0; i < taosArrayGetSize(execInfo.pTaskList); ++i) {
160✔
2677
    STaskId *p = taosArrayGet(execInfo.pTaskList, i);
140✔
2678
    if (p == NULL) {
140!
2679
      continue;
×
2680
    }
2681

2682
    if (p->streamId != streamId) {
140!
2683
      continue;
×
2684
    }
2685

2686
    num += 1;
140✔
2687
    STaskStatusEntry *pe = taosHashGet(execInfo.pTaskMap, p, sizeof(*p));
140✔
2688
    if (chkId > pe->checkpointInfo.latestId) {
140✔
2689
      if (chkId != INT64_MAX) {
20!
2690
        *pAllSame = false;
×
2691
      }
2692
      chkId = pe->checkpointInfo.latestId;
20✔
2693
    }
2694
  }
2695

2696
  *pExistedTasks = num;
20✔
2697
  if (num < numOfTasks) {  // not all task send info to mnode through hbMsg, no valid checkpoint Id
20!
2698
    return -1;
×
2699
  }
2700

2701
  return chkId;
20✔
2702
}
2703

2704
static void doSendQuickRsp(SRpcHandleInfo *pInfo, int32_t msgSize, int32_t vgId, int32_t code) {
2,524✔
2705
  SRpcMsg rsp = {.code = code, .info = *pInfo, .contLen = msgSize};
2,524✔
2706
  rsp.pCont = rpcMallocCont(rsp.contLen);
2,524✔
2707
  if (rsp.pCont != NULL) {
2,524!
2708
    SMsgHead *pHead = rsp.pCont;
2,524✔
2709
    pHead->vgId = htonl(vgId);
2,524✔
2710

2711
    tmsgSendRsp(&rsp);
2,524✔
2712
    pInfo->handle = NULL;  // disable auto rsp
2,524✔
2713
  }
2714
}
2,524✔
2715

2716
int32_t mndProcessConsensusInTmr(SRpcMsg *pMsg) {
7,629✔
2717
  SMnode *pMnode = pMsg->info.node;
7,629✔
2718
  int64_t now = taosGetTimestampMs();
7,629✔
2719
  SArray *pStreamList = taosArrayInit(4, sizeof(int64_t));
7,629✔
2720
  if (pStreamList == NULL) {
7,629!
2721
    return terrno;
×
2722
  }
2723

2724
  mDebug("start to process consensus-checkpointId in tmr");
7,629✔
2725

2726
  bool    allReady = true;
7,629✔
2727
  SArray *pNodeSnapshot = NULL;
7,629✔
2728

2729
  int32_t code = mndTakeVgroupSnapshot(pMnode, &allReady, &pNodeSnapshot);
7,629✔
2730
  taosArrayDestroy(pNodeSnapshot);
7,629✔
2731
  if (code) {
7,629✔
2732
    mError("failed to get the vgroup snapshot, ignore it and continue");
132!
2733
  }
2734

2735
  if (!allReady) {
7,629✔
2736
    mWarn("not all vnodes are ready, end to process the consensus-checkpointId in tmr process");
1,171!
2737
    taosArrayDestroy(pStreamList);
1,171✔
2738
    return 0;
1,171✔
2739
  }
2740

2741
  streamMutexLock(&execInfo.lock);
6,458✔
2742

2743
  void *pIter = NULL;
6,458✔
2744
  while ((pIter = taosHashIterate(execInfo.pStreamConsensus, pIter)) != NULL) {
6,461✔
2745
    SCheckpointConsensusInfo *pInfo = (SCheckpointConsensusInfo *)pIter;
3✔
2746

2747
    int64_t streamId = -1;
3✔
2748
    int32_t num = taosArrayGetSize(pInfo->pTaskList);
3✔
2749
    SArray *pList = taosArrayInit(4, sizeof(int32_t));
3✔
2750
    if (pList == NULL) {
3!
2751
      continue;
×
2752
    }
2753

2754
    SStreamObj *pStream = NULL;
3✔
2755
    code = mndGetStreamObj(pMnode, pInfo->streamId, &pStream);
3✔
2756
    if (pStream == NULL || code != 0) {  // stream has been dropped already
3!
2757
      mDebug("stream:0x%" PRIx64 " dropped already, continue", pInfo->streamId);
×
2758
      void *p = taosArrayPush(pStreamList, &pInfo->streamId);
×
2759
      taosArrayDestroy(pList);
×
2760
      continue;
×
2761
    }
2762

2763
    for (int32_t j = 0; j < num; ++j) {
23✔
2764
      SCheckpointConsensusEntry *pe = taosArrayGet(pInfo->pTaskList, j);
20✔
2765
      if (pe == NULL) {
20!
2766
        continue;
×
2767
      }
2768

2769
      streamId = pe->req.streamId;
20✔
2770

2771
      int32_t existed = 0;
20✔
2772
      bool    allSame = true;
20✔
2773
      int64_t chkId = getConsensusId(pe->req.streamId, pInfo->numOfTasks, &existed, &allSame);
20✔
2774
      if (chkId == -1) {
20!
2775
        mDebug("not all(%d/%d) task(s) send hbMsg yet, wait for a while and check again, s-task:0x%x", existed,
×
2776
               pInfo->numOfTasks, pe->req.taskId);
2777
        break;
×
2778
      }
2779

2780
      if (((now - pe->ts) >= 10 * 1000) || allSame) {
20!
2781
        mDebug("s-task:0x%x sendTs:%" PRId64 " wait %.2fs and all tasks have same checkpointId", pe->req.taskId,
20!
2782
               pe->req.startTs, (now - pe->ts) / 1000.0);
2783
        if (chkId > pe->req.checkpointId) {
20!
2784
          streamMutexUnlock(&execInfo.lock);
×
2785
          taosArrayDestroy(pStreamList);
×
2786
          mError("s-task:0x%x checkpointId:%" PRId64 " is updated to %" PRId64 ", update it", pe->req.taskId,
×
2787
                 pe->req.checkpointId, chkId);
2788
          return TSDB_CODE_FAILED;
×
2789
        }
2790
        code = mndCreateSetConsensusChkptIdTrans(pMnode, pStream, pe->req.taskId, chkId, pe->req.startTs);
20✔
2791
        if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
20!
2792
          mError("failed to create consensus-checkpoint trans, stream:0x%" PRIx64, pStream->uid);
×
2793
        }
2794

2795
        void *p = taosArrayPush(pList, &pe->req.taskId);
20✔
2796
        if (p == NULL) {
20!
2797
          mError("failed to put into task list, taskId:0x%x", pe->req.taskId);
×
2798
        }
2799
        streamId = pe->req.streamId;
20✔
2800
      } else {
2801
        mDebug("s-task:0x%x sendTs:%" PRId64 " wait %.2fs already, wait for next round to check", pe->req.taskId,
×
2802
               pe->req.startTs, (now - pe->ts) / 1000.0);
2803
      }
2804
    }
2805

2806
    mndReleaseStream(pMnode, pStream);
3✔
2807

2808
    if (taosArrayGetSize(pList) > 0) {
3!
2809
      for (int32_t i = 0; i < taosArrayGetSize(pList); ++i) {
23✔
2810
        int32_t *taskId = taosArrayGet(pList, i);
20✔
2811
        if (taskId == NULL) {
20!
2812
          continue;
×
2813
        }
2814

2815
        for (int32_t k = 0; k < taosArrayGetSize(pInfo->pTaskList); ++k) {
20!
2816
          SCheckpointConsensusEntry *pe = taosArrayGet(pInfo->pTaskList, k);
20✔
2817
          if ((pe != NULL) && (pe->req.taskId == *taskId)) {
20!
2818
            taosArrayRemove(pInfo->pTaskList, k);
20✔
2819
            break;
20✔
2820
          }
2821
        }
2822
      }
2823
    }
2824

2825
    taosArrayDestroy(pList);
3✔
2826

2827
    if (taosArrayGetSize(pInfo->pTaskList) == 0) {
3!
2828
      mndClearConsensusRspEntry(pInfo);
3✔
2829
      if (streamId == -1) {
3!
2830
        streamMutexUnlock(&execInfo.lock);
×
2831
        taosArrayDestroy(pStreamList);
×
2832
        mError("streamId is -1, streamId:%" PRIx64, pInfo->streamId);
×
2833
        return TSDB_CODE_FAILED;
×
2834
      }
2835
      void *p = taosArrayPush(pStreamList, &streamId);
3✔
2836
      if (p == NULL) {
3!
2837
        mError("failed to put into stream list, stream:0x%" PRIx64, streamId);
×
2838
      }
2839
    }
2840
  }
2841

2842
  for (int32_t i = 0; i < taosArrayGetSize(pStreamList); ++i) {
6,461✔
2843
    int64_t *pStreamId = (int64_t *)taosArrayGet(pStreamList, i);
3✔
2844
    if (pStreamId == NULL) {
3!
2845
      continue;
×
2846
    }
2847

2848
    code = mndClearConsensusCheckpointId(execInfo.pStreamConsensus, *pStreamId);
3✔
2849
  }
2850

2851
  streamMutexUnlock(&execInfo.lock);
6,458✔
2852

2853
  taosArrayDestroy(pStreamList);
6,458✔
2854
  mDebug("end to process consensus-checkpointId in tmr");
6,458✔
2855
  return code;
6,458✔
2856
}
2857

2858
static int32_t mndProcessCreateStreamReqFromMNode(SRpcMsg *pReq) {
259✔
2859
  int32_t code = mndProcessCreateStreamReq(pReq);
259✔
2860
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
259!
2861
    pReq->info.rsp = rpcMallocCont(1);
×
2862
    if (pReq->info.rsp == NULL) {
×
2863
      return terrno;
×
2864
    }
2865

2866
    pReq->info.rspLen = 1;
×
2867
    pReq->info.noResp = false;
×
2868
    pReq->code = code;
×
2869
  }
2870
  return code;
259✔
2871
}
2872

2873
static int32_t mndProcessDropStreamReqFromMNode(SRpcMsg *pReq) {
225✔
2874
  int32_t code = mndProcessDropStreamReq(pReq);
225✔
2875
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
225!
2876
    pReq->info.rsp = rpcMallocCont(1);
21✔
2877
    if (pReq->info.rsp == NULL) {
21!
2878
      return terrno;
×
2879
    }
2880

2881
    pReq->info.rspLen = 1;
21✔
2882
    pReq->info.noResp = false;
21✔
2883
    pReq->code = code;
21✔
2884
  }
2885
  return code;
225✔
2886
}
2887

2888
void mndInitStreamExecInfo(SMnode *pMnode, SStreamExecInfo *pExecInfo) {
6,137✔
2889
  if (pExecInfo->initTaskList || pMnode == NULL) {
6,137!
2890
    return;
6,102✔
2891
  }
2892

2893
  addAllStreamTasksIntoBuf(pMnode, pExecInfo);
35✔
2894
  pExecInfo->initTaskList = true;
35✔
2895
}
2896

2897
void mndStreamResetInitTaskListLoadFlag() {
895✔
2898
  mInfo("reset task list buffer init flag for leader");
895!
2899
  execInfo.initTaskList = false;
895✔
2900
}
895✔
2901

2902
void mndUpdateStreamExecInfoRole(SMnode *pMnode, int32_t role) {
1,154✔
2903
  execInfo.switchFromFollower = false;
1,154✔
2904

2905
  if (execInfo.role == NODE_ROLE_UNINIT) {
1,154✔
2906
    execInfo.role = role;
998✔
2907
    if (role == NODE_ROLE_LEADER) {
998✔
2908
      mInfo("init mnode is set to leader");
843!
2909
    } else {
2910
      mInfo("init mnode is set to follower");
155!
2911
    }
2912
  } else {
2913
    if (role == NODE_ROLE_LEADER) {
156✔
2914
      if (execInfo.role == NODE_ROLE_FOLLOWER) {
52!
2915
        execInfo.role = role;
52✔
2916
        execInfo.switchFromFollower = true;
52✔
2917
        mInfo("mnode switch to be leader from follower");
52!
2918
      } else {
2919
        mInfo("mnode remain to be leader, do nothing");
×
2920
      }
2921
    } else {  // follower's
2922
      if (execInfo.role == NODE_ROLE_LEADER) {
104✔
2923
        execInfo.role = role;
3✔
2924
        mInfo("mnode switch to be follower from leader");
3!
2925
      } else {
2926
        mInfo("mnode remain to be follower, do nothing");
101!
2927
      }
2928
    }
2929
  }
2930
}
1,154✔
2931

2932
void addAllStreamTasksIntoBuf(SMnode *pMnode, SStreamExecInfo *pExecInfo) {
35✔
2933
  SSdb       *pSdb = pMnode->pSdb;
35✔
2934
  SStreamObj *pStream = NULL;
35✔
2935
  void       *pIter = NULL;
35✔
2936

2937
  while (1) {
2938
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
87✔
2939
    if (pIter == NULL) {
87✔
2940
      break;
35✔
2941
    }
2942

2943
    saveTaskAndNodeInfoIntoBuf(pStream, pExecInfo);
52✔
2944
    sdbRelease(pSdb, pStream);
52✔
2945
  }
2946
}
35✔
2947

2948
int32_t mndCreateStreamChkptInfoUpdateTrans(SMnode *pMnode, SStreamObj *pStream, SArray *pChkptInfoList) {
348✔
2949
  STrans *pTrans = NULL;
348✔
2950
  int32_t code = doCreateTrans(pMnode, pStream, NULL, TRN_CONFLICT_NOTHING, MND_STREAM_CHKPT_UPDATE_NAME,
348✔
2951
                               "update checkpoint-info", &pTrans);
2952
  if (pTrans == NULL || code) {
348!
2953
    sdbRelease(pMnode->pSdb, pStream);
×
2954
    return code;
×
2955
  }
2956

2957
  code = mndStreamRegisterTrans(pTrans, MND_STREAM_CHKPT_UPDATE_NAME, pStream->uid);
348✔
2958
  if (code) {
348!
2959
    sdbRelease(pMnode->pSdb, pStream);
×
2960
    mndTransDrop(pTrans);
×
2961
    return code;
×
2962
  }
2963

2964
  code = mndStreamSetUpdateChkptAction(pMnode, pTrans, pStream);
348✔
2965
  if (code) {
348!
2966
    sdbRelease(pMnode->pSdb, pStream);
×
2967
    mndTransDrop(pTrans);
×
2968
    return code;
×
2969
  }
2970

2971
  code = mndPersistTransLog(pStream, pTrans, SDB_STATUS_READY);
348✔
2972
  if (code) {
348!
2973
    sdbRelease(pMnode->pSdb, pStream);
×
2974
    mndTransDrop(pTrans);
×
2975
    return code;
×
2976
  }
2977

2978
  code = mndTransPrepare(pMnode, pTrans);
348✔
2979
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
348!
2980
    mError("trans:%d, failed to prepare update checkpoint-info meta trans since %s", pTrans->id, tstrerror(code));
×
2981
    sdbRelease(pMnode->pSdb, pStream);
×
2982
    mndTransDrop(pTrans);
×
2983
    return code;
×
2984
  }
2985

2986
  sdbRelease(pMnode->pSdb, pStream);
348✔
2987
  mndTransDrop(pTrans);
348✔
2988

2989
  return TSDB_CODE_ACTION_IN_PROGRESS;
348✔
2990
}
2991

2992
static int32_t mndProcessDropOrphanTaskReq(SRpcMsg *pReq) {
×
2993
  SMnode      *pMnode = pReq->info.node;
×
2994
  int32_t      code = 0;
×
2995
  SOrphanTask *pTask = NULL;
×
2996
  int32_t      i = 0;
×
2997
  STrans      *pTrans = NULL;
×
2998
  int32_t      numOfTasks = 0;
×
2999

3000
  SMStreamDropOrphanMsg msg = {0};
×
3001
  code = tDeserializeDropOrphanTaskMsg(pReq->pCont, pReq->contLen, &msg);
×
3002
  if (code) {
×
3003
    return code;
×
3004
  }
3005

3006
  numOfTasks = taosArrayGetSize(msg.pList);
×
3007
  if (numOfTasks == 0) {
×
3008
    mDebug("no orphan tasks to drop, no need to create trans");
×
3009
    goto _err;
×
3010
  }
3011

3012
  mDebug("create trans to drop %d orphan tasks", numOfTasks);
×
3013

3014
  i = 0;
×
3015
  while (i < numOfTasks && ((pTask = taosArrayGet(msg.pList, i)) == NULL)) {
×
3016
    i += 1;
×
3017
  }
3018

3019
  if (pTask == NULL) {
×
3020
    mError("failed to extract entry in drop orphan task list, not create trans to drop orphan-task");
×
3021
    goto _err;
×
3022
  }
3023

3024
  // check if it is conflict with other trans in both sourceDb and targetDb.
3025
  code = mndStreamTransConflictCheck(pMnode, pTask->streamId, MND_STREAM_DROP_NAME, false);
×
3026
  if (code) {
×
3027
    goto _err;
×
3028
  }
3029

3030
  SStreamObj dummyObj = {.uid = pTask->streamId, .sourceDb = "", .targetSTbName = ""};
×
3031

3032
  code = doCreateTrans(pMnode, &dummyObj, NULL, TRN_CONFLICT_NOTHING, MND_STREAM_DROP_NAME, "drop stream", &pTrans);
×
3033
  if (pTrans == NULL || code != 0) {
×
3034
    mError("failed to create trans to drop orphan tasks since %s", tstrerror(code));
×
3035
    goto _err;
×
3036
  }
3037

3038
  code = mndStreamRegisterTrans(pTrans, MND_STREAM_DROP_NAME, pTask->streamId);
×
3039
  if (code) {
×
3040
    goto _err;
×
3041
  }
3042

3043
  // drop all tasks
3044
  if ((code = mndStreamSetDropActionFromList(pMnode, pTrans, msg.pList)) < 0) {
×
3045
    mError("failed to create trans to drop orphan tasks since %s", tstrerror(code));
×
3046
    goto _err;
×
3047
  }
3048

3049
  // drop stream
3050
  if ((code = mndPersistTransLog(&dummyObj, pTrans, SDB_STATUS_DROPPED)) < 0) {
×
3051
    goto _err;
×
3052
  }
3053

3054
  code = mndTransPrepare(pMnode, pTrans);
×
3055
  if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_ACTION_IN_PROGRESS) {
×
3056
    mError("trans:%d, failed to prepare drop stream trans since %s", pTrans->id, tstrerror(code));
×
3057
    goto _err;
×
3058
  }
3059

3060
_err:
×
3061
  tDestroyDropOrphanTaskMsg(&msg);
×
3062
  mndTransDrop(pTrans);
×
3063

3064
  if (code == TSDB_CODE_SUCCESS || code == TSDB_CODE_ACTION_IN_PROGRESS) {
×
3065
    mDebug("create drop %d orphan tasks trans succ", numOfTasks);
×
3066
  }
3067
  return code;
×
3068
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc