mndStream.c 40.8 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"

31
#define MND_STREAM_VER_NUMBER   2
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);
L
Liu Jicong 已提交
50 51

int32_t mndInitStream(SMnode *pMnode) {
52 53 54 55 56 57 58 59 60
  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 已提交
61 62

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

  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DEPLOY_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_DROP_RSP, mndTransProcessRsp);
L
Liu Jicong 已提交
68

5
54liuyao 已提交
69 70
  // mndSetMsgHandle(pMnode, TDMT_MND_STREAM_CHECKPOINT_TIMER, mndProcessStreamCheckpointTmr);
  // mndSetMsgHandle(pMnode, TDMT_MND_STREAM_BEGIN_CHECKPOINT, mndProcessStreamDoCheckpoint);
71 72
  mndSetMsgHandle(pMnode, TDMT_STREAM_TASK_REPORT_CHECKPOINT, mndTransProcessRsp);

L
Liu Jicong 已提交
73 74
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_STREAMS, mndRetrieveStream);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_STREAMS, mndCancelGetNextStream);
75 76
  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_STREAM_TASKS, mndRetrieveStreamTask);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_STREAM_TASKS, mndCancelGetNextStreamTask);
L
Liu Jicong 已提交
77 78 79 80 81 82 83 84 85 86

  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 已提交
87 88
  SEncoder encoder;
  tEncoderInit(&encoder, NULL, 0);
L
Liu Jicong 已提交
89
  if (tEncodeSStreamObj(&encoder, pStream) < 0) {
H
Hongze Cheng 已提交
90
    tEncoderClear(&encoder);
L
Liu Jicong 已提交
91 92 93
    goto STREAM_ENCODE_OVER;
  }
  int32_t tlen = encoder.pos;
H
Hongze Cheng 已提交
94
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
95 96 97 98 99

  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 已提交
100
  buf = taosMemoryMalloc(tlen);
L
Liu Jicong 已提交
101 102
  if (buf == NULL) goto STREAM_ENCODE_OVER;

H
Hongze Cheng 已提交
103
  tEncoderInit(&encoder, buf, tlen);
L
Liu Jicong 已提交
104
  if (tEncodeSStreamObj(&encoder, pStream) < 0) {
H
Hongze Cheng 已提交
105
    tEncoderClear(&encoder);
L
Liu Jicong 已提交
106 107
    goto STREAM_ENCODE_OVER;
  }
H
Hongze Cheng 已提交
108
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
109 110 111 112 113 114 115 116 117

  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 已提交
118
  taosMemoryFreeClear(buf);
L
Liu Jicong 已提交
119 120 121 122 123 124 125 126 127 128 129 130
  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;
131 132 133
  SSdbRow    *pRow = NULL;
  SStreamObj *pStream = NULL;
  void       *buf = NULL;
L
Liu Jicong 已提交
134 135 136 137

  int8_t sver = 0;
  if (sdbGetRawSoftVer(pRaw, &sver) != 0) goto STREAM_DECODE_OVER;

138
  if (sver != 1 && sver != 2) {
L
Liu Jicong 已提交
139 140 141 142
    terrno = TSDB_CODE_SDB_INVALID_DATA_VER;
    goto STREAM_DECODE_OVER;
  }

143
  pRow = sdbAllocRow(sizeof(SStreamObj));
L
Liu Jicong 已提交
144 145
  if (pRow == NULL) goto STREAM_DECODE_OVER;

146
  pStream = sdbGetRowObj(pRow);
L
Liu Jicong 已提交
147 148 149 150 151
  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 已提交
152
  buf = taosMemoryMalloc(tlen + 1);
L
Liu Jicong 已提交
153 154 155
  if (buf == NULL) goto STREAM_DECODE_OVER;
  SDB_GET_BINARY(pRaw, dataPos, buf, tlen, STREAM_DECODE_OVER);

H
Hongze Cheng 已提交
156 157
  SDecoder decoder;
  tDecoderInit(&decoder, buf, tlen + 1);
158
  if (tDecodeSStreamObj(&decoder, pStream, sver) < 0) {
L
Liu Jicong 已提交
159
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
160 161
    goto STREAM_DECODE_OVER;
  }
L
Liu Jicong 已提交
162
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
163 164 165 166

  terrno = TSDB_CODE_SUCCESS;

STREAM_DECODE_OVER:
wafwerar's avatar
wafwerar 已提交
167
  taosMemoryFreeClear(buf);
L
Liu Jicong 已提交
168
  if (terrno != TSDB_CODE_SUCCESS) {
169 170
    mError("stream:%s, failed to decode from raw:%p since %s", pStream == NULL ? "null" : pStream->name, pRaw,
           terrstr());
wafwerar's avatar
wafwerar 已提交
171
    taosMemoryFreeClear(pRow);
L
Liu Jicong 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185
    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 已提交
186 187 188
  taosWLockLatch(&pStream->lock);
  tFreeStreamObj(pStream);
  taosWUnLockLatch(&pStream->lock);
L
Liu Jicong 已提交
189 190 191 192 193
  return 0;
}

