tq.c 48.2 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 55 56 57
static void destroySTqHandle(void* data) {
  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;
L
Liu Jicong 已提交
71
  tDeleteSMqDataRsp(&p->dataRsp);
L
Liu Jicong 已提交
72 73 74
  taosMemoryFree(p);
}

L
Liu Jicong 已提交
75
STQ* tqOpen(const char* path, SVnode* pVnode) {
76
  STQ* pTq = taosMemoryCalloc(1, sizeof(STQ));
L
Liu Jicong 已提交
77
  if (pTq == NULL) {
S
Shengliang Guan 已提交
78
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
79 80
    return NULL;
  }
H
Hongze Cheng 已提交
81
  pTq->path = strdup(path);
L
Liu Jicong 已提交
82
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
83
  pTq->walLogLastVer = pVnode->pWal->vers.lastVer;
84

85
  pTq->pHandle = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
86 87
  taosHashSetFreeFp(pTq->pHandle, destroySTqHandle);

L
Liu Jicong 已提交
88 89
  taosInitRWLatch(&pTq->pushLock);
  pTq->pPushMgr = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
L
Liu Jicong 已提交
90
  taosHashSetFreeFp(pTq->pPushMgr, tqPushEntryFree);
L
Liu Jicong 已提交
91

92
  pTq->pCheckInfo = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
93
  taosHashSetFreeFp(pTq->pCheckInfo, (FDelete)tDeleteSTqCheckInfo);
L
Liu Jicong 已提交
94

L
Liu Jicong 已提交
95
  if (tqMetaOpen(pTq) < 0) {
L
Liu Jicong 已提交
96
    return NULL;
97 98
  }

L
Liu Jicong 已提交
99 100
  pTq->pOffsetStore = tqOffsetOpen(pTq);
  if (pTq->pOffsetStore == NULL) {
L
Liu Jicong 已提交
101
    return NULL;
102 103
  }

104
  pTq->pStreamMeta = streamMetaOpen(path, pTq, (FTaskExpand*)tqExpandTask, pTq->pVnode->config.vgId);
L
Liu Jicong 已提交
105
  if (pTq->pStreamMeta == NULL) {
L
Liu Jicong 已提交
106
    return NULL;
L
Liu Jicong 已提交
107 108
  }

L
Liu Jicong 已提交
109
  if (streamLoadTasks(pTq->pStreamMeta, walGetCommittedVer(pVnode->pWal)) < 0) {
L
Liu Jicong 已提交
110
    return NULL;
L
Liu Jicong 已提交
111 112
  }

L
Liu Jicong 已提交
113 114
  return pTq;
}
L
Liu Jicong 已提交
115

L
Liu Jicong 已提交
116
void tqClose(STQ* pTq) {
H
Hongze Cheng 已提交
117
  if (pTq) {
118
    tqOffsetClose(pTq->pOffsetStore);
119 120 121
    taosHashCleanup(pTq->pHandle);
    taosHashCleanup(pTq->pPushMgr);
    taosHashCleanup(pTq->pCheckInfo);
122
    taosMemoryFree(pTq->path);
L
Liu Jicong 已提交
123
    tqMetaClose(pTq);
L
Liu Jicong 已提交
124
    streamMetaClose(pTq->pStreamMeta);
wafwerar's avatar
wafwerar 已提交
125
    taosMemoryFree(pTq);
H
Hongze Cheng 已提交
126
  }
L
Liu Jicong 已提交
127
}
L
Liu Jicong 已提交
128

L
Liu Jicong 已提交
129
int32_t tqSendMetaPollRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqMetaRsp* pRsp) {
130 131 132 133 134 135 136
  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 已提交
137 138 139 140 141 142 143 144 145 146
  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));
147 148 149 150 151

  SEncoder encoder = {0};
  tEncoderInit(&encoder, abuf, len);
  tEncodeSMqMetaRsp(&encoder, pRsp);
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
152 153 154 155 156 157 158 159 160

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

161 162
  tqDebug("vgId:%d, from consumer:%" PRId64 ", (epoch %d) send rsp, res msg type %d, offset type:%d",
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->resMsgType, pRsp->rspOffset.type);
L
Liu Jicong 已提交
163 164 165 166

  return 0;
}

L
Liu Jicong 已提交
167 168 169
int32_t tqPushDataRsp(STQ* pTq, STqPushEntry* pPushEntry) {
  SMqDataRsp* pRsp = &pPushEntry->dataRsp;

L
Liu Jicong 已提交
170 171 172
#if 0
  A(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
  A(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);
L
Liu Jicong 已提交
173

L
Liu Jicong 已提交
174 175
  A(!pRsp->withSchema);
  A(taosArrayGetSize(pRsp->blockSchema) == 0);
L
Liu Jicong 已提交
176 177

  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
L
Liu Jicong 已提交
178
    A(pRsp->rspOffset.version > pRsp->reqOffset.version);
L
Liu Jicong 已提交
179
  }
L
Liu Jicong 已提交
180
#endif
L
Liu Jicong 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

  int32_t len = 0;
  int32_t code = 0;
  tEncodeSize(tEncodeSMqDataRsp, pRsp, len, code);

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

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

L
Liu Jicong 已提交
196
  memcpy(buf, &pPushEntry->dataRsp.head, sizeof(SMqRspHead));
L
Liu Jicong 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

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

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

  SRpcMsg rsp = {
      .info = pPushEntry->pInfo,
      .pCont = buf,
      .contLen = tlen,
      .code = 0,
  };

  tmsgSendRsp(&rsp);

  char buf1[80] = {0};
  char buf2[80] = {0};
  tFormatOffset(buf1, 80, &pRsp->reqOffset);
  tFormatOffset(buf2, 80, &pRsp->rspOffset);
  tqDebug("vgId:%d, from consumer:%" PRId64 ", (epoch %d) push rsp, block num: %d, reqOffset:%s, rspOffset:%s",
L
Liu Jicong 已提交
219
          TD_VID(pTq->pVnode), pRsp->head.consumerId, pRsp->head.epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
220 221 222 223

  return 0;
}

L
Liu Jicong 已提交
224
int32_t tqSendDataRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqDataRsp* pRsp) {
L
Liu Jicong 已提交
225 226 227
#if 0
  A(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
  A(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);
L
Liu Jicong 已提交
228

L
Liu Jicong 已提交
229 230
  A(!pRsp->withSchema);
  A(taosArrayGetSize(pRsp->blockSchema) == 0);
L
Liu Jicong 已提交
231

232 233
  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
    if (pRsp->blockNum > 0) {
L
Liu Jicong 已提交
234
      A(pRsp->rspOffset.version > pRsp->reqOffset.version);
235
    } else {
L
Liu Jicong 已提交
236
      A(pRsp->rspOffset.version >= pRsp->reqOffset.version);
237
    }
L
Liu Jicong 已提交
238
  }
L
Liu Jicong 已提交
239
#endif
L
Liu Jicong 已提交
240

wmmhello's avatar
wmmhello 已提交
241 242
  int32_t len = 0;
  int32_t code = 0;
L
Liu Jicong 已提交
243 244 245 246 247
  tEncodeSize(tEncodeSMqDataRsp, pRsp, len, code);
  if (code < 0) {
    return -1;
  }
  int32_t tlen = sizeof(SMqRspHead) + len;
L
Liu Jicong 已提交
248 249 250 251 252 253 254 255 256 257 258
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    return -1;
  }

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

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

