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

#include "mndStream.h"
#include "mndDb.h"
#include "mndDnode.h"
#include "mndMnode.h"
L
Liu Jicong 已提交
20
#include "mndPrivilege.h"
L
Liu Jicong 已提交
21
#include "mndScheduler.h"
L
Liu Jicong 已提交
22 23
#include "mndShow.h"
#include "mndStb.h"
L
Liu Jicong 已提交
24
#include "mndTopic.h"
L
Liu Jicong 已提交
25 26 27
#include "mndTrans.h"
#include "mndUser.h"
#include "mndVgroup.h"
L
Liu Jicong 已提交
28
#include "parser.h"
L
Liu Jicong 已提交
29 30
#include "tname.h"

Y
yihaoDeng 已提交
31
#define MND_STREAM_VER_NUMBER   3
L
Liu Jicong 已提交
32 33
#define MND_STREAM_RESERVE_SIZE 64

34
#define MND_STREAM_MAX_NUM 60
L
Liu Jicong 已提交
35

L
Liu Jicong 已提交
36 37
static int32_t mndStreamActionInsert(SSdb *pSdb, SStreamObj *pStream);
static int32_t mndStreamActionDelete(SSdb *pSdb, SStreamObj *pStream);
38
static int32_t mndStreamActionUpdate(SSdb *pSdb, SStreamObj *pOldStream, SStreamObj *pNewStream);
S
Shengliang Guan 已提交
39
static int32_t mndProcessCreateStreamReq(SRpcMsg *pReq);
L
Liu Jicong 已提交
40
static int32_t mndProcessDropStreamReq(SRpcMsg *pReq);
41
static int32_t mndProcessStreamCheckpointTmr(SRpcMsg *pReq);
42 43
static int32_t mndProcessStreamDoCheckpoint(SRpcMsg *pReq);
static int32_t mndProcessRecoverStreamReq(SRpcMsg *pReq);
S
Shengliang Guan 已提交
44 45 46
static int32_t mndProcessStreamMetaReq(SRpcMsg *pReq);
static int32_t mndGetStreamMeta(SRpcMsg *pReq, SShowObj *pShow, STableMetaRsp *pMeta);
static int32_t mndRetrieveStream(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows);
L
Liu Jicong 已提交
47
static void    mndCancelGetNextStream(SMnode *pMnode, void *pIter);
48 49
static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows);
static void    mndCancelGetNextStreamTask(SMnode *pMnode, void *pIter);
5
54liuyao 已提交
50 51
static int32_t mndProcessPauseStreamReq(SRpcMsg *pReq);
static int32_t mndProcessResumeStreamReq(SRpcMsg *pReq);
L
Liu Jicong 已提交
52 53

int32_t mndInitStream(SMnode *pMnode) {
54 55 56 57 58 59 60 61 62
  SSdbTable table = {
      .sdbType = SDB_STREAM,
      .keyType = SDB_KEY_BINARY,
      .encodeFp = (SdbEncodeFp)mndStreamActionEncode,
      .decodeFp = (SdbDecodeFp)mndStreamActionDecode,
      .insertFp = (SdbInsertFp)mndStreamActionInsert,
      .updateFp = (SdbUpdateFp)mndStreamActionUpdate,
      .deleteFp = (SdbDeleteFp)mndStreamActionDelete,
  };
L
Liu Jicong 已提交
63 64

  mndSetMsgHandle(pMnode, TDMT_MND_CREATE_STREAM, mndProcessCreateStreamReq);
L
Liu Jicong 已提交
65
  mndSetMsgHandle(pMnode, TDMT_MND_DROP_STREAM, mndProcessDropStreamReq);
L
Liu Jicong 已提交
66
  /*mndSetMsgHandle(pMnode, TDMT_MND_RECOVER_STREAM, mndProcessRecoverStreamReq);*/
L
Liu Jicong 已提交
67 68 69

  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DEPLOY_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DROP_RSP, mndTransProcessRsp);
5
54liuyao 已提交
70 71
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_PAUSE_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_RESUME_RSP, mndTransProcessRsp);
L
Liu Jicong 已提交
72

5
54liuyao 已提交
73 74
  // mndSetMsgHandle(pMnode, TDMT_MND_STREAM_CHECKPOINT_TIMER, mndProcessStreamCheckpointTmr);
  // mndSetMsgHandle(pMnode, TDMT_MND_STREAM_BEGIN_CHECKPOINT, mndProcessStreamDoCheckpoint);
75 76
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_REPORT_CHECKPOINT, mndTransProcessRsp);

5
54liuyao 已提交
77 78 79
  mndSetMsgHandle(pMnode, TDMT_MND_PAUSE_STREAM, mndProcessPauseStreamReq);
  mndSetMsgHandle(pMnode, TDMT_MND_RESUME_STREAM, mndProcessResumeStreamReq);

L
Liu Jicong 已提交
80 81
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_STREAMS, mndRetrieveStream);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_STREAMS, mndCancelGetNextStream);
82 83
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_STREAM_TASKS, mndRetrieveStreamTask);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_STREAM_TASKS, mndCancelGetNextStreamTask);
L
Liu Jicong 已提交
84 85 86 87 88 89 90 91 92 93

  return sdbSetTable(pMnode->pSdb, table);
}

void mndCleanupStream(SMnode *pMnode) {}

SSdbRaw *mndStreamActionEncode(SStreamObj *pStream) {
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  void *buf = NULL;

H
Hongze Cheng 已提交
94 95
  SEncoder encoder;
  tEncoderInit(&encoder, NULL, 0);
L
Liu Jicong 已提交
96
  if (tEncodeSStreamObj(&encoder, pStream) < 0) {
H
Hongze Cheng 已提交
97
    tEncoderClear(&encoder);
L
Liu Jicong 已提交
98 99 100
    goto STREAM_ENCODE_OVER;
  }
  int32_t tlen = encoder.pos;
H
Hongze Cheng 已提交
101
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
102 103 104 105 106

  int32_t  size = sizeof(int32_t) + tlen + MND_STREAM_RESERVE_SIZE;
  SSdbRaw *pRaw = sdbAllocRaw(SDB_STREAM, MND_STREAM_VER_NUMBER, size);
  if (pRaw == NULL) goto STREAM_ENCODE_OVER;

wafwerar's avatar
wafwerar 已提交
107
  buf = taosMemoryMalloc(tlen);
L
Liu Jicong 已提交
108 109
  if (buf == NULL) goto STREAM_ENCODE_OVER;

H
Hongze Cheng 已提交
110
  tEncoderInit(&encoder, buf, tlen);
L
Liu Jicong 已提交
111
  if (tEncodeSStreamObj(&encoder, pStream) < 0) {
H
Hongze Cheng 已提交
112
    tEncoderClear(&encoder);
L
Liu Jicong 已提交
113 114
    goto STREAM_ENCODE_OVER;
  }
H
Hongze Cheng 已提交
115
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
116 117 118 119 120 121 122 123 124

  int32_t dataPos = 0;
  SDB_SET_INT32(pRaw, dataPos, tlen, STREAM_ENCODE_OVER);
  SDB_SET_BINARY(pRaw, dataPos, buf, tlen, STREAM_ENCODE_OVER);
  SDB_SET_DATALEN(pRaw, dataPos, STREAM_ENCODE_OVER);

  terrno = TSDB_CODE_SUCCESS;

STREAM_ENCODE_OVER:
wafwerar's avatar
wafwerar 已提交
125
  taosMemoryFreeClear(buf);
L
Liu Jicong 已提交
126 127 128 129 130 131 132 133 134 135 136 137
  if (terrno != TSDB_CODE_SUCCESS) {
    mError("stream:%s, failed to encode to raw:%p since %s", pStream->name, pRaw, terrstr());
    sdbFreeRaw(pRaw);
    return NULL;
  }

  mTrace("stream:%s, encode to raw:%p, row:%p", pStream->name, pRaw, pStream);
  return pRaw;
}

SSdbRow *mndStreamActionDecode(SSdbRaw *pRaw) {
  terrno = TSDB_CODE_OUT_OF_MEMORY;
138 139 140
  SSdbRow    *pRow = NULL;
  SStreamObj *pStream = NULL;
  void       *buf = NULL;
L
Liu Jicong 已提交
141 142

  int8_t sver = 0;
Y
yihaoDeng 已提交
143 144 145
  if (sdbGetRawSoftVer(pRaw, &sver) != 0) {
    goto STREAM_DECODE_OVER;
  }
L
Liu Jicong 已提交
146

Y
yihaoDeng 已提交
147 148
  if (sver != MND_STREAM_VER_NUMBER) {
    terrno = 0;
L
Liu Jicong 已提交
149 150 151
    goto STREAM_DECODE_OVER;
  }

152
  pRow = sdbAllocRow(sizeof(SStreamObj));
L
Liu Jicong 已提交
153 154
  if (pRow == NULL) goto STREAM_DECODE_OVER;

155
  pStream = sdbGetRowObj(pRow);
L
Liu Jicong 已提交
156 157 158 159 160
  if (pStream == NULL) goto STREAM_DECODE_OVER;

  int32_t tlen;
  int32_t dataPos = 0;
  SDB_GET_INT32(pRaw, dataPos, &tlen, STREAM_DECODE_OVER);
wafwerar's avatar
wafwerar 已提交
161
  buf = taosMemoryMalloc(tlen + 1);
L
Liu Jicong 已提交
162 163 164
  if (buf == NULL) goto STREAM_DECODE_OVER;
  SDB_GET_BINARY(pRaw, dataPos, buf, tlen, STREAM_DECODE_OVER);

H
Hongze Cheng 已提交
165 166
  SDecoder decoder;
  tDecoderInit(&decoder, buf, tlen + 1);
167
  if (tDecodeSStreamObj(&decoder, pStream, sver) < 0) {
L
Liu Jicong 已提交
168
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
169 170
    goto STREAM_DECODE_OVER;
  }
L
Liu Jicong 已提交
171
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
172 173 174 175

  terrno = TSDB_CODE_SUCCESS;

STREAM_DECODE_OVER:
wafwerar's avatar
wafwerar 已提交
176
  taosMemoryFreeClear(buf);
L
Liu Jicong 已提交
177
  if (terrno != TSDB_CODE_SUCCESS) {
178 179
    mError("stream:%s, failed to decode from raw:%p since %s", pStream == NULL ? "null" : pStream->name, pRaw,
           terrstr());
wafwerar's avatar
wafwerar 已提交
180
    taosMemoryFreeClear(pRow);
L
Liu Jicong 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194
    return NULL;
  }

  mTrace("stream:%s, decode from raw:%p, row:%p", pStream->name, pRaw, pStream);
  return pRow;
}

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

