tq.c 49.8 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

L
Liu Jicong 已提交
18
int32_t tqInit() {
L
Liu Jicong 已提交
19 20 21 22 23 24
  int8_t old;
  while (1) {
    old = atomic_val_compare_exchange_8(&tqMgmt.inited, 0, 2);
    if (old != 2) break;
  }

25 26 27 28 29 30
  if (old == 0) {
    tqMgmt.timer = taosTmrInit(10000, 100, 10000, "TQ");
    if (tqMgmt.timer == NULL) {
      atomic_store_8(&tqMgmt.inited, 0);
      return -1;
    }
31 32 33
    if (streamInit() < 0) {
      return -1;
    }
L
Liu Jicong 已提交
34
    atomic_store_8(&tqMgmt.inited, 1);
35
  }
36

L
Liu Jicong 已提交
37 38
  return 0;
}
L
Liu Jicong 已提交
39

40
void tqCleanUp() {
L
Liu Jicong 已提交
41 42 43 44 45 46 47 48
  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 已提交
49
    streamCleanUp();
L
Liu Jicong 已提交
50 51
    atomic_store_8(&tqMgmt.inited, 0);
  }
52
}
L
Liu Jicong 已提交
53

54
static void destroyTqHandle(void* data) {
55 56 57
  STqHandle* pData = (STqHandle*)data;
  qDestroyTask(pData->execHandle.task);
  if (pData->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
58
    taosMemoryFreeClear(pData->execHandle.execCol.qmsg);
59 60 61 62
  } else if (pData->execHandle.subType == TOPIC_SUB_TYPE__DB) {
    tqCloseReader(pData->execHandle.pExecReader);
    walCloseReader(pData->pWalReader);
    taosHashCleanup(pData->execHandle.execDb.pFilterOutTbUid);
L
Liu Jicong 已提交
63
  } else if (pData->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
64 65 66 67 68
    walCloseReader(pData->pWalReader);
    tqCloseReader(pData->execHandle.pExecReader);
  }
}

L
Liu Jicong 已提交
69
static void tqPushEntryFree(void* data) {
L
Liu Jicong 已提交
70
  STqPushEntry* p = *(void**)data;
H
Haojun Liao 已提交
71 72 73 74 75 76 77
  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 已提交
78 79 80
  taosMemoryFree(p);
}

L
Liu Jicong 已提交
81
STQ* tqOpen(const char* path, SVnode* pVnode) {
82
  STQ* pTq = taosMemoryCalloc(1, sizeof(STQ));
L
Liu Jicong 已提交
83
  if (pTq == NULL) {
S
Shengliang Guan 已提交
84
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
85 86
    return NULL;
  }
87
  pTq->path = taosStrdup(path);
L
Liu Jicong 已提交
88
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
89
  pTq->walLogLastVer = pVnode->pWal->vers.lastVer;
90

91
  pTq->pHandle = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
92
  taosHashSetFreeFp(pTq->pHandle, destroyTqHandle);
93

94
  taosInitRWLatch(&pTq->lock);
L
Liu Jicong 已提交
95
  pTq->pPushMgr = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
L
Liu Jicong 已提交
96
  taosHashSetFreeFp(pTq->pPushMgr, tqPushEntryFree);
L
Liu Jicong 已提交
97

98
  pTq->pCheckInfo = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
99
  taosHashSetFreeFp(pTq->pCheckInfo, (FDelete)tDeleteSTqCheckInfo);
L
Liu Jicong 已提交
100

L
Liu Jicong 已提交
101
  if (tqMetaOpen(pTq) < 0) {
L
Liu Jicong 已提交
102
    return NULL;
103 104
  }

L
Liu Jicong 已提交
105 106
  pTq->pOffsetStore = tqOffsetOpen(pTq);
  if (pTq->pOffsetStore == NULL) {
L
Liu Jicong 已提交
107
    return NULL;
108 109
  }

110
  pTq->pStreamMeta = streamMetaOpen(path, pTq, (FTaskExpand*)tqExpandTask, pTq->pVnode->config.vgId);
L
Liu Jicong 已提交
111
  if (pTq->pStreamMeta == NULL) {
L
Liu Jicong 已提交
112
    return NULL;
L
Liu Jicong 已提交
113 114
  }

L
Liu Jicong 已提交
115
  if (streamLoadTasks(pTq->pStreamMeta, walGetCommittedVer(pVnode->pWal)) < 0) {
L
Liu Jicong 已提交
116
    return NULL;
L
Liu Jicong 已提交
117 118
  }

L
Liu Jicong 已提交
119 120
  return pTq;
}
L
Liu Jicong 已提交
121

L
Liu Jicong 已提交
122
void tqClose(STQ* pTq) {
123 124
  if (pTq == NULL) {
    return;
H
Hongze Cheng 已提交
125
  }
126 127 128 129 130 131 132 133 134

  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 已提交
135
}
L
Liu Jicong 已提交
136

L
Liu Jicong 已提交
137
int32_t tqSendMetaPollRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqMetaRsp* pRsp) {
138 139 140 141 142 143 144
  int32_t len = 0;
  int32_t code = 0;
  tEncodeSize(tEncodeSMqMetaRsp, pRsp, len, code);
  if (code < 0) {
    return -1;
  }
  int32_t tlen = sizeof(SMqRspHead) + len;
L
Liu Jicong 已提交
145 146 147 148 149 150 151 152 153 154
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    return -1;
  }

  ((SMqRspHead*)buf)->mqMsgType = TMQ_MSG_TYPE__POLL_META_RSP;
  ((SMqRspHead*)buf)->epoch = pReq->epoch;
  ((SMqRspHead*)buf)->consumerId = pReq->consumerId;

  void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
155 156 157 158 159

  SEncoder encoder = {0};
  tEncoderInit(&encoder, abuf, len);
  tEncodeSMqMetaRsp(&encoder, pRsp);
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
160 161 162 163 164 165 166 167 168

  SRpcMsg resp = {
      .info = pMsg->info,
      .pCont = buf,
      .contLen = tlen,
      .code = 0,
  };
  tmsgSendRsp(&resp);

169
  tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) send rsp, res msg type %d, offset type:%d",
170
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->resMsgType, pRsp->rspOffset.type);
L
Liu Jicong 已提交
171 172 173 174

  return 0;
}

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

  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 已提交