static int32_t mndStreamActionUpdate(SSdb *pSdb, SStreamObj *pOldStream, SStreamObj *pNewStream) {
  mTrace("stream:%s, perform update action", pOldStream->name);
wafwerar's avatar
wafwerar 已提交
194
  atomic_exchange_64(&pOldStream->updateTime, pNewStream->updateTime);
L
Liu Jicong 已提交
195 196 197 198
  atomic_exchange_32(&pOldStream->version, pNewStream->version);

  taosWLockLatch(&pOldStream->lock);

199
  pOldStream->status = pNewStream->status;
L
Liu Jicong 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

  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 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
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");
  }
}

static void mndShowStreamTrigger(char *dst, SStreamObj *pStream) {
  int8_t trigger = pStream->trigger;
  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 已提交
243
static int32_t mndCheckCreateStreamReq(SCMCreateStreamReq *pCreate) {
L
Liu Jicong 已提交
244 245
  if (pCreate->name[0] == 0 || pCreate->sql == NULL || pCreate->sql[0] == 0 || pCreate->sourceDB[0] == 0 ||
      pCreate->targetStbFullName[0] == 0) {
L
Liu Jicong 已提交
246 247 248 249 250 251
    terrno = TSDB_CODE_MND_INVALID_STREAM_OPTION;
    return -1;
  }
  return 0;
}

X
Xiaoyu Wang 已提交
252
static int32_t mndStreamGetPlanString(const char *ast, int8_t triggerType, int64_t watermark, char **pStr) {
S
sma  
Shengliang Guan 已提交
253
  if (NULL == ast) {
L
Liu Jicong 已提交
254 255 256 257
    return TSDB_CODE_SUCCESS;
  }

  SNode  *pAst = NULL;
S
sma  
Shengliang Guan 已提交
258
  int32_t code = nodesStringToNode(ast, &pAst);
L
Liu Jicong 已提交
259 260 261 262 263 264 265

  SQueryPlan *pPlan = NULL;
  if (TSDB_CODE_SUCCESS == code) {
    SPlanContext cxt = {
        .pAstRoot = pAst,
        .topicQuery = false,
        .streamQuery = true,
266
        .triggerType = triggerType == STREAM_TRIGGER_MAX_DELAY ? STREAM_TRIGGER_WINDOW_CLOSE : triggerType,
X
Xiaoyu Wang 已提交
267
        .watermark = watermark,
L
Liu Jicong 已提交
268 269 270 271 272
    };
    code = qCreateQueryPlan(&cxt, &pPlan, NULL);
  }

  if (TSDB_CODE_SUCCESS == code) {
273
    code = nodesNodeToString((SNode *)pPlan, false, pStr, NULL);
L
Liu Jicong 已提交
274 275
  }
  nodesDestroyNode(pAst);
276
  nodesDestroyNode((SNode *)pPlan);
L
Liu Jicong 已提交
277 278 279 280
  terrno = code;
  return code;
}

L
Liu Jicong 已提交
281
static int32_t mndBuildStreamObjFromCreateReq(SMnode *pMnode, SStreamObj *pObj, SCMCreateStreamReq *pCreate) {
282 283
  SNode      *pAst = NULL;
  SQueryPlan *pPlan = NULL;
L
Liu Jicong 已提交
284

285
  mInfo("stream:%s to create", pCreate->name);
L
Liu Jicong 已提交
286 287 288 289 290 291 292 293 294
  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));
  pObj->status = 0;

295
  pObj->igExpired = pCreate->igExpired;
L
Liu Jicong 已提交
296 297 298
  pObj->trigger = pCreate->triggerType;
  pObj->triggerParam = pCreate->maxDelay;
  pObj->watermark = pCreate->watermark;
L
Liu Jicong 已提交
299
  pObj->fillHistory = pCreate->fillHistory;
5
54liuyao 已提交
300
  pObj->deleteMark = pCreate->deleteMark;
301
  pObj->igCheckUpdate = pCreate->igUpdate;
L
Liu Jicong 已提交
302 303 304 305

  memcpy(pObj->sourceDb, pCreate->sourceDB, TSDB_DB_FNAME_LEN);
  SDbObj *pSourceDb = mndAcquireDb(pMnode, pCreate->sourceDB);
  if (pSourceDb == NULL) {
306
    mInfo("stream:%s failed to create, source db %s not exist since %s", pCreate->name, pObj->sourceDb, terrstr());
L
Liu Jicong 已提交
307 308 309
    return -1;
  }
  pObj->sourceDbUid = pSourceDb->uid;
310
  mndReleaseDb(pMnode, pSourceDb);
L
Liu Jicong 已提交
311 312 313 314 315

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

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

