tq.c 50.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;
  }
81
  pTq->path = taosStrdup(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) {
117 118
  if (pTq == NULL) {
    return;
H
Hongze Cheng 已提交
119
  }
120 121 122 123 124 125 126 127 128

  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 已提交
129
}
L
Liu Jicong 已提交
130

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

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

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

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

  return 0;
}

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

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

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

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

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

  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};
218 219
  tFormatOffset(buf1, tListLen(buf1), &pRsp->reqOffset);
  tFormatOffset(buf2, tListLen(buf2), &pRsp->rspOffset);
220
  tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) push rsp, block num: %d, req:%s, rsp:%s",
L
Liu Jicong 已提交
221
          TD_VID(pTq->pVnode), pRsp->head.consumerId, pRsp->head.epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
222 223 224 225

  return 0;
}

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

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

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

wmmhello's avatar
wmmhello 已提交
243 244
  int32_t len = 0;
  int32_t code = 0;
L
Liu Jicong 已提交
245 246 247 248 249
  tEncodeSize(tEncodeSMqDataRsp, pRsp, len, code);
  if (code < 0) {
    return -1;
  }
  int32_t tlen = sizeof(SMqRspHead) + len;
L
Liu Jicong 已提交
250 251 252 253 254 255 256 257 258 259 260
  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 已提交
261
  SEncoder encoder = {0};
L
Liu Jicong 已提交
262
  tEncoderInit(&encoder, abuf, len);
L
Liu Jicong 已提交
263
  tEncodeSMqDataRsp(&encoder, pRsp);
wmmhello's avatar
wmmhello 已提交
264
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
265 266

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

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

  return 0;
}

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

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

  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
    if (pRsp->blockNum > 0) {
L
Liu Jicong 已提交
297
      A(pRsp->rspOffset.version > pRsp->reqOffset.version);
298
    } else {
L
Liu Jicong 已提交
299
      A(pRsp->rspOffset.version >= pRsp->reqOffset.version);
300 301
    }
  }
L
Liu Jicong 已提交
302
#endif
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

  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,
  };
H
Haojun Liao 已提交
333

334 335 336 337 338 339 340
  tmsgSendRsp(&rsp);

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

H
Haojun Liao 已提交
341 342
  tqDebug("taosx rsp, vgId:%d, consumer:0x%" PRIx64 " (epoch %d) send rsp, numOfBlks:%d, req:%s, rsp:%s",
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2);
343 344 345
  return 0;
}

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

351
int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
352
  STqOffset offset = {0};
353

X
Xiaoyu Wang 已提交
354 355
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
356 357 358
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
    return -1;
  }
359

360 361
  tDecoderClear(&decoder);

wmmhello's avatar
wmmhello 已提交
362
  if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA || offset.val.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
363 364
    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 已提交
365
  } else if (offset.val.type == TMQ_OFFSET__LOG) {
S
Shengliang Guan 已提交
366
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey,
L
Liu Jicong 已提交
367
            TD_VID(pTq->pVnode), offset.val.version);
368
    if (offset.val.version + 1 == sversion) {
369 370
      offset.val.version += 1;
    }
371
  } else {
372 373
    tqError("invalid commit offset type:%d", offset.val.type);
    return -1;
374
  }
375 376 377 378

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

381
  // save the new offset value
382 383
  if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) {
    return -1;
384
  }
385 386

  if (offset.val.type == TMQ_OFFSET__LOG) {
387
    STqHandle* pHandle = taosHashGet(pTq->pHandle, offset.subKey, strlen(offset.subKey));
388 389
    if (pHandle && (walRefVer(pHandle->pRef, offset.val.version) < 0)) {
      return -1;
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
  void* pIter = NULL;
398

L
Liu Jicong 已提交
399
  while (1) {
400
    pIter = taosHashIterate(pTq->pCheckInfo, pIter);
401 402 403 404
    if (pIter == NULL) {
      break;
    }

405
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
406

L
Liu Jicong 已提交
407 408
    if (pCheck->ntbUid == tbUid) {
      int32_t sz = taosArrayGetSize(pCheck->colIdList);
L
Liu Jicong 已提交
409
      for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
410 411
        int16_t forbidColId = *(int16_t*)taosArrayGet(pCheck->colIdList, i);
        if (forbidColId == colId) {
412
          taosHashCancelIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
413 414 415 416 417
          return -1;
        }
      }
    }
  }
418

L
Liu Jicong 已提交
419 420 421
  return 0;
}

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

L
Liu Jicong 已提交
444
  /*A(subType == TOPIC_SUB_TYPE__COLUMN);*/
L
Liu Jicong 已提交
445 446
  pRsp->withSchema = false;

L
Liu Jicong 已提交
447 448 449
  return 0;
}

450 451 452 453 454 455 456 457 458 459 460 461 462
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;
  }
