tq.c 44.0 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
static int32_t tqInitialize(STQ* pTq);
dengyihao's avatar
dengyihao 已提交
24

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

L
Liu Jicong 已提交
76
static void tqPushEntryFree(void* data) {
L
Liu Jicong 已提交
77
  STqPushEntry* p = *(void**)data;
D
dapan1121 已提交
78 79 80 81 82 83 84
  if (p->pDataRsp->head.mqMsgType == TMQ_MSG_TYPE__POLL_RSP) {
    tDeleteSMqDataRsp(p->pDataRsp);
  } else if (p->pDataRsp->head.mqMsgType == TMQ_MSG_TYPE__TAOSX_RSP) {
    tDeleteSTaosxRsp((STaosxRsp*)p->pDataRsp);
  }

  taosMemoryFree(p->pDataRsp);
L
Liu Jicong 已提交
85 86 87
  taosMemoryFree(p);
}

88 89 90 91 92
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 已提交
93
STQ* tqOpen(const char* path, SVnode* pVnode) {
94
  STQ* pTq = taosMemoryCalloc(1, sizeof(STQ));
L
Liu Jicong 已提交
95
  if (pTq == NULL) {
S
Shengliang Guan 已提交
96
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
97 98
    return NULL;
  }
99

100
  pTq->path = taosStrdup(path);
L
Liu Jicong 已提交
101
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
102
  pTq->walLogLastVer = pVnode->pWal->vers.lastVer;
103

104
  pTq->pHandle = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
105
  taosHashSetFreeFp(pTq->pHandle, destroyTqHandle);
106

107
  taosInitRWLatch(&pTq->lock);
L
Liu Jicong 已提交
108
  pTq->pPushMgr = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
L
Liu Jicong 已提交
109
  taosHashSetFreeFp(pTq->pPushMgr, tqPushEntryFree);
L
Liu Jicong 已提交
110

111
  pTq->pCheckInfo = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
112
  taosHashSetFreeFp(pTq->pCheckInfo, (FDelete)tDeleteSTqCheckInfo);
L
Liu Jicong 已提交
113

114
  tqInitialize(pTq);
115 116 117 118
  return pTq;
}

int32_t tqInitialize(STQ* pTq) {
L
Liu Jicong 已提交
119
  if (tqMetaOpen(pTq) < 0) {
120
    return -1;
121 122
  }

L
Liu Jicong 已提交
123 124
  pTq->pOffsetStore = tqOffsetOpen(pTq);
  if (pTq->pOffsetStore == NULL) {
125
    return -1;
126 127
  }

128
  pTq->pStreamMeta = streamMetaOpen(pTq->path, pTq, (FTaskExpand*)tqExpandTask, pTq->pVnode->config.vgId);
L
Liu Jicong 已提交
129
  if (pTq->pStreamMeta == NULL) {
130
    return -1;
L
Liu Jicong 已提交
131 132
  }

133 134
  // the version is kept in task's meta data
  // todo check if this version is required or not
135 136
  if (streamLoadTasks(pTq->pStreamMeta, walGetCommittedVer(pTq->pVnode->pWal)) < 0) {
    return -1;
L
Liu Jicong 已提交
137 138
  }

139
  return 0;
L
Liu Jicong 已提交
140
}
L
Liu Jicong 已提交
141

L
Liu Jicong 已提交
142
void tqClose(STQ* pTq) {
143 144
  if (pTq == NULL) {
    return;
H
Hongze Cheng 已提交
145
  }
146 147 148 149 150 151 152 153 154

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

H
Haojun Liao 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169
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);
170 171 172
      pTask->status.taskStatus = TASK_STATUS__STOP;

      int64_t st = taosGetTimestampMs();
H
Haojun Liao 已提交
173
      qKillTask(pTask->exec.pExecutor, TSDB_CODE_SUCCESS);
174 175
      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 已提交
176 177 178 179 180 181
    }

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

D
dapan1121 已提交
182 183
static int32_t doSendDataRsp(const SRpcHandleInfo* pRpcHandleInfo, const SMqDataRsp* pRsp, int32_t epoch,
                             int64_t consumerId, int32_t type) {
L
Liu Jicong 已提交
184 185
  int32_t len = 0;
  int32_t code = 0;
D
dapan1121 已提交
186 187 188 189 190 191

  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 已提交
192 193 194 195 196 197 198 199 200 201 202

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

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

D
dapan1121 已提交
203 204 205
  ((SMqRspHead*)buf)->mqMsgType = type;
  ((SMqRspHead*)buf)->epoch = epoch;
  ((SMqRspHead*)buf)->consumerId = consumerId;
L
Liu Jicong 已提交
206 207 208 209 210 211

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

  SEncoder encoder = {0};
  tEncoderInit(&encoder, abuf, len);

D
dapan1121 已提交
212 213 214
  if (type == TMQ_MSG_TYPE__POLL_RSP) {
    tEncodeSMqDataRsp(&encoder, pRsp);
  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
X
Xiaoyu Wang 已提交
215
    tEncodeSTaosxRsp(&encoder, (STaosxRsp*)pRsp);
dengyihao's avatar
dengyihao 已提交
216
  }
L
Liu Jicong 已提交
217

wmmhello's avatar
wmmhello 已提交
218
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
219 220

  SRpcMsg rsp = {
D
dapan1121 已提交
221
      .info = *pRpcHandleInfo,
L
Liu Jicong 已提交
222 223 224 225
      .pCont = buf,
      .contLen = tlen,
      .code = 0,
  };
L
Liu Jicong 已提交
226

L
Liu Jicong 已提交
227
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
228 229
  return 0;
}
L
Liu Jicong 已提交
230

