tq.c 42.9 KB
Newer Older
H
refact  
Hongze Cheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * 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/>.
S
Shengliang Guan 已提交
14 15
 */

H
Hongze Cheng 已提交
16
#include "tq.h"
S
Shengliang Guan 已提交
17

dengyihao's avatar
dengyihao 已提交
18 19 20
// 0: not init
// 1: already inited
// 2: wait to be inited or cleaup
21
#define WAL_READ_TASKS_ID       (-1)
22

23 24
static int32_t tqInitialize(STQ* pTq);

L
Liu Jicong 已提交
25
int32_t tqInit() {
L
Liu Jicong 已提交
26 27 28 29 30 31
  int8_t old;
  while (1) {
    old = atomic_val_compare_exchange_8(&tqMgmt.inited, 0, 2);
    if (old != 2) break;
  }

32 33 34 35 36 37
  if (old == 0) {
    tqMgmt.timer = taosTmrInit(10000, 100, 10000, "TQ");
    if (tqMgmt.timer == NULL) {
      atomic_store_8(&tqMgmt.inited, 0);
      return -1;
    }
38 39 40
    if (streamInit() < 0) {
      return -1;
    }
L
Liu Jicong 已提交
41
    atomic_store_8(&tqMgmt.inited, 1);
42
  }
43

L
Liu Jicong 已提交
44 45
  return 0;
}
L
Liu Jicong 已提交
46

47
void tqCleanUp() {
L
Liu Jicong 已提交
48 49 50 51 52 53 54 55
  int8_t old;
  while (1) {
    old = atomic_val_compare_exchange_8(&tqMgmt.inited, 1, 2);
    if (old != 2) break;
  }

  if (old == 1) {
    taosTmrCleanUp(tqMgmt.timer);
L
Liu Jicong 已提交
56
    streamCleanUp();
L
Liu Jicong 已提交
57 58
    atomic_store_8(&tqMgmt.inited, 0);
  }
59
}
L
Liu Jicong 已提交
60

61
static void destroyTqHandle(void* data) {
62 63 64
  STqHandle* pData = (STqHandle*)data;
  qDestroyTask(pData->execHandle.task);
  if (pData->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
65
    taosMemoryFreeClear(pData->execHandle.execCol.qmsg);
66
  } else if (pData->execHandle.subType == TOPIC_SUB_TYPE__DB) {
67
    tqCloseReader(pData->execHandle.pTqReader);
68 69
    walCloseReader(pData->pWalReader);
    taosHashCleanup(pData->execHandle.execDb.pFilterOutTbUid);
L
Liu Jicong 已提交
70
  } else if (pData->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
71
    walCloseReader(pData->pWalReader);
72
    tqCloseReader(pData->execHandle.pTqReader);
73
  }
74 75 76 77 78
  if(pData->msg != NULL) {
    rpcFreeCont(pData->msg->pCont);
    taosMemoryFree(pData->msg);
    pData->msg = NULL;
  }
79 80
}

81 82 83 84 85
static bool tqOffsetLessOrEqual(const STqOffset* pLeft, const STqOffset* pRight) {
  return pLeft->val.type == TMQ_OFFSET__LOG && pRight->val.type == TMQ_OFFSET__LOG &&
         pLeft->val.version <= pRight->val.version;
}

L
Liu Jicong 已提交
86
STQ* tqOpen(const char* path, SVnode* pVnode) {
87
  STQ* pTq = taosMemoryCalloc(1, sizeof(STQ));
L
Liu Jicong 已提交
88
  if (pTq == NULL) {
S
Shengliang Guan 已提交
89
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
90 91
    return NULL;
  }
92

93
  pTq->path = taosStrdup(path);
L
Liu Jicong 已提交
94
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
95
  pTq->walLogLastVer = pVnode->pWal->vers.lastVer;
96

97
  pTq->pHandle = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
98
  taosHashSetFreeFp(pTq->pHandle, destroyTqHandle);
99

100
  taosInitRWLatch(&pTq->lock);
101
  pTq->pPushMgr = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
L
Liu Jicong 已提交
102

103
  pTq->pCheckInfo = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
104
  taosHashSetFreeFp(pTq->pCheckInfo, (FDelete)tDeleteSTqCheckInfo);
L
Liu Jicong 已提交
105

106
  tqInitialize(pTq);
107 108 109 110
  return pTq;
}

int32_t tqInitialize(STQ* pTq) {
L
Liu Jicong 已提交
111
  if (tqMetaOpen(pTq) < 0) {
112
    return -1;
113 114
  }

L
Liu Jicong 已提交
115 116
  pTq->pOffsetStore = tqOffsetOpen(pTq);
  if (pTq->pOffsetStore == NULL) {
117
    return -1;
118 119
  }

120
  pTq->pStreamMeta = streamMetaOpen(pTq->path, pTq, (FTaskExpand*)tqExpandTask, pTq->pVnode->config.vgId);
L
Liu Jicong 已提交
121
  if (pTq->pStreamMeta == NULL) {
122
    return -1;
L
Liu Jicong 已提交
123 124
  }

125 126
  // the version is kept in task's meta data
  // todo check if this version is required or not
127 128
  if (streamLoadTasks(pTq->pStreamMeta, walGetCommittedVer(pTq->pVnode->pWal)) < 0) {
    return -1;
L
Liu Jicong 已提交
129 130
  }

131
  return 0;
L
Liu Jicong 已提交
132
}
L
Liu Jicong 已提交
133

L
Liu Jicong 已提交
134
void tqClose(STQ* pTq) {
135 136
  if (pTq == NULL) {
    return;
H
Hongze Cheng 已提交
137
  }
138 139 140 141 142 143 144 145

  tqOffsetClose(pTq->pOffsetStore);
  taosHashCleanup(pTq->pHandle);
  taosHashCleanup(pTq->pPushMgr);
  taosHashCleanup(pTq->pCheckInfo);
  taosMemoryFree(pTq->path);
  tqMetaClose(pTq);
  streamMetaClose(pTq->pStreamMeta);
146
  taosMemoryFree(pTq);
L
Liu Jicong 已提交
147
}
L
Liu Jicong 已提交
148

H
Haojun Liao 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161
void tqNotifyClose(STQ* pTq) {
  if (pTq != NULL) {
    taosWLockLatch(&pTq->pStreamMeta->lock);

    void* pIter = NULL;
    while (1) {
      pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
      if (pIter == NULL) {
        break;
      }

      SStreamTask* pTask = *(SStreamTask**)pIter;
      tqDebug("vgId:%d s-task:%s set dropping flag", pTq->pStreamMeta->vgId, pTask->id.idStr);
162 163 164
      pTask->status.taskStatus = TASK_STATUS__STOP;

      int64_t st = taosGetTimestampMs();
H
Haojun Liao 已提交
165
      qKillTask(pTask->exec.pExecutor, TSDB_CODE_SUCCESS);
166 167
      int64_t el = taosGetTimestampMs() - st;
      tqDebug("vgId:%d s-task:%s is closed in %" PRId64 "ms", pTq->pStreamMeta->vgId, pTask->id.idStr, el);
H
Haojun Liao 已提交
168 169 170 171 172 173
    }

    taosWUnLockLatch(&pTq->pStreamMeta->lock);
  }
}