463

464 465 466
  return 0;
}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
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);
  *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);
    tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, prev offset found, offset reset to %s and continue.",
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), formatBuf);
    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) {
        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 已提交
498

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
        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));
        tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, offset reset to %" PRId64, consumerId,
                pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.rspOffset.version);
        int32_t code = tqSendDataRsp(pTq, pMsg, pRequest, &dataRsp);
        tDeleteSMqDataRsp(&dataRsp);

        *pBlockReturned = true;
        return code;
      } else {
        STaosxRsp taosxRsp = {0};
        tqInitTaosxRsp(&taosxRsp, pRequest);
        tqOffsetResetToLog(&taosxRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
        int32_t code = tqSendTaosxRsp(pTq, pMsg, pRequest, &taosxRsp);
        tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
520

521 522 523 524 525 526 527 528 529 530
        *pBlockReturned = true;
        return code;
      }
    } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) {
      tqError("tmq poll: subkey %s, no offset committed for consumer:0x%" PRIx64
              " in vg %d, subkey %s, reset none failed",
              pHandle->subKey, consumerId, TD_VID(pTq->pVnode), pRequest->subKey);
      terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
      return -1;
    }
L
Liu Jicong 已提交
531 532
  }

533 534
  return 0;
}
L
Liu Jicong 已提交
535

536 537
static int32_t extractDataForMq(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest, SRpcMsg* pMsg) {
  int32_t      code = -1;
538
  STqOffsetVal offset = {0};
539
  SWalCkHead*  pCkHead = NULL;
540 541 542
  int32_t      vgId = TD_VID(pTq->pVnode);

  STqOffsetVal reqOffset = pRequest->reqOffset;
543
  uint64_t     consumerId = pRequest->consumerId;
L
Liu Jicong 已提交
544

545
  // 1. reset the offset if needed
L
Liu Jicong 已提交
546
  if (reqOffset.type > 0) {
547
    offset = reqOffset;
548 549
  } else { // handle the reset offset cases, according to the consumer's choice.
    bool blockReturned = false;
550
    code = extractResetOffsetVal(&offset, pTq, pHandle, pRequest, pMsg, &blockReturned);
551 552 553 554 555 556 557
    if (code != 0) {
      return code;
    }

    // empty block returned, quit
    if (blockReturned) {
      return 0;
L
Liu Jicong 已提交
558 559 560
    }
  }

561
  // this is a normal subscription requirement
562 563
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
    SMqDataRsp dataRsp = {0};
564
    tqInitDataRsp(&dataRsp, pRequest, pHandle->execHandle.subType);
565

L
Liu Jicong 已提交
566 567
    // lock
    taosWLockLatch(&pTq->pushLock);
568
    code = tqScanData(pTq, pHandle, &dataRsp, &offset);
569

570
    // till now, all data has been transferred to consumer, new data needs to push client once arrived.
L
Liu Jicong 已提交
571
    if (dataRsp.blockNum == 0 && dataRsp.reqOffset.type == TMQ_OFFSET__LOG &&
572 573 574 575
        dataRsp.reqOffset.version == dataRsp.rspOffset.version && pHandle->consumerId == pRequest->consumerId) {
      code = tqRegisterPushEntry(pTq, pHandle, pRequest, pMsg, &dataRsp);
      taosWUnLockLatch(&pTq->pushLock);
      return code;
L
Liu Jicong 已提交
576 577
    }

578
    taosWUnLockLatch(&pTq->pushLock);
579
    code = tqSendDataRsp(pTq, pMsg, pRequest, &dataRsp);
580

581
    // NOTE: this pHandle->consumerId may have been changed already.
582 583 584 585
    tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, rsp block:%d, offset type:%d, uid/version:%" PRId64
            ", ts:%" PRId64,
            consumerId, pHandle->subKey, vgId, dataRsp.blockNum, dataRsp.rspOffset.type, dataRsp.rspOffset.uid,
            dataRsp.rspOffset.ts);
586 587 588 589 590

    tDeleteSMqDataRsp(&dataRsp);
    return code;
  }

591
  // todo handle the case where re-balance occurs.
592 593 594
  // for taosx
  SMqMetaRsp metaRsp = {0};
  STaosxRsp taosxRsp = {0};
595
  tqInitTaosxRsp(&taosxRsp, pRequest);
596

597 598
  if (offset.type != TMQ_OFFSET__LOG) {
    if (tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, &offset) < 0) {
L
Liu Jicong 已提交
599 600
      return -1;
    }
L
Liu Jicong 已提交
601