321 322 323 324 325
  if (pCreate->createStb == STREAM_CREATE_STABLE_TRUE) {
    pObj->targetStbUid = mndGenerateUid(pObj->targetSTbName, TSDB_TABLE_FNAME_LEN);
  } else {
    pObj->targetStbUid = pCreate->targetStbUid;
  }
L
Liu Jicong 已提交
326
  pObj->targetDbUid = pTargetDb->uid;
327
  mndReleaseDb(pMnode, pTargetDb);
L
Liu Jicong 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

  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;
  }

345
  int32_t numOfNULL = taosArrayGetSize(pCreate->fillNullCols);
X
Xiaoyu Wang 已提交
346
  if (numOfNULL > 0) {
347
    pObj->outputSchema.nCols += numOfNULL;
X
Xiaoyu Wang 已提交
348
    SSchema *pFullSchema = taosMemoryCalloc(pObj->outputSchema.nCols, sizeof(SSchema));
349 350 351 352 353 354 355
    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 已提交
356
      SColLocation *pos = taosArrayGet(pCreate->fillNullCols, nullIndex);
5
54liuyao 已提交
357
      if (nullIndex >= numOfNULL || i < pos->slotId) {
358
        pFullSchema[i].bytes = pObj->outputSchema.pSchema[dataIndex].bytes;
X
Xiaoyu Wang 已提交
359
        pFullSchema[i].colId = i + 1;  // pObj->outputSchema.pSchema[dataIndex].colId;
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
        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 已提交
377 378 379 380 381 382
  SPlanContext cxt = {
      .pAstRoot = pAst,
      .topicQuery = false,
      .streamQuery = true,
      .triggerType = pObj->trigger == STREAM_TRIGGER_MAX_DELAY ? STREAM_TRIGGER_WINDOW_CLOSE : pObj->trigger,
      .watermark = pObj->watermark,
383
      .igExpired = pObj->igExpired,
5
54liuyao 已提交
384
      .deleteMark = pObj->deleteMark,
385
      .igCheckUpdate = pObj->igCheckUpdate,
L
Liu Jicong 已提交
386 387 388 389 390 391 392 393 394 395 396 397
  };

  // 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;
  }

398 399 400 401
  pObj->tagSchema.nCols = pCreate->numOfTags;
  if (pCreate->numOfTags) {
    pObj->tagSchema.pSchema = taosMemoryCalloc(pCreate->numOfTags, sizeof(SSchema));
  }
L
Liu Jicong 已提交
402
  /*A(pCreate->numOfTags == taosArrayGetSize(pCreate->pTags));*/
403 404 405 406 407 408 409 410 411
  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 已提交
412 413
FAIL:
  if (pAst != NULL) nodesDestroyNode(pAst);
414
  if (pPlan != NULL) qDestroyQueryPlan(pPlan);
L
Liu Jicong 已提交
415 416 417
  return 0;
}

418 419 420
int32_t mndPersistTaskDeployReq(STrans *pTrans, const SStreamTask *pTask) {
  SEncoder encoder;
  tEncoderInit(&encoder, NULL, 0);
421
  tEncodeStreamTask(&encoder, pTask);
422 423 424 425 426 427
  int32_t size = encoder.pos;
  int32_t tlen = sizeof(SMsgHead) + size;
  tEncoderClear(&encoder);
  void *buf = taosMemoryCalloc(1, tlen);
  if (buf == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
428 429
    return -1;
  }
430 431 432
  ((SMsgHead *)buf)->vgId = htonl(pTask->nodeId);
  void *abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
  tEncoderInit(&encoder, abuf, size);
433
  tEncodeStreamTask(&encoder, pTask);
434
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
435

436
  STransAction action = {0};
dengyihao's avatar
dengyihao 已提交
437
  action.mTraceId = pTrans->mTraceId;
438 439 440 441 442 443
  memcpy(&action.epSet, &pTask->epSet, sizeof(SEpSet));
  action.pCont = buf;
  action.contLen = tlen;
  action.msgType = TDMT_STREAM_TASK_DEPLOY;
  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(buf);
L
Liu Jicong 已提交
444 445 446 447 448
    return -1;
  }
  return 0;
}

449 450 451 452 453 454 455 456 457 458 459
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);
    int32_t sz = taosArrayGetSize(pLevel);
    for (int32_t j = 0; j < sz; j++) {
      SStreamTask *pTask = taosArrayGetP(pLevel, j);
      if (mndPersistTaskDeployReq(pTrans, pTask) < 0) {
        return -1;
      }
    }
L
Liu Jicong 已提交
460
  }
461 462
  return 0;
}
L
Liu Jicong 已提交
463

464 465
int32_t mndPersistStream(SMnode *pMnode, STrans *pTrans, SStreamObj *pStream) {
  if (mndPersistStreamTasks(pMnode, pTrans, pStream) < 0) {
L
Liu Jicong 已提交
466 467
    return -1;
  }
468 469 470
  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 已提交
471 472
    return -1;
  }
S
Shengliang Guan 已提交
473
  (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY);