wmmhello's avatar
wmmhello 已提交
259
  SEncoder encoder = {0};
L
Liu Jicong 已提交
260
  tEncoderInit(&encoder, abuf, len);
L
Liu Jicong 已提交
261
  tEncodeSMqDataRsp(&encoder, pRsp);
wmmhello's avatar
wmmhello 已提交
262
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
263 264

  SRpcMsg rsp = {
L
Liu Jicong 已提交
265 266 267 268 269
      .info = pMsg->info,
      .pCont = buf,
      .contLen = tlen,
      .code = 0,
  };
L
Liu Jicong 已提交
270
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
271

wmmhello's avatar
wmmhello 已提交
272 273
  char buf1[80] = {0};
  char buf2[80] = {0};
L
Liu Jicong 已提交
274 275
  tFormatOffset(buf1, 80, &pRsp->reqOffset);
  tFormatOffset(buf2, 80, &pRsp->rspOffset);
S
Shengliang Guan 已提交
276
  tqDebug("vgId:%d, from consumer:%" PRId64 ", (epoch %d) send rsp, block num: %d, reqOffset:%s, rspOffset:%s",
L
Liu Jicong 已提交
277
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
278 279 280 281

  return 0;
}

282
int32_t tqSendTaosxRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const STaosxRsp* pRsp) {
L
Liu Jicong 已提交
283 284 285
#if 0
  A(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
  A(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);
286 287

  if (pRsp->withSchema) {
L
Liu Jicong 已提交
288
    A(taosArrayGetSize(pRsp->blockSchema) == pRsp->blockNum);
289
  } else {
L
Liu Jicong 已提交
290
    A(taosArrayGetSize(pRsp->blockSchema) == 0);
291 292 293 294
  }

  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
    if (pRsp->blockNum > 0) {
L
Liu Jicong 已提交
295
      A(pRsp->rspOffset.version > pRsp->reqOffset.version);
296
    } else {
L
Liu Jicong 已提交
297
      A(pRsp->rspOffset.version >= pRsp->reqOffset.version);
298 299
    }
  }
L
Liu Jicong 已提交
300
#endif
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

  int32_t len = 0;
  int32_t code = 0;
  tEncodeSize(tEncodeSTaosxRsp, pRsp, len, code);
  if (code < 0) {
    return -1;
  }
  int32_t tlen = sizeof(SMqRspHead) + len;
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    return -1;
  }

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

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

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

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

  char buf1[80] = {0};
  char buf2[80] = {0};
  tFormatOffset(buf1, 80, &pRsp->reqOffset);
  tFormatOffset(buf2, 80, &pRsp->rspOffset);
  tqDebug("taosx rsp, vgId:%d, from consumer:%" PRId64
          ", (epoch %d) send rsp, block num: %d, reqOffset:%s, rspOffset:%s",
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2);

  return 0;
}

344 345 346 347 348 349
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;
}

int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
350 351 352 353 354 355 356 357
  STqOffset offset = {0};
  SDecoder  decoder;
  tDecoderInit(&decoder, msg, msgLen);
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
    return -1;
  }
  tDecoderClear(&decoder);

wmmhello's avatar
wmmhello 已提交
358
  if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA || offset.val.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
359 360
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:snapshot) uid:%" PRId64 ", ts:%" PRId64,
            offset.subKey, TD_VID(pTq->pVnode), offset.val.uid, offset.val.ts);
L
Liu Jicong 已提交
361
  } else if (offset.val.type == TMQ_OFFSET__LOG) {
S
Shengliang Guan 已提交
362
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey,
L
Liu Jicong 已提交
363
            TD_VID(pTq->pVnode), offset.val.version);
364 365 366
    if (offset.val.version + 1 == version) {
      offset.val.version += 1;
    }
L
Liu Jicong 已提交
367 368
    /*} else {*/
    /*A(0);*/
369
  }
370 371 372 373 374
  STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, offset.subKey);
  if (pOffset != NULL && tqOffsetLessOrEqual(&offset, pOffset)) {
    return 0;
  }

375 376
  if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) {
    return -1;
377
  }
378 379

  if (offset.val.type == TMQ_OFFSET__LOG) {
380
    STqHandle* pHandle = taosHashGet(pTq->pHandle, offset.subKey, strlen(offset.subKey));
L
Liu Jicong 已提交
381 382 383 384
    if (pHandle) {
      if (walRefVer(pHandle->pRef, offset.val.version) < 0) {
        return -1;
      }
385 386 387
    }
  }

388 389
  // rsp

390 391
  /*}*/
  /*}*/
392 393 394 395

  return 0;
}