L
Liu Jicong 已提交
602
    if (metaRsp.metaRspLen > 0) {
603
      code = tqSendMetaPollRsp(pTq, pMsg, pRequest, &metaRsp);
H
Haojun Liao 已提交
604
      tqDebug("tmq poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send meta offset type:%d,uid:%" PRId64
605 606
              ",version:%" PRId64,
              consumerId, pHandle->subKey, vgId, metaRsp.rspOffset.type, metaRsp.rspOffset.uid,
L
Liu Jicong 已提交
607
              metaRsp.rspOffset.version);
wmmhello's avatar
wmmhello 已提交
608
      taosMemoryFree(metaRsp.metaRsp);
609 610
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
wmmhello's avatar
wmmhello 已提交
611 612
    }

613
    if (taosxRsp.blockNum > 0) {
614
      code = tqSendTaosxRsp(pTq, pMsg, pRequest, &taosxRsp);
615 616
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
L
Liu Jicong 已提交
617
    } else {
618
      offset = taosxRsp.rspOffset;
619
    }
wmmhello's avatar
wmmhello 已提交
620

H
Haojun Liao 已提交
621
    tqDebug("taosx poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send data blockNum:%d, offset type:%d,uid:%" PRId64
622
            ",version:%" PRId64,
623 624
            consumerId, pHandle->subKey, vgId, taosxRsp.blockNum, taosxRsp.rspOffset.type, taosxRsp.rspOffset.uid,
            taosxRsp.rspOffset.version);
625 626
  }

627 628
  if (offset.type == TMQ_OFFSET__LOG) {
    int64_t fetchVer = offset.version + 1;
wmmhello's avatar
wmmhello 已提交
629 630
    pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
631
      tDeleteSTaosxRsp(&taosxRsp);
632
      return -1;
633 634
    }

wmmhello's avatar
wmmhello 已提交
635 636 637
    walSetReaderCapacity(pHandle->pWalReader, 2048);

    while (1) {
638 639 640
      // todo refactor: this is not correct.
      int32_t savedEpoch = atomic_load_32(&pHandle->epoch);
      if (savedEpoch > pRequest->epoch) {
H
Haojun Liao 已提交
641
        tqWarn("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey:%s vgId:%d offset %" PRId64
L
Liu Jicong 已提交
642
               ", found new consumer epoch %d, discard req epoch %d",
643
               consumerId, pRequest->epoch, pHandle->subKey, vgId, fetchVer, savedEpoch, pRequest->epoch);
wmmhello's avatar
wmmhello 已提交
644 645 646 647
        break;
      }

      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead) < 0) {
648
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
H
Haojun Liao 已提交
649
        code = tqSendTaosxRsp(pTq, pMsg, pRequest, &taosxRsp);
650
        tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
651
        taosMemoryFreeClear(pCkHead);
652
        return code;
wmmhello's avatar
wmmhello 已提交
653 654 655
      }

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

657
      tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId,
658
              pRequest->epoch, vgId, fetchVer, pHead->msgType);
wmmhello's avatar
wmmhello 已提交
659 660

      if (pHead->msgType == TDMT_VND_SUBMIT) {
L
Liu Jicong 已提交
661
        SPackedData submit = {
662 663
            .msgStr = POINTER_SHIFT(pHead->body, sizeof(SSubmitReq2Msg)),
            .msgLen = pHead->bodyLen - sizeof(SSubmitReq2Msg),
L
Liu Jicong 已提交
664 665 666
            .ver = pHead->version,
        };
        if (tqTaosxScanLog(pTq, pHandle, submit, &taosxRsp) < 0) {
667
          tqError("tmq poll: tqTaosxScanLog error %" PRId64 ", in vgId:%d, subkey %s", consumerId, vgId,
668
                  pRequest->subKey);
669
          return -1;
wmmhello's avatar
wmmhello 已提交
670
        }
H
Haojun Liao 已提交
671 672

        if (taosxRsp.blockNum > 0) {
673
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
H
Haojun Liao 已提交
674
          code = tqSendTaosxRsp(pTq, pMsg, pRequest, &taosxRsp);
675
          tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
676
          taosMemoryFreeClear(pCkHead);
677
          return code;
wmmhello's avatar
wmmhello 已提交
678 679 680 681 682
        } else {
          fetchVer++;
        }

      } else {
L
Liu Jicong 已提交
683 684
        /*A(pHandle->fetchMeta);*/
        /*A(IS_META_MSG(pHead->msgType));*/
685
        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%s", pHead->version, TMSG_INFO(pHead->msgType));
wmmhello's avatar
wmmhello 已提交
686 687 688 689
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer);
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
690
        if (tqSendMetaPollRsp(pTq, pMsg, pRequest, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
691
          code = -1;
L
Liu Jicong 已提交
692
          taosMemoryFreeClear(pCkHead);
693
          tDeleteSTaosxRsp(&taosxRsp);
694
          return code;
wmmhello's avatar
wmmhello 已提交
695 696
        }
        code = 0;
L
Liu Jicong 已提交
697
        taosMemoryFreeClear(pCkHead);
698
        tDeleteSTaosxRsp(&taosxRsp);
699
        return code;
wmmhello's avatar
wmmhello 已提交
700 701 702
      }
    }
  }
