mndSma.c 39.0 KB
Newer Older
S
sma  
Shengliang Guan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * 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/>.
 */

#define _DEFAULT_SOURCE
#include "mndSma.h"
#include "mndDb.h"
#include "mndDnode.h"
#include "mndInfoSchema.h"
#include "mndMnode.h"
L
Liu Jicong 已提交
22
#include "mndPrivilege.h"
L
Liu Jicong 已提交
23
#include "mndScheduler.h"
S
sma  
Shengliang Guan 已提交
24
#include "mndShow.h"
S
Shengliang Guan 已提交
25
#include "mndStb.h"
S
sma  
Shengliang Guan 已提交
26
#include "mndStream.h"
S
sma  
Shengliang Guan 已提交
27 28 29
#include "mndTrans.h"
#include "mndUser.h"
#include "mndVgroup.h"
C
Cary Xu 已提交
30
#include "parser.h"
S
sma  
Shengliang Guan 已提交
31 32 33 34 35 36 37 38 39 40
#include "tname.h"

#define TSDB_SMA_VER_NUMBER   1
#define TSDB_SMA_RESERVE_SIZE 64

static SSdbRaw *mndSmaActionEncode(SSmaObj *pSma);
static SSdbRow *mndSmaActionDecode(SSdbRaw *pRaw);
static int32_t  mndSmaActionInsert(SSdb *pSdb, SSmaObj *pSma);
static int32_t  mndSmaActionDelete(SSdb *pSdb, SSmaObj *pSpSmatb);
static int32_t  mndSmaActionUpdate(SSdb *pSdb, SSmaObj *pOld, SSmaObj *pNew);
41 42
static int32_t  mndProcessCreateSmaReq(SRpcMsg *pReq);
static int32_t  mndProcessDropSmaReq(SRpcMsg *pReq);
S
Shengliang Guan 已提交
43
static int32_t  mndProcessGetSmaReq(SRpcMsg *pReq);
44
static int32_t  mndProcessGetTbSmaReq(SRpcMsg *pReq);
S
Shengliang Guan 已提交
45
static int32_t  mndRetrieveSma(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows);
S
sma  
Shengliang Guan 已提交
46
static void     mndCancelGetNextSma(SMnode *pMnode, void *pIter);
C
Cary Xu 已提交
47
static void     mndDestroySmaObj(SSmaObj *pSmaObj);
S
sma  
Shengliang Guan 已提交
48 49

int32_t mndInitSma(SMnode *pMnode) {
50 51 52 53 54 55 56 57 58
  SSdbTable table = {
      .sdbType = SDB_SMA,
      .keyType = SDB_KEY_BINARY,
      .encodeFp = (SdbEncodeFp)mndSmaActionEncode,
      .decodeFp = (SdbDecodeFp)mndSmaActionDecode,
      .insertFp = (SdbInsertFp)mndSmaActionInsert,
      .updateFp = (SdbUpdateFp)mndSmaActionUpdate,
      .deleteFp = (SdbDeleteFp)mndSmaActionDelete,
  };
S
sma  
Shengliang Guan 已提交
59

60 61
  mndSetMsgHandle(pMnode, TDMT_MND_CREATE_SMA, mndProcessCreateSmaReq);
  mndSetMsgHandle(pMnode, TDMT_MND_DROP_SMA, mndProcessDropSmaReq);
62 63
  mndSetMsgHandle(pMnode, TDMT_VND_CREATE_SMA_RSP, mndTransProcessRsp);
  mndSetMsgHandle(pMnode, TDMT_VND_DROP_SMA_RSP, mndTransProcessRsp);
S
Shengliang Guan 已提交
64
  mndSetMsgHandle(pMnode, TDMT_MND_GET_INDEX, mndProcessGetSmaReq);
D
dapan1121 已提交
65
  mndSetMsgHandle(pMnode, TDMT_MND_GET_TABLE_INDEX, mndProcessGetTbSmaReq);
S
sma  
Shengliang Guan 已提交
66 67 68 69 70 71 72 73 74 75 76

  mndAddShowRetrieveHandle(pMnode, TSDB_MGMT_TABLE_INDEX, mndRetrieveSma);
  mndAddShowFreeIterHandle(pMnode, TSDB_MGMT_TABLE_INDEX, mndCancelGetNextSma);
  return sdbSetTable(pMnode->pSdb, table);
}

void mndCleanupSma(SMnode *pMnode) {}