L
Liu Jicong 已提交
396
int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) {
L
Liu Jicong 已提交
397 398
  void* pIter = NULL;
  while (1) {
399
    pIter = taosHashIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
400
    if (pIter == NULL) break;
401
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
L
Liu Jicong 已提交
402 403
    if (pCheck->ntbUid == tbUid) {
      int32_t sz = taosArrayGetSize(pCheck->colIdList);
L
Liu Jicong 已提交
404
      for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
405 406
        int16_t forbidColId = *(int16_t*)taosArrayGet(pCheck->colIdList, i);
        if (forbidColId == colId) {
407
          taosHashCancelIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
408 409 410 411 412 413 414 415
          return -1;
        }
      }
    }
  }
  return 0;
}

L
Liu Jicong 已提交
416 417 418 419 420 421 422 423 424 425
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 已提交
426 427
  pRsp->withTbName = 0;
#if 0
L
Liu Jicong 已提交
428 429 430 431 432 433 434 435
  pRsp->withTbName = pReq->withTbName;
  if (pRsp->withTbName) {
    pRsp->blockTbName = taosArrayInit(0, sizeof(void*));
    if (pRsp->blockTbName == NULL) {
      // TODO free
      return -1;
    }
  }
L
Liu Jicong 已提交
436
#endif
L
Liu Jicong 已提交
437

L
Liu Jicong 已提交
438
  /*A(subType == TOPIC_SUB_TYPE__COLUMN);*/
L
Liu Jicong 已提交
439 440
  pRsp->withSchema = false;

L
Liu Jicong 已提交
441 442 443
  return 0;
}

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
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;
  }
  return 0;
}

L
Liu Jicong 已提交
460
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
D
dapan1121 已提交
461
  SMqPollReq   req = {0};
L
Liu Jicong 已提交
462 463
  int32_t      code = 0;
  STqOffsetVal fetchOffsetNew;
wmmhello's avatar
wmmhello 已提交
464
  SWalCkHead*  pCkHead = NULL;
L
Liu Jicong 已提交
465

D
dapan1121 已提交
466 467 468 469 470 471 472 473 474
  if (tDeserializeSMqPollReq(pMsg->pCont, pMsg->contLen, &req) < 0) {
    tqError("tDeserializeSMqPollReq %d failed", pMsg->contLen);
    return -1;
  }

  int64_t      consumerId = req.consumerId;
  int32_t      reqEpoch = req.epoch;
  STqOffsetVal reqOffset = req.reqOffset;

L
Liu Jicong 已提交
475
  // 1.find handle
D
dapan1121 已提交
476
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
477
  if (pHandle == NULL) {
S
Shengliang Guan 已提交
478
    tqError("tmq poll: no consumer handle for consumer:%" PRId64 ", in vgId:%d, subkey %s", consumerId,
D
dapan1121 已提交
479
            TD_VID(pTq->pVnode), req.subKey);
L
Liu Jicong 已提交
480 481 482 483 484
    return -1;
  }

  // check rebalance
  if (pHandle->consumerId != consumerId) {
S
Shengliang Guan 已提交
485 486
    tqError("tmq poll: consumer handle mismatch for consumer:%" PRId64
            ", in vgId:%d, subkey %s, handle consumer id %" PRId64,
D
dapan1121 已提交
487
            consumerId, TD_VID(pTq->pVnode), req.subKey, pHandle->consumerId);
L
Liu Jicong 已提交
488
    terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
L
Liu Jicong 已提交
489 490 491 492 493 494 495 496 497
    return -1;
  }

  // update epoch if need
  int32_t consumerEpoch = atomic_load_32(&pHandle->epoch);
  while (consumerEpoch < reqEpoch) {
    consumerEpoch = atomic_val_compare_exchange_32(&pHandle->epoch, consumerEpoch, reqEpoch);
  }

L
Liu Jicong 已提交
498 499
  char buf[80];
  tFormatOffset(buf, 80, &reqOffset);
S
Shengliang Guan 已提交
500
  tqDebug("tmq poll: consumer %" PRId64 " (epoch %d), subkey %s, recv poll req in vg %d, req offset %s", consumerId,
D
dapan1121 已提交
501
          req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), buf);
L
Liu Jicong 已提交
502

L
Liu Jicong 已提交
503 504 505 506
  // 2.reset offset if needed
  if (reqOffset.type > 0) {
    fetchOffsetNew = reqOffset;
  } else {
D
dapan1121 已提交
507
    STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, req.subKey);
L
Liu Jicong 已提交
508 509
    if (pOffset != NULL) {
      fetchOffsetNew = pOffset->val;
L
Liu Jicong 已提交
510 511
      char formatBuf[80];
      tFormatOffset(formatBuf, 80, &fetchOffsetNew);
L
Liu Jicong 已提交
512 513
      tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d, offset reset to %s", consumerId, pHandle->subKey,
              TD_VID(pTq->pVnode), formatBuf);
L
Liu Jicong 已提交
514 515
    } else {
      if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEAST) {
D
dapan1121 已提交
516
        if (req.useSnapshot) {
L
Liu Jicong 已提交
517
          if (pHandle->fetchMeta) {
wmmhello's avatar
wmmhello 已提交
518
            tqOffsetResetToMeta(&fetchOffsetNew, 0);
L
Liu Jicong 已提交
519
          } else {
520
            tqOffsetResetToData(&fetchOffsetNew, 0, 0);
L
Liu Jicong 已提交
521 522
          }
        } else {
L
Liu Jicong 已提交
523 524 525 526 527 528
          pHandle->pRef = walRefFirstVer(pTq->pVnode->pWal, pHandle->pRef);
          if (pHandle->pRef == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            return -1;
          }
          tqOffsetResetToLog(&fetchOffsetNew, pHandle->pRef->refVer - 1);
L
Liu Jicong 已提交
529 530
        }
      } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
L
Liu Jicong 已提交
531 532
        if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
          SMqDataRsp dataRsp = {0};
D
dapan1121 已提交
533
          tqInitDataRsp(&dataRsp, &req, pHandle->execHandle.subType);
L
Liu Jicong 已提交
534 535 536 537

          tqOffsetResetToLog(&dataRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
          tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d, offset reset to %" PRId64, consumerId,
                  pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.rspOffset.version);