474 475
  return 0;
}
L
Liu Jicong 已提交
476

477
int32_t mndPersistDropStreamLog(SMnode *pMnode, STrans *pTrans, SStreamObj *pStream) {
478 479 480
  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 已提交
481 482 483
    mndTransDrop(pTrans);
    return -1;
  }
S
Shengliang Guan 已提交
484
  (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_DROPPED);
S
sma  
Shengliang Guan 已提交
485 486 487
  return 0;
}

488 489 490 491
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 已提交
492

493
  SSdbRaw *pCommitRaw = mndStreamActionEncode(&streamObj);
S
Shengliang Guan 已提交
494 495
  if (pCommitRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) {
496 497 498 499
    mError("stream trans:%d, failed to append commit log since %s", pTrans->id, terrstr());
    mndTransDrop(pTrans);
    return -1;
  }
S
Shengliang Guan 已提交
500
  (void)sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY);
501 502 503
  return 0;
}

L
Liu Jicong 已提交
504
static int32_t mndCreateStbForStream(SMnode *pMnode, STrans *pTrans, const SStreamObj *pStream, const char *user) {
L
Liu Jicong 已提交
505 506
  SStbObj *pStb = NULL;
  SDbObj  *pDb = NULL;
507 508 509 510 511

  SMCreateStbReq createReq = {0};
  tstrncpy(createReq.name, pStream->targetSTbName, TSDB_TABLE_FNAME_LEN);
  createReq.numOfColumns = pStream->outputSchema.nCols;
  createReq.numOfTags = 1;  // group id
512
  createReq.pColumns = taosArrayInit_s(sizeof(SField), createReq.numOfColumns);
513
  // build fields
L
Liu Jicong 已提交
514 515 516 517 518 519 520
  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 已提交
521 522 523

  if (pStream->tagSchema.nCols == 0) {
    createReq.numOfTags = 1;
X
Xiaoyu Wang 已提交
524
    createReq.pTags = taosArrayInit_s(sizeof(SField), 1);
5
54liuyao 已提交
525 526 527 528 529 530 531 532
    // 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 已提交
533
    createReq.pTags = taosArrayInit_s(sizeof(SField), createReq.numOfTags);
5
54liuyao 已提交
534 535 536 537 538 539 540 541
    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);
    }
  }
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

  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 已提交
560 561 562 563
  if (mndGetNumOfStbs(pMnode, pDb->name, &numOfStbs) != 0) {
    goto _OVER;
  }

564 565 566 567 568 569 570 571 572 573 574
  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 已提交
575 576
  stbObj.uid = pStream->targetStbUid;

L
Liu Jicong 已提交
577 578 579 580 581 582 583
  if (mndAddStbToTrans(pMnode, pTrans, pDb, &stbObj) < 0) {
    mndFreeStb(&stbObj);
    goto _OVER;
  }

  tFreeSMCreateStbReq(&createReq);
  mndFreeStb(&stbObj);
S
Shengliang Guan 已提交
584
  mndReleaseStb(pMnode, pStb);
585
  mndReleaseDb(pMnode, pDb);
586

L
Liu Jicong 已提交
587
  return 0;
588
_OVER:
L
Liu Jicong 已提交
589
  tFreeSMCreateStbReq(&createReq);
590 591
  mndReleaseStb(pMnode, pStb);
  mndReleaseDb(pMnode, pDb);
L
Liu Jicong 已提交
592
  return -1;
593 594
}

L
Liu Jicong 已提交
595 596
static int32_t mndPersistTaskDropReq(STrans *pTrans, SStreamTask *pTask) {
  // vnode
L
Liu Jicong 已提交
597 598 599 600 601 602 603
  /*if (pTask->nodeId > 0) {*/
  SVDropStreamTaskReq *pReq = taosMemoryCalloc(1, sizeof(SVDropStreamTaskReq));
  if (pReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  pReq->head.vgId = htonl(pTask->nodeId);
604
  pReq->taskId = pTask->id.taskId;
L
Liu Jicong 已提交
605 606 607 608
  STransAction action = {0};
  memcpy(&action.epSet, &pTask->epSet, sizeof(SEpSet));
  action.pCont = pReq;
  action.contLen = sizeof(SVDropStreamTaskReq);
L
Liu Jicong 已提交
609
  action.msgType = TDMT_STREAM_TASK_DROP;
L
Liu Jicong 已提交
610 611 612
  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
L
Liu Jicong 已提交
613
  }
L
Liu Jicong 已提交
614
  /*}*/
L
Liu Jicong 已提交
615 616 617 618

  return 0;
}