185 186 187 188 189 190 191 192 193 194 195

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

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

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

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

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

  if (type == TMQ_MSG_TYPE__POLL_RSP) {
    tEncodeSMqDataRsp(&encoder, pRsp);
  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
    tEncodeSTaosxRsp(&encoder, (STaosxRsp*) pRsp);
  }

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

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

  tmsgSendRsp(&rsp);
  return 0;
}

H
Haojun Liao 已提交
224 225 226 227
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 已提交
228

wmmhello's avatar
wmmhello 已提交
229 230
  char buf1[80] = {0};
  char buf2[80] = {0};
H
Haojun Liao 已提交
231 232 233 234
  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 已提交
235 236 237
  return 0;
}

H
Haojun Liao 已提交
238 239
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);
240 241 242 243 244 245

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

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

249 250 251
  return 0;
}

252 253 254 255 256
static FORCE_INLINE 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;
}

257
int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
258
  STqOffset offset = {0};
H
Haojun Liao 已提交
259
  int32_t vgId = TD_VID(pTq->pVnode);
260

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

267 268
  tDecoderClear(&decoder);

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

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

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

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

300 301 302
  return 0;
}

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

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

312
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
313

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

L
Liu Jicong 已提交
326 327 328
  return 0;
}

L
Liu Jicong 已提交
329 330 331 332 333 334 335 336 337 338
static int32_t tqInitDataRsp(SMqDataRsp* pRsp, const SMqPollReq* pReq, int8_t subType) {
  pRsp->reqOffset = pReq->reqOffset;

  pRsp->blockData = taosArrayInit(0, sizeof(void*));
  pRsp->blockDataLen = taosArrayInit(0, sizeof(int32_t));

  if (pRsp->blockData == NULL || pRsp->blockDataLen == NULL) {
    return -1;
  }

L
Liu Jicong 已提交
339
  pRsp->withTbName = 0;
L
Liu Jicong 已提交
340
  pRsp->withSchema = false;
L
Liu Jicong 已提交
341 342 343
  return 0;
}

344 345 346 347 348 349 350 351 352 353 354 355 356
static int32_t tqInitTaosxRsp(STaosxRsp* pRsp, const SMqPollReq* pReq) {
  pRsp->reqOffset = pReq->reqOffset;

  pRsp->withTbName = 1;
  pRsp->withSchema = 1;
  pRsp->blockData = taosArrayInit(0, sizeof(void*));
  pRsp->blockDataLen = taosArrayInit(0, sizeof(int32_t));
  pRsp->blockTbName = taosArrayInit(0, sizeof(void*));
  pRsp->blockSchema = taosArrayInit(0, sizeof(void*));

  if (pRsp->blockData == NULL || pRsp->blockDataLen == NULL || pRsp->blockTbName == NULL || pRsp->blockSchema == NULL) {
    return -1;
  }
357

358 359 360
  return 0;
}

361 362 363 364 365
static int32_t extractResetOffsetVal(STqOffsetVal* pOffsetVal, STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest,
                                     SRpcMsg* pMsg, bool* pBlockReturned) {
  uint64_t     consumerId = pRequest->consumerId;
  STqOffsetVal reqOffset = pRequest->reqOffset;
  STqOffset*   pOffset = tqOffsetRead(pTq->pOffsetStore, pRequest->subKey);
H
Haojun Liao 已提交
366 367
  int32_t      vgId = TD_VID(pTq->pVnode);

368 369 370 371 372 373 374 375
  *pBlockReturned = false;

  // In this vnode, data has been polled by consumer for this topic, so let's continue from the last offset value.
  if (pOffset != NULL) {
    *pOffsetVal = pOffset->val;

    char formatBuf[80];
    tFormatOffset(formatBuf, 80, pOffsetVal);
376 377
    tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, existed offset found, offset reset to %s and continue. reqId:0x%"PRIx64,
            consumerId, pHandle->subKey, vgId, formatBuf, pRequest->reqId);
378 379 380 381 382
    return 0;
  } else {
    // no poll occurs in this vnode for this topic, let's seek to the right offset value.
    if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEAST) {
      if (pRequest->useSnapshot) {
H
Haojun Liao 已提交
383 384 385
        tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey:%s, vgId:%d, (earliest) set offset to be snapshot",
                consumerId, pHandle->subKey, vgId);

386 387 388 389 390 391 392 393 394 395 396
        if (pHandle->fetchMeta) {
          tqOffsetResetToMeta(pOffsetVal, 0);
        } else {
          tqOffsetResetToData(pOffsetVal, 0, 0);
        }
      } else {
        pHandle->pRef = walRefFirstVer(pTq->pVnode->pWal, pHandle->pRef);
        if (pHandle->pRef == NULL) {
          terrno = TSDB_CODE_OUT_OF_MEMORY;
          return -1;
        }
D
dapan1121 已提交
397

wmmhello's avatar
wmmhello 已提交
398
        // offset set to previous version when init
399 400 401 402 403 404 405 406
        tqOffsetResetToLog(pOffsetVal, pHandle->pRef->refVer - 1);
      }
    } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
      if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
        SMqDataRsp dataRsp = {0};
        tqInitDataRsp(&dataRsp, pRequest, pHandle->execHandle.subType);

        tqOffsetResetToLog(&dataRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
H
Haojun Liao 已提交
407 408
        tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, (latest) offset reset to %" PRId64, consumerId,
                pHandle->subKey, vgId, dataRsp.rspOffset.version);
H
Haojun Liao 已提交
409
        int32_t code = tqSendDataRsp(pTq, pMsg, pRequest, &dataRsp, TMQ_MSG_TYPE__POLL_RSP);
410 411 412 413 414 415 416 417
        tDeleteSMqDataRsp(&dataRsp);

        *pBlockReturned = true;
        return code;
      } else {
        STaosxRsp taosxRsp = {0};
        tqInitTaosxRsp(&taosxRsp, pRequest);
        tqOffsetResetToLog(&taosxRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
H
Haojun Liao 已提交
418
        int32_t code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
419
        tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
420

421 422 423 424
        *pBlockReturned = true;
        return code;
      }
    } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) {
H
Haojun Liao 已提交
425 426
      tqError("tmq poll: subkey:%s, no offset committed for consumer:0x%" PRIx64 " in vg %d, subkey %s, reset none failed",
              pHandle->subKey, consumerId, vgId, pRequest->subKey);
427 428 429
      terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
      return -1;
    }