D
dapan1121 已提交
538
          if (tqSendDataRsp(pTq, pMsg, &req, &dataRsp) < 0) {
L
Liu Jicong 已提交
539 540 541 542 543 544
            code = -1;
          }
          tDeleteSMqDataRsp(&dataRsp);
          return code;
        } else {
          STaosxRsp taosxRsp = {0};
D
dapan1121 已提交
545
          tqInitTaosxRsp(&taosxRsp, &req);
L
Liu Jicong 已提交
546
          tqOffsetResetToLog(&taosxRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
D
dapan1121 已提交
547
          if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
L
Liu Jicong 已提交
548 549 550 551
            code = -1;
          }
          tDeleteSTaosxRsp(&taosxRsp);
          return code;
L
Liu Jicong 已提交
552
        }
L
Liu Jicong 已提交
553
      } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) {
554 555
        tqError("tmq poll: subkey %s, no offset committed for consumer %" PRId64
                " in vg %d, subkey %s, reset none failed",
D
dapan1121 已提交
556
                pHandle->subKey, consumerId, TD_VID(pTq->pVnode), req.subKey);
L
Liu Jicong 已提交
557
        terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
558
        return -1;
L
Liu Jicong 已提交
559 560 561 562
      }
    }
  }

563 564
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
    SMqDataRsp dataRsp = {0};
D
dapan1121 已提交
565
    tqInitDataRsp(&dataRsp, &req, pHandle->execHandle.subType);
L
Liu Jicong 已提交
566 567
    // lock
    taosWLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
568 569 570
    if (tqScanData(pTq, pHandle, &dataRsp, &fetchOffsetNew) < 0) {
      return -1;
    }
571

L
Liu Jicong 已提交
572
#if 1
L
Liu Jicong 已提交
573
    if (dataRsp.blockNum == 0 && dataRsp.reqOffset.type == TMQ_OFFSET__LOG &&
574
        dataRsp.reqOffset.version == dataRsp.rspOffset.version) {
L
Liu Jicong 已提交
575 576 577
      STqPushEntry* pPushEntry = taosMemoryCalloc(1, sizeof(STqPushEntry));
      if (pPushEntry != NULL) {
        pPushEntry->pInfo = pMsg->info;
L
Liu Jicong 已提交
578
        memcpy(pPushEntry->subKey, pHandle->subKey, TSDB_SUBSCRIBE_KEY_LEN);
L
Liu Jicong 已提交
579
        dataRsp.withTbName = 0;
L
Liu Jicong 已提交
580
        memcpy(&pPushEntry->dataRsp, &dataRsp, sizeof(SMqDataRsp));
L
Liu Jicong 已提交
581 582 583
        pPushEntry->dataRsp.head.consumerId = consumerId;
        pPushEntry->dataRsp.head.epoch = reqEpoch;
        pPushEntry->dataRsp.head.mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
L
Liu Jicong 已提交
584
        taosHashPut(pTq->pPushMgr, pHandle->subKey, strlen(pHandle->subKey) + 1, &pPushEntry, sizeof(void*));
585
        tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d save handle to push mgr", consumerId, pHandle->subKey,
L
Liu Jicong 已提交
586 587 588 589 590 591
                TD_VID(pTq->pVnode));
        // unlock
        taosWUnLockLatch(&pTq->pushLock);
        return 0;
      }
    }
L
Liu Jicong 已提交
592
#endif
L
Liu Jicong 已提交
593
    taosWUnLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
594

D
dapan1121 已提交
595
    if (tqSendDataRsp(pTq, pMsg, &req, &dataRsp) < 0) {
596 597 598
      code = -1;
    }

599 600
    tqDebug("tmq poll: consumer %" PRId64
            ", subkey %s, vg %d, send data blockNum:%d, offset type:%d, uid/version:%" PRId64 ", ts:%" PRId64 "",
601
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.blockNum, dataRsp.rspOffset.type,
602
            dataRsp.rspOffset.uid, dataRsp.rspOffset.ts);
603 604 605 606 607 608

    tDeleteSMqDataRsp(&dataRsp);
    return code;
  }

  // for taosx
L
Liu Jicong 已提交
609
  /*A(pHandle->execHandle.subType != TOPIC_SUB_TYPE__COLUMN);*/
610 611 612 613

  SMqMetaRsp metaRsp = {0};

  STaosxRsp taosxRsp = {0};
D
dapan1121 已提交
614
  tqInitTaosxRsp(&taosxRsp, &req);
615 616

  if (fetchOffsetNew.type != TMQ_OFFSET__LOG) {
L
Liu Jicong 已提交
617 618 619
    if (tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, &fetchOffsetNew) < 0) {
      return -1;
    }
L
Liu Jicong 已提交
620

L
Liu Jicong 已提交
621
    if (metaRsp.metaRspLen > 0) {
D
dapan1121 已提交
622
      if (tqSendMetaPollRsp(pTq, pMsg, &req, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
623 624
        code = -1;
      }
625 626 627
      tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d, send meta offset type:%d,uid:%" PRId64
              ",version:%" PRId64 "",
              consumerId, pHandle->subKey, TD_VID(pTq->pVnode), metaRsp.rspOffset.type, metaRsp.rspOffset.uid,
L
Liu Jicong 已提交
628
              metaRsp.rspOffset.version);
wmmhello's avatar
wmmhello 已提交
629
      taosMemoryFree(metaRsp.metaRsp);
630 631
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
wmmhello's avatar
wmmhello 已提交
632 633
    }

634
    if (taosxRsp.blockNum > 0) {
D
dapan1121 已提交
635
      if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
636 637
        code = -1;
      }
638 639
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
L
Liu Jicong 已提交
640
    } else {
641
      fetchOffsetNew = taosxRsp.rspOffset;
642
    }
wmmhello's avatar
wmmhello 已提交
643

644 645
    tqDebug("taosx poll: consumer %" PRId64 ", subkey %s, vg %d, send data blockNum:%d, offset type:%d,uid:%" PRId64
            ",version:%" PRId64 "",
646 647
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), taosxRsp.blockNum, taosxRsp.rspOffset.type,
            taosxRsp.rspOffset.uid, taosxRsp.rspOffset.version);
648 649
  }