H
Haojun Liao 已提交
174 175
static int32_t doSendDataRsp(const SRpcHandleInfo* pRpcHandleInfo, const SMqDataRsp* pRsp, int32_t epoch,
                             int64_t consumerId, int32_t type) {
L
Liu Jicong 已提交
176 177
  int32_t len = 0;
  int32_t code = 0;
H
Haojun Liao 已提交
178 179 180 181 182 183

  if (type == TMQ_MSG_TYPE__POLL_RSP) {
    tEncodeSize(tEncodeSMqDataRsp, pRsp, len, code);
  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
    tEncodeSize(tEncodeSTaosxRsp, (STaosxRsp*)pRsp, len, code);
  }
L
Liu Jicong 已提交
184 185 186 187 188 189 190 191 192 193 194

  if (code < 0) {
    return -1;
  }

  int32_t tlen = sizeof(SMqRspHead) + len;
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    return -1;
  }

H
Haojun Liao 已提交
195 196 197
  ((SMqRspHead*)buf)->mqMsgType = type;
  ((SMqRspHead*)buf)->epoch = epoch;
  ((SMqRspHead*)buf)->consumerId = consumerId;
L
Liu Jicong 已提交
198 199 200 201 202

  void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));

  SEncoder encoder = {0};
  tEncoderInit(&encoder, abuf, len);
H
Haojun Liao 已提交
203 204 205 206

  if (type == TMQ_MSG_TYPE__POLL_RSP) {
    tEncodeSMqDataRsp(&encoder, pRsp);
  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
X
Xiaoyu Wang 已提交
207
    tEncodeSTaosxRsp(&encoder, (STaosxRsp*)pRsp);
H
Haojun Liao 已提交
208 209
  }

L
Liu Jicong 已提交
210 211 212
  tEncoderClear(&encoder);

  SRpcMsg rsp = {
H
Haojun Liao 已提交
213
      .info = *pRpcHandleInfo,
L
Liu Jicong 已提交
214 215 216 217 218 219 220 221 222
      .pCont = buf,
      .contLen = tlen,
      .code = 0,
  };

  tmsgSendRsp(&rsp);
  return 0;
}

H
Haojun Liao 已提交
223 224 225 226
int32_t tqPushDataRsp(STQ* pTq, STqPushEntry* pPushEntry) {
  SMqDataRsp* pRsp = pPushEntry->pDataRsp;
  SMqRspHead* pHeader = &pPushEntry->pDataRsp->head;
  doSendDataRsp(&pPushEntry->info, pRsp, pHeader->epoch, pHeader->consumerId, pHeader->mqMsgType);
L
Liu Jicong 已提交
227

wmmhello's avatar
wmmhello 已提交
228 229
  char buf1[80] = {0};
  char buf2[80] = {0};
H
Haojun Liao 已提交
230 231 232 233
  tFormatOffset(buf1, tListLen(buf1), &pRsp->reqOffset);
  tFormatOffset(buf2, tListLen(buf2), &pRsp->rspOffset);
  tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) push rsp, block num: %d, req:%s, rsp:%s",
          TD_VID(pTq->pVnode), pRsp->head.consumerId, pRsp->head.epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
234 235 236
  return 0;
}

H
Haojun Liao 已提交
237 238
int32_t tqSendDataRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqDataRsp* pRsp, int32_t type) {
  doSendDataRsp(&pMsg->info, pRsp, pReq->epoch, pReq->consumerId, type);
239 240 241 242 243 244

  char buf1[80] = {0};
  char buf2[80] = {0};
  tFormatOffset(buf1, 80, &pRsp->reqOffset);
  tFormatOffset(buf2, 80, &pRsp->rspOffset);

X
Xiaoyu Wang 已提交
245
  tqDebug("vgId:%d consumer:0x%" PRIx64 " (epoch %d) send rsp, block num:%d, req:%s, rsp:%s, reqId:0x%" PRIx64,
H
Haojun Liao 已提交
246
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2, pReq->reqId);
H
Haojun Liao 已提交
247

248 249 250
  return 0;
}

251
int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
252
  STqOffset offset = {0};
X
Xiaoyu Wang 已提交
253
  int32_t   vgId = TD_VID(pTq->pVnode);
254

X
Xiaoyu Wang 已提交
255 256
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
257 258 259
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
    return -1;
  }
260

261 262
  tDecoderClear(&decoder);

wmmhello's avatar
wmmhello 已提交
263
  if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA || offset.val.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
264
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:snapshot) uid:%" PRId64 ", ts:%" PRId64,
H
Haojun Liao 已提交
265
            offset.subKey, vgId, offset.val.uid, offset.val.ts);
L
Liu Jicong 已提交
266
  } else if (offset.val.type == TMQ_OFFSET__LOG) {
X
Xiaoyu Wang 已提交
267 268
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey, vgId,
            offset.val.version);
269
    if (offset.val.version + 1 == sversion) {
270 271
      offset.val.version += 1;
    }
272
  } else {
273 274
    tqError("invalid commit offset type:%d", offset.val.type);
    return -1;
275
  }
276 277 278 279

  STqOffset* pSavedOffset = tqOffsetRead(pTq->pOffsetStore, offset.subKey);
  if (pSavedOffset != NULL && tqOffsetLessOrEqual(&offset, pSavedOffset)) {
    return 0;  // no need to update the offset value
280 281
  }

282
  // save the new offset value
283 284
  if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) {
    return -1;
285
  }
286 287

  if (offset.val.type == TMQ_OFFSET__LOG) {
288
    STqHandle* pHandle = taosHashGet(pTq->pHandle, offset.subKey, strlen(offset.subKey));
289 290
    if (pHandle && (walRefVer(pHandle->pRef, offset.val.version) < 0)) {
      return -1;
291 292 293
    }
  }

294 295 296
  return 0;
}

L
Liu Jicong 已提交
297
int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) {
L
Liu Jicong 已提交
298
  void* pIter = NULL;
299

L
Liu Jicong 已提交
300
  while (1) {
301
    pIter = taosHashIterate(pTq->pCheckInfo, pIter);
302 303 304 305
    if (pIter == NULL) {
      break;
    }

306
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
307

L
Liu Jicong 已提交
308 309
    if (pCheck->ntbUid == tbUid) {
      int32_t sz = taosArrayGetSize(pCheck->colIdList);
L
Liu Jicong 已提交
310
      for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
311 312
        int16_t forbidColId = *(int16_t*)taosArrayGet(pCheck->colIdList, i);
        if (forbidColId == colId) {
313
          taosHashCancelIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
314 315 316 317 318
          return -1;
        }
      }
    }
  }
319

L
Liu Jicong 已提交
320 321 322
  return 0;
}