static SSdbRaw *mndSmaActionEncode(SSmaObj *pSma) {
  terrno = TSDB_CODE_OUT_OF_MEMORY;

L
Liu Jicong 已提交
77 78
  int32_t size =
      sizeof(SSmaObj) + pSma->exprLen + pSma->tagsFilterLen + pSma->sqlLen + pSma->astLen + TSDB_SMA_RESERVE_SIZE;
S
sma  
Shengliang Guan 已提交
79 80 81 82 83 84 85
  SSdbRaw *pRaw = sdbAllocRaw(SDB_SMA, TSDB_SMA_VER_NUMBER, size);
  if (pRaw == NULL) goto _OVER;

  int32_t dataPos = 0;
  SDB_SET_BINARY(pRaw, dataPos, pSma->name, TSDB_TABLE_FNAME_LEN, _OVER)
  SDB_SET_BINARY(pRaw, dataPos, pSma->stb, TSDB_TABLE_FNAME_LEN, _OVER)
  SDB_SET_BINARY(pRaw, dataPos, pSma->db, TSDB_DB_FNAME_LEN, _OVER)
C
Cary Xu 已提交
86
  SDB_SET_BINARY(pRaw, dataPos, pSma->dstTbName, TSDB_DB_FNAME_LEN, _OVER)
S
sma  
Shengliang Guan 已提交
87 88 89 90
  SDB_SET_INT64(pRaw, dataPos, pSma->createdTime, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pSma->uid, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pSma->stbUid, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pSma->dbUid, _OVER)
C
Cary Xu 已提交
91
  SDB_SET_INT64(pRaw, dataPos, pSma->dstTbUid, _OVER)
S
sma  
Shengliang Guan 已提交
92 93 94
  SDB_SET_INT8(pRaw, dataPos, pSma->intervalUnit, _OVER)
  SDB_SET_INT8(pRaw, dataPos, pSma->slidingUnit, _OVER)
  SDB_SET_INT8(pRaw, dataPos, pSma->timezone, _OVER)
S
sma  
Shengliang Guan 已提交
95
  SDB_SET_INT32(pRaw, dataPos, pSma->dstVgId, _OVER)
S
sma  
Shengliang Guan 已提交
96 97 98 99 100
  SDB_SET_INT64(pRaw, dataPos, pSma->interval, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pSma->offset, _OVER)
  SDB_SET_INT64(pRaw, dataPos, pSma->sliding, _OVER)
  SDB_SET_INT32(pRaw, dataPos, pSma->exprLen, _OVER)
  SDB_SET_INT32(pRaw, dataPos, pSma->tagsFilterLen, _OVER)
S
sma  
Shengliang Guan 已提交
101 102
  SDB_SET_INT32(pRaw, dataPos, pSma->sqlLen, _OVER)
  SDB_SET_INT32(pRaw, dataPos, pSma->astLen, _OVER)
103

S
sma  
Shengliang Guan 已提交
104 105 106 107 108 109 110 111 112 113 114 115
  if (pSma->exprLen > 0) {
    SDB_SET_BINARY(pRaw, dataPos, pSma->expr, pSma->exprLen, _OVER)
  }
  if (pSma->tagsFilterLen > 0) {
    SDB_SET_BINARY(pRaw, dataPos, pSma->tagsFilter, pSma->tagsFilterLen, _OVER)
  }
  if (pSma->sqlLen > 0) {
    SDB_SET_BINARY(pRaw, dataPos, pSma->sql, pSma->sqlLen, _OVER)
  }
  if (pSma->astLen > 0) {
    SDB_SET_BINARY(pRaw, dataPos, pSma->ast, pSma->astLen, _OVER)
  }
S
sma  
Shengliang Guan 已提交
116 117 118

  SDB_SET_RESERVE(pRaw, dataPos, TSDB_SMA_RESERVE_SIZE, _OVER)
  SDB_SET_DATALEN(pRaw, dataPos, _OVER)
119

S
sma  
Shengliang Guan 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  terrno = 0;

_OVER:
  if (terrno != 0) {
    mError("sma:%s, failed to encode to raw:%p since %s", pSma->name, pRaw, terrstr());
    sdbFreeRaw(pRaw);
    return NULL;
  }

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

static SSdbRow *mndSmaActionDecode(SSdbRaw *pRaw) {
  terrno = TSDB_CODE_OUT_OF_MEMORY;
135 136
  SSdbRow *pRow = NULL;
  SSmaObj *pSma = NULL;
S
sma  
Shengliang Guan 已提交
137 138 139 140 141 142 143 144 145

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

  if (sver != TSDB_SMA_VER_NUMBER) {
    terrno = TSDB_CODE_SDB_INVALID_DATA_VER;
    goto _OVER;
  }

146
  pRow = sdbAllocRow(sizeof(SSmaObj));
S
sma  
Shengliang Guan 已提交
147 148
  if (pRow == NULL) goto _OVER;

149
  pSma = sdbGetRowObj(pRow);
S
sma  
Shengliang Guan 已提交
150 151 152 153 154 155 156
  if (pSma == NULL) goto _OVER;

  int32_t dataPos = 0;

  SDB_GET_BINARY(pRaw, dataPos, pSma->name, TSDB_TABLE_FNAME_LEN, _OVER)
  SDB_GET_BINARY(pRaw, dataPos, pSma->stb, TSDB_TABLE_FNAME_LEN, _OVER)
  SDB_GET_BINARY(pRaw, dataPos, pSma->db, TSDB_DB_FNAME_LEN, _OVER)
C
Cary Xu 已提交
157
  SDB_GET_BINARY(pRaw, dataPos, pSma->dstTbName, TSDB_DB_FNAME_LEN, _OVER)
S
sma  
Shengliang Guan 已提交
158 159 160 161
  SDB_GET_INT64(pRaw, dataPos, &pSma->createdTime, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pSma->uid, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pSma->stbUid, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pSma->dbUid, _OVER)
C
Cary Xu 已提交
162
  SDB_GET_INT64(pRaw, dataPos, &pSma->dstTbUid, _OVER)
S
sma  
Shengliang Guan 已提交
163 164 165
  SDB_GET_INT8(pRaw, dataPos, &pSma->intervalUnit, _OVER)
  SDB_GET_INT8(pRaw, dataPos, &pSma->slidingUnit, _OVER)
  SDB_GET_INT8(pRaw, dataPos, &pSma->timezone, _OVER)
S
sma  
Shengliang Guan 已提交
166
  SDB_GET_INT32(pRaw, dataPos, &pSma->dstVgId, _OVER)
S
sma  
Shengliang Guan 已提交
167 168 169 170 171
  SDB_GET_INT64(pRaw, dataPos, &pSma->interval, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pSma->offset, _OVER)
  SDB_GET_INT64(pRaw, dataPos, &pSma->sliding, _OVER)
  SDB_GET_INT32(pRaw, dataPos, &pSma->exprLen, _OVER)
  SDB_GET_INT32(pRaw, dataPos, &pSma->tagsFilterLen, _OVER)
S
sma  
Shengliang Guan 已提交
172 173
  SDB_GET_INT32(pRaw, dataPos, &pSma->sqlLen, _OVER)
  SDB_GET_INT32(pRaw, dataPos, &pSma->astLen, _OVER)
S
sma  
Shengliang Guan 已提交
174

S
sma  
Shengliang Guan 已提交
175
  if (pSma->exprLen > 0) {
wafwerar's avatar
wafwerar 已提交
176
    pSma->expr = taosMemoryCalloc(pSma->exprLen, 1);
S
sma  
Shengliang Guan 已提交
177 178
    if (pSma->expr == NULL) goto _OVER;
    SDB_GET_BINARY(pRaw, dataPos, pSma->expr, pSma->exprLen, _OVER)
S
sma  
Shengliang Guan 已提交
179 180
  }

S
sma  
Shengliang Guan 已提交
181
  if (pSma->tagsFilterLen > 0) {
wafwerar's avatar
wafwerar 已提交
182
    pSma->tagsFilter = taosMemoryCalloc(pSma->tagsFilterLen, 1);
S
sma  
Shengliang Guan 已提交
183 184 185
    if (pSma->tagsFilter == NULL) goto _OVER;
    SDB_GET_BINARY(pRaw, dataPos, pSma->tagsFilter, pSma->tagsFilterLen, _OVER)
  }
S
sma  
Shengliang Guan 已提交
186

S
sma  
Shengliang Guan 已提交
187
  if (pSma->sqlLen > 0) {
wafwerar's avatar
wafwerar 已提交
188
    pSma->sql = taosMemoryCalloc(pSma->sqlLen, 1);
S
sma  
Shengliang Guan 已提交
189 190 191 192 193
    if (pSma->sql == NULL) goto _OVER;
    SDB_GET_BINARY(pRaw, dataPos, pSma->sql, pSma->sqlLen, _OVER)
  }

  if (pSma->astLen > 0) {
wafwerar's avatar
wafwerar 已提交
194
    pSma->ast = taosMemoryCalloc(pSma->astLen, 1);
S
sma  
Shengliang Guan 已提交
195 196 197 198 199
    if (pSma->ast == NULL) goto _OVER;
    SDB_GET_BINARY(pRaw, dataPos, pSma->ast, pSma->astLen, _OVER)
  }

  SDB_GET_RESERVE(pRaw, dataPos, TSDB_SMA_RESERVE_SIZE, _OVER)
200

S
sma  
Shengliang Guan 已提交
201 202 203 204
  terrno = 0;

_OVER:
  if (terrno != 0) {
205
    mError("sma:%s, failed to decode from raw:%p since %s", pSma == NULL ? "null" : pSma->name, pRaw, terrstr());
wafwerar's avatar
wafwerar 已提交
206 207
    taosMemoryFreeClear(pSma->expr);
    taosMemoryFreeClear(pSma->tagsFilter);
208 209
    taosMemoryFreeClear(pSma->sql);
    taosMemoryFreeClear(pSma->ast);
wafwerar's avatar
wafwerar 已提交
210
    taosMemoryFreeClear(pRow);
S
sma  
Shengliang Guan 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224
    return NULL;
  }

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

static int32_t mndSmaActionInsert(SSdb *pSdb, SSmaObj *pSma) {
  mTrace("sma:%s, perform insert action, row:%p", pSma->name, pSma);
  return 0;
}

static int32_t mndSmaActionDelete(SSdb *pSdb, SSmaObj *pSma) {
  mTrace("sma:%s, perform delete action, row:%p", pSma->name, pSma);
wafwerar's avatar
wafwerar 已提交
225 226
  taosMemoryFreeClear(pSma->tagsFilter);
  taosMemoryFreeClear(pSma->expr);
227 228
  taosMemoryFreeClear(pSma->sql);
  taosMemoryFreeClear(pSma->ast);
S
sma  
Shengliang Guan 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  return 0;
}

static int32_t mndSmaActionUpdate(SSdb *pSdb, SSmaObj *pOld, SSmaObj *pNew) {
  mTrace("sma:%s, perform update action, old row:%p new row:%p", pOld->name, pOld, pNew);
  return 0;
}

SSmaObj *mndAcquireSma(SMnode *pMnode, char *smaName) {
  SSdb    *pSdb = pMnode->pSdb;
  SSmaObj *pSma = sdbAcquire(pSdb, SDB_SMA, smaName);
  if (pSma == NULL && terrno == TSDB_CODE_SDB_OBJ_NOT_THERE) {
    terrno = TSDB_CODE_MND_SMA_NOT_EXIST;
  }
  return pSma;
}

void mndReleaseSma(SMnode *pMnode, SSmaObj *pSma) {
  SSdb *pSdb = pMnode->pSdb;
  sdbRelease(pSdb, pSma);
}

SDbObj *mndAcquireDbBySma(SMnode *pMnode, const char *smaName) {
  SName name = {0};
  tNameFromString(&name, smaName, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);

  char db[TSDB_TABLE_FNAME_LEN] = {0};
  tNameGetFullDbName(&name, db);

  return mndAcquireDb(pMnode, db);
}

static void *mndBuildVCreateSmaReq(SMnode *pMnode, SVgObj *pVgroup, SSmaObj *pSma, int32_t *pContLen) {
262 263 264
  SEncoder encoder = {0};
  int32_t  contLen = 0;
  SName    name = {0};
S
sma  
Shengliang Guan 已提交
265 266 267
  tNameFromString(&name, pSma->name, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);

  SVCreateTSmaReq req = {0};
268 269 270 271 272 273 274 275 276
  req.version = 0;
  req.intervalUnit = pSma->intervalUnit;
  req.slidingUnit = pSma->slidingUnit;
  req.timezoneInt = pSma->timezone;
  tstrncpy(req.indexName, (char *)tNameGetTableName(&name), TSDB_INDEX_NAME_LEN);
  req.exprLen = pSma->exprLen;
  req.tagsFilterLen = pSma->tagsFilterLen;
  req.indexUid = pSma->uid;
  req.tableUid = pSma->stbUid;
C
Cary Xu 已提交
277 278
  req.dstVgId = pSma->dstVgId;
  req.dstTbUid = pSma->dstTbUid;
279 280 281 282 283
  req.interval = pSma->interval;
  req.offset = pSma->offset;
  req.sliding = pSma->sliding;
  req.expr = pSma->expr;
  req.tagsFilter = pSma->tagsFilter;
C
Cary Xu 已提交
284 285 286 287
  req.schemaRow = pSma->schemaRow;
  req.schemaTag = pSma->schemaTag;
  req.dstTbName = pSma->dstTbName;

288 289 290 291 292 293 294 295
  // get length
  int32_t ret = 0;
  tEncodeSize(tEncodeSVCreateTSmaReq, &req, contLen, ret);
  if (ret < 0) {
    return NULL;
  }
  contLen += sizeof(SMsgHead);

wafwerar's avatar
wafwerar 已提交
296
  SMsgHead *pHead = taosMemoryMalloc(contLen);
S
sma  
Shengliang Guan 已提交
297 298 299 300 301 302 303 304 305
  if (pHead == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pHead->contLen = htonl(contLen);
  pHead->vgId = htonl(pVgroup->vgId);

  void *pBuf = POINTER_SHIFT(pHead, sizeof(SMsgHead));
306 307 308 309 310 311 312 313
  tEncoderInit(&encoder, pBuf, contLen - sizeof(SMsgHead));
  if (tEncodeSVCreateTSmaReq(&encoder, &req) < 0) {
    taosMemoryFreeClear(pHead);
    tEncoderClear(&encoder);
    return NULL;
  }

  tEncoderClear(&encoder);
S
sma  
Shengliang Guan 已提交
314 315 316 317 318 319

  *pContLen = contLen;
  return pHead;
}

static void *mndBuildVDropSmaReq(SMnode *pMnode, SVgObj *pVgroup, SSmaObj *pSma, int32_t *pContLen) {
L
Liu Jicong 已提交
320 321 322
  SEncoder encoder = {0};
  int32_t  contLen;
  SName    name = {0};
S
sma  
Shengliang Guan 已提交
323 324 325 326 327 328
  tNameFromString(&name, pSma->name, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);

  SVDropTSmaReq req = {0};
  req.indexUid = pSma->uid;
  tstrncpy(req.indexName, (char *)tNameGetTableName(&name), TSDB_INDEX_NAME_LEN);

329 330 331 332 333 334 335 336 337
  // get length
  int32_t ret = 0;
  tEncodeSize(tEncodeSVDropTSmaReq, &req, contLen, ret);
  if (ret < 0) {
    return NULL;
  }

  contLen += sizeof(SMsgHead);

wafwerar's avatar
wafwerar 已提交
338
  SMsgHead *pHead = taosMemoryMalloc(contLen);
S
sma  
Shengliang Guan 已提交
339 340 341 342 343 344 345 346 347
  if (pHead == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pHead->contLen = htonl(contLen);
  pHead->vgId = htonl(pVgroup->vgId);

  void *pBuf = POINTER_SHIFT(pHead, sizeof(SMsgHead));
348 349 350 351 352 353 354 355
  tEncoderInit(&encoder, pBuf, contLen - sizeof(SMsgHead));

  if (tEncodeSVDropTSmaReq(&encoder, &req) < 0) {
    taosMemoryFreeClear(pHead);
    tEncoderClear(&encoder);
    return NULL;
  }
  tEncoderClear(&encoder);
S
sma  
Shengliang Guan 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

  *pContLen = contLen;
  return pHead;
}

static int32_t mndSetCreateSmaRedoLogs(SMnode *pMnode, STrans *pTrans, SSmaObj *pSma) {
  SSdbRaw *pRedoRaw = mndSmaActionEncode(pSma);
  if (pRedoRaw == NULL) return -1;
  if (mndTransAppendRedolog(pTrans, pRedoRaw) != 0) return -1;
  if (sdbSetRawStatus(pRedoRaw, SDB_STATUS_CREATING) != 0) return -1;

  return 0;
}

static int32_t mndSetCreateSmaCommitLogs(SMnode *pMnode, STrans *pTrans, SSmaObj *pSma) {
  SSdbRaw *pCommitRaw = mndSmaActionEncode(pSma);
  if (pCommitRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) return -1;
  if (sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY) != 0) return -1;

  return 0;
}

S
Shengliang Guan 已提交
379 380 381 382
static int32_t mndSetCreateSmaVgroupRedoLogs(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup) {
  SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendRedolog(pTrans, pVgRaw) != 0) return -1;
S
Shengliang Guan 已提交
383
  if (sdbSetRawStatus(pVgRaw, SDB_STATUS_CREATING) != 0) return -1;
S
Shengliang Guan 已提交
384 385 386 387 388 389 390 391 392 393 394
  return 0;
}

static int32_t mndSetCreateSmaVgroupCommitLogs(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup) {
  SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pVgRaw) != 0) return -1;
  if (sdbSetRawStatus(pVgRaw, SDB_STATUS_READY) != 0) return -1;
  return 0;
}