650
  if (fetchOffsetNew.type == TMQ_OFFSET__LOG) {
wmmhello's avatar
wmmhello 已提交
651 652 653
    int64_t fetchVer = fetchOffsetNew.version + 1;
    pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
654
      tDeleteSTaosxRsp(&taosxRsp);
655
      return -1;
656 657
    }

wmmhello's avatar
wmmhello 已提交
658 659 660 661 662 663
    walSetReaderCapacity(pHandle->pWalReader, 2048);

    while (1) {
      consumerEpoch = atomic_load_32(&pHandle->epoch);
      if (consumerEpoch > reqEpoch) {
        tqWarn("tmq poll: consumer %" PRId64 " (epoch %d), subkey %s, vg %d offset %" PRId64
L
Liu Jicong 已提交
664
               ", found new consumer epoch %d, discard req epoch %d",
D
dapan1121 已提交
665
               consumerId, req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), fetchVer, consumerEpoch, reqEpoch);
wmmhello's avatar
wmmhello 已提交
666 667 668 669
        break;
      }

      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead) < 0) {
670
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
D
dapan1121 已提交
671
        if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
672 673
          code = -1;
        }
674
        tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
675
        taosMemoryFreeClear(pCkHead);
676
        return code;
wmmhello's avatar
wmmhello 已提交
677 678 679
      }

      SWalCont* pHead = &pCkHead->head;
wmmhello's avatar
wmmhello 已提交
680

wmmhello's avatar
wmmhello 已提交
681
      tqDebug("tmq poll: consumer:%" PRId64 ", (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId,
D
dapan1121 已提交
682
              req.epoch, TD_VID(pTq->pVnode), fetchVer, pHead->msgType);
wmmhello's avatar
wmmhello 已提交
683 684

      if (pHead->msgType == TDMT_VND_SUBMIT) {
L
Liu Jicong 已提交
685
        SPackedData submit = {
686 687
            .msgStr = POINTER_SHIFT(pHead->body, sizeof(SSubmitReq2Msg)),
            .msgLen = pHead->bodyLen - sizeof(SSubmitReq2Msg),
L
Liu Jicong 已提交
688 689 690
            .ver = pHead->version,
        };
        if (tqTaosxScanLog(pTq, pHandle, submit, &taosxRsp) < 0) {
691 692
          tqError("tmq poll: tqTaosxScanLog error %" PRId64 ", in vgId:%d, subkey %s", consumerId, TD_VID(pTq->pVnode),
                  req.subKey);
693
          return -1;
wmmhello's avatar
wmmhello 已提交
694
        }
695 696
        if (taosxRsp.blockNum > 0 /* threshold */) {
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
D
dapan1121 已提交
697
          if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
698 699
            code = -1;
          }
700
          tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
701
          taosMemoryFreeClear(pCkHead);
702
          return code;
wmmhello's avatar
wmmhello 已提交
703 704 705 706 707
        } else {
          fetchVer++;
        }

      } else {
L
Liu Jicong 已提交
708 709
        /*A(pHandle->fetchMeta);*/
        /*A(IS_META_MSG(pHead->msgType));*/
710
        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%s", pHead->version, TMSG_INFO(pHead->msgType));
wmmhello's avatar
wmmhello 已提交
711 712 713 714
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer);
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
D
dapan1121 已提交
715
        if (tqSendMetaPollRsp(pTq, pMsg, &req, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
716
          code = -1;
L
Liu Jicong 已提交
717
          taosMemoryFreeClear(pCkHead);
718
          tDeleteSTaosxRsp(&taosxRsp);
719
          return code;
wmmhello's avatar
wmmhello 已提交
720 721
        }
        code = 0;
L
Liu Jicong 已提交
722
        taosMemoryFreeClear(pCkHead);
723
        tDeleteSTaosxRsp(&taosxRsp);
724
        return code;
wmmhello's avatar
wmmhello 已提交
725 726 727
      }
    }
  }
728
  tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
729
  taosMemoryFreeClear(pCkHead);
730
  return 0;
L
Liu Jicong 已提交
731 732
}

L
Liu Jicong 已提交
733
int32_t tqProcessDeleteSubReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
734
  SMqVDeleteReq* pReq = (SMqVDeleteReq*)msg;
L
Liu Jicong 已提交
735

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

L
Liu Jicong 已提交
738 739 740 741 742 743 744
  taosWLockLatch(&pTq->pushLock);
  int32_t code = taosHashRemove(pTq->pPushMgr, pReq->subKey, strlen(pReq->subKey));
  if (code != 0) {
    tqDebug("vgId:%d, tq remove push handle %s", pTq->pVnode->config.vgId, pReq->subKey);
  }
  taosWUnLockLatch(&pTq->pushLock);

L
Liu Jicong 已提交
745 746
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
X
Xiaoyu Wang 已提交
747
    // walCloseRef(pHandle->pWalReader->pWal, pHandle->pRef->refId);
L
Liu Jicong 已提交
748 749 750 751 752 753 754
    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 已提交
755
  }
756

L
Liu Jicong 已提交
757 758
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
759
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
760
  }
L
Liu Jicong 已提交
761

L
Liu Jicong 已提交
762
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
763
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
764
  }
L
Liu Jicong 已提交
765
  return 0;
L
Liu Jicong 已提交
766 767
}

768 769 770
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
  STqCheckInfo info = {0};
  SDecoder     decoder;
L
Liu Jicong 已提交
771
  tDecoderInit(&decoder, msg, msgLen);
772
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
773 774 775 776
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
777 778 779 780 781
  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 已提交
782 783 784 785 786 787
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

788 789 790 791 792 793 794 795 796 797 798 799
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
  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;
}

L
Liu Jicong 已提交
800
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
801
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
802 803
  tDecodeSMqRebVgReq(msg, &req);
  // todo lock
L
Liu Jicong 已提交
804 805 806

  tqDebug("vgId:%d, tq process sub req %s", pTq->pVnode->config.vgId, req.subKey);