703

704
  tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
705
  taosMemoryFreeClear(pCkHead);
706
  return 0;
L
Liu Jicong 已提交
707 708
}

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
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;
  }

730 731
  // 2. check re-balance status
  taosRLockLatch(&pTq->pushLock);
732 733 734 735
  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;
736
    taosRUnLockLatch(&pTq->pushLock);
737 738
    return -1;
  }
739 740 741
  taosRUnLockLatch(&pTq->pushLock);

  taosWLockLatch(&pTq->pushLock);
742
  // 3. update the epoch value
H
Haojun Liao 已提交
743 744
  int32_t savedEpoch = pHandle->epoch;
  if (savedEpoch < reqEpoch) {
745 746
    tqDebug("tmq poll: consumer:0x%" PRIx64 " epoch update from %d to %d by poll req", consumerId, savedEpoch, reqEpoch);
    pHandle->epoch = reqEpoch;
H
Haojun Liao 已提交
747
  }
748
  taosWUnLockLatch(&pTq->pushLock);
749 750 751

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

755
  return extractDataForMq(pTq, pHandle, &req, pMsg);
756 757
}

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

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

L
Liu Jicong 已提交
763 764 765 766 767 768 769
  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 已提交
770 771
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
X
Xiaoyu Wang 已提交
772
    // walCloseRef(pHandle->pWalReader->pWal, pHandle->pRef->refId);
L
Liu Jicong 已提交
773 774 775 776 777 778 779
    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 已提交
780
  }
781

L
Liu Jicong 已提交
782 783
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
784
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
785
  }
L
Liu Jicong 已提交
786

L
Liu Jicong 已提交
787
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
788
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
789
  }
L
Liu Jicong 已提交
790
  return 0;
L
Liu Jicong 已提交
791 792
}

793
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
794 795
  STqCheckInfo info = {0};
  SDecoder     decoder;
X
Xiaoyu Wang 已提交
796
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
797
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
798 799 800 801
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
802 803 804 805 806
  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 已提交
807 808 809 810 811 812
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

813
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
814 815 816 817 818 819 820 821 822 823 824
  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;
}

825
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
826
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
827
  tDecodeSMqRebVgReq(msg, &req);
L
Liu Jicong 已提交
828

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

832
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
833
  if (pHandle == NULL) {
L
Liu Jicong 已提交
834
    if (req.oldConsumerId != -1) {
H
Haojun Liao 已提交
835
      tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId is %" PRId64 "",
836
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
837
    }
838

L
Liu Jicong 已提交
839
    if (req.newConsumerId == -1) {
840
      tqError("vgId:%d, tq invalid rebalance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
841
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
842 843
      return 0;
    }
844

L
Liu Jicong 已提交
845 846
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
847 848
    /*taosInitRWLatch(&pExec->lock);*/

H
Haojun Liao 已提交
849
    uint64_t oldConsumerId = pHandle->consumerId;
L
Liu Jicong 已提交
850 851 852
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
853

L
Liu Jicong 已提交
854
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
855
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
856

857 858 859
    // TODO version should be assigned and refed during preprocess
    SWalRef* pRef = walRefCommittedVer(pTq->pVnode->pWal);
    if (pRef == NULL) {
H
Haojun Liao 已提交
860
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
861
      return -1;
862
    }
H
Haojun Liao 已提交
863

864 865
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
866

867 868 869 870 871 872 873
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTableReader = true,
        .initTqReader = true,
        .version = ver,
    };
874

wmmhello's avatar
wmmhello 已提交
875
    pHandle->snapshotVer = ver;
876

L
Liu Jicong 已提交
877
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
878
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
879
      req.qmsg = NULL;
880 881

      pHandle->execHandle.task =
L
Liu Jicong 已提交
882
          qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, &pHandle->execHandle.numOfCols, NULL);
L
Liu Jicong 已提交
883
      void* scanner = NULL;
884
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
L
Liu Jicong 已提交
885
      pHandle->execHandle.pExecReader = qExtractReaderFromStreamScanner(scanner);
L
Liu Jicong 已提交
886
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
wmmhello's avatar
wmmhello 已提交
887
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
L
Liu Jicong 已提交
888
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
889

L
Liu Jicong 已提交
890
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
891
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
892 893
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
894

895
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, NULL, NULL);
L
Liu Jicong 已提交
896
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
wmmhello's avatar
wmmhello 已提交
897 898 899
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
      pHandle->execHandle.execTb.suid = req.suid;