D
dapan1121 已提交
231 232 233 234 235 236 237 238 239 240 241
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);

  char buf1[80] = {0};
  char buf2[80] = {0};
  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 已提交
242 243 244
  return 0;
}

D
dapan1121 已提交
245 246
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);
247

D
dapan1121 已提交
248 249 250 251
  char buf1[80] = {0};
  char buf2[80] = {0};
  tFormatOffset(buf1, 80, &pRsp->reqOffset);
  tFormatOffset(buf2, 80, &pRsp->rspOffset);
252

X
Xiaoyu Wang 已提交
253
  tqDebug("vgId:%d consumer:0x%" PRIx64 " (epoch %d) send rsp, block num:%d, req:%s, rsp:%s, reqId:0x%" PRIx64,
D
dapan1121 已提交
254
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2, pReq->reqId);
255 256 257 258

  return 0;
}

259
int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
260
  STqOffset offset = {0};
X
Xiaoyu Wang 已提交
261
  int32_t   vgId = TD_VID(pTq->pVnode);
262

X
Xiaoyu Wang 已提交
263 264
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
265 266 267
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
    return -1;
  }
268

269 270
  tDecoderClear(&decoder);

wmmhello's avatar
wmmhello 已提交
271
  if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA || offset.val.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
272
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:snapshot) uid:%" PRId64 ", ts:%" PRId64,
D
dapan1121 已提交
273
            offset.subKey, vgId, offset.val.uid, offset.val.ts);
L
Liu Jicong 已提交
274
  } else if (offset.val.type == TMQ_OFFSET__LOG) {
X
Xiaoyu Wang 已提交
275 276
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey, vgId,
            offset.val.version);
277
    if (offset.val.version + 1 == sversion) {
278 279
      offset.val.version += 1;
    }
280
  } else {
281 282
    tqError("invalid commit offset type:%d", offset.val.type);
    return -1;
283
  }
284 285 286 287

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

290
  // save the new offset value
291 292
  if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) {
    return -1;
293
  }
294 295

  if (offset.val.type == TMQ_OFFSET__LOG) {
296
    STqHandle* pHandle = taosHashGet(pTq->pHandle, offset.subKey, strlen(offset.subKey));
297 298
    if (pHandle && (walRefVer(pHandle->pRef, offset.val.version) < 0)) {
      return -1;
299 300 301
    }
  }

302 303 304
  return 0;
}

L
Liu Jicong 已提交
305
int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) {
L
Liu Jicong 已提交
306
  void* pIter = NULL;
307

L
Liu Jicong 已提交
308
  while (1) {
309
    pIter = taosHashIterate(pTq->pCheckInfo, pIter);
310 311 312 313
    if (pIter == NULL) {
      break;
    }

314
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
315

L
Liu Jicong 已提交
316 317
    if (pCheck->ntbUid == tbUid) {
      int32_t sz = taosArrayGetSize(pCheck->colIdList);
L
Liu Jicong 已提交
318
      for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
319 320
        int16_t forbidColId = *(int16_t*)taosArrayGet(pCheck->colIdList, i);
        if (forbidColId == colId) {
321
          taosHashCancelIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
322 323 324 325 326
          return -1;
        }
      }
    }
  }
327

L
Liu Jicong 已提交
328 329 330
  return 0;
}

D
dapan1121 已提交
331
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
X
Xiaoyu Wang 已提交
332
  SMqPollReq req = {0};
D
dapan1121 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
  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;
  }

  // 2. check re-balance status
353
  taosRLockLatch(&pTq->lock);
D
dapan1121 已提交
354 355 356 357
  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;
358
    taosRUnLockLatch(&pTq->lock);
D
dapan1121 已提交
359 360
    return -1;
  }
361
  taosRUnLockLatch(&pTq->lock);
D
dapan1121 已提交
362 363

  // 3. update the epoch value
364
  taosWLockLatch(&pTq->lock);