L
Liu Jicong 已提交
619
int32_t mndDropStreamTasks(SMnode *pMnode, STrans *pTrans, SStreamObj *pStream) {
L
Liu Jicong 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633
  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 已提交
634 635
static int32_t mndProcessCreateStreamReq(SRpcMsg *pReq) {
  SMnode            *pMnode = pReq->info.node;
L
Liu Jicong 已提交
636 637 638 639
  int32_t            code = -1;
  SStreamObj        *pStream = NULL;
  SDbObj            *pDb = NULL;
  SCMCreateStreamReq createStreamReq = {0};
640
  SStreamObj         streamObj = {0};
L
Liu Jicong 已提交
641

S
Shengliang Guan 已提交
642
  if (tDeserializeSCMCreateStreamReq(pReq->pCont, pReq->contLen, &createStreamReq) != 0) {
L
Liu Jicong 已提交
643
    terrno = TSDB_CODE_INVALID_MSG;
644
    goto _OVER;
L
Liu Jicong 已提交
645 646
  }

647
  mInfo("stream:%s, start to create, sql:%s", createStreamReq.name, createStreamReq.sql);
L
Liu Jicong 已提交
648 649 650

  if (mndCheckCreateStreamReq(&createStreamReq) != 0) {
    mError("stream:%s, failed to create since %s", createStreamReq.name, terrstr());
651
    goto _OVER;
L
Liu Jicong 已提交
652 653 654 655 656
  }

  pStream = mndAcquireStream(pMnode, createStreamReq.name);
  if (pStream != NULL) {
    if (createStreamReq.igExists) {
657
      mInfo("stream:%s, already exist, ignore exist is set", createStreamReq.name);
L
Liu Jicong 已提交
658
      code = 0;
659
      goto _OVER;
L
Liu Jicong 已提交
660 661
    } else {
      terrno = TSDB_CODE_MND_STREAM_ALREADY_EXIST;
662
      goto _OVER;
L
Liu Jicong 已提交
663 664
    }
  } else if (terrno != TSDB_CODE_MND_STREAM_NOT_EXIST) {
665
    goto _OVER;
L
Liu Jicong 已提交
666 667
  }

L
Liu Jicong 已提交
668 669 670 671 672 673
  // 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 已提交
674 675 676 677 678 679 680 681 682 683
  {
    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) {
684
          mError("too many streams, no more than %d for each database", MND_STREAM_MAX_NUM);
L
Liu Jicong 已提交
685 686 687 688 689 690 691 692 693
          terrno = TSDB_CODE_MND_TOO_MANY_STREAMS;
          goto _OVER;
        }
        break;
      }

      if (pStream->sourceDbUid == streamObj.sourceDbUid) {
        ++numOfStream;
      }
L
Liu Jicong 已提交
694
      sdbRelease(pMnode->pSdb, pStream);
L
Liu Jicong 已提交
695
      if (numOfStream > MND_STREAM_MAX_NUM) {
696
        mError("too many streams, no more than %d for each database", MND_STREAM_MAX_NUM);
L
Liu Jicong 已提交
697 698 699
        terrno = TSDB_CODE_MND_TOO_MANY_STREAMS;
        goto _OVER;
      }
5
54liuyao 已提交
700 701 702 703 704 705

      if (pStream->targetStbUid == streamObj.targetStbUid) {
        mError("Cannot write the same stable as other stream:%s", pStream->name);
        terrno = TSDB_CODE_MND_INVALID_TARGET_TABLE;
        goto _OVER;
      }
L
Liu Jicong 已提交
706 707 708
    }
  }

709 710 711 712 713 714 715 716
  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;
  }
717
  mndReleaseDb(pMnode, pDb);
718

719
  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_ROLLBACK, TRN_CONFLICT_DB_INSIDE, pReq, "create-stream");
720 721 722 723
  if (pTrans == NULL) {
    mError("stream:%s, failed to create since %s", createStreamReq.name, terrstr());
    goto _OVER;
  }
724
  mInfo("trans:%d, used to create stream:%s", pTrans->id, createStreamReq.name);
725

726
  mndTransSetDbName(pTrans, createStreamReq.sourceDB, streamObj.targetDb);
M
Minglei Jin 已提交
727 728 729 730
  if (mndTrancCheckConflict(pMnode, pTrans) != 0) {
    mndTransDrop(pTrans);
    goto _OVER;
  }
L
Liu Jicong 已提交
731
  // create stb for stream