395 396 397 398 399
static int32_t mndSetUpdateSmaStbCommitLogs(SMnode *pMnode, STrans *pTrans, SStbObj *pStb) {
  SStbObj stbObj = {0};
  taosRLockLatch(&pStb->lock);
  memcpy(&stbObj, pStb, sizeof(SStbObj));
  taosRUnLockLatch(&pStb->lock);
C
Cary Xu 已提交
400
  stbObj.numOfColumns = 0;
401
  stbObj.pColumns = NULL;
C
Cary Xu 已提交
402
  stbObj.numOfTags = 0;
403
  stbObj.pTags = NULL;
S
Shengliang Guan 已提交
404 405
  stbObj.numOfFuncs = 0;
  stbObj.pFuncs = NULL;
406 407 408 409 410 411 412 413 414 415 416 417
  stbObj.updateTime = taosGetTimestampMs();
  stbObj.lock = 0;
  stbObj.smaVer++;

  SSdbRaw *pCommitRaw = mndStbActionEncode(&stbObj);
  if (pCommitRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) return -1;
  if (sdbSetRawStatus(pCommitRaw, SDB_STATUS_READY) != 0) return -1;

  return 0;
}

C
Cary Xu 已提交
418 419
static int32_t mndSetCreateSmaVgroupRedoActions(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup,
                                                SSmaObj *pSma) {
S
Shengliang Guan 已提交
420 421 422 423 424 425 426 427 428
  SVnodeGid *pVgid = pVgroup->vnodeGid + 0;
  SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
  if (pDnode == NULL) return -1;

  STransAction action = {0};
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  // todo add sma info here
C
Cary Xu 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  SNode *pAst = NULL;
  if (nodesStringToNode(pSma->ast, &pAst) < 0) {
    return -1;
  }
  if (qExtractResultSchema(pAst, &pSma->schemaRow.nCols, &pSma->schemaRow.pSchema) != 0) {
    nodesDestroyNode(pAst);
    return -1;
  }
  nodesDestroyNode(pAst);
  pSma->schemaRow.version = 1;

  // TODO: the schemaTag generated by qExtractResultXXX later.
  pSma->schemaTag.nCols = 1;
  pSma->schemaTag.version = 1;
  pSma->schemaTag.pSchema = taosMemoryCalloc(1, sizeof(SSchema));
  if (!pSma->schemaTag.pSchema) {
    return -1;
  }
  pSma->schemaTag.pSchema[0].type = TSDB_DATA_TYPE_BIGINT;
  pSma->schemaTag.pSchema[0].bytes = TYPE_BYTES[TSDB_DATA_TYPE_BIGINT];
  pSma->schemaTag.pSchema[0].colId = pSma->schemaRow.nCols + PRIMARYKEY_TIMESTAMP_COL_ID;
  pSma->schemaTag.pSchema[0].flags = 0;
  snprintf(pSma->schemaTag.pSchema[0].name, TSDB_COL_NAME_LEN, "groupId");

C
Cary Xu 已提交
453 454 455 456
  int32_t smaContLen = 0;
  void   *pSmaReq = mndBuildVCreateSmaReq(pMnode, pVgroup, pSma, &smaContLen);
  if (pSmaReq == NULL) return -1;
  pVgroup->pTsma = pSmaReq;
S
Shengliang Guan 已提交
457 458

  int32_t contLen = 0;
S
Shengliang Guan 已提交
459
  void   *pReq = mndBuildCreateVnodeReq(pMnode, pDnode, pDb, pVgroup, &contLen);
C
Cary Xu 已提交
460
  taosMemoryFreeClear(pSmaReq);
S
Shengliang Guan 已提交
461 462 463 464 465
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_DND_CREATE_VNODE;
466
  action.acceptableCode = TSDB_CODE_VND_ALREADY_EXIST;
S
Shengliang Guan 已提交
467 468 469 470 471 472 473 474 475

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

C
Cary Xu 已提交
476 477 478 479 480 481 482
static void mndDestroySmaObj(SSmaObj *pSmaObj) {
  if (pSmaObj) {
    taosMemoryFreeClear(pSmaObj->schemaRow.pSchema);
    taosMemoryFreeClear(pSmaObj->schemaTag.pSchema);
  }
}

483 484
static int32_t mndCreateSma(SMnode *pMnode, SRpcMsg *pReq, SMCreateSmaReq *pCreate, SDbObj *pDb, SStbObj *pStb,
                            const char *streamName) {
S
sma  
Shengliang Guan 已提交
485 486 487
  SSmaObj smaObj = {0};
  memcpy(smaObj.name, pCreate->name, TSDB_TABLE_FNAME_LEN);
  memcpy(smaObj.stb, pStb->name, TSDB_TABLE_FNAME_LEN);
S
sma  
Shengliang Guan 已提交
488
  memcpy(smaObj.db, pDb->name, TSDB_DB_FNAME_LEN);
S
sma  
Shengliang Guan 已提交
489 490
  smaObj.createdTime = taosGetTimestampMs();
  smaObj.uid = mndGenerateUid(pCreate->name, TSDB_TABLE_FNAME_LEN);
S
Shengliang Guan 已提交
491

C
Cary Xu 已提交
492
  char resultTbName[TSDB_TABLE_FNAME_LEN + 16] = {0};
L
Liu Jicong 已提交
493
  snprintf(resultTbName, TSDB_TABLE_FNAME_LEN + 16, "%s_td_tsma_rst_tb", pCreate->name);
C
Cary Xu 已提交
494 495
  memcpy(smaObj.dstTbName, resultTbName, TSDB_TABLE_FNAME_LEN);
  smaObj.dstTbUid = mndGenerateUid(smaObj.dstTbName, TSDB_TABLE_FNAME_LEN);
S
sma  
Shengliang Guan 已提交
496
  smaObj.stbUid = pStb->uid;
S
sma  
Shengliang Guan 已提交
497
  smaObj.dbUid = pStb->dbUid;
S
sma  
Shengliang Guan 已提交
498 499
  smaObj.intervalUnit = pCreate->intervalUnit;
  smaObj.slidingUnit = pCreate->slidingUnit;
500
#if 0
S
sma  
Shengliang Guan 已提交
501
  smaObj.timezone = pCreate->timezone;
502
#endif
503
  smaObj.timezone = tsTimezone;  // use timezone of server
S
sma  
Shengliang Guan 已提交
504 505 506 507 508
  smaObj.interval = pCreate->interval;
  smaObj.offset = pCreate->offset;
  smaObj.sliding = pCreate->sliding;
  smaObj.exprLen = pCreate->exprLen;
  smaObj.tagsFilterLen = pCreate->tagsFilterLen;
S
sma  
Shengliang Guan 已提交
509 510 511
  smaObj.sqlLen = pCreate->sqlLen;
  smaObj.astLen = pCreate->astLen;
  if (smaObj.exprLen > 0) {
C
Cary Xu 已提交
512
    smaObj.expr = pCreate->expr;
S
sma  
Shengliang Guan 已提交
513 514
  }
  if (smaObj.tagsFilterLen > 0) {
C
Cary Xu 已提交
515
    smaObj.tagsFilter = pCreate->tagsFilter;
S
sma  
Shengliang Guan 已提交
516 517
  }
  if (smaObj.sqlLen > 0) {
C
Cary Xu 已提交
518
    smaObj.sql = pCreate->sql;
S
sma  
Shengliang Guan 已提交
519 520
  }
  if (smaObj.astLen > 0) {
C
Cary Xu 已提交
521
    smaObj.ast = pCreate->ast;
S
sma  
Shengliang Guan 已提交
522
  }
S
sma  
Shengliang Guan 已提交
523

S
sma  
Shengliang Guan 已提交
524
  SStreamObj streamObj = {0};
525
  tstrncpy(streamObj.name, streamName, TSDB_STREAM_FNAME_LEN);
L
Liu Jicong 已提交
526
  tstrncpy(streamObj.sourceDb, pDb->name, TSDB_DB_FNAME_LEN);
D
dapan1121 已提交
527
  tstrncpy(streamObj.targetDb, streamObj.sourceDb, TSDB_DB_FNAME_LEN);
S
sma  
Shengliang Guan 已提交
528 529
  streamObj.createTime = taosGetTimestampMs();
  streamObj.updateTime = streamObj.createTime;
530
  streamObj.uid = mndGenerateUid(streamName, strlen(streamName));
L
Liu Jicong 已提交
531
  streamObj.sourceDbUid = pDb->uid;
S
Shengliang Guan 已提交
532
  streamObj.targetDbUid = pDb->uid;
S
sma  
Shengliang Guan 已提交
533
  streamObj.version = 1;
L
Liu Jicong 已提交
534
  streamObj.sql = strdup(pCreate->sql);
L
Liu Jicong 已提交
535
  streamObj.smaId = smaObj.uid;
C
Cary Xu 已提交
536
  streamObj.watermark = pCreate->watermark;
537
  streamObj.deleteMark = pCreate->deleteMark;
538
  streamObj.fillHistory = STREAM_FILL_HISTORY_ON;
C
Cary Xu 已提交
539 540
  streamObj.trigger = STREAM_TRIGGER_WINDOW_CLOSE;
  streamObj.triggerParam = pCreate->maxDelay;
L
Liu Jicong 已提交
541
  streamObj.ast = strdup(smaObj.ast);
L
Liu Jicong 已提交
542

C
Cary Xu 已提交
543 544 545 546 547 548 549 550 551
  // check the maxDelay
  if (streamObj.triggerParam < TSDB_MIN_ROLLUP_MAX_DELAY) {
    int64_t msInterval = convertTimeFromPrecisionToUnit(pCreate->interval, pDb->cfg.precision, TIME_UNIT_MILLISECOND);
    streamObj.triggerParam = msInterval > TSDB_MIN_ROLLUP_MAX_DELAY ? msInterval : TSDB_MIN_ROLLUP_MAX_DELAY;
  }
  if (streamObj.triggerParam > TSDB_MAX_ROLLUP_MAX_DELAY) {
    streamObj.triggerParam = TSDB_MAX_ROLLUP_MAX_DELAY;
  }

L
Liu Jicong 已提交
552 553 554 555 556
  if (mndAllocSmaVgroup(pMnode, pDb, &streamObj.fixedSinkVg) != 0) {
    mError("sma:%s, failed to create since %s", smaObj.name, terrstr());
    return -1;
  }
  smaObj.dstVgId = streamObj.fixedSinkVg.vgId;
S
Shengliang Guan 已提交
557
  streamObj.fixedSinkVgId = smaObj.dstVgId;
S
sma  
Shengliang Guan 已提交
558

L
Liu Jicong 已提交
559 560
  SNode *pAst = NULL;
  if (nodesStringToNode(streamObj.ast, &pAst) < 0) {
S
Shengliang Guan 已提交
561 562
    terrno = TSDB_CODE_MND_INVALID_SMA_OPTION;
    mError("sma:%s, failed to create since parse ast error", smaObj.name);
L
Liu Jicong 已提交
563 564 565 566 567
    return -1;
  }

  // extract output schema from ast
  if (qExtractResultSchema(pAst, (int32_t *)&streamObj.outputSchema.nCols, &streamObj.outputSchema.pSchema) != 0) {
S
Shengliang Guan 已提交
568 569
    terrno = TSDB_CODE_MND_INVALID_SMA_OPTION;
    mError("sma:%s, failed to create since extract result schema error", smaObj.name);
L
Liu Jicong 已提交
570 571 572 573 574 575 576 577 578 579
    return -1;
  }

  SQueryPlan  *pPlan = NULL;
  SPlanContext cxt = {
      .pAstRoot = pAst,
      .topicQuery = false,
      .streamQuery = true,
      .triggerType = streamObj.trigger,
      .watermark = streamObj.watermark,
580
      .deleteMark = streamObj.deleteMark,
L
Liu Jicong 已提交
581 582 583
  };

  if (qCreateQueryPlan(&cxt, &pPlan, NULL) < 0) {
S
Shengliang Guan 已提交
584 585
    terrno = TSDB_CODE_MND_INVALID_SMA_OPTION;
    mError("sma:%s, failed to create since create query plan error", smaObj.name);
L
Liu Jicong 已提交
586 587 588 589 590
    return -1;
  }

  // save physcial plan
  if (nodesNodeToString((SNode *)pPlan, false, &streamObj.physicalPlan, NULL) != 0) {
S
Shengliang Guan 已提交
591 592
    terrno = TSDB_CODE_MND_INVALID_SMA_OPTION;
    mError("sma:%s, failed to create since save physcial plan error", smaObj.name);
L
Liu Jicong 已提交
593 594
    return -1;
  }
S
Shengliang Guan 已提交
595

L
Liu Jicong 已提交
596
  if (pAst != NULL) nodesDestroyNode(pAst);
L
Liu Jicong 已提交
597
  nodesDestroyNode((SNode *)pPlan);
L
Liu Jicong 已提交
598

S
sma  
Shengliang Guan 已提交
599
  int32_t code = -1;
600
  STrans *pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB, pReq, "create-sma");
S
sma  
Shengliang Guan 已提交
601
  if (pTrans == NULL) goto _OVER;
602
  mndTransSetDbName(pTrans, pDb->name, NULL);
603 604
  if (mndTrancCheckConflict(pMnode, pTrans) != 0) goto _OVER;

605
  mndTransSetSerial(pTrans);
606
  mInfo("trans:%d, used to create sma:%s stream:%s", pTrans->id, pCreate->name, streamObj.name);
S
sma  
Shengliang Guan 已提交
607 608

  if (mndSetCreateSmaRedoLogs(pMnode, pTrans, &smaObj) != 0) goto _OVER;
L
Liu Jicong 已提交
609
  if (mndSetCreateSmaVgroupRedoLogs(pMnode, pTrans, &streamObj.fixedSinkVg) != 0) goto _OVER;
S
sma  
Shengliang Guan 已提交
610
  if (mndSetCreateSmaCommitLogs(pMnode, pTrans, &smaObj) != 0) goto _OVER;
L
Liu Jicong 已提交
611
  if (mndSetCreateSmaVgroupCommitLogs(pMnode, pTrans, &streamObj.fixedSinkVg) != 0) goto _OVER;
612
  if (mndSetUpdateSmaStbCommitLogs(pMnode, pTrans, pStb) != 0) goto _OVER;
C
Cary Xu 已提交
613
  if (mndSetCreateSmaVgroupRedoActions(pMnode, pTrans, pDb, &streamObj.fixedSinkVg, &smaObj) != 0) goto _OVER;
614
  if (mndScheduleStream(pMnode, &streamObj) != 0) goto _OVER;
L
Liu Jicong 已提交
615
  if (mndPersistStream(pMnode, pTrans, &streamObj) != 0) goto _OVER;
S
sma  
Shengliang Guan 已提交
616 617
  if (mndTransPrepare(pMnode, pTrans) != 0) goto _OVER;

618
  mInfo("sma:%s, uid:%" PRIi64 " create on stb:%" PRIi64 ", dstSuid:%" PRIi64 " dstTb:%s dstVg:%d", pCreate->name,
H
Hongze Cheng 已提交
619
        smaObj.uid, smaObj.stbUid, smaObj.dstTbUid, smaObj.dstTbName, smaObj.dstVgId);
C
Cary Xu 已提交
620

S
sma  
Shengliang Guan 已提交
621 622 623
  code = 0;

_OVER:
L
Liu Jicong 已提交
624
  tFreeStreamObj(&streamObj);
C
Cary Xu 已提交
625
  mndDestroySmaObj(&smaObj);
S
sma  
Shengliang Guan 已提交
626 627 628 629 630
  mndTransDrop(pTrans);
  return code;
}