D
dapan1121 已提交
365 366
  int32_t savedEpoch = pHandle->epoch;
  if (savedEpoch < reqEpoch) {
X
Xiaoyu Wang 已提交
367 368
    tqDebug("tmq poll: consumer:0x%" PRIx64 " epoch update from %d to %d by poll req", consumerId, savedEpoch,
            reqEpoch);
D
dapan1121 已提交
369 370
    pHandle->epoch = reqEpoch;
  }
371
  taosWUnLockLatch(&pTq->lock);
D
dapan1121 已提交
372 373 374 375 376 377

  char buf[80];
  tFormatOffset(buf, 80, &reqOffset);
  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);

378
  return tqExtractDataForMq(pTq, pHandle, &req, pMsg);
D
dapan1121 已提交
379 380
}

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

L
Liu Jicong 已提交
384
  tqDebug("vgId:%d, tq process delete sub req %s", pTq->pVnode->config.vgId, pReq->subKey);
L
Liu Jicong 已提交
385

386
  taosWLockLatch(&pTq->lock);
L
Liu Jicong 已提交
387 388 389 390
  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);
  }
391
  taosWUnLockLatch(&pTq->lock);
L
Liu Jicong 已提交
392

L
Liu Jicong 已提交
393 394
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
X
Xiaoyu Wang 已提交
395
    // walCloseRef(pHandle->pWalReader->pWal, pHandle->pRef->refId);
L
Liu Jicong 已提交
396 397 398 399 400 401 402
    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 已提交
403
  }
404

L
Liu Jicong 已提交
405 406
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
407
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
408
  }
L
Liu Jicong 已提交
409

L
Liu Jicong 已提交
410
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
411
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
412
  }
L
Liu Jicong 已提交
413
  return 0;
L
Liu Jicong 已提交
414 415
}

416
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
417 418
  STqCheckInfo info = {0};
  SDecoder     decoder;
X
Xiaoyu Wang 已提交
419
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
420
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
421 422 423 424
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
425 426 427 428 429
  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 已提交
430 431 432 433 434 435
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

436
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
437 438 439 440 441 442 443 444 445 446 447
  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;
}

448
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
449
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
450
  tDecodeSMqRebVgReq(msg, &req);
L
Liu Jicong 已提交
451

D
dapan1121 已提交
452 453 454
  SVnode* pVnode = pTq->pVnode;
  int32_t vgId = TD_VID(pVnode);

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

458
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
459
  if (pHandle == NULL) {
L
Liu Jicong 已提交
460
    if (req.oldConsumerId != -1) {
461
      tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId:0x%" PRIx64,
462
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
463
    }
D
dapan1121 已提交
464

L
Liu Jicong 已提交
465
    if (req.newConsumerId == -1) {
466
      tqError("vgId:%d, tq invalid re-balance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
467
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
468 469
      return 0;
    }
D
dapan1121 已提交
470

L
Liu Jicong 已提交
471 472
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
473

H
Haojun Liao 已提交
474
    uint64_t oldConsumerId = pHandle->consumerId;
L
Liu Jicong 已提交
475 476 477
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
478

L
Liu Jicong 已提交
479
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
480
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
481

482
    // TODO version should be assigned and refed during preprocess
D
dapan1121 已提交
483
    SWalRef* pRef = walRefCommittedVer(pVnode->pWal);
484
    if (pRef == NULL) {
D
dapan1121 已提交
485
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
486
      return -1;
487
    }
D
dapan1121 已提交
488

489 490
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
491

492
    SReadHandle handle = {
493
        .meta = pVnode->pMeta, .vnode = pVnode, .initTableReader = true, .initTqReader = true, .version = ver};
wmmhello's avatar
wmmhello 已提交
494
    pHandle->snapshotVer = ver;
495

L
Liu Jicong 已提交
496
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
497
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
498
      req.qmsg = NULL;
499

X
Xiaoyu Wang 已提交
500 501
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, vgId,
                                                          &pHandle->execHandle.numOfCols, req.newConsumerId);
L
Liu Jicong 已提交
502
      void* scanner = NULL;
503
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
504
      pHandle->execHandle.pTqReader = qExtractReaderFromStreamScanner(scanner);
L
Liu Jicong 已提交
505
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
D
dapan1121 已提交
506
      pHandle->pWalReader = walOpenReader(pVnode->pWal, NULL);
507
      pHandle->execHandle.pTqReader = tqReaderOpen(pVnode);
D
dapan1121 已提交
508

L
Liu Jicong 已提交
509
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
510
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
511 512
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
513

514
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, vgId, NULL, req.newConsumerId);
L
Liu Jicong 已提交
515
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
D
dapan1121 已提交
516
      pHandle->pWalReader = walOpenReader(pVnode->pWal, NULL);
wmmhello's avatar
wmmhello 已提交
517 518
      pHandle->execHandle.execTb.suid = req.suid;