323
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
X
Xiaoyu Wang 已提交
324
  SMqPollReq req = {0};
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
  if (tDeserializeSMqPollReq(pMsg->pCont, pMsg->contLen, &req) < 0) {
    tqError("tDeserializeSMqPollReq %d failed", pMsg->contLen);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  int64_t      consumerId = req.consumerId;
  int32_t      reqEpoch = req.epoch;
  STqOffsetVal reqOffset = req.reqOffset;
  int32_t      vgId = TD_VID(pTq->pVnode);

  // 1. find handle
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
  if (pHandle == NULL) {
    tqError("tmq poll: consumer:0x%" PRIx64 " vgId:%d subkey %s not found", consumerId, vgId, req.subKey);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

344
  // 2. check re-balance status
345
  taosRLockLatch(&pTq->lock);
346 347 348 349
  if (pHandle->consumerId != consumerId) {
    tqDebug("ERROR tmq poll: consumer:0x%" PRIx64 " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64,
            consumerId, TD_VID(pTq->pVnode), req.subKey, pHandle->consumerId);
    terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
350
    taosRUnLockLatch(&pTq->lock);
351 352
    return -1;
  }
353
  taosRUnLockLatch(&pTq->lock);
354

wmmhello's avatar
wmmhello 已提交
355 356 357 358 359 360 361 362 363 364
  // 3. update the epoch value
  taosWLockLatch(&pTq->lock);
  int32_t savedEpoch = pHandle->epoch;
  if (savedEpoch < reqEpoch) {
    tqDebug("tmq poll: consumer:0x%" PRIx64 " epoch update from %d to %d by poll req", consumerId, savedEpoch,
            reqEpoch);
    pHandle->epoch = reqEpoch;
  }
  taosWUnLockLatch(&pTq->lock);

365 366
  char buf[80];
  tFormatOffset(buf, 80, &reqOffset);
H
Haojun Liao 已提交
367 368
  tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey %s, recv poll req vgId:%d, req:%s, reqId:0x%" PRIx64,
          consumerId, req.epoch, pHandle->subKey, vgId, buf, req.reqId);
369

370
  return tqExtractDataForMq(pTq, pHandle, &req, pMsg);
371 372
}

373
int32_t tqProcessDeleteSubReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
374
  SMqVDeleteReq* pReq = (SMqVDeleteReq*)msg;
L
Liu Jicong 已提交
375

L
Liu Jicong 已提交
376
  tqDebug("vgId:%d, tq process delete sub req %s", pTq->pVnode->config.vgId, pReq->subKey);
wmmhello's avatar
wmmhello 已提交
377
  int32_t code = 0;
wmmhello's avatar
wmmhello 已提交
378 379 380 381 382 383
//  taosWLockLatch(&pTq->lock);
//  int32_t code = taosHashRemove(pTq->pPushMgr, pReq->subKey, strlen(pReq->subKey));
//  if (code != 0) {
//    tqDebug("vgId:%d, tq remove push handle %s", pTq->pVnode->config.vgId, pReq->subKey);
//  }
//  taosWUnLockLatch(&pTq->lock);
L
Liu Jicong 已提交
384

L
Liu Jicong 已提交
385 386
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
X
Xiaoyu Wang 已提交
387
    // walCloseRef(pHandle->pWalReader->pWal, pHandle->pRef->refId);
L
Liu Jicong 已提交
388 389 390 391 392 393 394
    if (pHandle->pRef) {
      walCloseRef(pTq->pVnode->pWal, pHandle->pRef->refId);
    }
    code = taosHashRemove(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
    if (code != 0) {
      tqError("cannot process tq delete req %s, since no such handle", pReq->subKey);
    }
L
Liu Jicong 已提交
395
  }
396

L
Liu Jicong 已提交
397 398
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
399
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
400
  }
L
Liu Jicong 已提交
401

L
Liu Jicong 已提交
402
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
403
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
404
  }
L
Liu Jicong 已提交
405
  return 0;
L
Liu Jicong 已提交
406 407
}

408
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
409 410
  STqCheckInfo info = {0};
  SDecoder     decoder;
X
Xiaoyu Wang 已提交
411
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
412
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
413 414 415 416
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
417 418 419 420 421
  if (taosHashPut(pTq->pCheckInfo, info.topic, strlen(info.topic), &info, sizeof(STqCheckInfo)) < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  if (tqMetaSaveCheckInfo(pTq, info.topic, msg, msgLen) < 0) {
L
Liu Jicong 已提交
422 423 424 425 426 427
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

428
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
429 430 431 432 433 434 435 436 437 438 439
  if (taosHashRemove(pTq->pCheckInfo, msg, strlen(msg)) < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  if (tqMetaDeleteCheckInfo(pTq, msg) < 0) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

440
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
441
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
442
  tDecodeSMqRebVgReq(msg, &req);
L
Liu Jicong 已提交
443

444 445 446
  SVnode* pVnode = pTq->pVnode;
  int32_t vgId = TD_VID(pVnode);

447
  tqDebug("vgId:%d, tq process sub req:%s, Id:0x%" PRIx64 " -> Id:0x%" PRIx64, pVnode->config.vgId, req.subKey,
448
          req.oldConsumerId, req.newConsumerId);
L
Liu Jicong 已提交
449

450
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
451
  if (pHandle == NULL) {
L
Liu Jicong 已提交
452
    if (req.oldConsumerId != -1) {
453
      tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId:0x%" PRIx64,
454
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
455
    }
456

L
Liu Jicong 已提交
457
    if (req.newConsumerId == -1) {
458
      tqError("vgId:%d, tq invalid re-balance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
459
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
460 461
      return 0;
    }
462

L
Liu Jicong 已提交
463 464
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
465

H
Haojun Liao 已提交
466
    uint64_t oldConsumerId = pHandle->consumerId;
L
Liu Jicong 已提交
467 468 469
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
470

L
Liu Jicong 已提交
471
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
472
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
473

474
    // TODO version should be assigned and refed during preprocess
475
    SWalRef* pRef = walRefCommittedVer(pVnode->pWal);
476
    if (pRef == NULL) {
H
Haojun Liao 已提交
477
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
478
      return -1;
479
    }
H
Haojun Liao 已提交
480

481 482
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
483

484
    SReadHandle handle = {
485
        .meta = pVnode->pMeta, .vnode = pVnode, .initTableReader = true, .initTqReader = true, .version = ver};
wmmhello's avatar
wmmhello 已提交
486
    pHandle->snapshotVer = ver;
487

L
Liu Jicong 已提交
488
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
489
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
490
      req.qmsg = NULL;
491

X
Xiaoyu Wang 已提交
492 493
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, vgId,
                                                          &pHandle->execHandle.numOfCols, req.newConsumerId);
L
Liu Jicong 已提交
494
      void* scanner = NULL;
495
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
496
      pHandle->execHandle.pTqReader = qExtractReaderFromStreamScanner(scanner);
L
Liu Jicong 已提交
497
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
498
      pHandle->pWalReader = walOpenReader(pVnode->pWal, NULL);
499
      pHandle->execHandle.pTqReader = tqOpenReader(pVnode);
500

L
Liu Jicong 已提交
501
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
502
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
503 504
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
505

506
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, vgId, NULL, req.newConsumerId);
L
Liu Jicong 已提交
507
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
508
      pHandle->pWalReader = walOpenReader(pVnode->pWal, NULL);
wmmhello's avatar
wmmhello 已提交
509 510
      pHandle->execHandle.execTb.suid = req.suid;

L
Liu Jicong 已提交
511
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
512 513
      vnodeGetCtbIdList(pVnode, req.suid, tbUidList);
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
514 515
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
516
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, vgId, i, tbUid);
L
Liu Jicong 已提交
517
      }
518 519
      pHandle->execHandle.pTqReader = tqOpenReader(pVnode);
      tqReaderSetTbUidList(pHandle->execHandle.pTqReader, tbUidList);
L
Liu Jicong 已提交
520
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
521

L
Liu Jicong 已提交
522 523
      buildSnapContext(handle.meta, handle.version, req.suid, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
524
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, vgId, NULL, req.newConsumerId);
L
Liu Jicong 已提交
525
    }