L
Liu Jicong 已提交
900
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
H
Hongze Cheng 已提交
901
      vnodeGetCtbIdList(pTq->pVnode, req.suid, tbUidList);
902
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pTq->pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
903 904
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
S
Shengliang Guan 已提交
905
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, TD_VID(pTq->pVnode), i, tbUid);
L
Liu Jicong 已提交
906
      }
L
Liu Jicong 已提交
907 908
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
      tqReaderSetTbUidList(pHandle->execHandle.pExecReader, tbUidList);
L
Liu Jicong 已提交
909
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
910

L
Liu Jicong 已提交
911 912 913
      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 已提交
914
    }
H
Haojun Liao 已提交
915

916
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
917 918
    tqDebug("try to persist handle %s consumer:0x%" PRIx64 " , old consumer:0x%" PRIx64, req.subKey,
            pHandle->consumerId, oldConsumerId);
L
Liu Jicong 已提交
919
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
H
Haojun Liao 已提交
920
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
921
      return -1;
L
Liu Jicong 已提交
922
    }
L
Liu Jicong 已提交
923
  } else {
924 925 926 927
    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 已提交
928
      taosMemoryFree(req.qmsg);
929 930 931 932 933 934 935
      return tqMetaSaveHandle(pTq, req.subKey, pHandle);
    }

    tqInfo("vgId:%d switch consumer from Id:0x%" PRIx64 " to Id:0x%" PRIx64, req.vgId, pHandle->consumerId,
           req.newConsumerId);

    taosWLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
936
    atomic_store_32(&pHandle->epoch, -1);
937 938 939 940

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

L
Liu Jicong 已提交
941 942
    atomic_store_64(&pHandle->consumerId, req.newConsumerId);
    atomic_add_fetch_32(&pHandle->epoch, 1);
943

L
Liu Jicong 已提交
944 945 946
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
      qStreamCloseTsdbReader(pHandle->execHandle.task);
    }
H
Haojun Liao 已提交
947

948
    taosWUnLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
949
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
H
Haojun Liao 已提交
950
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
951
      return -1;
L
Liu Jicong 已提交
952
    }
L
Liu Jicong 已提交
953
  }
L
Liu Jicong 已提交
954

H
Haojun Liao 已提交
955
  taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
956
  return 0;
L
Liu Jicong 已提交
957
}
958

959
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
L
Liu Jicong 已提交
960
#if 0
961
  if (pTask->taskLevel == TASK_LEVEL__AGG) {
L
Liu Jicong 已提交
962
    A(taosArrayGetSize(pTask->childEpInfo) != 0);
L
Liu Jicong 已提交
963
  }
L
Liu Jicong 已提交
964
#endif
L
Liu Jicong 已提交
965

L
Liu Jicong 已提交
966
  pTask->refCnt = 1;
L
Liu Jicong 已提交
967
  pTask->schedStatus = TASK_SCHED_STATUS__INACTIVE;
L
Liu Jicong 已提交
968 969 970

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

  if (pTask->inputQueue == NULL || pTask->outputQueue == NULL) {
L
Liu Jicong 已提交
973
    return -1;
L
Liu Jicong 已提交
974 975
  }

L
Liu Jicong 已提交
976 977 978
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;

979 980
  pTask->pMsgCb = &pTq->pVnode->msgCb;

981 982
  pTask->startVer = ver;

983
  // expand executor
984 985 986 987
  if (pTask->fillHistory) {
    pTask->taskStatus = TASK_STATUS__WAIT_DOWNSTREAM;
  }

988
  if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
989
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
990 991 992 993
    if (pTask->pState == NULL) {
      return -1;
    }

994 995 996 997
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTqReader = 1,
998
        .pStateBackend = pTask->pState,
999 1000
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle);
L
Liu Jicong 已提交
1001 1002 1003
    if (pTask->exec.executor == NULL) {
      return -1;
    }
1004

1005
  } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
1006
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
1007 1008 1009
    if (pTask->pState == NULL) {
      return -1;
    }
1010 1011 1012
    SReadHandle mgHandle = {
        .vnode = NULL,
        .numOfVgroups = (int32_t)taosArrayGetSize(pTask->childEpInfo),
1013
        .pStateBackend = pTask->pState,
1014 1015
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &mgHandle);
L
Liu Jicong 已提交
1016 1017 1018
    if (pTask->exec.executor == NULL) {
      return -1;
    }
L
Liu Jicong 已提交
1019
  }
L
Liu Jicong 已提交
1020 1021

  // sink
L
Liu Jicong 已提交
1022
  /*pTask->ahandle = pTq->pVnode;*/