static int32_t mndCheckCreateSmaReq(SMCreateSmaReq *pCreate) {
S
sma  
Shengliang Guan 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
  terrno = TSDB_CODE_MND_INVALID_SMA_OPTION;
  if (pCreate->name[0] == 0) return -1;
  if (pCreate->stb[0] == 0) return -1;
  if (pCreate->igExists < 0 || pCreate->igExists > 1) return -1;
  if (pCreate->intervalUnit < 0) return -1;
  if (pCreate->slidingUnit < 0) return -1;
  if (pCreate->timezone < 0) return -1;
  if (pCreate->interval < 0) return -1;
  if (pCreate->offset < 0) return -1;
  if (pCreate->sliding < 0) return -1;
  if (pCreate->exprLen < 0) return -1;
  if (pCreate->tagsFilterLen < 0) return -1;
  if (pCreate->sqlLen < 0) return -1;
  if (pCreate->astLen < 0) return -1;
  if (pCreate->exprLen != 0 && strlen(pCreate->expr) + 1 != pCreate->exprLen) return -1;
  if (pCreate->tagsFilterLen != 0 && strlen(pCreate->tagsFilter) + 1 != pCreate->tagsFilterLen) return -1;
  if (pCreate->sqlLen != 0 && strlen(pCreate->sql) + 1 != pCreate->sqlLen) return -1;
  if (pCreate->astLen != 0 && strlen(pCreate->ast) + 1 != pCreate->astLen) return -1;

  SName smaName = {0};
  if (tNameFromString(&smaName, pCreate->name, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE) < 0) return -1;
  if (*(char *)tNameGetTableName(&smaName) == 0) return -1;
S
sma  
Shengliang Guan 已提交
653

S
sma  
Shengliang Guan 已提交
654
  terrno = 0;
S
sma  
Shengliang Guan 已提交
655 656 657
  return 0;
}