H
Haojun Liao 已提交
526

527
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
528 529
    tqDebug("try to persist handle %s consumer:0x%" PRIx64 " , old consumer:0x%" PRIx64, req.subKey,
            pHandle->consumerId, oldConsumerId);
L
Liu Jicong 已提交
530
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
H
Haojun Liao 已提交
531
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
532
      return -1;
L
Liu Jicong 已提交
533
    }
L
Liu Jicong 已提交
534
  } else {
535 536 537 538
    if (pHandle->consumerId == req.newConsumerId) {  // do nothing
      tqInfo("vgId:%d consumer:0x%" PRIx64 " remains, no switch occurs", req.vgId, req.newConsumerId);
      atomic_store_32(&pHandle->epoch, -1);
      atomic_add_fetch_32(&pHandle->epoch, 1);
H
Haojun Liao 已提交
539
      taosMemoryFree(req.qmsg);
540
      return tqMetaSaveHandle(pTq, req.subKey, pHandle);
541 542 543
    } else {
      tqInfo("vgId:%d switch consumer from Id:0x%" PRIx64 " to Id:0x%" PRIx64, req.vgId, pHandle->consumerId,
             req.newConsumerId);
544

545 546 547
      // kill executing task
      qTaskInfo_t pTaskInfo = pHandle->execHandle.task;
      if (pTaskInfo != NULL) {
548
        qKillTask(pTaskInfo, TSDB_CODE_SUCCESS);
549 550
      }

551 552
      taosWLockLatch(&pTq->lock);
      atomic_store_32(&pHandle->epoch, -1);
553

554
      // remove if it has been register in the push manager, and return one empty block to consumer
555
//      tqUnregisterPushHandle(pTq, req.subKey, (int32_t)strlen(req.subKey), pHandle->consumerId, true);
556 557
      taosHashRemove(pTq->pPushMgr, &pHandle->consumerId, sizeof(int64_t));

558 559 560 561 562
      if(pHandle->msg != NULL) {
        rpcFreeCont(pHandle->msg->pCont);
        taosMemoryFree(pHandle->msg);
        pHandle->msg = NULL;
      }
563 564
      atomic_store_64(&pHandle->consumerId, req.newConsumerId);
      atomic_add_fetch_32(&pHandle->epoch, 1);
565

566
      if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
567 568 569
        qStreamCloseTsdbReader(pTaskInfo);
      }

570 571 572 573 574
      taosWUnLockLatch(&pTq->lock);
      if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
        taosMemoryFree(req.qmsg);
        return -1;
      }
L
Liu Jicong 已提交
575
    }
L
Liu Jicong 已提交
576
  }
L
Liu Jicong 已提交
577

H
Haojun Liao 已提交
578
  taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
579
  return 0;
L
Liu Jicong 已提交
580
}
581

582
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
583
  int32_t vgId = TD_VID(pTq->pVnode);
584
  pTask->id.idStr = createStreamTaskIdStr(pTask->id.streamId, pTask->id.taskId);
L
Liu Jicong 已提交
585
  pTask->refCnt = 1;
586
  pTask->status.schedStatus = TASK_SCHED_STATUS__INACTIVE;
L
Liu Jicong 已提交
587 588
  pTask->inputQueue = streamQueueOpen();
  pTask->outputQueue = streamQueueOpen();
L
Liu Jicong 已提交
589 590

  if (pTask->inputQueue == NULL || pTask->outputQueue == NULL) {
L
Liu Jicong 已提交
591
    return -1;
L
Liu Jicong 已提交
592 593
  }

L
Liu Jicong 已提交
594 595
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;
596
  pTask->pMsgCb = &pTq->pVnode->msgCb;
597
  pTask->pMeta = pTq->pStreamMeta;
598
  pTask->chkInfo.version = ver;
599
  pTask->chkInfo.currentVer = ver;
600

601
  // expand executor
602
  if (pTask->fillHistory) {
603
    pTask->status.taskStatus = TASK_STATUS__WAIT_DOWNSTREAM;
604
  } else {
605
    pTask->status.taskStatus = TASK_STATUS__RESTORE;
606 607
  }

608
  if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
609
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
610 611 612 613
    if (pTask->pState == NULL) {
      return -1;
    }

614
    SReadHandle handle = {
615
        .meta = pTq->pVnode->pMeta, .vnode = pTq->pVnode, .initTqReader = 1, .pStateBackend = pTask->pState};
616

617 618
    pTask->exec.pExecutor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle, vgId);
    if (pTask->exec.pExecutor == NULL) {
L
Liu Jicong 已提交
619 620
      return -1;
    }
621

622
  } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
623
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
624 625 626
    if (pTask->pState == NULL) {
      return -1;
    }
627

628 629 630 631 632
    int32_t numOfVgroups = (int32_t)taosArrayGetSize(pTask->childEpInfo);
    SReadHandle mgHandle = { .vnode = NULL, .numOfVgroups = numOfVgroups, .pStateBackend = pTask->pState};

    pTask->exec.pExecutor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &mgHandle, vgId);
    if (pTask->exec.pExecutor == NULL) {
L
Liu Jicong 已提交
633 634
      return -1;
    }
L
Liu Jicong 已提交
635
  }
L
Liu Jicong 已提交
636 637

  // sink
L
Liu Jicong 已提交
638
  /*pTask->ahandle = pTq->pVnode;*/
639
  if (pTask->outputType == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
640
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
641
    pTask->smaSink.smaSink = smaHandleRes;
642
  } else if (pTask->outputType == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
643
    pTask->tbSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
644
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline2;
L
Liu Jicong 已提交
645

X
Xiaoyu Wang 已提交
646
    int32_t   ver1 = 1;
5
54liuyao 已提交
647
    SMetaInfo info = {0};
dengyihao's avatar
dengyihao 已提交
648
    int32_t   code = metaGetInfo(pTq->pVnode->pMeta, pTask->tbSink.stbUid, &info, NULL);
5
54liuyao 已提交
649
    if (code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
650
      ver1 = info.skmVer;
5
54liuyao 已提交
651
    }
L
Liu Jicong 已提交
652

653 654
    SSchemaWrapper* pschemaWrapper = pTask->tbSink.pSchemaWrapper;
    pTask->tbSink.pTSchema = tBuildTSchema(pschemaWrapper->pSchema, pschemaWrapper->nCols, ver1);
wmmhello's avatar
wmmhello 已提交
655
    if(pTask->tbSink.pTSchema == NULL) {
wmmhello's avatar
wmmhello 已提交
656
      return -1;
wmmhello's avatar
wmmhello 已提交
657
    }
L
Liu Jicong 已提交
658
  }