static int32_t mndStreamActionDelete(SSdb *pSdb, SStreamObj *pStream) {
  mTrace("stream:%s, perform delete action", pStream->name);
L
Liu Jicong 已提交
195 196 197
  taosWLockLatch(&pStream->lock);
  tFreeStreamObj(pStream);
  taosWUnLockLatch(&pStream->lock);
L
Liu Jicong 已提交
198 199 200 201 202
  return 0;
}

static int32_t mndStreamActionUpdate(SSdb *pSdb, SStreamObj *pOldStream, SStreamObj *pNewStream) {
  mTrace("stream:%s, perform update action", pOldStream->name);
L
liuyao 已提交
203

L
Liu Jicong 已提交
204 205 206 207
  atomic_exchange_32(&pOldStream->version, pNewStream->version);

  taosWLockLatch(&pOldStream->lock);

208
  pOldStream->status = pNewStream->status;
L
liuyao 已提交
209
  pOldStream->updateTime = pNewStream->updateTime;
L
Liu Jicong 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

  taosWUnLockLatch(&pOldStream->lock);
  return 0;
}

SStreamObj *mndAcquireStream(SMnode *pMnode, char *streamName) {
  SSdb       *pSdb = pMnode->pSdb;
  SStreamObj *pStream = sdbAcquire(pSdb, SDB_STREAM, streamName);
  if (pStream == NULL && terrno == TSDB_CODE_SDB_OBJ_NOT_THERE) {
    terrno = TSDB_CODE_MND_STREAM_NOT_EXIST;
  }
  return pStream;
}

void mndReleaseStream(SMnode *pMnode, SStreamObj *pStream) {
  SSdb *pSdb = pMnode->pSdb;
  sdbRelease(pSdb, pStream);
}

L
Liu Jicong 已提交
229 230 231 232 233 234 235 236 237 238
static void mndShowStreamStatus(char *dst, SStreamObj *pStream) {
  int8_t status = atomic_load_8(&pStream->status);
  if (status == STREAM_STATUS__NORMAL) {
    strcpy(dst, "normal");
  } else if (status == STREAM_STATUS__STOP) {
    strcpy(dst, "stop");
  } else if (status == STREAM_STATUS__FAILED) {
    strcpy(dst, "failed");
  } else if (status == STREAM_STATUS__RECOVER) {
    strcpy(dst, "recover");
5
54liuyao 已提交
239 240
  } else if (status == STREAM_STATUS__PAUSE) {
    strcpy(dst, "pause");
L
Liu Jicong 已提交
241 242 243 244
  }
}

static void mndShowStreamTrigger(char *dst, SStreamObj *pStream) {
245
  int8_t trigger = pStream->conf.trigger;
L
Liu Jicong 已提交
246 247 248 249 250 251 252 253 254
  if (trigger == STREAM_TRIGGER_AT_ONCE) {
    strcpy(dst, "at once");
  } else if (trigger == STREAM_TRIGGER_WINDOW_CLOSE) {
    strcpy(dst, "window close");
  } else if (trigger == STREAM_TRIGGER_MAX_DELAY) {
    strcpy(dst, "max delay");
  }
}

L
Liu Jicong 已提交
255
static int32_t mndCheckCreateStreamReq(SCMCreateStreamReq *pCreate) {
L
Liu Jicong 已提交
256 257
  if (pCreate->name[0] == 0 || pCreate->sql == NULL || pCreate->sql[0] == 0 || pCreate->sourceDB[0] == 0 ||
      pCreate->targetStbFullName[0] == 0) {
L
Liu Jicong 已提交
258 259 260 261 262 263
    terrno = TSDB_CODE_MND_INVALID_STREAM_OPTION;
    return -1;
  }
  return 0;
}

X
Xiaoyu Wang 已提交
264
static int32_t mndStreamGetPlanString(const char *ast, int8_t triggerType, int64_t watermark, char **pStr) {
S
sma  
Shengliang Guan 已提交
265
  if (NULL == ast) {
L
Liu Jicong 已提交
266 267 268 269
    return TSDB_CODE_SUCCESS;
  }

  SNode  *pAst = NULL;
S
sma  
Shengliang Guan 已提交
270
  int32_t code = nodesStringToNode(ast, &pAst);
L
Liu Jicong 已提交
271 272 273 274 275 276 277

  SQueryPlan *pPlan = NULL;
  if (TSDB_CODE_SUCCESS == code) {
    SPlanContext cxt = {
        .pAstRoot = pAst,
        .topicQuery = false,
        .streamQuery = true,
278
        .triggerType = triggerType == STREAM_TRIGGER_MAX_DELAY ? STREAM_TRIGGER_WINDOW_CLOSE : triggerType,
X
Xiaoyu Wang 已提交
279
        .watermark = watermark,
L
Liu Jicong 已提交
280 281 282 283 284
    };
    code = qCreateQueryPlan(&cxt, &pPlan, NULL);
  }

  if (TSDB_CODE_SUCCESS == code) {
285
    code = nodesNodeToString((SNode *)pPlan, false, pStr, NULL);
L
Liu Jicong 已提交
286 287
  }
  nodesDestroyNode(pAst);
288
  nodesDestroyNode((SNode *)pPlan);
L
Liu Jicong 已提交
289 290 291 292
  terrno = code;
  return code;
}