658 659 660 661 662 663 664 665
static void mndGetStreamNameFromSmaName(char *streamName, char *smaName) {
  SName n;
  tNameFromString(&n, smaName, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);
  streamName[0] = '1';
  streamName[1] = '.';
  strcpy(streamName + 2, tNameGetTableName(&n));
}

666
static int32_t mndProcessCreateSmaReq(SRpcMsg *pReq) {
S
Shengliang Guan 已提交
667
  SMnode        *pMnode = pReq->info.node;
S
sma  
Shengliang Guan 已提交
668 669 670
  int32_t        code = -1;
  SStbObj       *pStb = NULL;
  SSmaObj       *pSma = NULL;
S
sma  
Shengliang Guan 已提交
671
  SStreamObj    *pStream = NULL;
S
sma  
Shengliang Guan 已提交
672 673 674
  SDbObj        *pDb = NULL;
  SMCreateSmaReq createReq = {0};

S
Shengliang Guan 已提交
675
  if (tDeserializeSMCreateSmaReq(pReq->pCont, pReq->contLen, &createReq) != 0) {
S
sma  
Shengliang Guan 已提交
676 677 678 679
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

680
  mInfo("sma:%s, start to create", createReq.name);
S
sma  
Shengliang Guan 已提交
681 682 683 684 685 686 687 688 689
  if (mndCheckCreateSmaReq(&createReq) != 0) {
    goto _OVER;
  }

  pStb = mndAcquireStb(pMnode, createReq.stb);
  if (pStb == NULL) {
    mError("sma:%s, failed to create since stb:%s not exist", createReq.name, createReq.stb);
    goto _OVER;
  }
L
Liu Jicong 已提交
690

691 692 693 694
  char streamName[TSDB_TABLE_FNAME_LEN] = {0};
  mndGetStreamNameFromSmaName(streamName, createReq.name);

  pStream = mndAcquireStream(pMnode, streamName);
S
sma  
Shengliang Guan 已提交
695
  if (pStream != NULL) {
696
    mError("sma:%s, failed to create since stream:%s already exist", createReq.name, streamName);
C
Cary Xu 已提交
697
    terrno = TSDB_CODE_MND_STREAM_ALREADY_EXIST;
S
sma  
Shengliang Guan 已提交
698 699
    goto _OVER;
  }
S
sma  
Shengliang Guan 已提交
700 701 702 703

  pSma = mndAcquireSma(pMnode, createReq.name);
  if (pSma != NULL) {
    if (createReq.igExists) {
704
      mInfo("sma:%s, already exist in sma:%s, ignore exist is set", createReq.name, pSma->name);
S
sma  
Shengliang Guan 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718
      code = 0;
      goto _OVER;
    } else {
      terrno = TSDB_CODE_MND_SMA_ALREADY_EXIST;
      goto _OVER;
    }
  }

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

719
  if (mndCheckDbPrivilege(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pDb) != 0) {
S
sma  
Shengliang Guan 已提交
720 721 722
    goto _OVER;
  }

723
  code = mndCreateSma(pMnode, pReq, &createReq, pDb, pStb, streamName);
S
Shengliang Guan 已提交
724
  if (code == 0) code = TSDB_CODE_ACTION_IN_PROGRESS;
S
sma  
Shengliang Guan 已提交
725 726

_OVER:
S
Shengliang Guan 已提交
727
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
C
Cary Xu 已提交
728
    mError("sma:%s, failed to create since %s", createReq.name, terrstr());
S
sma  
Shengliang Guan 已提交
729 730 731 732
  }

  mndReleaseStb(pMnode, pStb);
  mndReleaseSma(pMnode, pSma);
S
sma  
Shengliang Guan 已提交
733
  mndReleaseStream(pMnode, pStream);
S
sma  
Shengliang Guan 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
  mndReleaseDb(pMnode, pDb);
  tFreeSMCreateSmaReq(&createReq);

  return code;
}