1023
  if (pTask->outputType == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
1024
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
1025
    pTask->smaSink.smaSink = smaHandleRes;
1026
  } else if (pTask->outputType == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
1027
    pTask->tbSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
1028
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline2;
L
Liu Jicong 已提交
1029

5
54liuyao 已提交
1030 1031 1032 1033 1034 1035
    int32_t version = 1;
    SMetaInfo info = {0};
    int32_t code = metaGetInfo(pTq->pVnode->pMeta, pTask->tbSink.stbUid, &info, NULL);
    if (code == TSDB_CODE_SUCCESS) {
      version = info.skmVer;
    }
L
Liu Jicong 已提交
1036

L
Liu Jicong 已提交
1037
    pTask->tbSink.pTSchema =
5
54liuyao 已提交
1038
        tBuildTSchema(pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols, version);
1039
    ASSERT(pTask->tbSink.pTSchema);
L
Liu Jicong 已提交
1040
  }
1041 1042 1043

  streamSetupTrigger(pTask);

1044 1045
  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 已提交
1046
  return 0;
L
Liu Jicong 已提交
1047
}
L
Liu Jicong 已提交
1048

1049 1050 1051 1052 1053 1054
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 已提交
1055
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  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 已提交
1068
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1069 1070 1071 1072 1073 1074
  if (pTask && atomic_load_8(&pTask->taskStatus) == TASK_STATUS__NORMAL) {
    rsp.status = 1;
  } else {
    rsp.status = 0;
  }

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

1077
  tqDebug("tq recv task check req(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d",
1078 1079 1080 1081 1082 1083 1084
          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 已提交
1085
    tqError("unable to encode rsp %d", __LINE__);
L
Liu Jicong 已提交
1086
    return -1;
1087
  }
L
Liu Jicong 已提交
1088

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
  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;
}

1108
int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
  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);

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

L
Liu Jicong 已提交
1124
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId);
1125 1126 1127 1128
  if (pTask == NULL) {
    return -1;
  }

1129
  code = streamProcessTaskCheckRsp(pTask, &rsp, sversion);
L
Liu Jicong 已提交
1130 1131
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
1132 1133
}

1134
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1135 1136 1137 1138 1139
  int32_t code;
#if 0
  code = streamMetaAddSerializedTask(pTq->pStreamMeta, version, msg, msgLen);
  if (code < 0) return code;
#endif
5
54liuyao 已提交
1140 1141 1142
  if (tsDisableStream) {
    return 0;
  }
1143 1144 1145 1146 1147 1148

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

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
  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
1161
  code = streamMetaAddTask(pTq->pStreamMeta, sversion, pTask);
1162 1163 1164 1165 1166 1167
  if (code < 0) {
    return -1;
  }

  // 3.go through recover steps to fill history
  if (pTask->fillHistory) {
1168
    streamTaskCheckDownstream(pTask, sversion);
1169 1170 1171 1172 1173
  }

  return 0;
}

L
Liu Jicong 已提交
1174 1175 1176 1177 1178
int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) {
  int32_t code;
  char*   msg = pMsg->pCont;
  int32_t msgLen = pMsg->contLen;

1179
  SStreamRecoverStep1Req* pReq = (SStreamRecoverStep1Req*)msg;
L
Liu Jicong 已提交
1180
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1181 1182 1183 1184 1185 1186 1187
  if (pTask == NULL) {
    return -1;
  }

  // check param
  int64_t fillVer1 = pTask->startVer;
  if (fillVer1 <= 0) {
L
Liu Jicong 已提交
1188
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1189 1190 1191 1192 1193 1194
    return -1;
  }

  // do recovery step 1
  streamSourceRecoverScanStep1(pTask);

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

1200 1201 1202 1203
  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
1204
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1205 1206 1207
    return -1;
  }

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

L
Liu Jicong 已提交
1210 1211 1212 1213
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    return 0;
  }

1214
  // serialize msg
L
Liu Jicong 已提交
1215 1216 1217 1218 1219 1220 1221 1222
  int32_t len = sizeof(SStreamRecoverStep1Req);

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

  memcpy(serializedReq, &req, len);
1223 1224 1225 1226 1227

  // dispatch msg
  SRpcMsg rpcMsg = {
      .code = 0,
      .contLen = len,
L
Liu Jicong 已提交
1228
      .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE,
L
Liu Jicong 已提交
1229
      .pCont = serializedReq,
1230 1231 1232 1233 1234 1235 1236
  };

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

  return 0;
}

1237
int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1238 1239
  int32_t                 code;
  SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg;
L
Liu Jicong 已提交
1240
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1241 1242 1243 1244 1245
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
1246
  code = streamSourceRecoverScanStep2(pTask, sversion);
1247
  if (code < 0) {
L
Liu Jicong 已提交
1248
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1249 1250 1251
    return -1;
  }

L
Liu Jicong 已提交
1252 1253 1254 1255 1256
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1257 1258 1259
  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1260
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1261 1262 1263 1264 1265 1266
    return -1;
  }

  // set status normal
  code = streamSetStatusNormal(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1267
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1268 1269 1270 1271 1272 1273
    return -1;
  }

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