L
Liu Jicong 已提交
430 431
  }

432 433
  return 0;
}
L
Liu Jicong 已提交
434

435 436 437 438 439 440 441 442 443 444 445 446 447 448
#define IS_OFFSET_RESET_TYPE(_t)  ((_t) < 0)

static int32_t extractDataAndRspForNormalSubscribe(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest,
                                                   SRpcMsg* pMsg, STqOffsetVal* pOffset) {
  uint64_t consumerId = pRequest->consumerId;
  int32_t  vgId = TD_VID(pTq->pVnode);

  SMqDataRsp dataRsp = {0};
  tqInitDataRsp(&dataRsp, pRequest, pHandle->execHandle.subType);

  // lock
  taosWLockLatch(&pTq->lock);

  qSetTaskId(pHandle->execHandle.task, consumerId, pRequest->reqId);
wmmhello's avatar
wmmhello 已提交
449
  int code = tqScanData(pTq, pHandle, &dataRsp, pOffset);
450
  if(code != 0) {
451
    goto end;
452
  }
453 454 455 456 457 458 459 460 461

  // till now, all data has been transferred to consumer, new data needs to push client once arrived.
  if (dataRsp.blockNum == 0 && dataRsp.reqOffset.type == TMQ_OFFSET__LOG &&
      dataRsp.reqOffset.version == dataRsp.rspOffset.version && pHandle->consumerId == pRequest->consumerId) {
    code = tqRegisterPushEntry(pTq, pHandle, pRequest, pMsg, &dataRsp, TMQ_MSG_TYPE__POLL_RSP);
    taosWUnLockLatch(&pTq->lock);
    return code;
  }

462

463 464 465 466
  code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&dataRsp, TMQ_MSG_TYPE__POLL_RSP);

  // NOTE: this pHandle->consumerId may have been changed already.

467 468 469 470 471 472 473 474 475
end:
  {
    char buf[80] = {0};
    tFormatOffset(buf, 80, &dataRsp.rspOffset);
    tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, rsp block:%d, rsp offset type:%s, reqId:0x%" PRIx64 " code:%d",
            consumerId, pHandle->subKey, vgId, dataRsp.blockNum, buf, pRequest->reqId, code);
    taosWUnLockLatch(&pTq->lock);
    tDeleteSMqDataRsp(&dataRsp);
  }
476 477 478
  return code;
}

wmmhello's avatar
wmmhello 已提交
479

wmmhello's avatar
wmmhello 已提交
480
static int32_t extractDataAndRspForDbStbSubscribe(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest, SRpcMsg* pMsg, STqOffsetVal *offset) {
481 482 483
  int code = 0;
  int32_t      vgId = TD_VID(pTq->pVnode);
  SWalCkHead*  pCkHead = NULL;
484 485
  SMqMetaRsp metaRsp = {0};
  STaosxRsp taosxRsp = {0};
486
  tqInitTaosxRsp(&taosxRsp, pRequest);
wmmhello's avatar
wmmhello 已提交
487

488 489
  if (offset->type != TMQ_OFFSET__LOG) {
    if (tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, offset) < 0) {
L
Liu Jicong 已提交
490 491
      return -1;
    }
wmmhello's avatar
wmmhello 已提交
492

L
Liu Jicong 已提交
493
    if (metaRsp.metaRspLen > 0) {
494
      code = tqSendMetaPollRsp(pTq, pMsg, pRequest, &metaRsp);
wmmhello's avatar
wmmhello 已提交
495
      tqDebug("tmq poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send meta offset type:%d,uid:%" PRId64 ",ts:%" PRId64,
wmmhello's avatar
wmmhello 已提交
496
              pRequest->consumerId, pHandle->subKey, vgId, metaRsp.rspOffset.type, metaRsp.rspOffset.uid, metaRsp.rspOffset.ts);
wmmhello's avatar
wmmhello 已提交
497
      taosMemoryFree(metaRsp.metaRsp);
498 499
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
H
Haojun Liao 已提交
500
    }
wmmhello's avatar
wmmhello 已提交
501

502
    tqDebug("taosx poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send data blockNum:%d, offset type:%d,uid:%" PRId64
wmmhello's avatar
wmmhello 已提交
503
    ",ts:%" PRId64,pRequest->consumerId, pHandle->subKey, vgId, taosxRsp.blockNum, taosxRsp.rspOffset.type, taosxRsp.rspOffset.uid,taosxRsp.rspOffset.ts);
504
    if (taosxRsp.blockNum > 0) {
H
Haojun Liao 已提交
505
      code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
506 507
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
wmmhello's avatar
wmmhello 已提交
508 509
    }else {
      *offset = taosxRsp.rspOffset;
510
    }
511 512
  }

wmmhello's avatar
wmmhello 已提交
513 514

  if (offset->type == TMQ_OFFSET__LOG) {
515
    int64_t fetchVer = offset->version + 1;
wmmhello's avatar
wmmhello 已提交
516 517
    pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
518
      tDeleteSTaosxRsp(&taosxRsp);
H
Haojun Liao 已提交
519
      terrno = TSDB_CODE_OUT_OF_MEMORY;
520
      return -1;
521
    }
wmmhello's avatar
wmmhello 已提交
522
    walSetReaderCapacity(pHandle->pWalReader, 2048);
523
    int totalRows = 0;
wmmhello's avatar
wmmhello 已提交
524
    while (1) {
525 526
      int32_t savedEpoch = atomic_load_32(&pHandle->epoch);
      if (savedEpoch > pRequest->epoch) {
H
Haojun Liao 已提交
527
        tqWarn("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey:%s vgId:%d offset %" PRId64
wmmhello's avatar
wmmhello 已提交
528
          ", found new consumer epoch %d, discard req epoch %d", pRequest->consumerId, pRequest->epoch, pHandle->subKey, vgId, fetchVer, savedEpoch, pRequest->epoch);
wmmhello's avatar
wmmhello 已提交
529
        break;
530
      }
wmmhello's avatar
wmmhello 已提交
531

532
      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead, pRequest->reqId) < 0) {
533
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
534 535 536 537
        code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
        tDeleteSTaosxRsp(&taosxRsp);
        taosMemoryFreeClear(pCkHead);
        return code;
wmmhello's avatar
wmmhello 已提交
538
      }