static int32_t mndSetDropSmaRedoLogs(SMnode *pMnode, STrans *pTrans, SSmaObj *pSma) {
  SSdbRaw *pRedoRaw = mndSmaActionEncode(pSma);
  if (pRedoRaw == NULL) return -1;
  if (mndTransAppendRedolog(pTrans, pRedoRaw) != 0) return -1;
  if (sdbSetRawStatus(pRedoRaw, SDB_STATUS_DROPPING) != 0) return -1;

  return 0;
}

static int32_t mndSetDropSmaCommitLogs(SMnode *pMnode, STrans *pTrans, SSmaObj *pSma) {
  SSdbRaw *pCommitRaw = mndSmaActionEncode(pSma);
  if (pCommitRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pCommitRaw) != 0) return -1;
  if (sdbSetRawStatus(pCommitRaw, SDB_STATUS_DROPPED) != 0) return -1;

  return 0;
}

L
Liu Jicong 已提交
758
static int32_t mndSetDropSmaVgroupRedoLogs(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup) {
S
Shengliang Guan 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
  SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendRedolog(pTrans, pVgRaw) != 0) return -1;
  if (sdbSetRawStatus(pVgRaw, SDB_STATUS_DROPPING) != 0) return -1;

  return 0;
}

static int32_t mndSetDropSmaVgroupCommitLogs(SMnode *pMnode, STrans *pTrans, SVgObj *pVgroup) {
  SSdbRaw *pVgRaw = mndVgroupActionEncode(pVgroup);
  if (pVgRaw == NULL) return -1;
  if (mndTransAppendCommitlog(pTrans, pVgRaw) != 0) return -1;
  if (sdbSetRawStatus(pVgRaw, SDB_STATUS_DROPPED) != 0) return -1;

  return 0;
}

static int32_t mndSetDropSmaVgroupRedoActions(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SVgObj *pVgroup) {
  SVnodeGid *pVgid = pVgroup->vnodeGid + 0;
  SDnodeObj *pDnode = mndAcquireDnode(pMnode, pVgid->dnodeId);
  if (pDnode == NULL) return -1;

  STransAction action = {0};
  action.epSet = mndGetDnodeEpset(pDnode);
  mndReleaseDnode(pMnode, pDnode);

  int32_t contLen = 0;
  void   *pReq = mndBuildDropVnodeReq(pMnode, pDnode, pDb, pVgroup, &contLen);
  if (pReq == NULL) return -1;

  action.pCont = pReq;
  action.contLen = contLen;
  action.msgType = TDMT_DND_DROP_VNODE;
792
  action.acceptableCode = TSDB_CODE_VND_NOT_EXIST;
S
Shengliang Guan 已提交
793 794 795 796 797 798 799 800 801

  if (mndTransAppendRedoAction(pTrans, &action) != 0) {
    taosMemoryFree(pReq);
    return -1;
  }

  return 0;
}

S
Shengliang Guan 已提交
802
static int32_t mndDropSma(SMnode *pMnode, SRpcMsg *pReq, SDbObj *pDb, SSmaObj *pSma) {
803 804 805 806
  int32_t  code = -1;
  SVgObj  *pVgroup = NULL;
  SStbObj *pStb = NULL;
  STrans  *pTrans = NULL;
S
Shengliang Guan 已提交
807 808 809 810

  pVgroup = mndAcquireVgroup(pMnode, pSma->dstVgId);
  if (pVgroup == NULL) goto _OVER;

811 812 813
  pStb = mndAcquireStb(pMnode, pSma->stb);
  if (pStb == NULL) goto _OVER;

814
  pTrans = mndTransCreate(pMnode, TRN_POLICY_RETRY, TRN_CONFLICT_DB, pReq, "drop-sma");
S
sma  
Shengliang Guan 已提交
815 816
  if (pTrans == NULL) goto _OVER;

817
  mInfo("trans:%d, used to drop sma:%s", pTrans->id, pSma->name);
818
  mndTransSetDbName(pTrans, pDb->name, NULL);
819 820
  if (mndTrancCheckConflict(pMnode, pTrans) != 0) goto _OVER;

C
Cary Xu 已提交
821
  mndTransSetSerial(pTrans);
S
sma  
Shengliang Guan 已提交
822

823 824 825 826
  char streamName[TSDB_TABLE_FNAME_LEN] = {0};
  mndGetStreamNameFromSmaName(streamName, pSma->name);

  SStreamObj *pStream = mndAcquireStream(pMnode, streamName);
L
Liu Jicong 已提交
827 828 829 830 831 832 833 834 835 836 837 838
  if (pStream == NULL || pStream->smaId != pSma->uid) {
    sdbRelease(pMnode->pSdb, pStream);
    goto _OVER;
  } else {
    if (mndDropStreamTasks(pMnode, pTrans, pStream) < 0) {
      mError("stream:%s, failed to drop task since %s", pStream->name, terrstr());
      sdbRelease(pMnode->pSdb, pStream);
      goto _OVER;
    }

    // drop stream
    if (mndPersistDropStreamLog(pMnode, pTrans, pStream) < 0) {
S
Shengliang Guan 已提交
839
      mError("stream:%s, failed to drop log since %s", pStream->name, terrstr());
L
Liu Jicong 已提交
840 841 842 843
      sdbRelease(pMnode->pSdb, pStream);
      goto _OVER;
    }
  }
S
sma  
Shengliang Guan 已提交
844
  if (mndSetDropSmaRedoLogs(pMnode, pTrans, pSma) != 0) goto _OVER;
S
Shengliang Guan 已提交
845
  if (mndSetDropSmaVgroupRedoLogs(pMnode, pTrans, pVgroup) != 0) goto _OVER;
S
sma  
Shengliang Guan 已提交
846
  if (mndSetDropSmaCommitLogs(pMnode, pTrans, pSma) != 0) goto _OVER;
S
Shengliang Guan 已提交
847
  if (mndSetDropSmaVgroupCommitLogs(pMnode, pTrans, pVgroup) != 0) goto _OVER;
848
  if (mndSetUpdateSmaStbCommitLogs(pMnode, pTrans, pStb) != 0) goto _OVER;
S
Shengliang Guan 已提交
849
  if (mndSetDropSmaVgroupRedoActions(pMnode, pTrans, pDb, pVgroup) != 0) goto _OVER;
S
sma  
Shengliang Guan 已提交
850 851 852 853 854 855
  if (mndTransPrepare(pMnode, pTrans) != 0) goto _OVER;

  code = 0;

_OVER:
  mndTransDrop(pTrans);
856
  mndReleaseStream(pMnode, pStream);
S
Shengliang Guan 已提交
857
  mndReleaseVgroup(pMnode, pVgroup);
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
  mndReleaseStb(pMnode, pStb);
  return code;
}