X
Xiaoyu Wang 已提交
732 733
  if (createStreamReq.createStb == STREAM_CREATE_STABLE_TRUE &&
      mndCreateStbForStream(pMnode, pTrans, &streamObj, pReq->info.conn.user) < 0) {
L
Liu Jicong 已提交
734 735 736 737 738
    mError("trans:%d, failed to create stb for stream %s since %s", pTrans->id, createStreamReq.name, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }

L
Liu Jicong 已提交
739
  // schedule stream task for stream obj
740
  if (mndScheduleStream(pMnode, &streamObj) < 0) {
L
Liu Jicong 已提交
741 742 743 744 745
    mError("stream:%s, failed to schedule since %s", createStreamReq.name, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }

L
Liu Jicong 已提交
746
  // add stream to trans
L
Liu Jicong 已提交
747 748 749 750 751 752
  if (mndPersistStream(pMnode, pTrans, &streamObj) < 0) {
    mError("stream:%s, failed to schedule since %s", createStreamReq.name, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }

753 754 755 756 757 758 759 760 761 762
  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 已提交
763
  // execute creation
L
Liu Jicong 已提交
764 765 766 767 768
  if (mndTransPrepare(pMnode, pTrans) != 0) {
    mError("trans:%d, failed to prepare since %s", pTrans->id, terrstr());
    mndTransDrop(pTrans);
    goto _OVER;
  }
L
Liu Jicong 已提交
769

L
Liu Jicong 已提交
770 771 772
  mndTransDrop(pTrans);

  code = TSDB_CODE_ACTION_IN_PROGRESS;
L
Liu Jicong 已提交
773

774
_OVER:
S
Shengliang Guan 已提交
775
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
L
Liu Jicong 已提交
776 777 778 779 780 781
    mError("stream:%s, failed to create since %s", createStreamReq.name, terrstr());
  }

  mndReleaseStream(pMnode, pStream);

  tFreeSCMCreateStreamReq(&createStreamReq);
L
Liu Jicong 已提交
782
  tFreeStreamObj(&streamObj);
L
Liu Jicong 已提交
783 784
  return code;
}
5
54liuyao 已提交
785 786 787

#if 0

788
static int32_t mndProcessStreamCheckpointTmr(SRpcMsg *pReq) {
L
Liu Jicong 已提交
789
  SMnode     *pMnode = pReq->info.node;
790 791
  SSdb       *pSdb = pMnode->pSdb;
  void       *pIter = NULL;
L
Liu Jicong 已提交
792 793
  SStreamObj *pStream = NULL;

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
  // 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 已提交
817
  }
L
Liu Jicong 已提交
818

819 820
  return 0;
}
L
Liu Jicong 已提交
821

822 823 824 825 826 827 828 829
static int32_t mndBuildStreamCheckpointSourceReq(void **pBuf, int32_t *pLen, const SStreamTask *pTask,
                                                 SMStreamDoCheckpointMsg *pMsg) {
  SStreamCheckpointSourceReq req = {0};
  req.checkpointId = pMsg->checkpointId;
  req.nodeId = pTask->nodeId;
  req.expireTime = -1;
  req.streamId = pTask->streamId;
  req.taskId = pTask->taskId;
L
Liu Jicong 已提交
830

831 832 833 834 835 836
  int32_t code;
  int32_t blen;

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

840 841 842 843 844
  int32_t tlen = sizeof(SMsgHead) + blen;

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

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
  void    *abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
  SEncoder encoder;
  tEncoderInit(&encoder, abuf, tlen);
  tEncodeSStreamCheckpointSourceReq(&encoder, &req);

  SMsgHead *pMsgHead = (SMsgHead *)buf;
  pMsgHead->contLen = htonl(tlen);
  pMsgHead->vgId = htonl(pTask->nodeId);

  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 已提交
875
    return -1;
L
Liu Jicong 已提交
876 877
  }

878 879 880 881
  // 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);
882 883 884 885 886 887
  if (mndTrancCheckConflict(pMnode, pTrans) != 0) {
    mndReleaseStream(pMnode, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

888 889 890 891 892 893 894 895 896 897
  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);
    if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
      int32_t sz = taosArrayGetSize(pLevel);
      for (int32_t j = 0; j < sz; j++) {
        SStreamTask *pTask = taosArrayGetP(pLevel, j);
L
Liu Jicong 已提交
898
        /*A(pTask->nodeId > 0);*/
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
        SVgObj *pVgObj = mndAcquireVgroup(pMnode, pTask->nodeId);
        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 已提交
933
  }
934 935 936 937
  // 2. reset tick
  atomic_store_64(&pStream->currentTick, 0);
  // 3. commit log: stream checkpoint info
  taosRUnLockLatch(&pStream->lock);
L
Liu Jicong 已提交
938

L
Liu Jicong 已提交
939
  if (mndTransPrepare(pMnode, pTrans) != 0) {
940
    mError("failed to prepare trans rebalance since %s", terrstr());
L
Liu Jicong 已提交
941
    mndTransDrop(pTrans);
942
    mndReleaseStream(pMnode, pStream);
L
Liu Jicong 已提交
943 944 945
    return -1;
  }

946
  mndReleaseStream(pMnode, pStream);
L
Liu Jicong 已提交
947
  mndTransDrop(pTrans);
L
Liu Jicong 已提交
948

949
  return 0;
L
Liu Jicong 已提交
950 951
}

5
54liuyao 已提交
952 953
#endif