H
Haojun Liao 已提交
539

wmmhello's avatar
wmmhello 已提交
540
      SWalCont* pHead = &pCkHead->head;
541
      tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", pRequest->consumerId,
542
              pRequest->epoch, vgId, fetchVer, pHead->msgType);
H
Haojun Liao 已提交
543

544 545
      // process meta
      if (pHead->msgType != TDMT_VND_SUBMIT) {
546 547
        if(totalRows > 0) {
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer - 1);
H
Haojun Liao 已提交
548
          code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
549
          tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
550
          taosMemoryFreeClear(pCkHead);
551
          return code;
wmmhello's avatar
wmmhello 已提交
552 553
        }

554
        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%s", pHead->version, TMSG_INFO(pHead->msgType));
wmmhello's avatar
wmmhello 已提交
555 556 557 558
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer);
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
559
        if (tqSendMetaPollRsp(pTq, pMsg, pRequest, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
560
          code = -1;
L
Liu Jicong 已提交
561
          taosMemoryFreeClear(pCkHead);
562
          tDeleteSTaosxRsp(&taosxRsp);
563
          return code;
wmmhello's avatar
wmmhello 已提交
564 565
        }
        code = 0;
L
Liu Jicong 已提交
566
        taosMemoryFreeClear(pCkHead);
567
        tDeleteSTaosxRsp(&taosxRsp);
568
        return code;
wmmhello's avatar
wmmhello 已提交
569
      }
570

571 572 573 574 575 576 577 578
      // process data
      SPackedData submit = {
          .msgStr = POINTER_SHIFT(pHead->body, sizeof(SSubmitReq2Msg)),
          .msgLen = pHead->bodyLen - sizeof(SSubmitReq2Msg),
          .ver = pHead->version,
      };

      if (tqTaosxScanLog(pTq, pHandle, submit, &taosxRsp, &totalRows) < 0) {
wmmhello's avatar
wmmhello 已提交
579
        tqError("tmq poll: tqTaosxScanLog error %" PRId64 ", in vgId:%d, subkey %s", pRequest->consumerId, vgId,
580
                pRequest->subKey);
581 582
        taosMemoryFreeClear(pCkHead);
        tDeleteSTaosxRsp(&taosxRsp);
583 584 585 586 587 588 589 590 591 592 593 594
        return -1;
      }

      if (totalRows >= 4096 || taosxRsp.createTableNum > 0) {
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
        code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
        tDeleteSTaosxRsp(&taosxRsp);
        taosMemoryFreeClear(pCkHead);
        return code;
      } else {
        fetchVer++;
      }
wmmhello's avatar
wmmhello 已提交
595
    }
596
  }
597

598
  tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
599
  taosMemoryFreeClear(pCkHead);
600
  return 0;
L
Liu Jicong 已提交
601 602
}

wmmhello's avatar
wmmhello 已提交
603
static int32_t doPollDataForMq(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest, SRpcMsg* pMsg) {
604 605 606 607 608
  int32_t      code = -1;
  STqOffsetVal offset = {0};
  STqOffsetVal reqOffset = pRequest->reqOffset;

  // 1. reset the offset if needed
wmmhello's avatar
wmmhello 已提交
609 610
  if (IS_OFFSET_RESET_TYPE(reqOffset.type)) {
    // handle the reset offset cases, according to the consumer's choice.
611 612 613 614 615 616 617 618 619 620
    bool blockReturned = false;
    code = extractResetOffsetVal(&offset, pTq, pHandle, pRequest, pMsg, &blockReturned);
    if (code != 0) {
      return code;
    }

    // empty block returned, quit
    if (blockReturned) {
      return 0;
    }
wmmhello's avatar
wmmhello 已提交
621 622 623
  } else { // use the consumer specified offset
    // the offset value can not be monotonious increase??
    offset = reqOffset;
624 625
  }

wmmhello's avatar
wmmhello 已提交
626
  // this is a normal subscribe requirement
627
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
wmmhello's avatar
wmmhello 已提交
628
    return extractDataAndRspForNormalSubscribe(pTq, pHandle, pRequest, pMsg, &offset);
629 630 631 632
  }

  // todo handle the case where re-balance occurs.
  // for taosx
wmmhello's avatar
wmmhello 已提交
633
  return extractDataAndRspForDbStbSubscribe(pTq, pHandle, pRequest, pMsg, &offset);
634 635
}

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
  SMqPollReq   req = {0};
  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;
  }

657
  // 2. check re-balance status
658
  taosRLockLatch(&pTq->lock);
659 660 661 662
  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;
663
    taosRUnLockLatch(&pTq->lock);
664 665
    return -1;
  }
666
  taosRUnLockLatch(&pTq->lock);
667

668
  // 3. update the epoch value
669
  taosWLockLatch(&pTq->lock);
H
Haojun Liao 已提交
670 671
  int32_t savedEpoch = pHandle->epoch;
  if (savedEpoch < reqEpoch) {
672 673
    tqDebug("tmq poll: consumer:0x%" PRIx64 " epoch update from %d to %d by poll req", consumerId, savedEpoch, reqEpoch);
    pHandle->epoch = reqEpoch;
H
Haojun Liao 已提交
674
  }
675
  taosWUnLockLatch(&pTq->lock);
676 677 678

  char buf[80];
  tFormatOffset(buf, 80, &reqOffset);
H
Haojun Liao 已提交
679 680
  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);
681

682
  return doPollDataForMq(pTq, pHandle, &req, pMsg);
683 684
}

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

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

690
  taosWLockLatch(&pTq->lock);
L
Liu Jicong 已提交
691 692 693 694
  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);
  }
695
  taosWUnLockLatch(&pTq->lock);
L
Liu Jicong 已提交
696

L
Liu Jicong 已提交
697 698
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
X
Xiaoyu Wang 已提交
699
    // walCloseRef(pHandle->pWalReader->pWal, pHandle->pRef->refId);
L
Liu Jicong 已提交
700 701 702 703 704 705 706
    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 已提交
707
  }
708

L
Liu Jicong 已提交
709 710
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
711
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
712
  }
L
Liu Jicong 已提交
713

L
Liu Jicong 已提交
714
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
715
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
716
  }