807
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
808
  if (pHandle == NULL) {
L
Liu Jicong 已提交
809
    if (req.oldConsumerId != -1) {
810 811
      tqError("vgId:%d, build new consumer handle %s for consumer %" PRId64 ", but old consumerId is %" PRId64 "",
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
812
    }
L
Liu Jicong 已提交
813
    if (req.newConsumerId == -1) {
814
      tqError("vgId:%d, tq invalid rebalance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
815
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
816 817
      return 0;
    }
L
Liu Jicong 已提交
818 819
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
820 821
    /*taosInitRWLatch(&pExec->lock);*/

L
Liu Jicong 已提交
822 823 824
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
825

L
Liu Jicong 已提交
826
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
827
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
828

829 830 831
    // TODO version should be assigned and refed during preprocess
    SWalRef* pRef = walRefCommittedVer(pTq->pVnode->pWal);
    if (pRef == NULL) {
L
Liu Jicong 已提交
832
      return -1;
833 834 835
    }
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
836

837 838 839 840 841 842 843
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTableReader = true,
        .initTqReader = true,
        .version = ver,
    };
wmmhello's avatar
wmmhello 已提交
844
    pHandle->snapshotVer = ver;
845

L
Liu Jicong 已提交
846
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
847
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
848
      req.qmsg = NULL;
849 850

      pHandle->execHandle.task =
L
Liu Jicong 已提交
851
          qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, &pHandle->execHandle.numOfCols, NULL);
L
Liu Jicong 已提交
852
      void* scanner = NULL;
853
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
L
Liu Jicong 已提交
854
      pHandle->execHandle.pExecReader = qExtractReaderFromStreamScanner(scanner);
L
Liu Jicong 已提交
855
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
wmmhello's avatar
wmmhello 已提交
856
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
L
Liu Jicong 已提交
857
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
L
Liu Jicong 已提交
858
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
859
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
860 861
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
862

863
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, NULL, NULL);
L
Liu Jicong 已提交
864
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
wmmhello's avatar
wmmhello 已提交
865 866 867 868
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);

      pHandle->execHandle.execTb.suid = req.suid;

L
Liu Jicong 已提交
869
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
H
Hongze Cheng 已提交
870
      vnodeGetCtbIdList(pTq->pVnode, req.suid, tbUidList);
871
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pTq->pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
872 873
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
S
Shengliang Guan 已提交
874
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, TD_VID(pTq->pVnode), i, tbUid);
L
Liu Jicong 已提交
875
      }
L
Liu Jicong 已提交
876 877
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
      tqReaderSetTbUidList(pHandle->execHandle.pExecReader, tbUidList);
L
Liu Jicong 已提交
878
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
879

L
Liu Jicong 已提交
880 881 882
      buildSnapContext(handle.meta, handle.version, req.suid, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, NULL, NULL);
L
Liu Jicong 已提交
883
    }
884
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
S
Shengliang Guan 已提交
885
    tqDebug("try to persist handle %s consumer %" PRId64, req.subKey, pHandle->consumerId);
L
Liu Jicong 已提交
886
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
L
Liu Jicong 已提交
887
      return -1;
L
Liu Jicong 已提交
888
    }
L
Liu Jicong 已提交
889
  } else {
L
Liu Jicong 已提交
890
    // TODO handle qmsg and exec modification
L
Liu Jicong 已提交
891 892 893
    atomic_store_32(&pHandle->epoch, -1);
    atomic_store_64(&pHandle->consumerId, req.newConsumerId);
    atomic_add_fetch_32(&pHandle->epoch, 1);
L
Liu Jicong 已提交
894
    taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
895 896 897
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
      qStreamCloseTsdbReader(pHandle->execHandle.task);
    }
L
Liu Jicong 已提交
898
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
L
Liu Jicong 已提交
899
      return -1;
L
Liu Jicong 已提交
900
    }
L
Liu Jicong 已提交
901
    // close handle
L
Liu Jicong 已提交
902
  }
L
Liu Jicong 已提交
903

L
Liu Jicong 已提交
904
  return 0;
L
Liu Jicong 已提交
905
}
906

907
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
L
Liu Jicong 已提交
908
#if 0
909
  if (pTask->taskLevel == TASK_LEVEL__AGG) {
L
Liu Jicong 已提交
910
    A(taosArrayGetSize(pTask->childEpInfo) != 0);
L
Liu Jicong 已提交
911
  }
L
Liu Jicong 已提交
912
#endif
L
Liu Jicong 已提交
913

L
Liu Jicong 已提交
914
  pTask->refCnt = 1;
L
Liu Jicong 已提交
915
  pTask->schedStatus = TASK_SCHED_STATUS__INACTIVE;
L
Liu Jicong 已提交
916 917 918

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

  if (pTask->inputQueue == NULL || pTask->outputQueue == NULL) {
L
Liu Jicong 已提交
921
    return -1;
L
Liu Jicong 已提交
922 923
  }

L
Liu Jicong 已提交
924 925 926
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;

927 928
  pTask->pMsgCb = &pTq->pVnode->msgCb;

929 930
  pTask->startVer = ver;

931
  // expand executor
932 933 934 935
  if (pTask->fillHistory) {
    pTask->taskStatus = TASK_STATUS__WAIT_DOWNSTREAM;
  }

936
  if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
937
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
938 939 940 941
    if (pTask->pState == NULL) {
      return -1;
    }

942 943 944 945
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTqReader = 1,
946
        .pStateBackend = pTask->pState,
947 948
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle);
L
Liu Jicong 已提交
949 950 951
    if (pTask->exec.executor == NULL) {
      return -1;
    }
952

953
  } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
954
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
955 956 957
    if (pTask->pState == NULL) {
      return -1;
    }
958 959 960
    SReadHandle mgHandle = {
        .vnode = NULL,
        .numOfVgroups = (int32_t)taosArrayGetSize(pTask->childEpInfo),
961
        .pStateBackend = pTask->pState,
962 963
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &mgHandle);
L
Liu Jicong 已提交
964 965 966
    if (pTask->exec.executor == NULL) {
      return -1;
    }
L
Liu Jicong 已提交
967
  }
L
Liu Jicong 已提交
968 969

  // sink
L
Liu Jicong 已提交
970
  /*pTask->ahandle = pTq->pVnode;*/