954
static int32_t mndProcessDropStreamReq(SRpcMsg *pReq) {
L
Liu Jicong 已提交
955 956 957 958 959
  SMnode     *pMnode = pReq->info.node;
  SStreamObj *pStream = NULL;
  /*SDbObj     *pDb = NULL;*/
  /*SUserObj   *pUser = NULL;*/

960 961
  SMDropStreamReq dropReq = {0};
  if (tDeserializeSMDropStreamReq(pReq->pCont, pReq->contLen, &dropReq) < 0) {
L
Liu Jicong 已提交
962 963 964 965
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

966
  pStream = mndAcquireStream(pMnode, dropReq.name);
L
Liu Jicong 已提交
967 968

  if (pStream == NULL) {
969 970
    if (dropReq.igNotExists) {
      mInfo("stream:%s, not exist, ignore not exist is set", dropReq.name);
L
Liu Jicong 已提交
971 972 973 974 975 976 977 978 979
      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) {
980
    sdbRelease(pMnode->pSdb, pStream);
L
Liu Jicong 已提交
981 982 983
    return -1;
  }

984
  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB_INSIDE, pReq, "drop-stream");
L
Liu Jicong 已提交
985
  if (pTrans == NULL) {
986
    mError("stream:%s, failed to drop since %s", dropReq.name, terrstr());
L
Liu Jicong 已提交
987 988 989
    sdbRelease(pMnode->pSdb, pStream);
    return -1;
  }
990
  mInfo("trans:%d, used to drop stream:%s", pTrans->id, dropReq.name);
L
Liu Jicong 已提交
991

992 993 994 995 996 997 998
  mndTransSetDbName(pTrans, pStream->sourceDb, pStream->targetDb);
  if (mndTrancCheckConflict(pMnode, pTrans) != 0) {
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

999 1000 1001
  // drop all tasks
  if (mndDropStreamTasks(pMnode, pTrans, pStream) < 0) {
    mError("stream:%s, failed to drop task since %s", dropReq.name, terrstr());
L
Liu Jicong 已提交
1002
    sdbRelease(pMnode->pSdb, pStream);
1003
    mndTransDrop(pTrans);
L
Liu Jicong 已提交
1004 1005 1006
    return -1;
  }

1007 1008
  // drop stream
  if (mndPersistDropStreamLog(pMnode, pTrans, pStream) < 0) {
L
Liu Jicong 已提交
1009
    sdbRelease(pMnode->pSdb, pStream);
1010
    mndTransDrop(pTrans);
L
Liu Jicong 已提交
1011 1012 1013 1014
    return -1;
  }

  if (mndTransPrepare(pMnode, pTrans) != 0) {
1015
    mError("trans:%d, failed to prepare drop stream trans since %s", pTrans->id, terrstr());
L
Liu Jicong 已提交
1016 1017 1018 1019 1020 1021
    sdbRelease(pMnode->pSdb, pStream);
    mndTransDrop(pTrans);
    return -1;
  }

  sdbRelease(pMnode->pSdb, pStream);
1022
  mndTransDrop(pTrans);
L
Liu Jicong 已提交
1023 1024 1025 1026

  return TSDB_CODE_ACTION_IN_PROGRESS;
}

L
Liu Jicong 已提交
1027 1028
int32_t mndDropStreamByDb(SMnode *pMnode, STrans *pTrans, SDbObj *pDb) {
  SSdb *pSdb = pMnode->pSdb;
S
Shengliang Guan 已提交
1029
  void *pIter = NULL;
L
Liu Jicong 已提交
1030 1031

  while (1) {
S
Shengliang Guan 已提交
1032
    SStreamObj *pStream = NULL;
L
Liu Jicong 已提交
1033 1034 1035 1036 1037 1038
    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 已提交
1039 1040 1041
        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);
1042
        terrno = TSDB_CODE_MND_STREAM_MUST_BE_DELETED;
L
Liu Jicong 已提交
1043 1044
        return -1;
      } else {
1045 1046 1047 1048 1049 1050 1051 1052
#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 已提交
1053 1054
        if (mndPersistDropStreamLog(pMnode, pTrans, pStream) < 0) {
          sdbRelease(pSdb, pStream);
S
Shengliang Guan 已提交
1055
          sdbCancelFetch(pSdb, pIter);
L
Liu Jicong 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
          return -1;
        }
      }
    }

    sdbRelease(pSdb, pStream);
  }

  return 0;
}

L
Liu Jicong 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
static int32_t mndGetNumOfStreams(SMnode *pMnode, char *dbName, int32_t *pNumOfStreams) {
  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 已提交
1082
    if (pStream->sourceDbUid == pDb->uid) {
L
Liu Jicong 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
      numOfStreams++;
    }

    sdbRelease(pSdb, pStream);
  }

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