L
Liu Jicong 已提交
717
  return 0;
L
Liu Jicong 已提交
718 719
}

720
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
721 722
  STqCheckInfo info = {0};
  SDecoder     decoder;
X
Xiaoyu Wang 已提交
723
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
724
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
725 726 727 728
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
729 730 731 732 733
  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 已提交
734 735 736 737 738 739
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

740
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
741 742 743 744 745 746 747 748 749 750 751
  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;
}

752
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
753
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
754
  tDecodeSMqRebVgReq(msg, &req);
L
Liu Jicong 已提交
755

756 757 758
  SVnode* pVnode = pTq->pVnode;
  int32_t vgId = TD_VID(pVnode);

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

762
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
763
  if (pHandle == NULL) {
L
Liu Jicong 已提交
764
    if (req.oldConsumerId != -1) {
765
      tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId:0x%" PRIx64,
766
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
767
    }
768

L
Liu Jicong 已提交
769
    if (req.newConsumerId == -1) {
770
      tqError("vgId:%d, tq invalid re-balance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
771
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
772 773
      return 0;
    }
774

L
Liu Jicong 已提交
775 776
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
777

H
Haojun Liao 已提交
778
    uint64_t oldConsumerId = pHandle->consumerId;
L
Liu Jicong 已提交
779 780 781
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
782

L
Liu Jicong 已提交
783
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
784
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
785

786
    // TODO version should be assigned and refed during preprocess
787
    SWalRef* pRef = walRefCommittedVer(pVnode->pWal);
788
    if (pRef == NULL) {
H
Haojun Liao 已提交
789
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
790
      return -1;
791
    }
H
Haojun Liao 已提交
792

793 794
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
795

796
    SReadHandle handle = {
797
        .meta = pVnode->pMeta, .vnode = pVnode, .initTableReader = true, .initTqReader = true, .version = ver};
wmmhello's avatar
wmmhello 已提交
798
    pHandle->snapshotVer = ver;
799

L
Liu Jicong 已提交
800
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
801
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
802
      req.qmsg = NULL;
803 804

      pHandle->execHandle.task =
805
          qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, vgId, &pHandle->execHandle.numOfCols, req.newConsumerId);
L
Liu Jicong 已提交
806
      void* scanner = NULL;
807
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
L
Liu Jicong 已提交
808
      pHandle->execHandle.pExecReader = qExtractReaderFromStreamScanner(scanner);
L
Liu Jicong 已提交
809
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
810 811
      pHandle->pWalReader = walOpenReader(pVnode->pWal, NULL);
      pHandle->execHandle.pExecReader = tqOpenReader(pVnode);
812

L
Liu Jicong 已提交
813
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
814
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
815 816
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
817

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

L
Liu Jicong 已提交
823
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
824 825
      vnodeGetCtbIdList(pVnode, req.suid, tbUidList);
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
826 827
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
828
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, vgId, i, tbUid);
L
Liu Jicong 已提交
829
      }
830
      pHandle->execHandle.pExecReader = tqOpenReader(pVnode);
L
Liu Jicong 已提交
831
      tqReaderSetTbUidList(pHandle->execHandle.pExecReader, tbUidList);
L
Liu Jicong 已提交
832
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
833

L
Liu Jicong 已提交
834 835
      buildSnapContext(handle.meta, handle.version, req.suid, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
836
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, vgId, NULL, req.newConsumerId);
L
Liu Jicong 已提交
837
    }
H
Haojun Liao 已提交
838

839
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
840 841
    tqDebug("try to persist handle %s consumer:0x%" PRIx64 " , old consumer:0x%" PRIx64, req.subKey,
            pHandle->consumerId, oldConsumerId);
L
Liu Jicong 已提交
842
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
H
Haojun Liao 已提交
843
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
844
      return -1;
L
Liu Jicong 已提交
845
    }
L
Liu Jicong 已提交
846
  } else {
847 848 849 850
    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 已提交
851
      taosMemoryFree(req.qmsg);
852
      return tqMetaSaveHandle(pTq, req.subKey, pHandle);
853 854 855
    } else {
      tqInfo("vgId:%d switch consumer from Id:0x%" PRIx64 " to Id:0x%" PRIx64, req.vgId, pHandle->consumerId,
             req.newConsumerId);
856

857 858 859
      // kill executing task
      qTaskInfo_t pTaskInfo = pHandle->execHandle.task;
      if (pTaskInfo != NULL) {
860
        qKillTask(pTaskInfo, TSDB_CODE_SUCCESS);
861 862
      }

863 864
      taosWLockLatch(&pTq->lock);
      atomic_store_32(&pHandle->epoch, -1);
865

866
      // remove if it has been register in the push manager, and return one empty block to consumer
867
      tqUnregisterPushEntry(pTq, req.subKey, (int32_t)strlen(req.subKey), pHandle->consumerId, true);
868

869 870
      atomic_store_64(&pHandle->consumerId, req.newConsumerId);
      atomic_add_fetch_32(&pHandle->epoch, 1);
871

872
      if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
873 874 875
        qStreamCloseTsdbReader(pTaskInfo);
      }

876 877 878 879 880
      taosWUnLockLatch(&pTq->lock);
      if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
        taosMemoryFree(req.qmsg);
        return -1;
      }
L
Liu Jicong 已提交
881
    }
L
Liu Jicong 已提交
882
  }
L
Liu Jicong 已提交
883

H
Haojun Liao 已提交
884
  taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
885
  return 0;
L
Liu Jicong 已提交
886
}
887

888
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
L
Liu Jicong 已提交
889
#if 0
890
  if (pTask->taskLevel == TASK_LEVEL__AGG) {
L
Liu Jicong 已提交
891
    A(taosArrayGetSize(pTask->childEpInfo) != 0);
L
Liu Jicong 已提交
892
  }
L
Liu Jicong 已提交
893
#endif
L
Liu Jicong 已提交
894

895
  int32_t vgId = TD_VID(pTq->pVnode);
L
Liu Jicong 已提交
896
  pTask->refCnt = 1;
L
Liu Jicong 已提交
897
  pTask->schedStatus = TASK_SCHED_STATUS__INACTIVE;
L
Liu Jicong 已提交
898 899 900

  pTask->inputQueue = streamQueueOpen();
  pTask->outputQueue = streamQueueOpen();