int32_t mndDropSmasByStb(SMnode *pMnode, STrans *pTrans, SDbObj *pDb, SStbObj *pStb) {
  SSdb    *pSdb = pMnode->pSdb;
  SSmaObj *pSma = NULL;
  void    *pIter = NULL;
  SVgObj  *pVgroup = NULL;
  int32_t  code = -1;

  while (1) {
    pIter = sdbFetch(pSdb, SDB_SMA, pIter, (void **)&pSma);
    if (pIter == NULL) break;

    if (pSma->stbUid == pStb->uid) {
C
Cary Xu 已提交
874
      mndTransSetSerial(pTrans);
875 876
      pVgroup = mndAcquireVgroup(pMnode, pSma->dstVgId);
      if (pVgroup == NULL) goto _OVER;
S
Shengliang Guan 已提交
877

878 879 880 881
      char streamName[TSDB_TABLE_FNAME_LEN] = {0};
      mndGetStreamNameFromSmaName(streamName, pSma->name);

      SStreamObj *pStream = mndAcquireStream(pMnode, streamName);
S
Shengliang Guan 已提交
882 883 884 885 886 887 888 889 890
      if (pStream != NULL && pStream->smaId == pSma->uid) {
        if (mndDropStreamTasks(pMnode, pTrans, pStream) < 0) {
          mError("stream:%s, failed to drop task since %s", pStream->name, terrstr());
          goto _OVER;
        }
        if (mndPersistDropStreamLog(pMnode, pTrans, pStream) < 0) {
          goto _OVER;
        }
      }
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
      if (mndSetDropSmaVgroupCommitLogs(pMnode, pTrans, pVgroup) != 0) goto _OVER;
      if (mndSetDropSmaVgroupRedoActions(pMnode, pTrans, pDb, pVgroup) != 0) goto _OVER;
      if (mndSetDropSmaCommitLogs(pMnode, pTrans, pSma) != 0) goto _OVER;
      mndReleaseVgroup(pMnode, pVgroup);
      pVgroup = NULL;
    }

    sdbRelease(pSdb, pSma);
  }

  code = 0;

_OVER:
  sdbCancelFetch(pSdb, pIter);
  sdbRelease(pSdb, pSma);
  mndReleaseVgroup(pMnode, pVgroup);
S
sma  
Shengliang Guan 已提交
907 908 909
  return code;
}

910
int32_t mndDropSmasByDb(SMnode *pMnode, STrans *pTrans, SDbObj *pDb) {
S
Shengliang Guan 已提交
911 912
  SSdb *pSdb = pMnode->pSdb;
  void *pIter = NULL;
913 914

  while (1) {
S
Shengliang Guan 已提交
915
    SSmaObj *pSma = NULL;
916 917 918 919
    pIter = sdbFetch(pSdb, SDB_SMA, pIter, (void **)&pSma);
    if (pIter == NULL) break;

    if (pSma->dbUid == pDb->uid) {
S
Shengliang Guan 已提交
920 921 922 923
      if (mndSetDropSmaCommitLogs(pMnode, pTrans, pSma) != 0) {
        sdbRelease(pSdb, pSma);
        sdbCancelFetch(pSdb, pSma);
        return -1;
S
Shengliang Guan 已提交
924
      }
925 926 927 928 929
    }

    sdbRelease(pSdb, pSma);
  }

S
Shengliang Guan 已提交
930
  return 0;
931 932 933
}