659

660
  if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
661
    pTask->exec.pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
662 663
  }

664
  streamSetupTrigger(pTask);
665
  tqInfo("vgId:%d expand stream task, s-task:%s, checkpoint ver:%" PRId64 " child id:%d, level:%d", vgId, pTask->id.idStr,
666
         pTask->chkInfo.version, pTask->selfChildId, pTask->taskLevel);
667 668 669

  // next valid version will add one
  pTask->chkInfo.version += 1;
L
Liu Jicong 已提交
670
  return 0;
L
Liu Jicong 已提交
671
}
L
Liu Jicong 已提交
672

673 674 675 676 677 678
int32_t tqProcessStreamTaskCheckReq(STQ* pTq, SRpcMsg* pMsg) {
  char*               msgStr = pMsg->pCont;
  char*               msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t             msgLen = pMsg->contLen - sizeof(SMsgHead);
  SStreamTaskCheckReq req;
  SDecoder            decoder;
X
Xiaoyu Wang 已提交
679
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
680 681 682 683 684 685 686 687 688 689 690 691
  tDecodeSStreamTaskCheckReq(&decoder, &req);
  tDecoderClear(&decoder);
  int32_t             taskId = req.downstreamTaskId;
  SStreamTaskCheckRsp rsp = {
      .reqId = req.reqId,
      .streamId = req.streamId,
      .childId = req.childId,
      .downstreamNodeId = req.downstreamNodeId,
      .downstreamTaskId = req.downstreamTaskId,
      .upstreamNodeId = req.upstreamNodeId,
      .upstreamTaskId = req.upstreamTaskId,
  };
692

L
Liu Jicong 已提交
693
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
694 695 696 697 698 699 700 701
  if (pTask) {
    rsp.status = (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__NORMAL) ? 1 : 0;
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);

    tqDebug("tq recv task check req(reqId:0x%" PRIx64
            ") %d at node %d task status:%d, check req from task %d at node %d, rsp status %d",
            rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, pTask->status.taskStatus, rsp.upstreamTaskId,
            rsp.upstreamNodeId, rsp.status);
702 703
  } else {
    rsp.status = 0;
704 705 706 707
    tqDebug("tq recv task check(taskId:%d not built yet) req(reqId:0x%" PRIx64
            ") %d at node %d, check req from task %d at node %d, rsp status %d",
            taskId, rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.upstreamTaskId, rsp.upstreamNodeId,
            rsp.status);
708 709 710 711 712 713 714
  }

  SEncoder encoder;
  int32_t  code;
  int32_t  len;
  tEncodeSize(tEncodeSStreamTaskCheckRsp, &rsp, len, code);
  if (code < 0) {
L
Liu Jicong 已提交
715
    tqError("unable to encode rsp %d", __LINE__);
L
Liu Jicong 已提交
716
    return -1;
717
  }
L
Liu Jicong 已提交
718

719 720 721 722 723 724 725 726
  void* buf = rpcMallocCont(sizeof(SMsgHead) + len);
  ((SMsgHead*)buf)->vgId = htonl(req.upstreamNodeId);

  void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
  tEncoderInit(&encoder, (uint8_t*)abuf, len);
  tEncodeSStreamTaskCheckRsp(&encoder, &rsp);
  tEncoderClear(&encoder);

727
  SRpcMsg rspMsg = { .code = 0, .pCont = buf, .contLen = sizeof(SMsgHead) + len, .info = pMsg->info };
728 729 730 731
  tmsgSendRsp(&rspMsg);
  return 0;
}

732
int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
733 734 735 736 737 738 739 740 741 742 743
  int32_t             code;
  SStreamTaskCheckRsp rsp;

  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
  code = tDecodeSStreamTaskCheckRsp(&decoder, &rsp);
  if (code < 0) {
    tDecoderClear(&decoder);
    return -1;
  }

744
  tDecoderClear(&decoder);
745
  tqDebug("tq recv task check rsp(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d",
746 747
          rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status);

L
Liu Jicong 已提交
748
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId);
749 750 751 752
  if (pTask == NULL) {
    return -1;
  }

753
  code = streamProcessTaskCheckRsp(pTask, &rsp, sversion);
L
Liu Jicong 已提交
754 755
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
756 757
}

758
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
759 760 761 762 763
  int32_t code;
#if 0
  code = streamMetaAddSerializedTask(pTq->pStreamMeta, version, msg, msgLen);
  if (code < 0) return code;
#endif
5
54liuyao 已提交
764 765 766
  if (tsDisableStream) {
    return 0;
  }
767 768 769 770 771 772

  // 1.deserialize msg and build task
  SStreamTask* pTask = taosMemoryCalloc(1, sizeof(SStreamTask));
  if (pTask == NULL) {
    return -1;
  }
773

774 775
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
776
  code = tDecodeStreamTask(&decoder, pTask);
777 778 779 780 781
  if (code < 0) {
    tDecoderClear(&decoder);
    taosMemoryFree(pTask);
    return -1;
  }
782

783 784
  tDecoderClear(&decoder);

785
  // 2.save task, use the newest commit version as the initial start version of stream task.
786
  code = streamMetaAddDeployedTask(pTq->pStreamMeta, sversion, pTask);
787
  if (code < 0) {
788 789
    tqError("vgId:%d failed to add s-task:%s, total:%d", TD_VID(pTq->pVnode), pTask->id.idStr,
            streamMetaGetNumOfTasks(pTq->pStreamMeta));
790 791 792 793 794
    return -1;
  }

  // 3.go through recover steps to fill history
  if (pTask->fillHistory) {
795
    streamTaskCheckDownstream(pTask, sversion);
796 797
  }

798 799
  tqDebug("vgId:%d s-task:%s is deployed and add meta from mnd, status:%d, total:%d", TD_VID(pTq->pVnode),
          pTask->id.idStr, pTask->status.taskStatus, streamMetaGetNumOfTasks(pTq->pStreamMeta));
800 801 802
  return 0;
}

L
Liu Jicong 已提交
803 804 805 806 807
int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) {
  int32_t code;
  char*   msg = pMsg->pCont;
  int32_t msgLen = pMsg->contLen;

808
  SStreamRecoverStep1Req* pReq = (SStreamRecoverStep1Req*)msg;
L
Liu Jicong 已提交
809
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
810 811 812 813 814
  if (pTask == NULL) {
    return -1;
  }

  // check param
815
  int64_t fillVer1 = pTask->chkInfo.version;
816
  if (fillVer1 <= 0) {
L
Liu Jicong 已提交
817
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
818 819 820 821 822 823
    return -1;
  }

  // do recovery step 1
  streamSourceRecoverScanStep1(pTask);

824
  if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__DROPPING) {
L
Liu Jicong 已提交
825 826 827 828
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

829 830 831 832
  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
833
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
834 835 836
    return -1;
  }

L
Liu Jicong 已提交
837
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
838

839
  if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__DROPPING) {
L
Liu Jicong 已提交
840 841 842
    return 0;
  }

843
  // serialize msg