L
Liu Jicong 已提交
901 902

  if (pTask->inputQueue == NULL || pTask->outputQueue == NULL) {
L
Liu Jicong 已提交
903
    return -1;
L
Liu Jicong 已提交
904 905
  }

L
Liu Jicong 已提交
906 907
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;
908
  pTask->pMsgCb = &pTq->pVnode->msgCb;
909 910
  pTask->startVer = ver;

911
  // expand executor
912 913 914 915
  if (pTask->fillHistory) {
    pTask->taskStatus = TASK_STATUS__WAIT_DOWNSTREAM;
  }

916
  if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
917
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
918 919 920 921
    if (pTask->pState == NULL) {
      return -1;
    }

922 923 924 925
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTqReader = 1,
926
        .pStateBackend = pTask->pState,
927
    };
928 929

    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle, vgId);
L
Liu Jicong 已提交
930 931 932
    if (pTask->exec.executor == NULL) {
      return -1;
    }
933

934
  } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
935
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
936 937 938
    if (pTask->pState == NULL) {
      return -1;
    }
939 940 941
    SReadHandle mgHandle = {
        .vnode = NULL,
        .numOfVgroups = (int32_t)taosArrayGetSize(pTask->childEpInfo),
942
        .pStateBackend = pTask->pState,
943
    };
944 945

    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &mgHandle, vgId);
L
Liu Jicong 已提交
946 947 948
    if (pTask->exec.executor == NULL) {
      return -1;
    }
L
Liu Jicong 已提交
949
  }
L
Liu Jicong 已提交
950 951

  // sink
L
Liu Jicong 已提交
952
  /*pTask->ahandle = pTq->pVnode;*/
953
  if (pTask->outputType == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
954
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
955
    pTask->smaSink.smaSink = smaHandleRes;
956
  } else if (pTask->outputType == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
957
    pTask->tbSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
958
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline2;
L
Liu Jicong 已提交
959

H
Haojun Liao 已提交
960
    int32_t ver1 = 1;
5
54liuyao 已提交
961 962 963
    SMetaInfo info = {0};
    int32_t code = metaGetInfo(pTq->pVnode->pMeta, pTask->tbSink.stbUid, &info, NULL);
    if (code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
964
      ver1 = info.skmVer;
5
54liuyao 已提交
965
    }
L
Liu Jicong 已提交
966

L
Liu Jicong 已提交
967
    pTask->tbSink.pTSchema =
H
Haojun Liao 已提交
968
        tBuildTSchema(pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols, ver1);
wmmhello's avatar
wmmhello 已提交
969
    if(pTask->tbSink.pTSchema == NULL) {
wmmhello's avatar
wmmhello 已提交
970
      return -1;
wmmhello's avatar
wmmhello 已提交
971
    }
L
Liu Jicong 已提交
972
  }
973 974

  streamSetupTrigger(pTask);
975
  tqInfo("expand stream task on vg %d, task id %d, child id %d, level %d", vgId, pTask->taskId, pTask->selfChildId, pTask->taskLevel);
L
Liu Jicong 已提交
976
  return 0;
L
Liu Jicong 已提交
977
}
L
Liu Jicong 已提交
978

979 980 981 982 983 984
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 已提交
985
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
986 987 988 989 990 991 992 993 994 995 996 997
  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,
  };
L
Liu Jicong 已提交
998
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
999 1000 1001 1002 1003 1004
  if (pTask && atomic_load_8(&pTask->taskStatus) == TASK_STATUS__NORMAL) {
    rsp.status = 1;
  } else {
    rsp.status = 0;
  }

L
Liu Jicong 已提交
1005
  if (pTask) streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1006

1007
  tqDebug("tq recv task check req(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d",
1008 1009 1010 1011 1012 1013 1014
          rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status);

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

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
  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);

  SRpcMsg rspMsg = {
      .code = 0,
      .pCont = buf,
      .contLen = sizeof(SMsgHead) + len,
      .info = pMsg->info,
  };

  tmsgSendRsp(&rspMsg);
  return 0;
}

1038
int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
  int32_t             code;
  SStreamTaskCheckRsp rsp;

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

1051
  tqDebug("tq recv task check rsp(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d",
1052 1053
          rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status);

L
Liu Jicong 已提交
1054
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId);
1055 1056 1057 1058
  if (pTask == NULL) {
    return -1;
  }

1059
  code = streamProcessTaskCheckRsp(pTask, &rsp, sversion);
L
Liu Jicong 已提交
1060 1061
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
1062 1063
}

1064
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1065 1066 1067 1068 1069
  int32_t code;
#if 0
  code = streamMetaAddSerializedTask(pTq->pStreamMeta, version, msg, msgLen);
  if (code < 0) return code;
#endif
5
54liuyao 已提交
1070 1071 1072
  if (tsDisableStream) {
    return 0;
  }
1073 1074 1075 1076 1077 1078

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

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
  code = tDecodeSStreamTask(&decoder, pTask);
  if (code < 0) {
    tDecoderClear(&decoder);
    taosMemoryFree(pTask);
    return -1;
  }
  tDecoderClear(&decoder);

  // 2.save task
1091
  code = streamMetaAddTask(pTq->pStreamMeta, sversion, pTask);
1092 1093 1094 1095 1096 1097
  if (code < 0) {
    return -1;
  }

  // 3.go through recover steps to fill history
  if (pTask->fillHistory) {
1098
    streamTaskCheckDownstream(pTask, sversion);
1099 1100 1101 1102 1103
  }

  return 0;
}

L
Liu Jicong 已提交
1104 1105 1106 1107 1108
int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) {
  int32_t code;
  char*   msg = pMsg->pCont;
  int32_t msgLen = pMsg->contLen;

1109
  SStreamRecoverStep1Req* pReq = (SStreamRecoverStep1Req*)msg;
L
Liu Jicong 已提交
1110
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1111 1112 1113 1114 1115 1116 1117
  if (pTask == NULL) {
    return -1;
  }

  // check param
  int64_t fillVer1 = pTask->startVer;
  if (fillVer1 <= 0) {
L
Liu Jicong 已提交
1118
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1119 1120 1121 1122 1123 1124
    return -1;
  }

  // do recovery step 1
  streamSourceRecoverScanStep1(pTask);

L
Liu Jicong 已提交
1125 1126 1127 1128 1129
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1130 1131 1132 1133
  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
1134
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1135 1136 1137
    return -1;
  }

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