L
Liu Jicong 已提交
519
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
D
dapan1121 已提交
520 521
      vnodeGetCtbIdList(pVnode, req.suid, tbUidList);
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
522 523
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
D
dapan1121 已提交
524
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, vgId, i, tbUid);
L
Liu Jicong 已提交
525
      }
526
      pHandle->execHandle.pTqReader = tqReaderOpen(pVnode);
527
      tqReaderSetTbUidList(pHandle->execHandle.pTqReader, tbUidList);
L
Liu Jicong 已提交
528
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
529

L
Liu Jicong 已提交
530 531
      buildSnapContext(handle.meta, handle.version, req.suid, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
532
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, vgId, NULL, req.newConsumerId);
L
Liu Jicong 已提交
533
    }
H
Haojun Liao 已提交
534

535
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
dengyihao's avatar
dengyihao 已提交
536 537
    tqDebug("try to persist handle %s consumer:0x%" PRIx64 " , old consumer:0x%" PRIx64, req.subKey,
            pHandle->consumerId, oldConsumerId);
L
Liu Jicong 已提交
538
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
D
dapan1121 已提交
539
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
540
      return -1;
L
Liu Jicong 已提交
541
    }
L
Liu Jicong 已提交
542
  } else {
D
dapan1121 已提交
543 544 545 546 547 548
    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);
      taosMemoryFree(req.qmsg);
      return tqMetaSaveHandle(pTq, req.subKey, pHandle);
549 550 551
    } else {
      tqInfo("vgId:%d switch consumer from Id:0x%" PRIx64 " to Id:0x%" PRIx64, req.vgId, pHandle->consumerId,
             req.newConsumerId);
H
Haojun Liao 已提交
552

553 554 555
      // kill executing task
      qTaskInfo_t pTaskInfo = pHandle->execHandle.task;
      if (pTaskInfo != NULL) {
556
        qKillTask(pTaskInfo, TSDB_CODE_SUCCESS);
557
      }
D
dapan1121 已提交
558

559 560
      taosWLockLatch(&pTq->lock);
      atomic_store_32(&pHandle->epoch, -1);
D
dapan1121 已提交
561

562
      // remove if it has been register in the push manager, and return one empty block to consumer
563
      tqUnregisterPushHandle(pTq, req.subKey, (int32_t)strlen(req.subKey), pHandle->consumerId, true);
D
dapan1121 已提交
564

565 566
      atomic_store_64(&pHandle->consumerId, req.newConsumerId);
      atomic_add_fetch_32(&pHandle->epoch, 1);
D
dapan1121 已提交
567

568
      if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
569 570
        qStreamCloseTsdbReader(pTaskInfo);
      }
H
Haojun Liao 已提交
571

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

D
dapan1121 已提交
580
  taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
581
  return 0;
L
Liu Jicong 已提交
582
}
583

584
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
D
dapan1121 已提交
585
  int32_t vgId = TD_VID(pTq->pVnode);
586
  pTask->id.idStr = createStreamTaskIdStr(pTask->id.streamId, pTask->id.taskId);
L
Liu Jicong 已提交
587
  pTask->refCnt = 1;
588
  pTask->status.schedStatus = TASK_SCHED_STATUS__INACTIVE;
dengyihao's avatar
dengyihao 已提交
589 590
  pTask->inputQueue = streamQueueOpen(512 << 10);
  pTask->outputQueue = streamQueueOpen(512 << 10);
L
Liu Jicong 已提交
591 592

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

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

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

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

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

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

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

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

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

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

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

655 656
    SSchemaWrapper* pschemaWrapper = pTask->tbSink.pSchemaWrapper;
    pTask->tbSink.pTSchema = tBuildTSchema(pschemaWrapper->pSchema, pschemaWrapper->nCols, ver1);
657
    if (pTask->tbSink.pTSchema == NULL) {
D
dapan1121 已提交
658 659
      return -1;
    }
L
Liu Jicong 已提交
660
  }
661

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

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

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

675 676 677 678 679 680
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 已提交
681
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
682 683 684 685 686 687 688 689 690 691 692 693
  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,
  };
694

L
Liu Jicong 已提交
695
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
696 697 698 699 700 701 702 703
  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);
704 705
  } else {
    rsp.status = 0;
706 707 708 709
    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);
710 711 712 713 714 715 716
  }

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

721 722 723 724 725 726 727 728
  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);

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

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

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

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

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

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

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

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

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

785 786
  tDecoderClear(&decoder);

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

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

800 801
  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));
802 803 804
  return 0;
}

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

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

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

  // do recovery step 1
H
Haojun Liao 已提交
824 825
  tqDebug("s-task:%s start recover step 1 scan", pTask->id.idStr);
  int64_t st = taosGetTimestampMs();