L
Liu Jicong 已提交
844 845 846 847 848 849 850 851
  int32_t len = sizeof(SStreamRecoverStep1Req);

  void* serializedReq = rpcMallocCont(len);
  if (serializedReq == NULL) {
    return -1;
  }

  memcpy(serializedReq, &req, len);
852 853 854 855 856

  // dispatch msg
  SRpcMsg rpcMsg = {
      .code = 0,
      .contLen = len,
L
Liu Jicong 已提交
857
      .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE,
L
Liu Jicong 已提交
858
      .pCont = serializedReq,
859 860 861 862 863 864 865
  };

  tmsgPutToQueue(&pTq->pVnode->msgCb, WRITE_QUEUE, &rpcMsg);

  return 0;
}

866
int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
867 868
  int32_t                 code;
  SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg;
L
Liu Jicong 已提交
869
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
870 871 872 873 874
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
875
  code = streamSourceRecoverScanStep2(pTask, sversion);
876
  if (code < 0) {
L
Liu Jicong 已提交
877
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
878 879 880
    return -1;
  }

881
  if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__DROPPING) {
L
Liu Jicong 已提交
882 883 884 885
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

886 887 888
  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
889
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
890 891 892 893 894 895
    return -1;
  }

  // set status normal
  code = streamSetStatusNormal(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
896
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
897 898 899 900 901 902
    return -1;
  }

  // dispatch recover finish req to all related downstream task
  code = streamDispatchRecoverFinishReq(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
903
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
904 905 906
    return -1;
  }

L
Liu Jicong 已提交
907 908 909
  atomic_store_8(&pTask->fillHistory, 0);
  streamMetaSaveTask(pTq->pStreamMeta, pTask);

L
Liu Jicong 已提交
910 911
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);

912 913 914
  return 0;
}

L
Liu Jicong 已提交
915 916 917
int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
918 919

  // deserialize
920 921 922
  SStreamRecoverFinishReq req;

  SDecoder decoder;
X
Xiaoyu Wang 已提交
923
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
924 925 926
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

927
  // find task
L
Liu Jicong 已提交
928
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
929 930 931
  if (pTask == NULL) {
    return -1;
  }
932
  // do process request
933
  if (streamProcessRecoverFinishReq(pTask, req.childId) < 0) {
L
Liu Jicong 已提交
934
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
935 936 937
    return -1;
  }

L
Liu Jicong 已提交
938
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
939
  return 0;
L
Liu Jicong 已提交
940
}
L
Liu Jicong 已提交
941

L
Liu Jicong 已提交
942 943 944 945 946
int32_t tqProcessTaskRecoverFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}

L
Liu Jicong 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
int32_t tqProcessDelReq(STQ* pTq, void* pReq, int32_t len, int64_t ver) {
  bool        failed = false;
  SDecoder*   pCoder = &(SDecoder){0};
  SDeleteRes* pRes = &(SDeleteRes){0};

  pRes->uidList = taosArrayInit(0, sizeof(tb_uid_t));
  if (pRes->uidList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    failed = true;
  }

  tDecoderInit(pCoder, pReq, len);
  tDecodeDeleteRes(pCoder, pRes);
  tDecoderClear(pCoder);

  int32_t sz = taosArrayGetSize(pRes->uidList);
L
Liu Jicong 已提交
963
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
964 965 966 967 968 969 970 971 972 973 974
    taosArrayDestroy(pRes->uidList);
    return 0;
  }
  SSDataBlock* pDelBlock = createSpecialDataBlock(STREAM_DELETE_DATA);
  blockDataEnsureCapacity(pDelBlock, sz);
  pDelBlock->info.rows = sz;
  pDelBlock->info.version = ver;

  for (int32_t i = 0; i < sz; i++) {
    // start key column
    SColumnInfoData* pStartCol = taosArrayGet(pDelBlock->pDataBlock, START_TS_COLUMN_INDEX);
975
    colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
L
Liu Jicong 已提交
976
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
977
    colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false);
L
Liu Jicong 已提交
978 979 980
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
981
    colDataSetVal(pUidCol, i, (const char*)pUid, false);
L
Liu Jicong 已提交
982

983 984 985
    colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, GROUPID_COLUMN_INDEX), i);
    colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), i);
    colDataSetNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), i);
L
Liu Jicong 已提交
986 987
  }

L
Liu Jicong 已提交
988 989
  taosArrayDestroy(pRes->uidList);

L
Liu Jicong 已提交
990 991 992
  int32_t* pRef = taosMemoryMalloc(sizeof(int32_t));
  *pRef = 1;

993 994
  taosWLockLatch(&pTq->pStreamMeta->lock);

L
Liu Jicong 已提交
995 996 997
  void* pIter = NULL;
  while (1) {
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
998 999 1000 1001
    if (pIter == NULL) {
      break;
    }

L
Liu Jicong 已提交
1002
    SStreamTask* pTask = *(SStreamTask**)pIter;
1003 1004 1005
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) {
      continue;
    }
L
Liu Jicong 已提交
1006

1007
    qDebug("s-task:%s delete req enqueue, ver: %" PRId64, pTask->id.idStr, ver);
L
Liu Jicong 已提交
1008