static int32_t mndProcessDropSmaReq(SRpcMsg *pReq) {
S
Shengliang Guan 已提交
934
  SMnode      *pMnode = pReq->info.node;
S
sma  
Shengliang Guan 已提交
935 936 937 938 939
  int32_t      code = -1;
  SDbObj      *pDb = NULL;
  SSmaObj     *pSma = NULL;
  SMDropSmaReq dropReq = {0};

S
Shengliang Guan 已提交
940
  if (tDeserializeSMDropSmaReq(pReq->pCont, pReq->contLen, &dropReq) != 0) {
S
sma  
Shengliang Guan 已提交
941 942 943 944
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

945
  mInfo("sma:%s, start to drop", dropReq.name);
S
sma  
Shengliang Guan 已提交
946 947 948 949

  pSma = mndAcquireSma(pMnode, dropReq.name);
  if (pSma == NULL) {
    if (dropReq.igNotExists) {
950
      mInfo("sma:%s, not exist, ignore not exist is set", dropReq.name);
S
sma  
Shengliang Guan 已提交
951 952 953 954 955 956 957 958 959 960 961 962 963 964
      code = 0;
      goto _OVER;
    } else {
      terrno = TSDB_CODE_MND_SMA_NOT_EXIST;
      goto _OVER;
    }
  }

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

965
  if (mndCheckDbPrivilege(pMnode, pReq->info.conn.user, MND_OPER_WRITE_DB, pDb) != 0) {
S
sma  
Shengliang Guan 已提交
966 967 968 969
    goto _OVER;
  }

  code = mndDropSma(pMnode, pReq, pDb, pSma);
S
Shengliang Guan 已提交
970
  if (code == 0) code = TSDB_CODE_ACTION_IN_PROGRESS;
S
sma  
Shengliang Guan 已提交
971 972

_OVER:
S
Shengliang Guan 已提交
973
  if (code != 0 && code != TSDB_CODE_ACTION_IN_PROGRESS) {
S
sma  
Shengliang Guan 已提交
974 975 976
    mError("sma:%s, failed to drop since %s", dropReq.name, terrstr());
  }

977
  mndReleaseSma(pMnode, pSma);
978
  mndReleaseDb(pMnode, pDb);
S
sma  
Shengliang Guan 已提交
979 980 981
  return code;
}

S
Shengliang Guan 已提交
982
static int32_t mndGetSma(SMnode *pMnode, SUserIndexReq *indexReq, SUserIndexRsp *rsp, bool *exist) {
L
Liu Jicong 已提交
983 984
  int32_t  code = -1;
  SSmaObj *pSma = NULL;
D
dapan1121 已提交
985

D
dapan1121 已提交
986
  pSma = mndAcquireSma(pMnode, indexReq->indexFName);
D
dapan1121 已提交
987 988 989 990 991 992 993 994 995 996
  if (pSma == NULL) {
    *exist = false;
    return 0;
  }

  memcpy(rsp->dbFName, pSma->db, sizeof(pSma->db));
  memcpy(rsp->tblFName, pSma->stb, sizeof(pSma->stb));
  strcpy(rsp->indexType, TSDB_INDEX_TYPE_SMA);

  SNodeList *pList = NULL;
L
Liu Jicong 已提交
997
  int32_t    extOffset = 0;
D
dapan1121 已提交
998 999 1000 1001 1002
  code = nodesStringToList(pSma->expr, &pList);
  if (0 == code) {
    SNode *node = NULL;
    FOREACH(node, pList) {
      SFunctionNode *pFunc = (SFunctionNode *)node;
L
Liu Jicong 已提交
1003 1004
      extOffset += snprintf(rsp->indexExts + extOffset, sizeof(rsp->indexExts) - extOffset - 1, "%s%s",
                            (extOffset ? "," : ""), pFunc->functionName);
D
dapan1121 已提交
1005 1006 1007 1008 1009 1010
    }

    *exist = true;
  }

  mndReleaseSma(pMnode, pSma);
S
Shengliang Guan 已提交
1011 1012 1013
  return code;
}

D
dapan1121 已提交
1014
int32_t mndGetTableSma(SMnode *pMnode, char *tbFName, STableIndexRsp *rsp, bool *exist) {
1015 1016 1017 1018
  int32_t         code = 0;
  SSmaObj        *pSma = NULL;
  SSdb           *pSdb = pMnode->pSdb;
  void           *pIter = NULL;
D
dapan1121 已提交
1019 1020
  STableIndexInfo info;

1021
  SStbObj *pStb = mndAcquireStb(pMnode, tbFName);
D
dapan1121 已提交
1022 1023 1024 1025 1026
  if (NULL == pStb) {
    *exist = false;
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
1027
  strcpy(rsp->dbFName, pStb->db);
D
dapan1121 已提交
1028
  strcpy(rsp->tbName, pStb->name + strlen(pStb->db) + 1);
D
dapan1121 已提交
1029 1030 1031 1032
  rsp->suid = pStb->uid;
  rsp->version = pStb->smaVer;
  mndReleaseStb(pMnode, pStb);

D
dapan1121 已提交
1033 1034 1035 1036
  while (1) {
    pIter = sdbFetch(pSdb, SDB_SMA, pIter, (void **)&pSma);
    if (pIter == NULL) break;

D
dapan1121 已提交
1037
    if (pSma->stb[0] != tbFName[0] || strcmp(pSma->stb, tbFName)) {
D
dapan1121 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
      continue;
    }

    info.intervalUnit = pSma->intervalUnit;
    info.slidingUnit = pSma->slidingUnit;
    info.interval = pSma->interval;
    info.offset = pSma->offset;
    info.sliding = pSma->sliding;
    info.dstTbUid = pSma->dstTbUid;
    info.dstVgId = pSma->dstVgId;
D
dapan1121 已提交
1048

1049
    SVgObj *pVg = mndAcquireVgroup(pMnode, pSma->dstVgId);
D
dapan1121 已提交
1050 1051 1052 1053 1054 1055
    if (pVg == NULL) {
      code = -1;
      sdbRelease(pSdb, pSma);
      return code;
    }
    info.epSet = mndGetVgroupEpset(pMnode, pVg);
1056

D
dapan1121 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    info.expr = taosMemoryMalloc(pSma->exprLen + 1);
    if (info.expr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      code = -1;
      sdbRelease(pSdb, pSma);
      return code;
    }

    memcpy(info.expr, pSma->expr, pSma->exprLen);
    info.expr[pSma->exprLen] = 0;

    if (NULL == taosArrayPush(rsp->pIndex, &info)) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      code = -1;
      taosMemoryFree(info.expr);
      sdbRelease(pSdb, pSma);
      return code;
    }

    *exist = true;

    sdbRelease(pSdb, pSma);
  }
1080

D
dapan1121 已提交
1081 1082 1083
  return code;
}

S
Shengliang Guan 已提交
1084
static int32_t mndProcessGetSmaReq(SRpcMsg *pReq) {
S
Shengliang Guan 已提交
1085
  SUserIndexReq indexReq = {0};
S
Shengliang Guan 已提交
1086
  SMnode       *pMnode = pReq->info.node;
S
Shengliang Guan 已提交
1087 1088 1089 1090
  int32_t       code = -1;
  SUserIndexRsp rsp = {0};
  bool          exist = false;

S
Shengliang Guan 已提交
1091
  if (tDeserializeSUserIndexReq(pReq->pCont, pReq->contLen, &indexReq) != 0) {
S
Shengliang Guan 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

  code = mndGetSma(pMnode, &indexReq, &rsp, &exist);
  if (code) {
    goto _OVER;
  }

  if (!exist) {
    // TODO GET INDEX FROM FULLTEXT
    code = -1;
    terrno = TSDB_CODE_MND_DB_INDEX_NOT_EXIST;
  } else {
    int32_t contLen = tSerializeSUserIndexRsp(NULL, 0, &rsp);
    void   *pRsp = rpcMallocCont(contLen);
    if (pRsp == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      code = -1;
      goto _OVER;
    }

    tSerializeSUserIndexRsp(pRsp, contLen, &rsp);

S
Shengliang Guan 已提交
1116 1117
    pReq->info.rsp = pRsp;
    pReq->info.rspLen = contLen;
S
Shengliang Guan 已提交
1118 1119 1120 1121 1122 1123 1124 1125

    code = 0;
  }

_OVER:
  if (code != 0) {
    mError("failed to get index %s since %s", indexReq.indexFName, terrstr());
  }
D
dapan1121 已提交
1126 1127 1128 1129

  return code;
}

D
dapan1121 已提交
1130 1131
static int32_t mndProcessGetTbSmaReq(SRpcMsg *pReq) {
  STableIndexReq indexReq = {0};
1132 1133
  SMnode        *pMnode = pReq->info.node;
  int32_t        code = -1;
D
dapan1121 已提交
1134
  STableIndexRsp rsp = {0};
1135
  bool           exist = false;
D
dapan1121 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148

  if (tDeserializeSTableIndexReq(pReq->pCont, pReq->contLen, &indexReq) != 0) {
    terrno = TSDB_CODE_INVALID_MSG;
    goto _OVER;
  }

  rsp.pIndex = taosArrayInit(10, sizeof(STableIndexInfo));
  if (NULL == rsp.pIndex) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    code = -1;
    goto _OVER;
  }

D
dapan1121 已提交
1149
  code = mndGetTableSma(pMnode, indexReq.tbFName, &rsp, &exist);
D
dapan1121 已提交
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
  if (code) {
    goto _OVER;
  }

  if (!exist) {
    code = -1;
    terrno = TSDB_CODE_MND_DB_INDEX_NOT_EXIST;
  } else {
    int32_t contLen = tSerializeSTableIndexRsp(NULL, 0, &rsp);
    void   *pRsp = rpcMallocCont(contLen);
    if (pRsp == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      code = -1;
      goto _OVER;
    }

    tSerializeSTableIndexRsp(pRsp, contLen, &rsp);

    pReq->info.rsp = pRsp;
    pReq->info.rspLen = contLen;

    code = 0;
  }

_OVER:
  if (code != 0) {
    mError("failed to get table index %s since %s", indexReq.tbFName, terrstr());
  }

1179
  tFreeSerializeSTableIndexRsp(&rsp);
D
dapan1121 已提交
1180 1181 1182
  return code;
}

S
Shengliang Guan 已提交
1183 1184
static int32_t mndRetrieveSma(SRpcMsg *pReq, SShowObj *pShow, SSDataBlock *pBlock, int32_t rows) {
  SMnode  *pMnode = pReq->info.node;
S
sma  
Shengliang Guan 已提交
1185 1186 1187 1188 1189
  SSdb    *pSdb = pMnode->pSdb;
  int32_t  numOfRows = 0;
  SSmaObj *pSma = NULL;
  int32_t  cols = 0;

1190 1191 1192 1193 1194
  SDbObj *pDb = NULL;
  if (strlen(pShow->db) > 0) {
    pDb = mndAcquireDb(pMnode, pShow->db);
    if (pDb == NULL) return 0;
  }
S
sma  
Shengliang Guan 已提交
1195 1196 1197 1198 1199

  while (numOfRows < rows) {
    pShow->pIter = sdbFetch(pSdb, SDB_SMA, pShow->pIter, (void **)&pSma);
    if (pShow->pIter == NULL) break;

1200
    if (NULL != pDb && pSma->dbUid != pDb->uid) {
S
sma  
Shengliang Guan 已提交
1201 1202 1203 1204 1205 1206 1207 1208
      sdbRelease(pSdb, pSma);
      continue;
    }

    cols = 0;

    SName smaName = {0};
    tNameFromString(&smaName, pSma->name, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);
X
Xiaoyu Wang 已提交
1209 1210 1211
    char n1[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(n1, (char *)tNameGetTableName(&smaName));

S
Shengliang Guan 已提交
1212
    char n2[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
1213
    STR_TO_VARSTR(n2, (char *)mndGetDbStr(pSma->db));
X
Xiaoyu Wang 已提交
1214

S
sma  
Shengliang Guan 已提交
1215 1216
    SName stbName = {0};
    tNameFromString(&stbName, pSma->stb, T_NAME_ACCT | T_NAME_DB | T_NAME_TABLE);
X
Xiaoyu Wang 已提交
1217 1218
    char n3[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(n3, (char *)tNameGetTableName(&stbName));
1219

L
Liu Jicong 已提交
1220
    SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
X
Xiaoyu Wang 已提交
1221
    colDataAppend(pColInfo, numOfRows, (const char *)n1, false);
1222 1223

    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
X
Xiaoyu Wang 已提交
1224 1225 1226 1227
    colDataAppend(pColInfo, numOfRows, (const char *)n2, false);

    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataAppend(pColInfo, numOfRows, (const char *)n3, false);
S
sma  
Shengliang Guan 已提交
1228

S
Shengliang Guan 已提交
1229 1230 1231
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataAppend(pColInfo, numOfRows, (const char *)&pSma->dstVgId, false);

S
Shengliang Guan 已提交
1232 1233 1234
    pColInfo = taosArrayGet(pBlock->pDataBlock, cols++);
    colDataAppend(pColInfo, numOfRows, (const char *)&pSma->createdTime, false);

S
sma  
Shengliang Guan 已提交
1235 1236 1237 1238
    numOfRows++;
    sdbRelease(pSdb, pSma);
  }

X
Xiaoyu Wang 已提交
1239
  mndReleaseDb(pMnode, pDb);
1240
  pShow->numOfRows += numOfRows;
S
sma  
Shengliang Guan 已提交
1241 1242 1243 1244 1245 1246
  return numOfRows;
}

static void mndCancelGetNextSma(SMnode *pMnode, void *pIter) {
  SSdb *pSdb = pMnode->pSdb;
  sdbCancelFetch(pSdb, pIter);
D
dapan1121 已提交
1247
}