826

H
Haojun Liao 已提交
827
  streamSourceRecoverScanStep1(pTask);
828
  if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__DROPPING) {
H
Haojun Liao 已提交
829 830 831
    double el = (taosGetTimestampMs() - st) / 1000.0;
    tqDebug("s-task:%s is dropped, abort recover in step1", pTask->id.idStr);

L
Liu Jicong 已提交
832 833 834 835
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

H
Haojun Liao 已提交
836 837 838
  double el = (taosGetTimestampMs() - st) / 1000.0;
  tqDebug("s-task:%s recover step 1 ended, elapsed time:%.2fs", pTask->id.idStr, el);

839 840 841 842
  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
843
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
844 845 846
    return -1;
  }

L
Liu Jicong 已提交
847
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
848
  if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__DROPPING) {
L
Liu Jicong 已提交
849 850 851
    return 0;
  }

852
  // serialize msg
L
Liu Jicong 已提交
853 854 855 856
  int32_t len = sizeof(SStreamRecoverStep1Req);

  void* serializedReq = rpcMallocCont(len);
  if (serializedReq == NULL) {
H
Haojun Liao 已提交
857
    tqError("s-task:%s failed to prepare the step2 stage, out of memory", pTask->id.idStr);
L
Liu Jicong 已提交
858 859 860 861
    return -1;
  }

  memcpy(serializedReq, &req, len);
862 863

  // dispatch msg
H
Haojun Liao 已提交
864
  tqDebug("s-task:%s start recover block stage(step 2)", pTask->id.idStr);
865

H
Haojun Liao 已提交
866 867
  SRpcMsg rpcMsg = {
      .code = 0, .contLen = len, .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE, .pCont = serializedReq};
868 869 870 871
  tmsgPutToQueue(&pTq->pVnode->msgCb, WRITE_QUEUE, &rpcMsg);
  return 0;
}

872
int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
H
Haojun Liao 已提交
873 874
  int32_t code = 0;

875
  SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg;
H
Haojun Liao 已提交
876 877

  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
878 879 880 881 882
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
883
  code = streamSourceRecoverScanStep2(pTask, sversion);
884
  if (code < 0) {
L
Liu Jicong 已提交
885
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
886 887 888
    return -1;
  }

889
  if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__DROPPING) {
L
Liu Jicong 已提交
890 891 892 893
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

894 895 896
  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
897
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
898 899 900 901 902 903
    return -1;
  }

  // set status normal
  code = streamSetStatusNormal(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
904
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
905 906 907 908 909 910
    return -1;
  }

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

L
Liu Jicong 已提交
915 916 917
  atomic_store_8(&pTask->fillHistory, 0);
  streamMetaSaveTask(pTq->pStreamMeta, pTask);

L
Liu Jicong 已提交
918
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
919 920 921
  return 0;
}

L
Liu Jicong 已提交
922 923 924
int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
925 926

  // deserialize
927 928 929
  SStreamRecoverFinishReq req;

  SDecoder decoder;
X
Xiaoyu Wang 已提交
930
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
931 932 933
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

934
  // find task
L
Liu Jicong 已提交
935
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
936 937 938
  if (pTask == NULL) {
    return -1;
  }
939
  // do process request
940
  if (streamProcessRecoverFinishReq(pTask, req.childId) < 0) {
L
Liu Jicong 已提交
941
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
942 943 944
    return -1;
  }

L
Liu Jicong 已提交
945
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
946
  return 0;
L
Liu Jicong 已提交
947
}
L
Liu Jicong 已提交
948

L
Liu Jicong 已提交
949 950 951 952 953
int32_t tqProcessTaskRecoverFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}

L
Liu Jicong 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
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 已提交
970
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
971 972 973 974 975 976 977 978 979 980 981
    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);
982
    colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
L
Liu Jicong 已提交
983
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
984
    colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false);
L
Liu Jicong 已提交
985 986 987
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
988
    colDataSetVal(pUidCol, i, (const char*)pUid, false);
L
Liu Jicong 已提交
989

990 991 992
    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 已提交
993 994
  }

L
Liu Jicong 已提交
995 996
  taosArrayDestroy(pRes->uidList);

L
Liu Jicong 已提交
997 998 999
  int32_t* pRef = taosMemoryMalloc(sizeof(int32_t));
  *pRef = 1;

1000 1001
  taosWLockLatch(&pTq->pStreamMeta->lock);

L
Liu Jicong 已提交
1002 1003 1004
  void* pIter = NULL;
  while (1) {
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
1005 1006 1007 1008
    if (pIter == NULL) {
      break;
    }

L
Liu Jicong 已提交
1009
    SStreamTask* pTask = *(SStreamTask**)pIter;
1010 1011 1012
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) {
      continue;
    }
L
Liu Jicong 已提交
1013

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