L
Liu Jicong 已提交
1009
    if (!failed) {
S
Shengliang Guan 已提交
1010
      SStreamRefDataBlock* pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1011 1012 1013 1014 1015
      pRefBlock->type = STREAM_INPUT__REF_DATA_BLOCK;
      pRefBlock->pBlock = pDelBlock;
      pRefBlock->dataRef = pRef;
      atomic_add_fetch_32(pRefBlock->dataRef, 1);

1016
      if (tAppendDataToInputQueue(pTask, (SStreamQueueItem*)pRefBlock) < 0) {
L
Liu Jicong 已提交
1017
        atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1018
        taosFreeQitem(pRefBlock);
L
Liu Jicong 已提交
1019 1020
        continue;
      }
L
Liu Jicong 已提交
1021

L
Liu Jicong 已提交
1022
      if (streamSchedExec(pTask) < 0) {
1023
        qError("s-task:%s stream task launch failed", pTask->id.idStr);
L
Liu Jicong 已提交
1024 1025
        continue;
      }
L
Liu Jicong 已提交
1026

L
Liu Jicong 已提交
1027 1028 1029 1030
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1031

1032 1033
  taosWUnLockLatch(&pTq->pStreamMeta->lock);

L
Liu Jicong 已提交
1034 1035
  int32_t ref = atomic_sub_fetch_32(pRef, 1);
  if (ref == 0) {
L
Liu Jicong 已提交
1036
    blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1037 1038 1039 1040
    taosMemoryFree(pRef);
  }

#if 0
S
Shengliang Guan 已提交
1041
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1042 1043 1044 1045 1046 1047 1048 1049
    pStreamBlock->type = STREAM_INPUT__DATA_BLOCK;
    pStreamBlock->blocks = taosArrayInit(0, sizeof(SSDataBlock));
    SSDataBlock block = {0};
    assignOneDataBlock(&block, pDelBlock);
    block.info.type = STREAM_DELETE_DATA;
    taosArrayPush(pStreamBlock->blocks, &block);

    if (!failed) {
1050
      if (tAppendDataToInputQueue(pTask, (SStreamQueueItem*)pStreamBlock) < 0) {
1051
        qError("stream task input del failed, task id %d", pTask->id.taskId);
L
Liu Jicong 已提交
1052 1053 1054 1055
        continue;
      }

      if (streamSchedExec(pTask) < 0) {
1056
        qError("stream task launch failed, task id %d", pTask->id.taskId);
L
Liu Jicong 已提交
1057 1058 1059 1060 1061 1062
        continue;
      }
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1063
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1064
#endif
L
Liu Jicong 已提交
1065 1066 1067
  return 0;
}

1068 1069 1070 1071
int32_t tqProcessSubmitReqForSubscribe(STQ* pTq) {
  int32_t vgId = TD_VID(pTq->pVnode);

  taosWLockLatch(&pTq->lock);
1072 1073 1074
  void *pIter = taosHashIterate(pTq->pPushMgr, NULL);
  while(pIter){
    STqHandle* pHandle = *(STqHandle**)pIter;
1075
    tqDebug("vgId:%d start set submit for pHandle:%p", vgId, pHandle);
1076
    if(ASSERT(pHandle->msg != NULL)){
1077
      tqError("pHandle->msg should not be null");
1078 1079 1080 1081 1082 1083
      break;
    }else{
      SRpcMsg msg = {.msgType = TDMT_VND_TMQ_CONSUME, .pCont = pHandle->msg->pCont, .contLen = pHandle->msg->contLen, .info = pHandle->msg->info};
      tmsgPutToQueue(&pTq->pVnode->msgCb, QUERY_QUEUE, &msg);
      taosMemoryFree(pHandle->msg);
      pHandle->msg = NULL;
1084
    }
1085
    pIter = taosHashIterate(pTq->pPushMgr, pIter);
1086
  }
1087
  taosHashClear(pTq->pPushMgr);
1088 1089 1090 1091 1092 1093
  // unlock
  taosWUnLockLatch(&pTq->lock);

  return 0;
}

L
Liu Jicong 已提交
1094
int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) {
1095
#if 0
1096
  void* pIter = NULL;
1097
  SStreamDataSubmit2* pSubmit = streamDataSubmitNew(submit, STREAM_INPUT__DATA_SUBMIT);
L
Liu Jicong 已提交
1098
  if (pSubmit == NULL) {
L
Liu Jicong 已提交
1099
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1100
    tqError("failed to create data submit for stream since out of memory");
1101
    saveOffsetForAllTasks(pTq, submit.ver);
1102
    return -1;
L
Liu Jicong 已提交
1103 1104
  }

1105 1106
  SArray* pInputQueueFullTasks = taosArrayInit(4, POINTER_BYTES);

L
Liu Jicong 已提交
1107
  while (1) {
L
Liu Jicong 已提交
1108
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
1109 1110 1111 1112
    if (pIter == NULL) {
      break;
    }

1113
    SStreamTask* pTask = *(SStreamTask**)pIter;
1114 1115 1116 1117
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) {
      continue;
    }

1118
    if (pTask->status.taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->status.taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
1119
      tqDebug("stream task:%d skip push data, not ready for processing, status %d", pTask->id.taskId,
1120
              pTask->status.taskStatus);
L
Liu Jicong 已提交
1121 1122
      continue;
    }
L
Liu Jicong 已提交
1123

1124 1125 1126
    // check if offset value exists
    char key[128] = {0};
    createStreamTaskOffsetKey(key, pTask->id.streamId, pTask->id.taskId);
1127

1128 1129 1130 1131 1132 1133 1134 1135
    if (tInputQueueIsFull(pTask)) {
      STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, key);

      int64_t ver = submit.ver;
      if (pOffset == NULL) {
        doSaveTaskOffset(pTq->pOffsetStore, key, submit.ver);
      } else {
        ver = pOffset->val.version;
L
Liu Jicong 已提交
1136 1137
      }

1138 1139
      tqDebug("s-task:%s input queue is full, discard submit block, ver:%" PRId64, pTask->id.idStr, ver);
      taosArrayPush(pInputQueueFullTasks, &pTask);
1140 1141 1142 1143 1144
      continue;
    }

    // check if offset value exists
    STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, key);
1145
    ASSERT(pOffset == NULL);
1146

1147
    addSubmitBlockNLaunchTask(pTq->pOffsetStore, pTask, pSubmit, key, submit.ver);
L
Liu Jicong 已提交
1148 1149
  }

1150 1151
  streamDataSubmitDestroy(pSubmit);
  taosFreeQitem(pSubmit);
1152
#endif
L
Liu Jicong 已提交
1153

1154
  tqStartStreamTasks(pTq);
1155
  return 0;
L
Liu Jicong 已提交
1156 1157
}

L
Liu Jicong 已提交
1158 1159
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRunReq* pReq = pMsg->pCont;
1160 1161 1162 1163

  int32_t taskId = pReq->taskId;
  int32_t vgId = TD_VID(pTq->pVnode);

1164 1165
  if (taskId == WAL_READ_TASKS_ID) {  // all tasks are extracted submit data from the wal
    tqStreamTasksScanWal(pTq);
L
Liu Jicong 已提交
1166
    return 0;
1167
  }
1168

1169
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1170 1171 1172 1173 1174 1175 1176 1177
  if (pTask != NULL) {
    if (pTask->status.taskStatus == TASK_STATUS__NORMAL) {
      tqDebug("vgId:%d s-task:%s start to process run req", vgId, pTask->id.idStr);
      streamProcessRunReq(pTask);
    } else if (pTask->status.taskStatus == TASK_STATUS__RESTORE) {
      tqDebug("vgId:%d s-task:%s start to process block from wal, last chk point:%" PRId64, vgId,
              pTask->id.idStr, pTask->chkInfo.version);
      streamProcessRunReq(pTask);
1178
    } else {
1179
      tqDebug("vgId:%d s-task:%s ignore run req since not in ready state", vgId, pTask->id.idStr);
1180
    }
1181 1182 1183 1184 1185 1186 1187

    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    tqStartStreamTasks(pTq);
    return 0;
  } else {
    tqError("vgId:%d failed to found s-task, taskId:%d", vgId, taskId);
    return -1;
L
Liu Jicong 已提交
1188
  }
L
Liu Jicong 已提交
1189 1190
}

L
Liu Jicong 已提交
1191
int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg, bool exec) {
1192 1193 1194 1195 1196
  char*              msgStr = pMsg->pCont;
  char*              msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t            msgLen = pMsg->contLen - sizeof(SMsgHead);
  SStreamDispatchReq req;
  SDecoder           decoder;
L
Liu Jicong 已提交
1197
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1198
  tDecodeStreamDispatchReq(&decoder, &req);
L
Liu Jicong 已提交
1199

1200
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
L
Liu Jicong 已提交
1201
  if (pTask) {
1202
    SRpcMsg rsp = { .info = pMsg->info, .code = 0 };
L
Liu Jicong 已提交
1203
    streamProcessDispatchReq(pTask, &req, &rsp, exec);
L
Liu Jicong 已提交
1204
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1205
    return 0;
1206
  } else {
L
liuyao 已提交
1207
    tDeleteStreamDispatchReq(&req);
1208
    return -1;
L
Liu Jicong 已提交
1209
  }
L
Liu Jicong 已提交
1210 1211
}