S
Shengliang Guan 已提交
1094 1095
static int32_t mndRetrieveStream(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
  SMnode     *pMnode = pReq->info.node;
L
Liu Jicong 已提交
1096 1097 1098 1099 1100
  SSdb       *pSdb = pMnode->pSdb;
  int32_t     numOfRows = 0;
  SStreamObj *pStream = NULL;

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

L
Liu Jicong 已提交
1104 1105 1106
    SColumnInfoData *pColInfo;
    SName            n;
    int32_t          cols = 0;
L
Liu Jicong 已提交
1107

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

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

L
Liu Jicong 已提交
1116
    char sql[TSDB_SHOW_SQL_LEN + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1117
    STR_WITH_MAXSIZE_TO_VARSTR(sql, pStream->sql, sizeof(sql));
L
Liu Jicong 已提交
1118
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1119
    colDataSetVal(pColInfo, numOfRows, (const char *)sql, false);
L
Liu Jicong 已提交
1120

L
Liu Jicong 已提交
1121
    char status[20 + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1122 1123 1124
    char status2[20] = {0};
    mndShowStreamStatus(status2, pStream);
    STR_WITH_MAXSIZE_TO_VARSTR(status, status2, sizeof(status));
L
Liu Jicong 已提交
1125
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1126
    colDataSetVal(pColInfo, numOfRows, (const char *)&status, false);
L
Liu Jicong 已提交
1127

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

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

1138 1139
    if (pStream->targetSTbName[0] == 0) {
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1140
      colDataSetVal(pColInfo, numOfRows, NULL, true);
1141 1142
    } else {
      char targetSTB[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1143
      STR_WITH_MAXSIZE_TO_VARSTR(targetSTB, mndGetStbStr(pStream->targetSTbName), sizeof(targetSTB));
1144
      pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1145
      colDataSetVal(pColInfo, numOfRows, (const char *)&targetSTB, false);
1146
    }
L
Liu Jicong 已提交
1147 1148

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

L
Liu Jicong 已提交
1151
    char trigger[20 + VARSTR_HEADER_SIZE] = {0};
S
Shengliang Guan 已提交
1152 1153 1154
    char trigger2[20] = {0};
    mndShowStreamTrigger(trigger2, pStream);
    STR_WITH_MAXSIZE_TO_VARSTR(trigger, trigger2, sizeof(trigger));
L
Liu Jicong 已提交
1155
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1156
    colDataSetVal(pColInfo, numOfRows, (const char *)&trigger, false);
L
Liu Jicong 已提交
1157 1158 1159

    numOfRows++;
    sdbRelease(pSdb, pStream);
L
Liu Jicong 已提交
1160
  }
L
Liu Jicong 已提交
1161 1162 1163

  pShow->numOfRows += numOfRows;
  return numOfRows;
L
Liu Jicong 已提交
1164 1165 1166 1167 1168 1169
}

static void mndCancelGetNextStream(SMnode *pMnode, void *pIter) {
  SSdb *pSdb = pMnode->pSdb;
  sdbCancelFetch(pSdb, pIter);
}
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207

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);
    if (pShow->pIter == NULL) break;

    // lock
    taosRLockLatch(&pStream->lock);
    // count task num
    int32_t sz = taosArrayGetSize(pStream->tasks);
    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);
    }
    // add row for each task
    for (int32_t i = 0; i < sz; i++) {
      SArray *pLevel = taosArrayGetP(pStream->tasks, i);
      int32_t levelCnt = taosArrayGetSize(pLevel);
      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));
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1208
        colDataSetVal(pColInfo, numOfRows, (const char *)streamName, false);
1209 1210 1211

        // task id
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1212
        colDataSetVal(pColInfo, numOfRows, (const char *)&pTask->id.taskId, false);
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

        // node type
        char nodeType[20 + VARSTR_HEADER_SIZE] = {0};
        varDataSetLen(nodeType, 5);
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
        if (pTask->nodeId > 0) {
          memcpy(varDataVal(nodeType), "vnode", 5);
        } else {
          memcpy(varDataVal(nodeType), "snode", 5);
        }
1223
        colDataSetVal(pColInfo, numOfRows, nodeType, false);
1224 1225 1226

        // node id
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
5
54liuyao 已提交
1227
        int64_t nodeId = TMAX(pTask->nodeId, 0);
1228
        colDataSetVal(pColInfo, numOfRows, (const char *)&nodeId, false);
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

        // level
        char level[20 + VARSTR_HEADER_SIZE] = {0};
        if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
          memcpy(varDataVal(level), "source", 6);
          varDataSetLen(level, 6);
        } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
          memcpy(varDataVal(level), "agg", 3);
          varDataSetLen(level, 3);
        } else if (pTask->taskLevel == TASK_LEVEL__SINK) {
          memcpy(varDataVal(level), "sink", 4);
          varDataSetLen(level, 4);
        } else if (pTask->taskLevel == TASK_LEVEL__SINK) {
        }
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1244
        colDataSetVal(pColInfo, numOfRows, (const char *)&level, false);
1245 1246 1247 1248 1249 1250 1251

        // status
        char status[20 + VARSTR_HEADER_SIZE] = {0};
        char status2[20] = {0};
        strcpy(status, "normal");
        STR_WITH_MAXSIZE_TO_VARSTR(status, status2, sizeof(status));
        pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
1252
        colDataSetVal(pColInfo, numOfRows, (const char *)&status, false);
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

        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);
}