L
Liu Jicong 已提交
1278 1279 1280
  atomic_store_8(&pTask->fillHistory, 0);
  streamMetaSaveTask(pTq->pStreamMeta, pTask);

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

1283 1284 1285
  return 0;
}

L
Liu Jicong 已提交
1286 1287 1288
int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
1289 1290

  // deserialize
1291 1292 1293
  SStreamRecoverFinishReq req;

  SDecoder decoder;
X
Xiaoyu Wang 已提交
1294
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
1295 1296 1297
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

1298
  // find task
L
Liu Jicong 已提交
1299
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
1300 1301 1302
  if (pTask == NULL) {
    return -1;
  }
1303
  // do process request
1304
  if (streamProcessRecoverFinishReq(pTask, req.childId) < 0) {
L
Liu Jicong 已提交
1305
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1306 1307 1308
    return -1;
  }

L
Liu Jicong 已提交
1309
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1310
  return 0;
L
Liu Jicong 已提交
1311
}
L
Liu Jicong 已提交
1312

L
Liu Jicong 已提交
1313 1314 1315 1316 1317
int32_t tqProcessTaskRecoverFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}

L
Liu Jicong 已提交
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
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 已提交
1334
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    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);
1346
    colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
L
Liu Jicong 已提交
1347
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
1348
    colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false);
L
Liu Jicong 已提交
1349 1350 1351
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
1352
    colDataSetVal(pUidCol, i, (const char*)pUid, false);
L
Liu Jicong 已提交
1353

1354 1355 1356
    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 已提交
1357 1358
  }

L
Liu Jicong 已提交
1359 1360
  taosArrayDestroy(pRes->uidList);

L
Liu Jicong 已提交
1361 1362 1363
  int32_t* pRef = taosMemoryMalloc(sizeof(int32_t));
  *pRef = 1;

L
Liu Jicong 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372
  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 已提交
1373
    if (!failed) {
S
Shengliang Guan 已提交
1374
      SStreamRefDataBlock* pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1375 1376 1377 1378 1379 1380 1381
      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 已提交
1382

L
Liu Jicong 已提交
1383
        atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1384
        taosFreeQitem(pRefBlock);
L
Liu Jicong 已提交
1385 1386
        continue;
      }
L
Liu Jicong 已提交
1387

L
Liu Jicong 已提交
1388 1389 1390 1391
      if (streamSchedExec(pTask) < 0) {
        qError("stream task launch failed, task id %d", pTask->taskId);
        continue;
      }
L
Liu Jicong 已提交
1392

L
Liu Jicong 已提交
1393 1394 1395 1396
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1397

L
Liu Jicong 已提交
1398
  int32_t ref = atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1399
  /*A(ref >= 0);*/
L
Liu Jicong 已提交
1400
  if (ref == 0) {
L
Liu Jicong 已提交
1401
    blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1402 1403 1404 1405
    taosMemoryFree(pRef);
  }

#if 0
S
Shengliang Guan 已提交
1406
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    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 已提交
1428
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1429
#endif
L
Liu Jicong 已提交
1430 1431 1432 1433

  return 0;
}

L
Liu Jicong 已提交
1434
int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) {
L
Liu Jicong 已提交
1435 1436 1437
  void*               pIter = NULL;
  bool                failed = false;
  SStreamDataSubmit2* pSubmit = NULL;
L
Liu Jicong 已提交
1438

L
Liu Jicong 已提交
1439
  pSubmit = streamDataSubmitNew(submit);
L
Liu Jicong 已提交
1440
  if (pSubmit == NULL) {
L
Liu Jicong 已提交
1441
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1442
    tqError("failed to create data submit for stream since out of memory");
L
Liu Jicong 已提交
1443 1444 1445 1446
    failed = true;
  }

  while (1) {
L
Liu Jicong 已提交
1447
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
1448 1449 1450 1451
    if (pIter == NULL) {
      break;
    }

1452
    SStreamTask* pTask = *(SStreamTask**)pIter;
1453
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) continue;
1454
    if (pTask->taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
L
Liu Jicong 已提交
1455 1456 1457
      tqDebug("skip push task %d, task status %d", pTask->taskId, pTask->taskStatus);
      continue;
    }
L
Liu Jicong 已提交
1458

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

L
Liu Jicong 已提交
1461 1462
    if (!failed) {
      if (streamTaskInput(pTask, (SStreamQueueItem*)pSubmit) < 0) {
L
Liu Jicong 已提交
1463
        tqError("stream task input failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1464 1465 1466
        continue;
      }

L
Liu Jicong 已提交
1467
      if (streamSchedExec(pTask) < 0) {
L
Liu Jicong 已提交
1468
        tqError("stream task launch failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1469 1470
        continue;
      }
L
Liu Jicong 已提交
1471
    } else {
L
Liu Jicong 已提交
1472
      streamTaskInputFail(pTask);
L
Liu Jicong 已提交
1473 1474 1475
    }
  }

L
Liu Jicong 已提交
1476
  if (pSubmit) {
L
Liu Jicong 已提交
1477
    streamDataSubmitRefDec(pSubmit);
L
Liu Jicong 已提交
1478
    taosFreeQitem(pSubmit);
L
Liu Jicong 已提交
1479
  }
L
Liu Jicong 已提交
1480 1481

  return failed ? -1 : 0;
L
Liu Jicong 已提交
1482 1483
}

L
Liu Jicong 已提交
1484 1485 1486
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRunReq* pReq = pMsg->pCont;
  int32_t            taskId = pReq->taskId;
L
Liu Jicong 已提交
1487
  SStreamTask*       pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1488 1489
  if (pTask) {
    streamProcessRunReq(pTask);
L
Liu Jicong 已提交
1490
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1491
    return 0;
1492 1493
  } else {
    return -1;
L
Liu Jicong 已提交
1494
  }
L
Liu Jicong 已提交
1495 1496
}