L
Liu Jicong 已提交
1140 1141 1142 1143
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    return 0;
  }

1144
  // serialize msg
L
Liu Jicong 已提交
1145 1146 1147 1148 1149 1150 1151 1152
  int32_t len = sizeof(SStreamRecoverStep1Req);

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

  memcpy(serializedReq, &req, len);
1153 1154 1155 1156 1157

  // dispatch msg
  SRpcMsg rpcMsg = {
      .code = 0,
      .contLen = len,
L
Liu Jicong 已提交
1158
      .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE,
L
Liu Jicong 已提交
1159
      .pCont = serializedReq,
1160 1161 1162 1163 1164 1165 1166
  };

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

  return 0;
}

1167
int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1168 1169
  int32_t                 code;
  SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg;
L
Liu Jicong 已提交
1170
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1171 1172 1173 1174 1175
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
1176
  code = streamSourceRecoverScanStep2(pTask, sversion);
1177
  if (code < 0) {
L
Liu Jicong 已提交
1178
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1179 1180 1181
    return -1;
  }

L
Liu Jicong 已提交
1182 1183 1184 1185 1186
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1187 1188 1189
  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1190
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1191 1192 1193 1194 1195 1196
    return -1;
  }

  // set status normal
  code = streamSetStatusNormal(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1197
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1198 1199 1200 1201 1202 1203
    return -1;
  }

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

L
Liu Jicong 已提交
1208 1209 1210
  atomic_store_8(&pTask->fillHistory, 0);
  streamMetaSaveTask(pTq->pStreamMeta, pTask);

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

1213 1214 1215
  return 0;
}

L
Liu Jicong 已提交
1216 1217 1218
int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
1219 1220

  // deserialize
1221 1222 1223
  SStreamRecoverFinishReq req;

  SDecoder decoder;
X
Xiaoyu Wang 已提交
1224
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
1225 1226 1227
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

1228
  // find task
L
Liu Jicong 已提交
1229
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
1230 1231 1232
  if (pTask == NULL) {
    return -1;
  }
1233
  // do process request
1234
  if (streamProcessRecoverFinishReq(pTask, req.childId) < 0) {
L
Liu Jicong 已提交
1235
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1236 1237 1238
    return -1;
  }

L
Liu Jicong 已提交
1239
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1240
  return 0;
L
Liu Jicong 已提交
1241
}
L
Liu Jicong 已提交
1242

L
Liu Jicong 已提交
1243 1244 1245 1246 1247
int32_t tqProcessTaskRecoverFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}

L
Liu Jicong 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
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 已提交
1264
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    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);
1276
    colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
L
Liu Jicong 已提交
1277
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
1278
    colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false);
L
Liu Jicong 已提交
1279 1280 1281
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
1282
    colDataSetVal(pUidCol, i, (const char*)pUid, false);
L
Liu Jicong 已提交
1283

1284 1285 1286
    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 已提交
1287 1288
  }

L
Liu Jicong 已提交
1289 1290
  taosArrayDestroy(pRes->uidList);

L
Liu Jicong 已提交
1291 1292 1293
  int32_t* pRef = taosMemoryMalloc(sizeof(int32_t));
  *pRef = 1;

L
Liu Jicong 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302
  void* pIter = NULL;
  while (1) {
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
    if (pIter == NULL) break;
    SStreamTask* pTask = *(SStreamTask**)pIter;
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) continue;

    qDebug("delete req enqueue stream task: %d, ver: %" PRId64, pTask->taskId, ver);

L
Liu Jicong 已提交
1303
    if (!failed) {
S
Shengliang Guan 已提交
1304
      SStreamRefDataBlock* pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1305 1306 1307 1308 1309
      pRefBlock->type = STREAM_INPUT__REF_DATA_BLOCK;
      pRefBlock->pBlock = pDelBlock;
      pRefBlock->dataRef = pRef;
      atomic_add_fetch_32(pRefBlock->dataRef, 1);

1310
      if (tAppendDataForStream(pTask, (SStreamQueueItem*)pRefBlock) < 0) {
L
Liu Jicong 已提交
1311
        qError("stream task input del failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1312

L
Liu Jicong 已提交
1313
        atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1314
        taosFreeQitem(pRefBlock);
L
Liu Jicong 已提交
1315 1316
        continue;
      }
L
Liu Jicong 已提交
1317

L
Liu Jicong 已提交
1318 1319 1320 1321
      if (streamSchedExec(pTask) < 0) {
        qError("stream task launch failed, task id %d", pTask->taskId);
        continue;
      }
L
Liu Jicong 已提交
1322

L
Liu Jicong 已提交
1323 1324 1325 1326
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1327

L
Liu Jicong 已提交
1328
  int32_t ref = atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1329
  /*A(ref >= 0);*/
L
Liu Jicong 已提交
1330
  if (ref == 0) {
L
Liu Jicong 已提交
1331
    blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1332 1333 1334 1335
    taosMemoryFree(pRef);
  }

#if 0
S
Shengliang Guan 已提交
1336
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1337 1338 1339 1340 1341 1342 1343 1344
    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) {
1345
      if (tAppendDataForStream(pTask, (SStreamQueueItem*)pStreamBlock) < 0) {
L
Liu Jicong 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
        qError("stream task input del failed, task id %d", pTask->taskId);
        continue;
      }

      if (streamSchedExec(pTask) < 0) {
        qError("stream task launch failed, task id %d", pTask->taskId);
        continue;
      }
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1358
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1359
#endif
L
Liu Jicong 已提交
1360 1361 1362 1363

  return 0;
}

L
Liu Jicong 已提交
1364
int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) {
1365
  void* pIter = NULL;
1366
  bool  succ = true;
L
Liu Jicong 已提交
1367

1368
  SStreamDataSubmit2* pSubmit = streamDataSubmitNew(submit);
L
Liu Jicong 已提交
1369
  if (pSubmit == NULL) {
L
Liu Jicong 已提交
1370
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1371
    tqError("failed to create data submit for stream since out of memory");
1372
    succ = false;
L
Liu Jicong 已提交
1373 1374 1375
  }

  while (1) {
L
Liu Jicong 已提交
1376
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
1377 1378 1379 1380
    if (pIter == NULL) {
      break;
    }

1381
    SStreamTask* pTask = *(SStreamTask**)pIter;
1382 1383 1384 1385
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) {
      continue;
    }

1386
    if (pTask->taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
1387
      tqDebug("stream task:%d skip push data, not ready for processing, status %d", pTask->taskId, pTask->taskStatus);
L
Liu Jicong 已提交
1388 1389
      continue;
    }
L
Liu Jicong 已提交
1390

1391 1392
    tqDebug("data submit enqueue stream task:%d, ver: %" PRId64, pTask->taskId, submit.ver);
    if (succ) {
1393 1394 1395 1396
      int32_t code = tAppendDataForStream(pTask, (SStreamQueueItem*)pSubmit);
      if (code < 0) {
        // let's handle the back pressure

1397
        tqError("stream task:%d failed to put into queue for, too many", pTask->taskId);
L
Liu Jicong 已提交
1398 1399 1400
        continue;
      }

L
Liu Jicong 已提交
1401
      if (streamSchedExec(pTask) < 0) {
1402
        tqError("stream task:%d launch failed, code:%s", pTask->taskId, tstrerror(terrno));
L
Liu Jicong 已提交
1403 1404
        continue;
      }
L
Liu Jicong 已提交
1405
    } else {
L
Liu Jicong 已提交
1406
      streamTaskInputFail(pTask);
L
Liu Jicong 已提交
1407 1408 1409
    }
  }