971
  if (pTask->outputType == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
972
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
973
    pTask->smaSink.smaSink = smaHandleRes;
974
  } else if (pTask->outputType == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
975
    pTask->tbSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
976
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline2;
L
Liu Jicong 已提交
977

L
Liu Jicong 已提交
978 979
    /*A(pTask->tbSink.pSchemaWrapper);*/
    /*A(pTask->tbSink.pSchemaWrapper->pSchema);*/
L
Liu Jicong 已提交
980

L
Liu Jicong 已提交
981
    pTask->tbSink.pTSchema =
H
Hongze Cheng 已提交
982
        tBuildTSchema(pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols, 1);
983
    ASSERT(pTask->tbSink.pTSchema);
L
Liu Jicong 已提交
984
  }
985 986 987

  streamSetupTrigger(pTask);

988 989
  tqInfo("expand stream task on vg %d, task id %d, child id %d, level %d", TD_VID(pTq->pVnode), pTask->taskId,
         pTask->selfChildId, pTask->taskLevel);
L
Liu Jicong 已提交
990
  return 0;
L
Liu Jicong 已提交
991
}
L
Liu Jicong 已提交
992

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
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;
  tDecoderInit(&decoder, msgBody, msgLen);
  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 已提交
1012
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1013 1014 1015 1016 1017 1018
  if (pTask && atomic_load_8(&pTask->taskStatus) == TASK_STATUS__NORMAL) {
    rsp.status = 1;
  } else {
    rsp.status = 0;
  }

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

1021 1022 1023 1024 1025 1026 1027 1028
  tqDebug("tq recv task check req(reqId: %" PRId64 ") %d at node %d check req from task %d at node %d, status %d",
          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 已提交
1029
    tqError("unable to encode rsp %d", __LINE__);
L
Liu Jicong 已提交
1030
    return -1;
1031
  }
L
Liu Jicong 已提交
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  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;
}

int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
  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);

  tqDebug("tq recv task check rsp(reqId: %" PRId64 ") %d at node %d check req from task %d at node %d, status %d",
          rsp.reqId, rsp.downstreamTaskId, rsp.downstreamNodeId, rsp.upstreamTaskId, rsp.upstreamNodeId, rsp.status);

L
Liu Jicong 已提交
1068
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId);
1069 1070 1071 1072
  if (pTask == NULL) {
    return -1;
  }

L
Liu Jicong 已提交
1073 1074 1075
  code = streamProcessTaskCheckRsp(pTask, &rsp, version);
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
1076 1077
}

1078
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
  int32_t code;
#if 0
  code = streamMetaAddSerializedTask(pTq->pStreamMeta, version, msg, msgLen);
  if (code < 0) return code;
#endif

  // 1.deserialize msg and build task
  SStreamTask* pTask = taosMemoryCalloc(1, sizeof(SStreamTask));
  if (pTask == NULL) {
    return -1;
  }
  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
  code = streamMetaAddTask(pTq->pStreamMeta, version, pTask);
  if (code < 0) {
    return -1;
  }

  // 3.go through recover steps to fill history
  if (pTask->fillHistory) {
1108
    streamTaskCheckDownstream(pTask, version);
1109 1110 1111 1112 1113
  }

  return 0;
}

L
Liu Jicong 已提交
1114 1115 1116 1117 1118
int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) {
  int32_t code;
  char*   msg = pMsg->pCont;
  int32_t msgLen = pMsg->contLen;

1119
  SStreamRecoverStep1Req* pReq = (SStreamRecoverStep1Req*)msg;
L
Liu Jicong 已提交
1120
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1121 1122 1123 1124 1125 1126 1127
  if (pTask == NULL) {
    return -1;
  }

  // check param
  int64_t fillVer1 = pTask->startVer;
  if (fillVer1 <= 0) {
L
Liu Jicong 已提交
1128
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1129 1130 1131 1132 1133 1134
    return -1;
  }

  // do recovery step 1
  streamSourceRecoverScanStep1(pTask);

L
Liu Jicong 已提交
1135 1136 1137 1138 1139
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1140 1141 1142 1143
  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
1144
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1145 1146 1147
    return -1;
  }

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

L
Liu Jicong 已提交
1150 1151 1152 1153
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    return 0;
  }

1154
  // serialize msg
L
Liu Jicong 已提交
1155 1156 1157 1158 1159 1160 1161 1162
  int32_t len = sizeof(SStreamRecoverStep1Req);

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

  memcpy(serializedReq, &req, len);
1163 1164 1165 1166 1167

  // dispatch msg
  SRpcMsg rpcMsg = {
      .code = 0,
      .contLen = len,
L
Liu Jicong 已提交
1168
      .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE,
L
Liu Jicong 已提交
1169
      .pCont = serializedReq,
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
  };

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

  return 0;
}

int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
  int32_t                 code;
  SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg;
L
Liu Jicong 已提交
1180
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1181 1182 1183 1184 1185 1186 1187
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
  code = streamSourceRecoverScanStep2(pTask, version);
  if (code < 0) {
L
Liu Jicong 已提交
1188
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1189 1190 1191
    return -1;
  }

L
Liu Jicong 已提交
1192 1193 1194 1195 1196
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1197 1198 1199
  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1200
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1201 1202 1203 1204 1205 1206
    return -1;
  }

  // set status normal
  code = streamSetStatusNormal(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1207
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1208 1209 1210 1211 1212 1213
    return -1;
  }

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

L
Liu Jicong 已提交
1218 1219 1220
  atomic_store_8(&pTask->fillHistory, 0);
  streamMetaSaveTask(pTq->pStreamMeta, pTask);

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

1223 1224 1225
  return 0;
}

L
Liu Jicong 已提交
1226 1227 1228
int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
1229 1230

  // deserialize
1231 1232 1233
  SStreamRecoverFinishReq req;

  SDecoder decoder;
L
Liu Jicong 已提交
1234
  tDecoderInit(&decoder, msg, msgLen);
1235 1236 1237
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

1238
  // find task
L
Liu Jicong 已提交
1239
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
1240 1241 1242
  if (pTask == NULL) {
    return -1;
  }
1243
  // do process request
1244
  if (streamProcessRecoverFinishReq(pTask, req.childId) < 0) {
L
Liu Jicong 已提交
1245
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1246 1247 1248
    return -1;
  }