L
Liu Jicong 已提交
1497
int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg, bool exec) {
1498 1499 1500 1501 1502
  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 已提交
1503
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1504
  tDecodeStreamDispatchReq(&decoder, &req);
L
Liu Jicong 已提交
1505 1506
  int32_t taskId = req.taskId;

L
Liu Jicong 已提交
1507
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1508
  if (pTask) {
1509 1510 1511 1512
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1513
    streamProcessDispatchReq(pTask, &req, &rsp, exec);
L
Liu Jicong 已提交
1514
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1515
    return 0;
1516 1517
  } else {
    return -1;
L
Liu Jicong 已提交
1518
  }
L
Liu Jicong 已提交
1519 1520
}

L
Liu Jicong 已提交
1521 1522
int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
1523
  int32_t             taskId = ntohl(pRsp->upstreamTaskId);
L
Liu Jicong 已提交
1524
  SStreamTask*        pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1525
  tqDebug("recv dispatch rsp, code: %x", pMsg->code);
L
Liu Jicong 已提交
1526
  if (pTask) {
1527
    streamProcessDispatchRsp(pTask, pRsp, pMsg->code);
L
Liu Jicong 已提交
1528
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1529
    return 0;
1530 1531
  } else {
    return -1;
L
Liu Jicong 已提交
1532
  }
L
Liu Jicong 已提交
1533
}
L
Liu Jicong 已提交
1534

1535
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1536
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1537
  streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId);
L
Liu Jicong 已提交
1538
  return 0;
L
Liu Jicong 已提交
1539
}
L
Liu Jicong 已提交
1540 1541 1542 1543 1544 1545 1546

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;
1547
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1548
  tDecodeStreamRetrieveReq(&decoder, &req);
L
Liu Jicong 已提交
1549
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1550
  int32_t      taskId = req.dstTaskId;
L
Liu Jicong 已提交
1551
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1552
  if (pTask) {
L
Liu Jicong 已提交
1553 1554 1555 1556
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1557
    streamProcessRetrieveReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
1558
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1559
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1560
    return 0;
L
Liu Jicong 已提交
1561 1562
  } else {
    return -1;
L
Liu Jicong 已提交
1563 1564 1565 1566 1567 1568 1569
  }
}

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

1571 1572 1573 1574 1575 1576
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 已提交
1577 1578 1579

  SStreamDispatchReq req;
  SDecoder           decoder;
1580
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1581 1582
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1583
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1584 1585
    goto FAIL;
  }
L
Liu Jicong 已提交
1586
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1587

L
Liu Jicong 已提交
1588
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1589

L
Liu Jicong 已提交
1590
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1591
  if (pTask) {
L
Liu Jicong 已提交
1592 1593 1594 1595
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1596
    streamProcessDispatchReq(pTask, &req, &rsp, false);
L
Liu Jicong 已提交
1597
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1598 1599
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
1600
    return 0;
L
Liu Jicong 已提交
1601
  }
L
Liu Jicong 已提交
1602

1603 1604
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1605
FAIL:
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
  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 已提交
1630 1631 1632
  SRpcMsg rsp = {
      .code = code,
      .info = pMsg->info,
1633 1634
      .contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp),
      .pCont = pRspHead,
L
Liu Jicong 已提交
1635
  };
1636
  tqDebug("send dispatch error rsp, code: %x", code);
L
Liu Jicong 已提交
1637
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1638 1639
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1640
  return -1;
L
Liu Jicong 已提交
1641
}
L
Liu Jicong 已提交
1642

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