1410
  if (pSubmit != NULL) {
1411
    streamDataSubmitDestroy(pSubmit);
L
Liu Jicong 已提交
1412
    taosFreeQitem(pSubmit);
L
Liu Jicong 已提交
1413
  }
L
Liu Jicong 已提交
1414

1415
  return succ ? 0 : -1;
L
Liu Jicong 已提交
1416 1417
}

L
Liu Jicong 已提交
1418 1419 1420
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRunReq* pReq = pMsg->pCont;
  int32_t            taskId = pReq->taskId;
L
Liu Jicong 已提交
1421
  SStreamTask*       pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1422 1423
  if (pTask) {
    streamProcessRunReq(pTask);
L
Liu Jicong 已提交
1424
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1425
    return 0;
1426 1427
  } else {
    return -1;
L
Liu Jicong 已提交
1428
  }
L
Liu Jicong 已提交
1429 1430
}

L
Liu Jicong 已提交
1431
int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg, bool exec) {
1432 1433 1434 1435 1436
  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 已提交
1437
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1438
  tDecodeStreamDispatchReq(&decoder, &req);
L
Liu Jicong 已提交
1439 1440
  int32_t taskId = req.taskId;

L
Liu Jicong 已提交
1441
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1442
  if (pTask) {
1443 1444 1445 1446
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1447
    streamProcessDispatchReq(pTask, &req, &rsp, exec);
L
Liu Jicong 已提交
1448
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1449
    return 0;
1450 1451
  } else {
    return -1;
L
Liu Jicong 已提交
1452
  }
L
Liu Jicong 已提交
1453 1454
}

L
Liu Jicong 已提交
1455 1456
int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
1457
  int32_t             taskId = ntohl(pRsp->upstreamTaskId);
L
Liu Jicong 已提交
1458
  SStreamTask*        pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1459
  tqDebug("recv dispatch rsp, code: %x", pMsg->code);
L
Liu Jicong 已提交
1460
  if (pTask) {
1461
    streamProcessDispatchRsp(pTask, pRsp, pMsg->code);
L
Liu Jicong 已提交
1462
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1463
    return 0;
1464 1465
  } else {
    return -1;
L
Liu Jicong 已提交
1466
  }
L
Liu Jicong 已提交
1467
}
L
Liu Jicong 已提交
1468

1469
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1470
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1471
  streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId);
L
Liu Jicong 已提交
1472
  return 0;
L
Liu Jicong 已提交
1473
}
L
Liu Jicong 已提交
1474 1475 1476 1477 1478 1479 1480

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;
1481
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1482
  tDecodeStreamRetrieveReq(&decoder, &req);
L
Liu Jicong 已提交
1483
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1484
  int32_t      taskId = req.dstTaskId;
L
Liu Jicong 已提交
1485
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1486
  if (pTask) {
L
Liu Jicong 已提交
1487 1488 1489 1490
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1491
    streamProcessRetrieveReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
1492
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1493
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1494
    return 0;
L
Liu Jicong 已提交
1495 1496
  } else {
    return -1;
L
Liu Jicong 已提交
1497 1498 1499 1500 1501 1502 1503
  }
}

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

1505 1506 1507 1508 1509 1510
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 已提交
1511 1512 1513

  SStreamDispatchReq req;
  SDecoder           decoder;
1514
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1515 1516
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1517
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1518 1519
    goto FAIL;
  }
L
Liu Jicong 已提交
1520
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1521

L
Liu Jicong 已提交
1522
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1523

L
Liu Jicong 已提交
1524
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1525
  if (pTask) {
L
Liu Jicong 已提交
1526 1527 1528 1529
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1530
    streamProcessDispatchReq(pTask, &req, &rsp, false);
L
Liu Jicong 已提交
1531
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1532 1533
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
1534
    return 0;
5
54liuyao 已提交
1535 1536
  } else {
    tDeleteStreamDispatchReq(&req);
L
Liu Jicong 已提交
1537
  }
L
Liu Jicong 已提交
1538

1539 1540
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1541
FAIL:
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
  if (pMsg->info.handle == NULL) return -1;

  SMsgHead* pRspHead = rpcMallocCont(sizeof(SMsgHead) + sizeof(SStreamDispatchRsp));
  if (pRspHead == NULL) {
    SRpcMsg rsp = {
        .code = TSDB_CODE_OUT_OF_MEMORY,
        .info = pMsg->info,
    };
    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 已提交
1566 1567 1568
  SRpcMsg rsp = {
      .code = code,
      .info = pMsg->info,
1569 1570
      .contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp),
      .pCont = pRspHead,
L
Liu Jicong 已提交
1571
  };
1572
  tqDebug("send dispatch error rsp, code: %x", code);
L
Liu Jicong 已提交
1573
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1574 1575
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1576
  return -1;
L
Liu Jicong 已提交
1577
}
L
Liu Jicong 已提交
1578

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