L
Liu Jicong 已提交
293
static int32_t mndBuildStreamObjFromCreateReq(SMnode *pMnode, SStreamObj *pObj, SCMCreateStreamReq *pCreate) {
294 295
  SNode      *pAst = NULL;
  SQueryPlan *pPlan = NULL;
L
Liu Jicong 已提交
296

297
  mInfo("stream:%s to create", pCreate->name);
L
Liu Jicong 已提交
298 299 300 301 302 303 304
  memcpy(pObj->name, pCreate->name, TSDB_STREAM_FNAME_LEN);
  pObj->createTime = taosGetTimestampMs();
  pObj->updateTime = pObj->createTime;
  pObj->version = 1;
  pObj->smaId = 0;

  pObj->uid = mndGenerateUid(pObj->name, strlen(pObj->name));
305 306 307 308 309

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

  pObj->hTaskUid = mndGenerateUid(pObj->name, strlen(pObj->name));
L
Liu Jicong 已提交
310 311
  pObj->status = 0;

312 313 314 315 316
  pObj->conf.igExpired = pCreate->igExpired;
  pObj->conf.trigger = pCreate->triggerType;
  pObj->conf.triggerParam = pCreate->maxDelay;
  pObj->conf.watermark = pCreate->watermark;
  pObj->conf.fillHistory = pCreate->fillHistory;
5
54liuyao 已提交
317
  pObj->deleteMark = pCreate->deleteMark;
318
  pObj->igCheckUpdate = pCreate->igUpdate;
L
Liu Jicong 已提交
319 320 321 322

  memcpy(pObj->sourceDb, pCreate->sourceDB, TSDB_DB_FNAME_LEN);
  SDbObj *pSourceDb = mndAcquireDb(pMnode, pCreate->sourceDB);
  if (pSourceDb == NULL) {
323
    mInfo("stream:%s failed to create, source db %s not exist since %s", pCreate->name, pObj->sourceDb, terrstr());
L
Liu Jicong 已提交
324 325 326
    return -1;
  }
  pObj->sourceDbUid = pSourceDb->uid;
327
  mndReleaseDb(pMnode, pSourceDb);
L
Liu Jicong 已提交
328 329 330 331 332

  memcpy(pObj->targetSTbName, pCreate->targetStbFullName, TSDB_TABLE_FNAME_LEN);

  SDbObj *pTargetDb = mndAcquireDbByStb(pMnode, pObj->targetSTbName);
  if (pTargetDb == NULL) {
333
    mInfo("stream:%s failed to create, target db %s not exist since %s", pCreate->name, pObj->targetDb, terrstr());
L
Liu Jicong 已提交
334 335 336 337
    return -1;
  }
  tstrncpy(pObj->targetDb, pTargetDb->name, TSDB_DB_FNAME_LEN);

338 339 340 341 342
  if (pCreate->createStb == STREAM_CREATE_STABLE_TRUE) {
    pObj->targetStbUid = mndGenerateUid(pObj->targetSTbName, TSDB_TABLE_FNAME_LEN);
  } else {
    pObj->targetStbUid = pCreate->targetStbUid;
  }
L
Liu Jicong 已提交
343
  pObj->targetDbUid = pTargetDb->uid;
344
  mndReleaseDb(pMnode, pTargetDb);
L
Liu Jicong 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361

  pObj->sql = pCreate->sql;
  pObj->ast = pCreate->ast;

  pCreate->sql = NULL;
  pCreate->ast = NULL;

  // deserialize ast
  if (nodesStringToNode(pObj->ast, &pAst) < 0) {
    goto FAIL;
  }

  // extract output schema from ast
  if (qExtractResultSchema(pAst, (int32_t *)&pObj->outputSchema.nCols, &pObj->outputSchema.pSchema) != 0) {
    goto FAIL;
  }

362
  int32_t numOfNULL = taosArrayGetSize(pCreate->fillNullCols);
X
Xiaoyu Wang 已提交
363
  if (numOfNULL > 0) {
364
    pObj->outputSchema.nCols += numOfNULL;
X
Xiaoyu Wang 已提交
365
    SSchema *pFullSchema = taosMemoryCalloc(pObj->outputSchema.nCols, sizeof(SSchema));
366 367 368 369 370 371 372
    if (!pFullSchema) {
      goto FAIL;
    }

    int32_t nullIndex = 0;
    int32_t dataIndex = 0;
    for (int16_t i = 0; i < pObj->outputSchema.nCols; i++) {
X
Xiaoyu Wang 已提交
373
      SColLocation *pos = taosArrayGet(pCreate->fillNullCols, nullIndex);
5
54liuyao 已提交
374
      if (nullIndex >= numOfNULL || i < pos->slotId) {
375
        pFullSchema[i].bytes = pObj->outputSchema.pSchema[dataIndex].bytes;
X
Xiaoyu Wang 已提交
376
        pFullSchema[i].colId = i + 1;  // pObj->outputSchema.pSchema[dataIndex].colId;
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        pFullSchema[i].flags = pObj->outputSchema.pSchema[dataIndex].flags;
        strcpy(pFullSchema[i].name, pObj->outputSchema.pSchema[dataIndex].name);
        pFullSchema[i].type = pObj->outputSchema.pSchema[dataIndex].type;
        dataIndex++;
      } else {
        pFullSchema[i].bytes = 0;
        pFullSchema[i].colId = pos->colId;
        pFullSchema[i].flags = COL_SET_NULL;
        memset(pFullSchema[i].name, 0, TSDB_COL_NAME_LEN);
        pFullSchema[i].type = pos->type;
        nullIndex++;
      }
    }
    taosMemoryFree(pObj->outputSchema.pSchema);
    pObj->outputSchema.pSchema = pFullSchema;
  }

L
Liu Jicong 已提交
394 395 396 397
  SPlanContext cxt = {
      .pAstRoot = pAst,
      .topicQuery = false,
      .streamQuery = true,
398 399 400
      .triggerType = pObj->conf.trigger == STREAM_TRIGGER_MAX_DELAY ? STREAM_TRIGGER_WINDOW_CLOSE : pObj->conf.trigger,
      .watermark = pObj->conf.watermark,
      .igExpired = pObj->conf.igExpired,
5
54liuyao 已提交
401
      .deleteMark = pObj->deleteMark,
402
      .igCheckUpdate = pObj->igCheckUpdate,
L
Liu Jicong 已提交
403 404 405 406 407 408 409 410 411 412 413 414
  };

  // using ast and param to build physical plan
  if (qCreateQueryPlan(&cxt, &pPlan, NULL) < 0) {
    goto FAIL;
  }

  // save physcial plan
  if (nodesNodeToString((SNode *)pPlan, false, &pObj->physicalPlan, NULL) != 0) {
    goto FAIL;
  }

415 416 417 418
  pObj->tagSchema.nCols = pCreate->numOfTags;
  if (pCreate->numOfTags) {
    pObj->tagSchema.pSchema = taosMemoryCalloc(pCreate->numOfTags, sizeof(SSchema));
  }
L
Liu Jicong 已提交
419
  /*A(pCreate->numOfTags == taosArrayGetSize(pCreate->pTags));*/
420 421 422 423 424 425 426 427 428
  for (int32_t i = 0; i < pCreate->numOfTags; i++) {
    SField *pField = taosArrayGet(pCreate->pTags, i);
    pObj->tagSchema.pSchema[i].colId = pObj->outputSchema.nCols + i + 1;
    pObj->tagSchema.pSchema[i].bytes = pField->bytes;
    pObj->tagSchema.pSchema[i].flags = pField->flags;
    pObj->tagSchema.pSchema[i].type = pField->type;
    memcpy(pObj->tagSchema.pSchema[i].name, pField->name, TSDB_COL_NAME_LEN);
  }

L
Liu Jicong 已提交
429 430
FAIL:
  if (pAst != NULL) nodesDestroyNode(pAst);
431
  if (pPlan != NULL) qDestroyQueryPlan(pPlan);
L
Liu Jicong 已提交
432 433 434
  return 0;
}

Y
yihaoDeng 已提交
435
int32_t mndPersistTaskDeployReq(STrans *pTrans, SStreamTask *pTask) {
436 437
  SEncoder encoder;
  tEncoderInit(&encoder, NULL, 0);
Y
yihaoDeng 已提交
438 439

  pTask->ver = SSTREAM_TASK_VER;
440
  tEncodeStreamTask(&encoder, pTask);
441

442 443 444
  int32_t size = encoder.pos;
  int32_t tlen = sizeof(SMsgHead) + size;
  tEncoderClear(&encoder);
445

446 447 448
  void *buf = taosMemoryCalloc(1, tlen);
  if (buf == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
449 450
    return -1;
  }
451

452
  ((SMsgHead *)buf)->vgId = htonl(pTask->info.nodeId);
453

454 455
  void *abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
  tEncoderInit(&encoder, abuf, size);
456

457
  tEncodeStreamTask(&encoder, pTask);
458
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
459

460
  STransAction action = {0};
dengyihao's avatar
dengyihao 已提交
461
  action.mTraceId = pTrans->mTraceId;
462
  memcpy(&action.epSet, &pTask->info.epSet, sizeof(SEpSet));
463 464 465
  action.pCont = buf;
  action.contLen = tlen;
  action.msgType = TDMT_STREAM_TASK_DEPLOY;
466

467 468
  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(buf);
L
Liu Jicong 已提交
469 470
    return -1;
  }
471

L
Liu Jicong 已提交
472 473 474
  return 0;
}

475 476 477 478
int32_t mndPersistStreamTasks(SMnode *pMnode, STrans *pTrans, SStreamObj *pStream) {
  int32_t level = taosArrayGetSize(pStream->tasks);
  for (int32_t i = 0; i < level; i++) {
    SArray *pLevel = taosArrayGetP(pStream->tasks, i);
479 480 481

    int32_t numOfTasks = taosArrayGetSize(pLevel);
    for (int32_t j = 0; j < numOfTasks; j++) {
482 483 484 485 486
      SStreamTask *pTask = taosArrayGetP(pLevel, j);
      if (mndPersistTaskDeployReq(pTrans, pTask) < 0) {
        return -1;
      }
    }
L
Liu Jicong 已提交
487
  }
488

489
  // persistent stream task for already stored ts data
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
  if (pStream->conf.fillHistory) {
    level = taosArrayGetSize(pStream->pHTasksList);

    for (int32_t i = 0; i < level; i++) {
      SArray *pLevel = taosArrayGetP(pStream->pHTasksList, i);

      int32_t numOfTasks = taosArrayGetSize(pLevel);
      for (int32_t j = 0; j < numOfTasks; j++) {
        SStreamTask *pTask = taosArrayGetP(pLevel, j);
        if (mndPersistTaskDeployReq(pTrans, pTask) < 0) {
          return -1;
        }
      }
    }
  }

506 507
  return 0;
}
L
Liu Jicong 已提交
508

509 510
int32_t mndPersistStream(SMnode *pMnode, STrans *pTrans, SStreamObj *pStream) {
  if (mndPersistStreamTasks(pMnode, pTrans, pStream) < 0) {
L
Liu Jicong 已提交
511 512
    return -1;
  }
513

514 515 516
  SSdbRaw *pCommitRaw = mndStreamActionEncode(pStream);
  if (pCommitRaw == NULL || mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) {
    mError("trans:%d, failed to append commit log since %s", pTrans->id, terrstr());
L
Liu Jicong 已提交
517 518
    return -1;
  }
519

S
Shengliang Guan 已提交
520
  (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY);
521 522
  return 0;
}
L
Liu Jicong 已提交
523

524
int32_t mndPersistDropStreamLog(SMnode *pMnode, STrans *pTrans, SStreamObj *pStream) {
525 526 527
  SSdbRaw *pCommitRaw = mndStreamActionEncode(pStream);
  if (pCommitRaw == NULL || mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) {
    mError("trans:%d, failed to append commit log since %s", pTrans->id, terrstr());
L
Liu Jicong 已提交
528 529
    return -1;
  }
530

S
Shengliang Guan 已提交
531
  (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_DROPPED);
S
sma  
Shengliang Guan 已提交
532 533 534
  return 0;
}

535 536 537 538
static int32_t mndSetStreamRecover(SMnode *pMnode, STrans *pTrans, const SStreamObj *pStream) {
  SStreamObj streamObj = {0};
  memcpy(streamObj.name, pStream->name, TSDB_STREAM_FNAME_LEN);
  streamObj.status = STREAM_STATUS__RECOVER;
S
Shengliang Guan 已提交
539

540
  SSdbRaw *pCommitRaw = mndStreamActionEncode(&streamObj);
S
Shengliang Guan 已提交
541 542
  if (pCommitRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) {
543 544 545
    mError("stream trans:%d, failed to append commit log since %s", pTrans->id, terrstr());
    return -1;
  }
S
Shengliang Guan 已提交
546
  (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY);
547 548 549
  return 0;
}