L
Liu Jicong 已提交
1212 1213
int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
1214
  int32_t             taskId = ntohl(pRsp->upstreamTaskId);
L
Liu Jicong 已提交
1215
  SStreamTask*        pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1216
  tqDebug("recv dispatch rsp, code:%x", pMsg->code);
L
Liu Jicong 已提交
1217
  if (pTask) {
1218
    streamProcessDispatchRsp(pTask, pRsp, pMsg->code);
L
Liu Jicong 已提交
1219
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1220
    return 0;
1221 1222
  } else {
    return -1;
L
Liu Jicong 已提交
1223
  }
L
Liu Jicong 已提交
1224
}
L
Liu Jicong 已提交
1225

1226
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1227
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1228
  streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId);
L
Liu Jicong 已提交
1229
  return 0;
L
Liu Jicong 已提交
1230
}
L
Liu Jicong 已提交
1231 1232 1233 1234 1235 1236 1237

int32_t tqProcessTaskRetrieveReq(STQ* pTq, SRpcMsg* pMsg) {
  char*              msgStr = pMsg->pCont;
  char*              msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t            msgLen = pMsg->contLen - sizeof(SMsgHead);
  SStreamRetrieveReq req;
  SDecoder           decoder;
1238
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1239
  tDecodeStreamRetrieveReq(&decoder, &req);
L
Liu Jicong 已提交
1240
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1241
  int32_t      taskId = req.dstTaskId;
L
Liu Jicong 已提交
1242
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1243
  if (pTask) {
1244
    SRpcMsg rsp = { .info = pMsg->info, .code = 0 };
L
Liu Jicong 已提交
1245
    streamProcessRetrieveReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
1246
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1247
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1248
    return 0;
L
Liu Jicong 已提交
1249
  } else {
L
liuyao 已提交
1250
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1251
    return -1;
L
Liu Jicong 已提交
1252 1253 1254 1255 1256 1257 1258
  }
}

int32_t tqProcessTaskRetrieveRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}
L
Liu Jicong 已提交
1259

1260 1261 1262 1263 1264 1265
int32_t vnodeEnqueueStreamMsg(SVnode* pVnode, SRpcMsg* pMsg) {
  STQ*      pTq = pVnode->pTq;
  SMsgHead* msgStr = pMsg->pCont;
  char*     msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t   msgLen = pMsg->contLen - sizeof(SMsgHead);
  int32_t   code = 0;
L
Liu Jicong 已提交
1266 1267 1268

  SStreamDispatchReq req;
  SDecoder           decoder;
1269
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1270 1271
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1272
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1273 1274
    goto FAIL;
  }
L
Liu Jicong 已提交
1275
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1276

L
Liu Jicong 已提交
1277
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1278

L
Liu Jicong 已提交
1279
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1280
  if (pTask) {
1281
    SRpcMsg rsp = { .info = pMsg->info, .code = 0 };
L
Liu Jicong 已提交
1282
    streamProcessDispatchReq(pTask, &req, &rsp, false);
L
Liu Jicong 已提交
1283
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1284 1285
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
1286
    return 0;
5
54liuyao 已提交
1287 1288
  } else {
    tDeleteStreamDispatchReq(&req);
L
Liu Jicong 已提交
1289
  }
L
Liu Jicong 已提交
1290

1291 1292
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1293
FAIL:
1294 1295 1296 1297
  if (pMsg->info.handle == NULL) return -1;

  SMsgHead* pRspHead = rpcMallocCont(sizeof(SMsgHead) + sizeof(SStreamDispatchRsp));
  if (pRspHead == NULL) {
1298
    SRpcMsg rsp = { .code = TSDB_CODE_OUT_OF_MEMORY, .info = pMsg->info };
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    tqDebug("send dispatch error rsp, code: %x", code);
    tmsgSendRsp(&rsp);
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
    return -1;
  }

  pRspHead->vgId = htonl(req.upstreamNodeId);
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pRspHead, sizeof(SMsgHead));
  pRsp->streamId = htobe64(req.streamId);
  pRsp->upstreamTaskId = htonl(req.upstreamTaskId);
  pRsp->upstreamNodeId = htonl(req.upstreamNodeId);
  pRsp->downstreamNodeId = htonl(pVnode->config.vgId);
  pRsp->downstreamTaskId = htonl(req.taskId);
  pRsp->inputStatus = TASK_OUTPUT_STATUS__NORMAL;

L
Liu Jicong 已提交
1315
  SRpcMsg rsp = {
1316
      .code = code, .info = pMsg->info, .contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp), .pCont = pRspHead};
1317
  tqDebug("send dispatch error rsp, code: %x", code);
L
Liu Jicong 已提交
1318
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1319 1320
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1321
  return -1;
L
Liu Jicong 已提交
1322
}
L
Liu Jicong 已提交
1323

1324
int32_t tqCheckLogInWal(STQ* pTq, int64_t sversion) { return sversion <= pTq->walLogLastVer; }
1325

1326
int32_t tqStartStreamTasks(STQ* pTq) {
1327 1328
  int32_t vgId = TD_VID(pTq->pVnode);

1329 1330
  SStreamMeta* pMeta = pTq->pStreamMeta;
  taosWLockLatch(&pMeta->lock);
1331 1332 1333 1334 1335 1336 1337
  int32_t numOfTasks = taosHashGetSize(pTq->pStreamMeta->pTasks);
  if (numOfTasks == 0) {
    tqInfo("vgId:%d no stream tasks exists", vgId);
    taosWUnLockLatch(&pTq->pStreamMeta->lock);
    return 0;
  }

1338 1339 1340 1341 1342 1343 1344 1345
  pMeta->walScan += 1;

  if (pMeta->walScan > 1) {
    tqDebug("vgId:%d wal read task has been launched, remain scan times:%d", vgId, pMeta->walScan);
    taosWUnLockLatch(&pTq->pStreamMeta->lock);
    return 0;
  }

1346 1347 1348 1349
  SStreamTaskRunReq* pRunReq = rpcMallocCont(sizeof(SStreamTaskRunReq));
  if (pRunReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    tqError("vgId:%d failed restore stream tasks, code:%s", vgId, terrstr(terrno));
1350
    taosWUnLockLatch(&pTq->pStreamMeta->lock);
1351 1352 1353
    return -1;
  }

H
Haojun Liao 已提交
1354
  tqDebug("vgId:%d start wal scan stream tasks, tasks:%d", vgId, numOfTasks);
1355 1356
  pRunReq->head.vgId = vgId;
  pRunReq->streamId = 0;
1357
  pRunReq->taskId = WAL_READ_TASKS_ID;
1358 1359 1360

  SRpcMsg msg = {.msgType = TDMT_STREAM_TASK_RUN, .pCont = pRunReq, .contLen = sizeof(SStreamTaskRunReq)};
  tmsgPutToQueue(&pTq->pVnode->msgCb, STREAM_QUEUE, &msg);
1361
  taosWUnLockLatch(&pTq->pStreamMeta->lock);
1362 1363 1364

  return 0;
}