L
Liu Jicong 已提交
1016
    if (!failed) {
S
Shengliang Guan 已提交
1017
      SStreamRefDataBlock* pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1018 1019 1020 1021 1022
      pRefBlock->type = STREAM_INPUT__REF_DATA_BLOCK;
      pRefBlock->pBlock = pDelBlock;
      pRefBlock->dataRef = pRef;
      atomic_add_fetch_32(pRefBlock->dataRef, 1);

1023
      if (tAppendDataToInputQueue(pTask, (SStreamQueueItem*)pRefBlock) < 0) {
L
Liu Jicong 已提交
1024
        atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1025
        taosFreeQitem(pRefBlock);
L
Liu Jicong 已提交
1026 1027
        continue;
      }
L
Liu Jicong 已提交
1028

L
Liu Jicong 已提交
1029
      if (streamSchedExec(pTask) < 0) {
1030
        qError("s-task:%s stream task launch failed", pTask->id.idStr);
L
Liu Jicong 已提交
1031 1032
        continue;
      }
L
Liu Jicong 已提交
1033

L
Liu Jicong 已提交
1034 1035 1036 1037
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1038

1039 1040
  taosWUnLockLatch(&pTq->pStreamMeta->lock);

L
Liu Jicong 已提交
1041 1042
  int32_t ref = atomic_sub_fetch_32(pRef, 1);
  if (ref == 0) {
L
Liu Jicong 已提交
1043
    blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1044 1045 1046 1047
    taosMemoryFree(pRef);
  }

#if 0
S
Shengliang Guan 已提交
1048
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1049 1050 1051 1052 1053 1054 1055 1056
    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) {
1057
      if (tAppendDataToInputQueue(pTask, (SStreamQueueItem*)pStreamBlock) < 0) {
1058
        qError("stream task input del failed, task id %d", pTask->id.taskId);
L
Liu Jicong 已提交
1059 1060 1061 1062
        continue;
      }

      if (streamSchedExec(pTask) < 0) {
1063
        qError("stream task launch failed, task id %d", pTask->id.taskId);
L
Liu Jicong 已提交
1064 1065 1066 1067 1068 1069
        continue;
      }
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1070
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1071
#endif
L
Liu Jicong 已提交
1072 1073 1074
  return 0;
}

L
Liu Jicong 已提交
1075
int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) {
1076
#if 0
1077
  void* pIter = NULL;
1078
  SStreamDataSubmit2* pSubmit = streamDataSubmitNew(submit, STREAM_INPUT__DATA_SUBMIT);
L
Liu Jicong 已提交
1079
  if (pSubmit == NULL) {
L
Liu Jicong 已提交
1080
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1081
    tqError("failed to create data submit for stream since out of memory");
1082
    saveOffsetForAllTasks(pTq, submit.ver);
1083
    return -1;
L
Liu Jicong 已提交
1084 1085
  }

1086 1087
  SArray* pInputQueueFullTasks = taosArrayInit(4, POINTER_BYTES);

L
Liu Jicong 已提交
1088
  while (1) {
L
Liu Jicong 已提交
1089
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
1090 1091 1092 1093
    if (pIter == NULL) {
      break;
    }

1094
    SStreamTask* pTask = *(SStreamTask**)pIter;
1095
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) {
L
Liu Jicong 已提交
1096 1097
      continue;
    }
L
Liu Jicong 已提交
1098

1099
    if (pTask->status.taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->status.taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
1100
      tqDebug("stream task:%d skip push data, not ready for processing, status %d", pTask->id.taskId,
1101
              pTask->status.taskStatus);
L
Liu Jicong 已提交
1102 1103
      continue;
    }
L
Liu Jicong 已提交
1104

1105 1106 1107
    // check if offset value exists
    char key[128] = {0};
    createStreamTaskOffsetKey(key, pTask->id.streamId, pTask->id.taskId);
L
Liu Jicong 已提交
1108

1109 1110 1111 1112 1113 1114 1115 1116
    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 已提交
1117
      }
L
Liu Jicong 已提交
1118

1119 1120
      tqDebug("s-task:%s input queue is full, discard submit block, ver:%" PRId64, pTask->id.idStr, ver);
      taosArrayPush(pInputQueueFullTasks, &pTask);
1121
      continue;
L
Liu Jicong 已提交
1122 1123
    }

1124 1125
    // check if offset value exists
    STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, key);
1126
    ASSERT(pOffset == NULL);
1127

1128
    addSubmitBlockNLaunchTask(pTq->pOffsetStore, pTask, pSubmit, key, submit.ver);
L
Liu Jicong 已提交
1129
  }
L
Liu Jicong 已提交
1130

1131 1132
  streamDataSubmitDestroy(pSubmit);
  taosFreeQitem(pSubmit);
1133
#endif
L
Liu Jicong 已提交
1134