L
Liu Jicong 已提交
550
static int32_t mndCreateStbForStream(SMnode *pMnode, STrans *pTrans, const SStreamObj *pStream, const char *user) {
L
Liu Jicong 已提交
551 552
  SStbObj *pStb = NULL;
  SDbObj  *pDb = NULL;
553 554 555 556 557

  SMCreateStbReq createReq = {0};
  tstrncpy(createReq.name, pStream->targetSTbName, TSDB_TABLE_FNAME_LEN);
  createReq.numOfColumns = pStream->outputSchema.nCols;
  createReq.numOfTags = 1;  // group id
558
  createReq.pColumns = taosArrayInit_s(sizeof(SField), createReq.numOfColumns);
559
  // build fields
L
Liu Jicong 已提交
560 561 562 563 564 565 566
  for (int32_t i = 0; i < createReq.numOfColumns; i++) {
    SField *pField = taosArrayGet(createReq.pColumns, i);
    tstrncpy(pField->name, pStream->outputSchema.pSchema[i].name, TSDB_COL_NAME_LEN);
    pField->flags = pStream->outputSchema.pSchema[i].flags;
    pField->type = pStream->outputSchema.pSchema[i].type;
    pField->bytes = pStream->outputSchema.pSchema[i].bytes;
  }
5
54liuyao 已提交
567 568 569

  if (pStream->tagSchema.nCols == 0) {
    createReq.numOfTags = 1;
X
Xiaoyu Wang 已提交
570
    createReq.pTags = taosArrayInit_s(sizeof(SField), 1);
5
54liuyao 已提交
571 572 573 574 575 576 577 578
    // build tags
    SField *pField = taosArrayGet(createReq.pTags, 0);
    strcpy(pField->name, "group_id");
    pField->type = TSDB_DATA_TYPE_UBIGINT;
    pField->flags = 0;
    pField->bytes = 8;
  } else {
    createReq.numOfTags = pStream->tagSchema.nCols;
X
Xiaoyu Wang 已提交
579
    createReq.pTags = taosArrayInit_s(sizeof(SField), createReq.numOfTags);
5
54liuyao 已提交
580 581 582 583 584 585 586 587
    for (int32_t i = 0; i < createReq.numOfTags; i++) {
      SField *pField = taosArrayGet(createReq.pTags, i);
      pField->bytes = pStream->tagSchema.pSchema[i].bytes;
      pField->flags = pStream->tagSchema.pSchema[i].flags;
      pField->type = pStream->tagSchema.pSchema[i].type;
      tstrncpy(pField->name, pStream->tagSchema.pSchema[i].name, TSDB_COL_NAME_LEN);
    }
  }
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

  if (mndCheckCreateStbReq(&createReq) != 0) {
    goto _OVER;
  }

  pStb = mndAcquireStb(pMnode, createReq.name);
  if (pStb != NULL) {
    terrno = TSDB_CODE_MND_STB_ALREADY_EXIST;
    goto _OVER;
  }

  pDb = mndAcquireDbByStb(pMnode, createReq.name);
  if (pDb == NULL) {
    terrno = TSDB_CODE_MND_DB_NOT_SELECTED;
    goto _OVER;
  }

  int32_t numOfStbs = -1;
S
Shengliang Guan 已提交
606 607 608 609
  if (mndGetNumOfStbs(pMnode, pDb->name, &numOfStbs) != 0) {
    goto _OVER;
  }

610 611 612 613 614 615 616 617 618 619 620
  if (pDb->cfg.numOfStables == 1 && numOfStbs != 0) {
    terrno = TSDB_CODE_MND_SINGLE_STB_MODE_DB;
    goto _OVER;
  }

  SStbObj stbObj = {0};

  if (mndBuildStbFromReq(pMnode, &stbObj, &createReq, pDb) != 0) {
    goto _OVER;
  }

L
Liu Jicong 已提交
621 622
  stbObj.uid = pStream->targetStbUid;

L
Liu Jicong 已提交
623 624 625 626 627 628 629
  if (mndAddStbToTrans(pMnode, pTrans, pDb, &stbObj) < 0) {
    mndFreeStb(&stbObj);
    goto _OVER;
  }

  tFreeSMCreateStbReq(&createReq);
  mndFreeStb(&stbObj);
S
Shengliang Guan 已提交
630
  mndReleaseStb(pMnode, pStb);
631
  mndReleaseDb(pMnode, pDb);
632

L
Liu Jicong 已提交
633
  return 0;
634
_OVER:
L
Liu Jicong 已提交
635
  tFreeSMCreateStbReq(&createReq);
636 637
  mndReleaseStb(pMnode, pStb);
  mndReleaseDb(pMnode, pDb);
L
Liu Jicong 已提交
638
  return -1;
639 640
}

L
Liu Jicong 已提交
641 642
static int32_t mndPersistTaskDropReq(STrans *pTrans, SStreamTask *pTask) {
  // vnode
643
  /*if (pTask->info.nodeId > 0) {*/
L
Liu Jicong 已提交
644 645 646 647 648
  SVDropStreamTaskReq *pReq = taosMemoryCalloc(1, sizeof(SVDropStreamTaskReq));
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
649

650
  pReq->head.vgId = htonl(pTask->info.nodeId);
651
  pReq->taskId = pTask->id.taskId;
652 653
  pReq->streamId = pTask->id.streamId;

L
Liu Jicong 已提交
654
  STransAction action = {0};
655
  memcpy(&action.epSet, &pTask->info.epSet, sizeof(SEpSet));
L
Liu Jicong 已提交
656 657
  action.pCont = pReq;
  action.contLen = sizeof(SVDropStreamTaskReq);
L
Liu Jicong 已提交
658
  action.msgType = TDMT_STREAM_TASK_DROP;
L
Liu Jicong 已提交
659 660 661
  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
L
Liu Jicong 已提交
662
  }
L
Liu Jicong 已提交
663
  /*}*/
L
Liu Jicong 已提交
664 665 666 667

  return 0;
}

L
Liu Jicong 已提交
668
int32_t mndDropStreamTasks(SMnode *pMnode, STrans *pTrans, SStreamObj *pStream) {
L
Liu Jicong 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682
  int32_t lv = taosArrayGetSize(pStream->tasks);
  for (int32_t i = 0; i < lv; i++) {
    SArray *pTasks = taosArrayGetP(pStream->tasks, i);
    int32_t sz = taosArrayGetSize(pTasks);
    for (int32_t j = 0; j < sz; j++) {
      SStreamTask *pTask = taosArrayGetP(pTasks, j);
      if (mndPersistTaskDropReq(pTrans, pTask) < 0) {
        return -1;
      }
    }
  }
  return 0;
}

S
Shengliang Guan 已提交
683 684
static int32_t mndProcessCreateStreamReq(SRpcMsg *pReq) {
  SMnode            *pMnode = pReq->info.node;
L
Liu Jicong 已提交
685 686 687 688
  int32_t            code = -1;
  SStreamObj        *pStream = NULL;
  SDbObj            *pDb = NULL;
  SCMCreateStreamReq createStreamReq = {0};
689
  SStreamObj         streamObj = {0};
L
Liu Jicong 已提交
690

S
Shengliang Guan 已提交
691
  if (tDeserializeSCMCreateStreamReq(pReq->pCont, pReq->contLen, &createStreamReq) != 0) {
L
Liu Jicong 已提交
692
    terrno = TSDB_CODE_INVALID_MSG;
693
    goto _OVER;
L
Liu Jicong 已提交
694 695
  }

696
  mInfo("stream:%s, start to create, sql:%s", createStreamReq.name, createStreamReq.sql);
L
Liu Jicong 已提交
697 698 699

  if (mndCheckCreateStreamReq(&createStreamReq) != 0) {
    mError("stream:%s, failed to create since %s", createStreamReq.name, terrstr());
700
    goto _OVER;
L
Liu Jicong 已提交
701 702 703 704 705
  }

  pStream = mndAcquireStream(pMnode, createStreamReq.name);
  if (pStream != NULL) {
    if (createStreamReq.igExists) {
706
      mInfo("stream:%s, already exist, ignore exist is set", createStreamReq.name);
L
Liu Jicong 已提交
707
      code = 0;
708
      goto _OVER;
L
Liu Jicong 已提交
709 710
    } else {
      terrno = TSDB_CODE_MND_STREAM_ALREADY_EXIST;
711
      goto _OVER;
L
Liu Jicong 已提交
712 713
    }
  } else if (terrno != TSDB_CODE_MND_STREAM_NOT_EXIST) {
714
    goto _OVER;
L
Liu Jicong 已提交
715 716
  }

L
Liu Jicong 已提交
717 718 719 720 721 722
  // build stream obj from request
  if (mndBuildStreamObjFromCreateReq(pMnode, &streamObj, &createStreamReq) < 0) {
    mError("stream:%s, failed to create since %s", createStreamReq.name, terrstr());
    goto _OVER;
  }

L
Liu Jicong 已提交
723 724 725 726 727 728 729 730 731 732
  {
    int32_t numOfStream = 0;

    SStreamObj *pStream = NULL;
    void       *pIter = NULL;

    while (1) {
      pIter = sdbFetch(pMnode->pSdb, SDB_STREAM, pIter, (void **)&pStream);
      if (pIter == NULL) {
        if (numOfStream > MND_STREAM_MAX_NUM) {
733
          mError("too many streams, no more than %d for each database", MND_STREAM_MAX_NUM);
L
Liu Jicong 已提交
734 735 736 737 738 739 740 741 742
          terrno = TSDB_CODE_MND_TOO_MANY_STREAMS;
          goto _OVER;
        }
        break;
      }

      if (pStream->sourceDbUid == streamObj.sourceDbUid) {
        ++numOfStream;
      }
743

L
Liu Jicong 已提交
744
      sdbRelease(pMnode->pSdb, pStream);
L
Liu Jicong 已提交
745
      if (numOfStream > MND_STREAM_MAX_NUM) {
746
        mError("too many streams, no more than %d for each database", MND_STREAM_MAX_NUM);
L
Liu Jicong 已提交
747
        terrno = TSDB_CODE_MND_TOO_MANY_STREAMS;
748
        sdbCancelFetch(pMnode->pSdb, pIter);
L
Liu Jicong 已提交
749 750
        goto _OVER;
      }
5
54liuyao 已提交
751 752 753 754

      if (pStream->targetStbUid == streamObj.targetStbUid) {
        mError("Cannot write the same stable as other stream:%s", pStream->name);
        terrno = TSDB_CODE_MND_INVALID_TARGET_TABLE;
755
        sdbCancelFetch(pMnode->pSdb, pIter);
5
54liuyao 已提交
756 757
        goto _OVER;
      }
L
Liu Jicong 已提交
758 759 760
    }
  }

761 762 763 764 765 766 767 768
  pDb = mndAcquireDb(pMnode, streamObj.sourceDb);
  if (pDb->cfg.replications != 1) {
    mError("stream source db must have only 1 replica, but %s has %d", pDb->name, pDb->cfg.replications);
    terrno = TSDB_CODE_MND_MULTI_REPLICA_SOURCE_DB;
    mndReleaseDb(pMnode, pDb);
    pDb = NULL;
    goto _OVER;
  }
769

770
  mndReleaseDb(pMnode, pDb);
771

772
  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_ROLLBACK, TRN_CONFLICT_DB_INSIDE, pReq, "create-stream");