L
Liu Jicong 已提交
1249
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1250
  return 0;
L
Liu Jicong 已提交
1251
}
L
Liu Jicong 已提交
1252

L
Liu Jicong 已提交
1253 1254 1255 1256 1257
int32_t tqProcessTaskRecoverFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}

L
Liu Jicong 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
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 已提交
1274
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
    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);
    colDataAppend(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
    colDataAppend(pEndCol, i, (const char*)&pRes->ekey, false);
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
    colDataAppend(pUidCol, i, (const char*)pUid, false);

    colDataAppendNULL(taosArrayGet(pDelBlock->pDataBlock, GROUPID_COLUMN_INDEX), i);
    colDataAppendNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), i);
    colDataAppendNULL(taosArrayGet(pDelBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), i);
  }

L
Liu Jicong 已提交
1299 1300
  taosArrayDestroy(pRes->uidList);

L
Liu Jicong 已提交
1301 1302 1303
  int32_t* pRef = taosMemoryMalloc(sizeof(int32_t));
  *pRef = 1;

L
Liu Jicong 已提交
1304 1305 1306 1307 1308 1309 1310 1311 1312
  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 已提交
1313
    if (!failed) {
S
Shengliang Guan 已提交
1314
      SStreamRefDataBlock* pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1315 1316 1317 1318 1319 1320 1321
      pRefBlock->type = STREAM_INPUT__REF_DATA_BLOCK;
      pRefBlock->pBlock = pDelBlock;
      pRefBlock->dataRef = pRef;
      atomic_add_fetch_32(pRefBlock->dataRef, 1);

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

L
Liu Jicong 已提交
1323
        atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1324
        taosFreeQitem(pRefBlock);
L
Liu Jicong 已提交
1325 1326
        continue;
      }
L
Liu Jicong 已提交
1327

L
Liu Jicong 已提交
1328 1329 1330 1331
      if (streamSchedExec(pTask) < 0) {
        qError("stream task launch failed, task id %d", pTask->taskId);
        continue;
      }
L
Liu Jicong 已提交
1332

L
Liu Jicong 已提交
1333 1334 1335 1336
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1337

L
Liu Jicong 已提交
1338
  int32_t ref = atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1339
  /*A(ref >= 0);*/
L
Liu Jicong 已提交
1340
  if (ref == 0) {
L
Liu Jicong 已提交
1341
    blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1342 1343 1344 1345
    taosMemoryFree(pRef);
  }

#if 0
S
Shengliang Guan 已提交
1346
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    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) {
      if (streamTaskInput(pTask, (SStreamQueueItem*)pStreamBlock) < 0) {
        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 已提交
1368
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1369
#endif
L
Liu Jicong 已提交
1370 1371 1372 1373

  return 0;
}

L
Liu Jicong 已提交
1374
int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) {
L
Liu Jicong 已提交
1375 1376 1377
  void*               pIter = NULL;
  bool                failed = false;
  SStreamDataSubmit2* pSubmit = NULL;
L
Liu Jicong 已提交
1378

L
Liu Jicong 已提交
1379
  pSubmit = streamDataSubmitNew(submit);
L
Liu Jicong 已提交
1380
  if (pSubmit == NULL) {
L
Liu Jicong 已提交
1381
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1382
    tqError("failed to create data submit for stream since out of memory");
L
Liu Jicong 已提交
1383 1384 1385 1386
    failed = true;
  }

  while (1) {
L
Liu Jicong 已提交
1387
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
L
Liu Jicong 已提交
1388
    if (pIter == NULL) break;
1389
    SStreamTask* pTask = *(SStreamTask**)pIter;
1390
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) continue;
1391
    if (pTask->taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
L
Liu Jicong 已提交
1392 1393 1394
      tqDebug("skip push task %d, task status %d", pTask->taskId, pTask->taskStatus);
      continue;
    }
L
Liu Jicong 已提交
1395

L
Liu Jicong 已提交
1396
    tqDebug("data submit enqueue stream task: %d, ver: %" PRId64, pTask->taskId, submit.ver);
L
Liu Jicong 已提交
1397

L
Liu Jicong 已提交
1398 1399
    if (!failed) {
      if (streamTaskInput(pTask, (SStreamQueueItem*)pSubmit) < 0) {
L
Liu Jicong 已提交
1400
        tqError("stream task input failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1401 1402 1403
        continue;
      }

L
Liu Jicong 已提交
1404
      if (streamSchedExec(pTask) < 0) {
L
Liu Jicong 已提交
1405
        tqError("stream task launch failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1406 1407
        continue;
      }
L
Liu Jicong 已提交
1408
    } else {
L
Liu Jicong 已提交
1409
      streamTaskInputFail(pTask);
L
Liu Jicong 已提交
1410 1411 1412
    }
  }

L
Liu Jicong 已提交
1413
  if (pSubmit) {
L
Liu Jicong 已提交
1414
    streamDataSubmitRefDec(pSubmit);
L
Liu Jicong 已提交
1415
    taosFreeQitem(pSubmit);
L
Liu Jicong 已提交
1416
  }
L
Liu Jicong 已提交
1417 1418

  return failed ? -1 : 0;
L
Liu Jicong 已提交
1419 1420
}

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

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

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

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

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

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

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

1508 1509 1510 1511 1512 1513
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 已提交
1514 1515 1516 1517 1518 1519

  SStreamDispatchReq req;
  SDecoder           decoder;
  tDecoderInit(&decoder, msgBody, msgLen);
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1520
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1521 1522
    goto FAIL;
  }
L
Liu Jicong 已提交
1523
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1524

L
Liu Jicong 已提交
1525
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1526

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

1540 1541
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1542
FAIL:
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
  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 已提交
1567 1568 1569
  SRpcMsg rsp = {
      .code = code,
      .info = pMsg->info,
1570 1571
      .contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp),
      .pCont = pRspHead,
L
Liu Jicong 已提交
1572
  };
1573
  tqDebug("send dispatch error rsp, code: %x", code);
L
Liu Jicong 已提交
1574
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1575 1576
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1577
  return -1;
L
Liu Jicong 已提交
1578
}
L
Liu Jicong 已提交
1579 1580

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