1135
  tqStartStreamTasks(pTq);
1136
  return 0;
L
Liu Jicong 已提交
1137 1138
}

L
Liu Jicong 已提交
1139 1140
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRunReq* pReq = pMsg->pCont;
1141 1142 1143 1144

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

1145 1146
  if (taskId == WAL_READ_TASKS_ID) {  // all tasks are extracted submit data from the wal
    tqStreamTasksScanWal(pTq);
L
Liu Jicong 已提交
1147
    return 0;
1148
  }
1149

1150
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1151 1152 1153 1154 1155
  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) {
1156 1157
      tqDebug("vgId:%d s-task:%s start to process block from wal, last chk point:%" PRId64, vgId, pTask->id.idStr,
              pTask->chkInfo.version);
1158
      streamProcessRunReq(pTask);
1159
    } else {
1160
      tqDebug("vgId:%d s-task:%s ignore run req since not in ready state", vgId, pTask->id.idStr);
1161
    }
1162

L
Liu Jicong 已提交
1163
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1164
    tqStartStreamTasks(pTq);
L
Liu Jicong 已提交
1165
    return 0;
1166
  } else {
1167
    tqError("vgId:%d failed to found s-task, taskId:%d", vgId, taskId);
1168
    return -1;
L
Liu Jicong 已提交
1169
  }
L
Liu Jicong 已提交
1170 1171
}

L
Liu Jicong 已提交
1172
int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg, bool exec) {
1173 1174 1175 1176 1177
  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 已提交
1178
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1179
  tDecodeStreamDispatchReq(&decoder, &req);
L
Liu Jicong 已提交
1180

1181
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
L
Liu Jicong 已提交
1182
  if (pTask) {
1183
    SRpcMsg rsp = {.info = pMsg->info, .code = 0};
L
Liu Jicong 已提交
1184
    streamProcessDispatchReq(pTask, &req, &rsp, exec);
L
Liu Jicong 已提交
1185
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1186
    return 0;
1187
  } else {
L
liuyao 已提交
1188
    tDeleteStreamDispatchReq(&req);
1189
    return -1;
L
Liu Jicong 已提交
1190
  }
L
Liu Jicong 已提交
1191 1192
}

L
Liu Jicong 已提交
1193 1194
int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
1195
  int32_t             taskId = ntohl(pRsp->upstreamTaskId);
L
Liu Jicong 已提交
1196
  SStreamTask*        pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1197
  tqDebug("recv dispatch rsp, code:%x", pMsg->code);
L
Liu Jicong 已提交
1198
  if (pTask) {
1199
    streamProcessDispatchRsp(pTask, pRsp, pMsg->code);
L
Liu Jicong 已提交
1200
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1201
    return 0;
1202 1203
  } else {
    return -1;
L
Liu Jicong 已提交
1204
  }
L
Liu Jicong 已提交
1205
}
L
Liu Jicong 已提交
1206

1207
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1208
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1209
  streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId);
L
Liu Jicong 已提交
1210
  return 0;
L
Liu Jicong 已提交
1211
}
L
Liu Jicong 已提交
1212

5
54liuyao 已提交
1213 1214
int32_t tqProcessTaskPauseReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
  SVPauseStreamTaskReq* pReq = (SVPauseStreamTaskReq*)msg;
L
liuyao 已提交
1215 1216 1217 1218 1219 1220
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
  if (pTask) {
    tqDebug("vgId:%d s-task:%s set pause flag", pTq->pStreamMeta->vgId, pTask->id.idStr);
    atomic_store_8(&pTask->status.taskStatus, TASK_STATUS__PAUSE);
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  }
5
54liuyao 已提交
1221 1222 1223 1224 1225
  return 0;
}

int32_t tqProcessTaskResumeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
  SVResumeStreamTaskReq* pReq = (SVResumeStreamTaskReq*)msg;
L
liuyao 已提交
1226 1227 1228
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
  if (pTask) {
    streamSetStatusNormal(pTask);
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

    // no lock needs to secure the access of the version
    if (pReq->igUntreated) {  // discard all the data  when the stream task is suspended.
      pTask->chkInfo.currentVer = sversion;
      tqDebug("vgId:%d s-task:%s resume to normal from the latest version:%" PRId64 ", vnode ver:%" PRId64, pTq->pStreamMeta->vgId,
              pTask->id.idStr, pTask->chkInfo.currentVer, sversion);
    } else {  // from the previous paused version and go on
      tqDebug("vgId:%d s-task:%s resume to normal from paused ver:%" PRId64 ", vnode ver:%" PRId64, pTq->pStreamMeta->vgId,
              pTask->id.idStr, pTask->chkInfo.currentVer, sversion);
    }

L
liuyao 已提交
1240
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
5
54liuyao 已提交
1241
    tqStartStreamTasks(pTq);
L
liuyao 已提交
1242
  }