773 774 775 776
  if (pTrans == NULL) {
    mError("stream:%s, failed to create since %s", createStreamReq.name, terrstr());
    goto _OVER;
  }
777

778
  mInfo("trans:%d, used to create stream:%s", pTrans->id, createStreamReq.name);
779

780
  mndTransSetDbName(pTrans, createStreamReq.sourceDB, streamObj.targetDb);
781
  if (mndTransCheckConflict(pMnode, pTrans) != 0) {
M
Minglei Jin 已提交
782 783 784
    mndTransDrop(pTrans);
    goto _OVER;
  }
L
Liu Jicong 已提交
785
  // create stb for stream
X
Xiaoyu Wang 已提交
786 787
  if (createStreamReq.createStb == STREAM_CREATE_STABLE_TRUE &&
      mndCreateStbForStream(pMnode, pTrans, &streamObj, pReq->info.conn.user) < 0) {
L
Liu Jicong 已提交
788 789 790 791 792
    mError("trans:%d, failed to create stb for stream %s since %s", pTrans->id, createStreamReq.name, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }

L
Liu Jicong 已提交
793
  // schedule stream task for stream obj
H
Haojun Liao 已提交
794
  if (mndScheduleStream(pMnode, &streamObj, createStreamReq.lastTs) < 0) {
L
Liu Jicong 已提交
795 796 797 798 799
    mError("stream:%s, failed to schedule since %s", createStreamReq.name, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }

L
Liu Jicong 已提交
800
  // add stream to trans
L
Liu Jicong 已提交
801 802 803 804 805 806
  if (mndPersistStream(pMnode, pTrans, &streamObj) < 0) {
    mError("stream:%s, failed to schedule since %s", createStreamReq.name, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }

807 808 809 810 811 812 813 814 815 816
  if (mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_READ_DB, streamObj.sourceDb) != 0) {
    mndTransDrop(pTrans);
    goto _OVER;
  }

  if (mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, streamObj.targetDb) != 0) {
    mndTransDrop(pTrans);
    goto _OVER;
  }

L
Liu Jicong 已提交
817
  // execute creation
L
Liu Jicong 已提交
818 819 820 821 822
  if (mndTransPrepare(pMnode, pTrans) != 0) {
    mError("trans:%d, failed to prepare since %s", pTrans->id, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }
L
Liu Jicong 已提交
823

L
Liu Jicong 已提交
824 825 826
  mndTransDrop(pTrans);

  code = TSDB_CODE_ACTION_IN_PROGRESS;
L
Liu Jicong 已提交
827

828
_OVER:
S
Shengliang Guan 已提交
829
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
L
Liu Jicong 已提交
830 831 832 833 834 835
    mError("stream:%s, failed to create since %s", createStreamReq.name, terrstr());
  }

  mndReleaseStream(pMnode, pStream);

  tFreeSCMCreateStreamReq(&createStreamReq);
L
Liu Jicong 已提交
836
  tFreeStreamObj(&streamObj);
L
Liu Jicong 已提交
837 838
  return code;
}
5
54liuyao 已提交
839 840 841

#if 0

842
static int32_t mndProcessStreamCheckpointTmr(SRpcMsg *pReq) {
L
Liu Jicong 已提交
843
  SMnode     *pMnode = pReq->info.node;
844 845
  SSdb       *pSdb = pMnode->pSdb;
  void       *pIter = NULL;
L
Liu Jicong 已提交
846 847
  SStreamObj *pStream = NULL;

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
  // iterate all stream obj
  while (1) {
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
    if (pIter == NULL) break;
    // incr tick
    int64_t currentTick = atomic_add_fetch_64(&pStream->currentTick, 1);
    // if >= checkpointFreq, build msg TDMT_MND_STREAM_BEGIN_CHECKPOINT, put into write q
    if (currentTick >= pStream->checkpointFreq) {
      atomic_store_64(&pStream->currentTick, 0);
      SMStreamDoCheckpointMsg *pMsg = rpcMallocCont(sizeof(SMStreamDoCheckpointMsg));

      pMsg->streamId = pStream->uid;
      pMsg->checkpointId = tGenIdPI64();
      memcpy(pMsg->streamName, pStream->name, TSDB_STREAM_FNAME_LEN);

      SRpcMsg rpcMsg = {
          .msgType = TDMT_MND_STREAM_BEGIN_CHECKPOINT,
          .pCont = pMsg,
          .contLen = sizeof(SMStreamDoCheckpointMsg),
      };

      tmsgPutToQueue(&pMnode->msgCb, WRITE_QUEUE, &rpcMsg);
    }
L
Liu Jicong 已提交
871
  }
L
Liu Jicong 已提交
872

873 874
  return 0;
}
L
Liu Jicong 已提交
875

876 877 878 879
static int32_t mndBuildStreamCheckpointSourceReq(void **pBuf, int32_t *pLen, const SStreamTask *pTask,
                                                 SMStreamDoCheckpointMsg *pMsg) {
  SStreamCheckpointSourceReq req = {0};
  req.checkpointId = pMsg->checkpointId;
880
  req.nodeId = pTask->info.nodeId;
881 882 883
  req.expireTime = -1;
  req.streamId = pTask->streamId;
  req.taskId = pTask->taskId;
L
Liu Jicong 已提交
884

885 886 887 888 889 890
  int32_t code;
  int32_t blen;

  tEncodeSize(tEncodeSStreamCheckpointSourceReq, &req, blen, code);
  if (code < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
891
    return -1;
L
Liu Jicong 已提交
892 893
  }

894 895 896 897 898
  int32_t tlen = sizeof(SMsgHead) + blen;

  void *buf = taosMemoryMalloc(tlen);
  if (buf == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
899
    return -1;
L
Liu Jicong 已提交
900 901
  }

902 903 904 905 906 907 908
  void    *abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
  SEncoder encoder;
  tEncoderInit(&encoder, abuf, tlen);
  tEncodeSStreamCheckpointSourceReq(&encoder, &req);

  SMsgHead *pMsgHead = (SMsgHead *)buf;
  pMsgHead->contLen = htonl(tlen);
909
  pMsgHead->vgId = htonl(pTask->info.nodeId);
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928

  tEncoderClear(&encoder);

  *pBuf = buf;
  *pLen = tlen;

  return 0;
}

static int32_t mndProcessStreamDoCheckpoint(SRpcMsg *pReq) {
  SMnode *pMnode = pReq->info.node;
  SSdb   *pSdb = pMnode->pSdb;

  SMStreamDoCheckpointMsg *pMsg = (SMStreamDoCheckpointMsg *)pReq->pCont;

  SStreamObj *pStream = mndAcquireStream(pMnode, pMsg->streamName);

  if (pStream == NULL || pStream->uid != pMsg->streamId) {
    mError("start checkpointing failed since stream %s not found", pMsg->streamName);
L
Liu Jicong 已提交
929
    return -1;
L
Liu Jicong 已提交
930 931
  }

932 933 934 935
  // build new transaction:
  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB_INSIDE, pReq, "stream-checkpoint");
  if (pTrans == NULL) return -1;
  mndTransSetDbName(pTrans, pStream->sourceDb, pStream->targetDb);