1243

5
54liuyao 已提交
1244 1245 1246
  return 0;
}

L
Liu Jicong 已提交
1247 1248 1249 1250 1251 1252
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;
1253
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1254
  tDecodeStreamRetrieveReq(&decoder, &req);
L
Liu Jicong 已提交
1255
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1256
  int32_t      taskId = req.dstTaskId;
L
Liu Jicong 已提交
1257
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1258
  if (pTask) {
1259
    SRpcMsg rsp = {.info = pMsg->info, .code = 0};
L
Liu Jicong 已提交
1260
    streamProcessRetrieveReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
1261
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1262
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1263
    return 0;
L
Liu Jicong 已提交
1264
  } else {
L
liuyao 已提交
1265
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1266
    return -1;
L
Liu Jicong 已提交
1267 1268 1269 1270 1271 1272 1273
  }
}

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

1275 1276 1277 1278 1279 1280
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 已提交
1281 1282 1283

  SStreamDispatchReq req;
  SDecoder           decoder;
1284
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1285 1286
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1287
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1288 1289
    goto FAIL;
  }
L
Liu Jicong 已提交
1290
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1291

L
Liu Jicong 已提交
1292
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1293

L
Liu Jicong 已提交
1294
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1295
  if (pTask) {
1296
    SRpcMsg rsp = {.info = pMsg->info, .code = 0};
L
Liu Jicong 已提交
1297
    streamProcessDispatchReq(pTask, &req, &rsp, false);
L
Liu Jicong 已提交
1298
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1299 1300
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
1301
    return 0;
5
54liuyao 已提交
1302 1303
  } else {
    tDeleteStreamDispatchReq(&req);
L
Liu Jicong 已提交
1304
  }
L
Liu Jicong 已提交
1305

1306 1307
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1308
FAIL:
1309 1310 1311 1312
  if (pMsg->info.handle == NULL) return -1;

  SMsgHead* pRspHead = rpcMallocCont(sizeof(SMsgHead) + sizeof(SStreamDispatchRsp));
  if (pRspHead == NULL) {
1313
    SRpcMsg rsp = {.code = TSDB_CODE_OUT_OF_MEMORY, .info = pMsg->info};
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
    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 已提交
1330
  SRpcMsg rsp = {
1331
      .code = code, .info = pMsg->info, .contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp), .pCont = pRspHead};
1332
  tqDebug("send dispatch error rsp, code: %x", code);
L
Liu Jicong 已提交
1333
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1334 1335
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1336
  return -1;
L
Liu Jicong 已提交
1337
}
L
Liu Jicong 已提交
1338

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

1341
int32_t tqStartStreamTasks(STQ* pTq) {
1342 1343
  int32_t vgId = TD_VID(pTq->pVnode);

1344 1345
  SStreamMeta* pMeta = pTq->pStreamMeta;
  taosWLockLatch(&pMeta->lock);
1346 1347
  int32_t numOfTasks = taosHashGetSize(pTq->pStreamMeta->pTasks);
  if (numOfTasks == 0) {
1348
    tqInfo("vgId:%d no stream tasks exist", vgId);
1349 1350 1351 1352
    taosWUnLockLatch(&pTq->pStreamMeta->lock);
    return 0;
  }

1353 1354 1355 1356
  pMeta->walScan += 1;

  if (pMeta->walScan > 1) {
    tqDebug("vgId:%d wal read task has been launched, remain scan times:%d", vgId, pMeta->walScan);
H
Haojun Liao 已提交
1357
    taosWUnLockLatch(&pMeta->lock);
1358 1359 1360
    return 0;
  }

1361 1362 1363
  SStreamTaskRunReq* pRunReq = rpcMallocCont(sizeof(SStreamTaskRunReq));
  if (pRunReq == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
1364
    tqError("vgId:%d failed restore stream tasks, code:%s", vgId, terrstr());
1365
    taosWUnLockLatch(&pTq->pStreamMeta->lock);
1366 1367 1368
    return -1;
  }

H
Haojun Liao 已提交
1369
  tqDebug("vgId:%d start wal scan stream tasks, tasks:%d", vgId, numOfTasks);
1370 1371
  pRunReq->head.vgId = vgId;
  pRunReq->streamId = 0;
1372
  pRunReq->taskId = WAL_READ_TASKS_ID;
1373 1374 1375

  SRpcMsg msg = {.msgType = TDMT_STREAM_TASK_RUN, .pCont = pRunReq, .contLen = sizeof(SStreamTaskRunReq)};
  tmsgPutToQueue(&pTq->pVnode->msgCb, STREAM_QUEUE, &msg);
1376
  taosWUnLockLatch(&pTq->pStreamMeta->lock);
1377 1378 1379

  return 0;
}