936
  if (mndTransCheckConflict(pMnode, pTrans) != 0) {
937 938 939 940 941
    mndReleaseStream(pMnode, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

942 943 944 945 946 947
  taosRLockLatch(&pStream->lock);
  // 1. redo action: broadcast checkpoint source msg for all source vg
  int32_t totLevel = taosArrayGetSize(pStream->tasks);
  for (int32_t i = 0; i < totLevel; i++) {
    SArray      *pLevel = taosArrayGetP(pStream->tasks, i);
    SStreamTask *pTask = taosArrayGetP(pLevel, 0);
948
    if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
949 950 951
      int32_t sz = taosArrayGetSize(pLevel);
      for (int32_t j = 0; j < sz; j++) {
        SStreamTask *pTask = taosArrayGetP(pLevel, j);
952 953
        /*A(pTask->info.nodeId > 0);*/
        SVgObj *pVgObj = mndAcquireVgroup(pMnode, pTask->info.nodeId);
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
        if (pVgObj == NULL) {
          taosRUnLockLatch(&pStream->lock);
          mndReleaseStream(pMnode, pStream);
          mndTransDrop(pTrans);
          return -1;
        }

        void   *buf;
        int32_t tlen;
        if (mndBuildStreamCheckpointSourceReq(&buf, &tlen, pTask, pMsg) < 0) {
          taosRUnLockLatch(&pStream->lock);
          mndReleaseStream(pMnode, pStream);
          mndTransDrop(pTrans);
          return -1;
        }

        STransAction action = {0};
        action.epSet = mndGetVgroupEpset(pMnode, pVgObj);
        action.pCont = buf;
        action.contLen = tlen;
        action.msgType = TDMT_VND_STREAM_CHECK_POINT_SOURCE;

        mndReleaseVgroup(pMnode, pVgObj);

        if (mndTransAppendRedoAction(pTrans, &action) != 0) {
          taosMemoryFree(buf);
          taosRUnLockLatch(&pStream->lock);
          mndReleaseStream(pMnode, pStream);
          mndTransDrop(pTrans);
          return -1;
        }
      }
    }
L
Liu Jicong 已提交
987
  }
988 989 990 991
  // 2. reset tick
  atomic_store_64(&pStream->currentTick, 0);
  // 3. commit log: stream checkpoint info
  taosRUnLockLatch(&pStream->lock);
L
Liu Jicong 已提交
992

L
Liu Jicong 已提交
993
  if (mndTransPrepare(pMnode, pTrans) != 0) {
994
    mError("failed to prepare trans rebalance since %s", terrstr());
L
Liu Jicong 已提交
995
    mndTransDrop(pTrans);
996
    mndReleaseStream(pMnode, pStream);
L
Liu Jicong 已提交
997 998 999
    return -1;
  }

1000
  mndReleaseStream(pMnode, pStream);
L
Liu Jicong 已提交
1001
  mndTransDrop(pTrans);
L
Liu Jicong 已提交
1002

1003
  return 0;
L
Liu Jicong 已提交
1004 1005
}

5
54liuyao 已提交
1006 1007
#endif

1008
static int32_t mndProcessDropStreamReq(SRpcMsg *pReq) {
L
Liu Jicong 已提交
1009 1010 1011
  SMnode     *pMnode = pReq->info.node;
  SStreamObj *pStream = NULL;

1012 1013
  SMDropStreamReq dropReq = {0};
  if (tDeserializeSMDropStreamReq(pReq->pCont, pReq->contLen, &dropReq) < 0) {
L
Liu Jicong 已提交
1014 1015 1016 1017
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

1018
  pStream = mndAcquireStream(pMnode, dropReq.name);
L
Liu Jicong 已提交
1019 1020

  if (pStream == NULL) {
1021 1022
    if (dropReq.igNotExists) {
      mInfo("stream:%s, not exist, ignore not exist is set", dropReq.name);
L
Liu Jicong 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031
      sdbRelease(pMnode->pSdb, pStream);
      return 0;
    } else {
      terrno = TSDB_CODE_MND_STREAM_NOT_EXIST;
      return -1;
    }
  }

  if (mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pStream->targetDb) != 0) {
1032
    sdbRelease(pMnode->pSdb, pStream);
L
Liu Jicong 已提交
1033 1034 1035
    return -1;
  }

1036
  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB_INSIDE, pReq, "drop-stream");
L
Liu Jicong 已提交
1037
  if (pTrans == NULL) {
1038
    mError("stream:%s, failed to drop since %s", dropReq.name, terrstr());
L
Liu Jicong 已提交
1039 1040 1041
    sdbRelease(pMnode->pSdb, pStream);
    return -1;
  }
1042
  mInfo("trans:%d, used to drop stream:%s", pTrans->id, dropReq.name);
L
Liu Jicong 已提交
1043

1044
  mndTransSetDbName(pTrans, pStream->sourceDb, pStream->targetDb);
1045
  if (mndTransCheckConflict(pMnode, pTrans) != 0) {
1046 1047 1048 1049 1050
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

1051 1052 1053
  // drop all tasks
  if (mndDropStreamTasks(pMnode, pTrans, pStream) < 0) {
    mError("stream:%s, failed to drop task since %s", dropReq.name, terrstr());
L
Liu Jicong 已提交
1054
    sdbRelease(pMnode->pSdb, pStream);
1055
    mndTransDrop(pTrans);
L
Liu Jicong 已提交
1056 1057 1058
    return -1;
  }

1059 1060
  // drop stream
  if (mndPersistDropStreamLog(pMnode, pTrans, pStream) < 0) {
L
Liu Jicong 已提交
1061
    sdbRelease(pMnode->pSdb, pStream);
1062
    mndTransDrop(pTrans);
L
Liu Jicong 已提交
1063 1064 1065 1066
    return -1;
  }

  if (mndTransPrepare(pMnode, pTrans) != 0) {
1067
    mError("trans:%d, failed to prepare drop stream trans since %s", pTrans->id, terrstr());
L
Liu Jicong 已提交
1068 1069 1070 1071 1072 1073
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  sdbRelease(pMnode->pSdb, pStream);
1074
  mndTransDrop(pTrans);
L
Liu Jicong 已提交
1075 1076 1077 1078

  return TSDB_CODE_ACTION_IN_PROGRESS;
}

L
Liu Jicong 已提交
1079 1080
int32_t mndDropStreamByDb(SMnode *pMnode, STrans *pTrans, SDbObj *pDb) {
  SSdb *pSdb = pMnode->pSdb;
S
Shengliang Guan 已提交
1081
  void *pIter = NULL;
L
Liu Jicong 已提交
1082 1083

  while (1) {
S
Shengliang Guan 已提交
1084
    SStreamObj *pStream = NULL;
L
Liu Jicong 已提交
1085 1086 1087 1088 1089 1090
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
    if (pIter == NULL) break;

    if (pStream->sourceDbUid == pDb->uid || pStream->targetDbUid == pDb->uid) {
      if (pStream->sourceDbUid != pStream->targetDbUid) {
        sdbRelease(pSdb, pStream);
S
Shengliang Guan 已提交
1091 1092 1093
        sdbCancelFetch(pSdb, pIter);
        mError("db:%s, failed to drop stream:%s since sourceDbUid:%" PRId64 " not match with targetDbUid:%" PRId64,
               pDb->name, pStream->name, pStream->sourceDbUid, pStream->targetDbUid);
1094
        terrno = TSDB_CODE_MND_STREAM_MUST_BE_DELETED;
L
Liu Jicong 已提交
1095 1096
        return -1;
      } else {
1097 1098 1099 1100 1101 1102 1103 1104
#if 0
        if (mndDropStreamTasks(pMnode, pTrans, pStream) < 0) {
          mError("stream:%s, failed to drop task since %s", pStream->name, terrstr());
          sdbRelease(pMnode->pSdb, pStream);
          sdbCancelFetch(pSdb, pIter);
          return -1;
        }
#endif
L
Liu Jicong 已提交
1105 1106
        if (mndPersistDropStreamLog(pMnode, pTrans, pStream) < 0) {
          sdbRelease(pSdb, pStream);
S
Shengliang Guan 已提交
1107
          sdbCancelFetch(pSdb, pIter);
L
Liu Jicong 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
          return -1;
        }
      }
    }

    sdbRelease(pSdb, pStream);
  }

  return 0;
}

1119
int32_t mndGetNumOfStreams(SMnode *pMnode, char *dbName, int32_t *pNumOfStreams) {
L
Liu Jicong 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
  SSdb   *pSdb = pMnode->pSdb;
  SDbObj *pDb = mndAcquireDb(pMnode, dbName);
  if (pDb == NULL) {
    terrno = TSDB_CODE_MND_DB_NOT_SELECTED;
    return -1;
  }

  int32_t numOfStreams = 0;
  void   *pIter = NULL;
  while (1) {
    SStreamObj *pStream = NULL;
    pIter = sdbFetch(pSdb, SDB_STREAM, pIter, (void **)&pStream);
    if (pIter == NULL) break;

L
Liu Jicong 已提交
1134
    if (pStream->sourceDbUid == pDb->uid) {
L
Liu Jicong 已提交
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
      numOfStreams++;
    }

    sdbRelease(pSdb, pStream);
  }

  *pNumOfStreams = numOfStreams;
  mndReleaseDb(pMnode, pDb);
  return 0;
}

S
Shengliang Guan 已提交
1146 1147
static int32_t mndRetrieveStream(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
  SMnode     *pMnode = pReq->info.node;
L
Liu Jicong 已提交
1148 1149 1150 1151 1152
  SSdb       *pSdb = pMnode->pSdb;
  int32_t     numOfRows = 0;
  SStreamObj *pStream = NULL;

  while (numOfRows < rows) {
L
Liu Jicong 已提交
1153
    pShow->pIter = sdbFetch(pSdb, SDB_STREAM, pShow->pIter, (void **)&pStream);
L
Liu Jicong 已提交
1154 1155
    if (pShow->pIter == NULL) break;

L
Liu Jicong 已提交
1156 1157 1158
    SColumnInfoData *pColInfo;
    SName            n;
    int32_t          cols = 0;
L
Liu Jicong 已提交
1159

1160
    char streamName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1161
    STR_WITH_MAXSIZE_TO_VARSTR(streamName, mndGetDbStr(pStream->name), sizeof(streamName));
L
Liu Jicong 已提交
1162
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1163
    colDataSetVal(pColInfo, numOfRows, (const char *)streamName, false);
L
Liu Jicong 已提交
1164

L
Liu Jicong 已提交
1165
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1166
    colDataSetVal(pColInfo, numOfRows, (const char *)&pStream->createTime, false);
L
Liu Jicong 已提交
1167

L
Liu Jicong 已提交
1168
    char sql[TSDB_SHOW_SQL_LEN + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1169
    STR_WITH_MAXSIZE_TO_VARSTR(sql, pStream->sql, sizeof(sql));
L
Liu Jicong 已提交
1170
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1171
    colDataSetVal(pColInfo, numOfRows, (const char *)sql, false);
L
Liu Jicong 已提交
1172

L
Liu Jicong 已提交
1173
    char status[20 + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1174 1175 1176
    char status2[20] = {0};
    mndShowStreamStatus(status2, pStream);
    STR_WITH_MAXSIZE_TO_VARSTR(status, status2, sizeof(status));
L
Liu Jicong 已提交
1177
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1178
    colDataSetVal(pColInfo, numOfRows, (const char *)&status, false);
L
Liu Jicong 已提交
1179

1180
    char sourceDB[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1181
    STR_WITH_MAXSIZE_TO_VARSTR(sourceDB, mndGetDbStr(pStream->sourceDb), sizeof(sourceDB));
L
Liu Jicong 已提交
1182
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1183
    colDataSetVal(pColInfo, numOfRows, (const char *)&sourceDB, false);
L
Liu Jicong 已提交
1184

1185
    char targetDB[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1186
    STR_WITH_MAXSIZE_TO_VARSTR(targetDB, mndGetDbStr(pStream->targetDb), sizeof(targetDB));
L
Liu Jicong 已提交
1187
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1188
    colDataSetVal(pColInfo, numOfRows, (const char *)&targetDB, false);
L
Liu Jicong 已提交
1189

1190 1191
    if (pStream->targetSTbName[0] == 0) {
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1192
      colDataSetVal(pColInfo, numOfRows, NULL, true);
1193 1194
    } else {
      char targetSTB[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1195
      STR_WITH_MAXSIZE_TO_VARSTR(targetSTB, mndGetStbStr(pStream->targetSTbName), sizeof(targetSTB));
1196
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1197
      colDataSetVal(pColInfo, numOfRows, (const char *)&targetSTB, false);
1198
    }
L
Liu Jicong 已提交
1199 1200

    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1201
    colDataSetVal(pColInfo, numOfRows, (const char *)&pStream->conf.watermark, false);
L
Liu Jicong 已提交
1202

L
Liu Jicong 已提交
1203
    char trigger[20 + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1204 1205 1206
    char trigger2[20] = {0};
    mndShowStreamTrigger(trigger2, pStream);
    STR_WITH_MAXSIZE_TO_VARSTR(trigger, trigger2, sizeof(trigger));
L
Liu Jicong 已提交
1207
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1208
    colDataSetVal(pColInfo, numOfRows, (const char *)&trigger, false);
L
Liu Jicong 已提交
1209 1210 1211

    numOfRows++;
    sdbRelease(pSdb, pStream);
L
Liu Jicong 已提交
1212
  }
L
Liu Jicong 已提交
1213 1214 1215

  pShow->numOfRows += numOfRows;
  return numOfRows;
L
Liu Jicong 已提交
1216 1217 1218 1219 1220 1221
}

static void mndCancelGetNextStream(SMnode *pMnode, void *pIter) {
  SSdb *pSdb = pMnode->pSdb;
  sdbCancelFetch(pSdb, pIter);
}
1222 1223 1224 1225 1226 1227 1228 1229 1230

static int32_t mndRetrieveStreamTask(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rowsCapacity) {
  SMnode     *pMnode = pReq->info.node;
  SSdb       *pSdb = pMnode->pSdb;
  int32_t     numOfRows = 0;
  SStreamObj *pStream = NULL;

  while (numOfRows < rowsCapacity) {
    pShow->pIter = sdbFetch(pSdb, SDB_STREAM, pShow->pIter, (void **)&pStream);
1231 1232 1233
    if (pShow->pIter == NULL) {
      break;
    }
1234 1235 1236

    // lock
    taosRLockLatch(&pStream->lock);
1237

1238 1239
    // count task num
    int32_t sz = taosArrayGetSize(pStream->tasks);
1240

1241 1242 1243 1244 1245 1246 1247 1248 1249
    int32_t count = 0;
    for (int32_t i = 0; i < sz; i++) {
      SArray *pLevel = taosArrayGetP(pStream->tasks, i);
      count += taosArrayGetSize(pLevel);
    }

    if (numOfRows + count > rowsCapacity) {
      blockDataEnsureCapacity(pBlock, numOfRows + count);
    }
1250

1251 1252 1253 1254
    // add row for each task
    for (int32_t i = 0; i < sz; i++) {
      SArray *pLevel = taosArrayGetP(pStream->tasks, i);
      int32_t levelCnt = taosArrayGetSize(pLevel);
1255

1256 1257 1258 1259 1260 1261 1262 1263 1264
      for (int32_t j = 0; j < levelCnt; j++) {
        SStreamTask *pTask = taosArrayGetP(pLevel, j);

        SColumnInfoData *pColInfo;
        int32_t          cols = 0;

        // stream name
        char streamName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
        STR_WITH_MAXSIZE_TO_VARSTR(streamName, mndGetDbStr(pStream->name), sizeof(streamName));
1265

1266
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1267
        colDataSetVal(pColInfo, numOfRows, (const char *)streamName, false);
1268 1269 1270

        // task id
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1271

Y
yihaoDeng 已提交
1272
        char    idstr[128] = {0};
1273 1274 1275 1276 1277
        int32_t len = tintToHex(pTask->id.taskId, &idstr[4]);
        idstr[2] = '0';
        idstr[3] = 'x';
        varDataSetLen(idstr, len + 2);
        colDataSetVal(pColInfo, numOfRows, idstr, false);
1278 1279 1280 1281 1282

        // node type
        char nodeType[20 + VARSTR_HEADER_SIZE] = {0};
        varDataSetLen(nodeType, 5);
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1283
        if (pTask->info.nodeId > 0) {
1284 1285 1286 1287
          memcpy(varDataVal(nodeType), "vnode", 5);
        } else {
          memcpy(varDataVal(nodeType), "snode", 5);
        }
1288
        colDataSetVal(pColInfo, numOfRows, nodeType, false);
1289 1290 1291

        // node id
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1292
        int64_t nodeId = TMAX(pTask->info.nodeId, 0);
1293
        colDataSetVal(pColInfo, numOfRows, (const char *)&nodeId, false);
1294 1295 1296

        // level
        char level[20 + VARSTR_HEADER_SIZE] = {0};
1297
        if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
1298 1299
          memcpy(varDataVal(level), "source", 6);
          varDataSetLen(level, 6);
1300
        } else if (pTask->info.taskLevel == TASK_LEVEL__AGG) {
1301 1302
          memcpy(varDataVal(level), "agg", 3);
          varDataSetLen(level, 3);
1303
        } else if (pTask->info.taskLevel == TASK_LEVEL__SINK) {
1304 1305 1306
          memcpy(varDataVal(level), "sink", 4);
          varDataSetLen(level, 4);
        }
1307

1308
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1309
        colDataSetVal(pColInfo, numOfRows, (const char *)&level, false);
1310 1311

        // status
Y
yihaoDeng 已提交
1312
        char   status[20 + VARSTR_HEADER_SIZE] = {0};
L
liuyao 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
        int8_t taskStatus = atomic_load_8(&pTask->status.taskStatus);
        if (taskStatus == TASK_STATUS__NORMAL) {
          memcpy(varDataVal(status), "normal", 6);
          varDataSetLen(status, 6);
        } else if (taskStatus == TASK_STATUS__DROPPING) {
          memcpy(varDataVal(status), "dropping", 8);
          varDataSetLen(status, 8);
        } else if (taskStatus == TASK_STATUS__FAIL) {
          memcpy(varDataVal(status), "fail", 4);
          varDataSetLen(status, 4);
        } else if (taskStatus == TASK_STATUS__STOP) {
          memcpy(varDataVal(status), "stop", 4);
          varDataSetLen(status, 4);
        } else if (taskStatus == TASK_STATUS__SCAN_HISTORY) {
L
liuyao 已提交
1327 1328
          memcpy(varDataVal(status), "history", 7);
          varDataSetLen(status, 7);
L
liuyao 已提交
1329 1330 1331 1332 1333 1334 1335
        } else if (taskStatus == TASK_STATUS__HALT) {
          memcpy(varDataVal(status), "halt", 4);
          varDataSetLen(status, 4);
        } else if (taskStatus == TASK_STATUS__PAUSE) {
          memcpy(varDataVal(status), "pause", 5);
          varDataSetLen(status, 5);
        }
1336
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1337
        colDataSetVal(pColInfo, numOfRows, (const char *)&status, false);
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356

        numOfRows++;
      }
    }

    // unlock
    taosRUnLockLatch(&pStream->lock);

    sdbRelease(pSdb, pStream);
  }

  pShow->numOfRows += numOfRows;
  return numOfRows;
}

static void mndCancelGetNextStreamTask(SMnode *pMnode, void *pIter) {
  SSdb *pSdb = pMnode->pSdb;
  sdbCancelFetch(pSdb, pIter);
}
5
54liuyao 已提交
1357 1358 1359 1360 1361 1362 1363

static int32_t mndPauseStreamTask(STrans *pTrans, SStreamTask *pTask) {
  SVPauseStreamTaskReq *pReq = taosMemoryCalloc(1, sizeof(SVPauseStreamTaskReq));
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
1364
  pReq->head.vgId = htonl(pTask->info.nodeId);
5
54liuyao 已提交
1365
  pReq->taskId = pTask->id.taskId;
1366 1367
  pReq->streamId = pTask->id.streamId;

5
54liuyao 已提交
1368
  STransAction action = {0};
1369
  memcpy(&action.epSet, &pTask->info.epSet, sizeof(SEpSet));
5
54liuyao 已提交
1370 1371
  action.pCont = pReq;
  action.contLen = sizeof(SVPauseStreamTaskReq);
L
liuyao 已提交
1372
  action.msgType = TDMT_STREAM_TASK_PAUSE;
5
54liuyao 已提交
1373 1374 1375 1376 1377 1378 1379
  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }
  return 0;
}

Y
yihaoDeng 已提交
1380
int32_t mndPauseAllStreamTaskImpl(STrans *pTrans, SArray *tasks) {
L
liuyao 已提交
1381
  int32_t size = taosArrayGetSize(tasks);
5
54liuyao 已提交
1382
  for (int32_t i = 0; i < size; i++) {
L
liuyao 已提交
1383
    SArray *pTasks = taosArrayGetP(tasks, i);
5
54liuyao 已提交
1384 1385 1386
    int32_t sz = taosArrayGetSize(pTasks);
    for (int32_t j = 0; j < sz; j++) {
      SStreamTask *pTask = taosArrayGetP(pTasks, j);
1387
      if (pTask->info.taskLevel != TASK_LEVEL__SINK && mndPauseStreamTask(pTrans, pTask) < 0) {
5
54liuyao 已提交
1388 1389
        return -1;
      }
L
liuyao 已提交
1390 1391 1392 1393 1394

      if (atomic_load_8(&pTask->status.taskStatus) != TASK_STATUS__PAUSE) {
        atomic_store_8(&pTask->status.keepTaskStatus, pTask->status.taskStatus);
        atomic_store_8(&pTask->status.taskStatus, TASK_STATUS__PAUSE);
      }
5
54liuyao 已提交
1395 1396 1397 1398 1399
    }
  }
  return 0;
}

L
liuyao 已提交
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
int32_t mndPauseAllStreamTasks(STrans *pTrans, SStreamObj *pStream) {
  int32_t code = mndPauseAllStreamTaskImpl(pTrans, pStream->tasks);
  if (code != 0) {
    return code;
  }
  // pStream->pHTasksList is null
  // code = mndPauseAllStreamTaskImpl(pTrans, pStream->pHTasksList);
  return code;
}

5
54liuyao 已提交
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
static int32_t mndPersistStreamLog(STrans *pTrans, const SStreamObj *pStream, int8_t status) {
  SStreamObj streamObj = {0};
  memcpy(streamObj.name, pStream->name, TSDB_STREAM_FNAME_LEN);
  streamObj.status = status;

  SSdbRaw *pCommitRaw = mndStreamActionEncode(&streamObj);
  if (pCommitRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) {
    mError("stream trans:%d, failed to append commit log since %s", pTrans->id, terrstr());
    return -1;
  }
  (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY);
  return 0;
}

static int32_t mndProcessPauseStreamReq(SRpcMsg *pReq) {
  SMnode     *pMnode = pReq->info.node;
  SStreamObj *pStream = NULL;

  SMPauseStreamReq pauseReq = {0};
  if (tDeserializeSMPauseStreamReq(pReq->pCont, pReq->contLen, &pauseReq) < 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  pStream = mndAcquireStream(pMnode, pauseReq.name);

  if (pStream == NULL) {
    if (pauseReq.igNotExists) {
      mInfo("stream:%s, not exist, if exist is set", pauseReq.name);
      return 0;
    } else {
      terrno = TSDB_CODE_MND_STREAM_NOT_EXIST;
      return -1;
    }
  }

L
liuyao 已提交
1447
  if (pStream->status == STREAM_STATUS__PAUSE) {
L
liuyao 已提交
1448
    sdbRelease(pMnode->pSdb, pStream);
L
liuyao 已提交
1449 1450 1451
    return 0;
  }

5
54liuyao 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
  if (mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pStream->targetDb) != 0) {
    sdbRelease(pMnode->pSdb, pStream);
    return -1;
  }

  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB_INSIDE, pReq, "pause-stream");
  if (pTrans == NULL) {
    mError("stream:%s, failed to pause stream since %s", pauseReq.name, terrstr());
    sdbRelease(pMnode->pSdb, pStream);
    return -1;
  }
  mInfo("trans:%d, used to pause stream:%s", pTrans->id, pauseReq.name);

  mndTransSetDbName(pTrans, pStream->sourceDb, pStream->targetDb);
1466
  if (mndTransCheckConflict(pMnode, pTrans) != 0) {
5
54liuyao 已提交
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  // pause all tasks
  if (mndPauseAllStreamTasks(pTrans, pStream) < 0) {
    mError("stream:%s, failed to drop task since %s", pauseReq.name, terrstr());
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  // pause stream
  if (mndPersistStreamLog(pTrans, pStream, STREAM_STATUS__PAUSE) < 0) {
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  if (mndTransPrepare(pMnode, pTrans) != 0) {
    mError("trans:%d, failed to prepare pause stream trans since %s", pTrans->id, terrstr());
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  sdbRelease(pMnode->pSdb, pStream);
  mndTransDrop(pTrans);

  return TSDB_CODE_ACTION_IN_PROGRESS;
}

5
54liuyao 已提交
1500
static int32_t mndResumeStreamTask(STrans *pTrans, SStreamTask *pTask, int8_t igUntreated) {
5
54liuyao 已提交
1501 1502 1503 1504 1505
  SVResumeStreamTaskReq *pReq = taosMemoryCalloc(1, sizeof(SVResumeStreamTaskReq));
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
1506
  pReq->head.vgId = htonl(pTask->info.nodeId);
5
54liuyao 已提交
1507
  pReq->taskId = pTask->id.taskId;
1508
  pReq->streamId = pTask->id.streamId;
5
54liuyao 已提交
1509
  pReq->igUntreated = igUntreated;
1510

5
54liuyao 已提交
1511
  STransAction action = {0};
1512
  memcpy(&action.epSet, &pTask->info.epSet, sizeof(SEpSet));
5
54liuyao 已提交
1513
  action.pCont = pReq;
5
54liuyao 已提交
1514
  action.contLen = sizeof(SVResumeStreamTaskReq);
5
54liuyao 已提交
1515 1516 1517 1518 1519 1520 1521 1522
  action.msgType = TDMT_STREAM_TASK_RESUME;
  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }
  return 0;
}

5
54liuyao 已提交
1523
int32_t mndResumeAllStreamTasks(STrans *pTrans, SStreamObj *pStream, int8_t igUntreated) {
5
54liuyao 已提交
1524 1525 1526 1527 1528 1529
  int32_t size = taosArrayGetSize(pStream->tasks);
  for (int32_t i = 0; i < size; i++) {
    SArray *pTasks = taosArrayGetP(pStream->tasks, i);
    int32_t sz = taosArrayGetSize(pTasks);
    for (int32_t j = 0; j < sz; j++) {
      SStreamTask *pTask = taosArrayGetP(pTasks, j);
1530
      if (pTask->info.taskLevel != TASK_LEVEL__SINK && mndResumeStreamTask(pTrans, pTask, igUntreated) < 0) {
5
54liuyao 已提交
1531 1532
        return -1;
      }
L
liuyao 已提交
1533 1534 1535 1536

      if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__PAUSE) {
        atomic_store_8(&pTask->status.taskStatus, pTask->status.keepTaskStatus);
      }
5
54liuyao 已提交
1537 1538
    }
  }
L
liuyao 已提交
1539
  // pStream->pHTasksList is null
5
54liuyao 已提交
1540 1541 1542 1543 1544 1545 1546
  return 0;
}

static int32_t mndProcessResumeStreamReq(SRpcMsg *pReq) {
  SMnode     *pMnode = pReq->info.node;
  SStreamObj *pStream = NULL;

5
54liuyao 已提交
1547 1548
  SMResumeStreamReq pauseReq = {0};
  if (tDeserializeSMResumeStreamReq(pReq->pCont, pReq->contLen, &pauseReq) < 0) {
5
54liuyao 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  pStream = mndAcquireStream(pMnode, pauseReq.name);

  if (pStream == NULL) {
    if (pauseReq.igNotExists) {
      mInfo("stream:%s, not exist, if exist is set", pauseReq.name);
      sdbRelease(pMnode->pSdb, pStream);
      return 0;
    } else {
      terrno = TSDB_CODE_MND_STREAM_NOT_EXIST;
      return -1;
    }
  }

L
liuyao 已提交
1566 1567 1568 1569
  if (pStream->status != STREAM_STATUS__PAUSE) {
    return 0;
  }

5
54liuyao 已提交
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
  if (mndCheckDbPrivilegeByName(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pStream->targetDb) != 0) {
    sdbRelease(pMnode->pSdb, pStream);
    return -1;
  }

  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB_INSIDE, pReq, "pause-stream");
  if (pTrans == NULL) {
    mError("stream:%s, failed to pause stream since %s", pauseReq.name, terrstr());
    sdbRelease(pMnode->pSdb, pStream);
    return -1;
  }
  mInfo("trans:%d, used to pause stream:%s", pTrans->id, pauseReq.name);

  mndTransSetDbName(pTrans, pStream->sourceDb, pStream->targetDb);
1584
  if (mndTransCheckConflict(pMnode, pTrans) != 0) {
5
54liuyao 已提交
1585 1586 1587 1588 1589 1590
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  // resume all tasks
5
54liuyao 已提交
1591
  if (mndResumeAllStreamTasks(pTrans, pStream, pauseReq.igUntreated) < 0) {
5
54liuyao 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    mError("stream:%s, failed to drop task since %s", pauseReq.name, terrstr());
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  // resume stream
  if (mndPersistStreamLog(pTrans, pStream, STREAM_STATUS__NORMAL) < 0) {
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  if (mndTransPrepare(pMnode, pTrans) != 0) {
    mError("trans:%d, failed to prepare pause stream trans since %s", pTrans->id, terrstr());
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  sdbRelease(pMnode->pSdb, pStream);
  mndTransDrop(pTrans);

  return TSDB_CODE_ACTION_IN_PROGRESS;
}