tq.c 47.0 KB
Newer Older
H
refact  
Hongze Cheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
S
Shengliang Guan 已提交
14 15
 */

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

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;
83

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

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

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

L
Liu Jicong 已提交
94
  if (tqMetaOpen(pTq) < 0) {
95
    ASSERT(0);
96 97
  }

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

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

L
Liu Jicong 已提交
108
  if (streamLoadTasks(pTq->pStreamMeta) < 0) {
109
    ASSERT(0);
L
Liu Jicong 已提交
110 111
  }

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

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

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

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

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

160 161
  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 已提交
162 163 164 165

  return 0;
}

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

169 170
  ASSERT(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
  ASSERT(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);
L
Liu Jicong 已提交
171

172 173
  ASSERT(!pRsp->withSchema);
  ASSERT(taosArrayGetSize(pRsp->blockSchema) == 0);
L
Liu Jicong 已提交
174 175

  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
L
Liu Jicong 已提交
176
    /*if (pRsp->blockNum > 0) {*/
177
    /*ASSERT(pRsp->rspOffset.version > pRsp->reqOffset.version);*/
L
Liu Jicong 已提交
178
    /*} else {*/
179
    ASSERT(pRsp->rspOffset.version > pRsp->reqOffset.version);
L
Liu Jicong 已提交
180
    /*}*/
L
Liu Jicong 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  }

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

  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 已提交
220
          TD_VID(pTq->pVnode), pRsp->head.consumerId, pRsp->head.epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
221 222 223 224

  return 0;
}

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

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

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

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

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

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

  return 0;
}

281
int32_t tqSendTaosxRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const STaosxRsp* pRsp) {
282 283
  ASSERT(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
  ASSERT(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);
284 285

  if (pRsp->withSchema) {
286
    ASSERT(taosArrayGetSize(pRsp->blockSchema) == pRsp->blockNum);
287
  } else {
288
    ASSERT(taosArrayGetSize(pRsp->blockSchema) == 0);
289 290 291 292
  }

  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
    if (pRsp->blockNum > 0) {
293
      ASSERT(pRsp->rspOffset.version > pRsp->reqOffset.version);
294
    } else {
295
      ASSERT(pRsp->rspOffset.version >= pRsp->reqOffset.version);
296 297 298 299 300 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
    }
  }

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

341 342 343 344 345 346
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) {
347 348 349 350
  STqOffset offset = {0};
  SDecoder  decoder;
  tDecoderInit(&decoder, msg, msgLen);
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
351
    ASSERT(0);
352 353 354 355
    return -1;
  }
  tDecoderClear(&decoder);

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

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

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

387 388
  // rsp

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

  return 0;
}

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

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

437
  ASSERT(subType == TOPIC_SUB_TYPE__COLUMN);
L
Liu Jicong 已提交
438 439
  pRsp->withSchema = false;

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

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
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 已提交
459
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
D
dapan1121 已提交
460
  SMqPollReq   req = {0};
L
Liu Jicong 已提交
461 462
  int32_t      code = 0;
  STqOffsetVal fetchOffsetNew;
wmmhello's avatar
wmmhello 已提交
463
  SWalCkHead*  pCkHead = NULL;
L
Liu Jicong 已提交
464

D
dapan1121 已提交
465 466 467 468 469 470 471 472 473
  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 已提交
474
  // 1.find handle
D
dapan1121 已提交
475
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
476
  /*ASSERT(pHandle);*/
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 523 524 525
          }
        } else {
          tqOffsetResetToLog(&fetchOffsetNew, walGetFirstVer(pTq->pVnode->pWal));
        }
      } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
L
Liu Jicong 已提交
526 527
        if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
          SMqDataRsp dataRsp = {0};
D
dapan1121 已提交
528
          tqInitDataRsp(&dataRsp, &req, pHandle->execHandle.subType);
L
Liu Jicong 已提交
529 530 531 532

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

558 559
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
    SMqDataRsp dataRsp = {0};
D
dapan1121 已提交
560
    tqInitDataRsp(&dataRsp, &req, pHandle->execHandle.subType);
L
Liu Jicong 已提交
561 562
    // lock
    taosWLockLatch(&pTq->pushLock);
563 564
    tqScanData(pTq, pHandle, &dataRsp, &fetchOffsetNew);

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

D
dapan1121 已提交
588
    if (tqSendDataRsp(pTq, pMsg, &req, &dataRsp) < 0) {
589 590 591
      code = -1;
    }

592 593
    tqDebug("tmq poll: consumer %" PRId64
            ", subkey %s, vg %d, send data blockNum:%d, offset type:%d, uid/version:%" PRId64 ", ts:%" PRId64 "",
594
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.blockNum, dataRsp.rspOffset.type,
595
            dataRsp.rspOffset.uid, dataRsp.rspOffset.ts);
596 597 598 599 600 601

    tDeleteSMqDataRsp(&dataRsp);
    return code;
  }

  // for taosx
602
  ASSERT(pHandle->execHandle.subType != TOPIC_SUB_TYPE__COLUMN);
603 604 605 606

  SMqMetaRsp metaRsp = {0};

  STaosxRsp taosxRsp = {0};
D
dapan1121 已提交
607
  tqInitTaosxRsp(&taosxRsp, &req);
608 609

  if (fetchOffsetNew.type != TMQ_OFFSET__LOG) {
L
Liu Jicong 已提交
610
    tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, &fetchOffsetNew);
L
Liu Jicong 已提交
611

L
Liu Jicong 已提交
612
    if (metaRsp.metaRspLen > 0) {
D
dapan1121 已提交
613
      if (tqSendMetaPollRsp(pTq, pMsg, &req, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
614 615
        code = -1;
      }
616 617 618
      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 已提交
619
              metaRsp.rspOffset.version);
wmmhello's avatar
wmmhello 已提交
620
      taosMemoryFree(metaRsp.metaRsp);
621 622
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
wmmhello's avatar
wmmhello 已提交
623 624
    }

625
    if (taosxRsp.blockNum > 0) {
D
dapan1121 已提交
626
      if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
627 628
        code = -1;
      }
629 630
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
L
Liu Jicong 已提交
631
    } else {
632
      fetchOffsetNew = taosxRsp.rspOffset;
633
    }
wmmhello's avatar
wmmhello 已提交
634

635 636
    tqDebug("taosx poll: consumer %" PRId64 ", subkey %s, vg %d, send data blockNum:%d, offset type:%d,uid:%" PRId64
            ",version:%" PRId64 "",
637 638
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), taosxRsp.blockNum, taosxRsp.rspOffset.type,
            taosxRsp.rspOffset.uid, taosxRsp.rspOffset.version);
639 640
  }

641
  if (fetchOffsetNew.type == TMQ_OFFSET__LOG) {
wmmhello's avatar
wmmhello 已提交
642 643 644
    int64_t fetchVer = fetchOffsetNew.version + 1;
    pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
645
      tDeleteSTaosxRsp(&taosxRsp);
646
      return -1;
647 648
    }

wmmhello's avatar
wmmhello 已提交
649 650 651 652 653 654
    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 已提交
655
               ", found new consumer epoch %d, discard req epoch %d",
D
dapan1121 已提交
656
               consumerId, req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), fetchVer, consumerEpoch, reqEpoch);
wmmhello's avatar
wmmhello 已提交
657 658 659 660
        break;
      }

      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead) < 0) {
661
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
D
dapan1121 已提交
662
        if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
663 664
          code = -1;
        }
665
        tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
666
        taosMemoryFreeClear(pCkHead);
667
        return code;
wmmhello's avatar
wmmhello 已提交
668 669 670
      }

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

wmmhello's avatar
wmmhello 已提交
672
      tqDebug("tmq poll: consumer:%" PRId64 ", (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId,
D
dapan1121 已提交
673
              req.epoch, TD_VID(pTq->pVnode), fetchVer, pHead->msgType);
wmmhello's avatar
wmmhello 已提交
674 675 676 677

      if (pHead->msgType == TDMT_VND_SUBMIT) {
        SSubmitReq* pCont = (SSubmitReq*)&pHead->body;

678
        if (tqTaosxScanLog(pTq, pHandle, pCont, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
679
        }
680 681
        if (taosxRsp.blockNum > 0 /* threshold */) {
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
D
dapan1121 已提交
682
          if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
683 684
            code = -1;
          }
685
          tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
686
          taosMemoryFreeClear(pCkHead);
687
          return code;
wmmhello's avatar
wmmhello 已提交
688 689 690 691 692
        } else {
          fetchVer++;
        }

      } else {
693 694
        ASSERT(pHandle->fetchMeta);
        ASSERT(IS_META_MSG(pHead->msgType));
wmmhello's avatar
wmmhello 已提交
695 696 697 698 699
        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%d", pHead->version, pHead->msgType);
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer);
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
D
dapan1121 已提交
700
        if (tqSendMetaPollRsp(pTq, pMsg, &req, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
701
          code = -1;
L
Liu Jicong 已提交
702
          taosMemoryFreeClear(pCkHead);
703
          tDeleteSTaosxRsp(&taosxRsp);
704
          return code;
wmmhello's avatar
wmmhello 已提交
705 706
        }
        code = 0;
L
Liu Jicong 已提交
707
        taosMemoryFreeClear(pCkHead);
708
        tDeleteSTaosxRsp(&taosxRsp);
709
        return code;
wmmhello's avatar
wmmhello 已提交
710 711 712
      }
    }
  }
713
  tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
714
  taosMemoryFreeClear(pCkHead);
715
  return 0;
L
Liu Jicong 已提交
716 717
}

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

L
Liu Jicong 已提交
721 722 723 724 725 726 727
  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 已提交
728 729 730 731 732 733 734 735 736
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
    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 已提交
737
  }
738

L
Liu Jicong 已提交
739 740 741 742
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
    tqError("cannot process tq delete req %s, since no such offset", pReq->subKey);
  }
L
Liu Jicong 已提交
743

L
Liu Jicong 已提交
744
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
745
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
746
  }
L
Liu Jicong 已提交
747
  return 0;
L
Liu Jicong 已提交
748 749
}

750 751 752
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
  STqCheckInfo info = {0};
  SDecoder     decoder;
L
Liu Jicong 已提交
753
  tDecoderInit(&decoder, msg, msgLen);
754
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
755 756 757 758
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
759 760 761 762 763
  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 已提交
764 765 766 767 768 769
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

770 771 772 773 774 775 776 777 778 779 780 781
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 已提交
782
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
783
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
784 785
  tDecodeSMqRebVgReq(msg, &req);
  // todo lock
786
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
787
  if (pHandle == NULL) {
L
Liu Jicong 已提交
788
    if (req.oldConsumerId != -1) {
789 790
      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 已提交
791
    }
L
Liu Jicong 已提交
792
    if (req.newConsumerId == -1) {
793
      tqError("vgId:%d, tq invalid rebalance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
794
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
795 796
      return 0;
    }
L
Liu Jicong 已提交
797 798
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
799 800
    /*taosInitRWLatch(&pExec->lock);*/

L
Liu Jicong 已提交
801 802 803
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
804

L
Liu Jicong 已提交
805
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
806
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
807

808 809 810
    // TODO version should be assigned and refed during preprocess
    SWalRef* pRef = walRefCommittedVer(pTq->pVnode->pWal);
    if (pRef == NULL) {
811
      ASSERT(0);
L
Liu Jicong 已提交
812
      return -1;
813 814 815
    }
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
816

817 818 819 820 821 822 823
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTableReader = true,
        .initTqReader = true,
        .version = ver,
    };
wmmhello's avatar
wmmhello 已提交
824
    pHandle->snapshotVer = ver;
825

L
Liu Jicong 已提交
826
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
827
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
828
      req.qmsg = NULL;
829 830

      pHandle->execHandle.task =
L
Liu Jicong 已提交
831
          qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, &pHandle->execHandle.numOfCols, NULL);
832
      ASSERT(pHandle->execHandle.task);
L
Liu Jicong 已提交
833
      void* scanner = NULL;
834
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
835
      ASSERT(scanner);
L
Liu Jicong 已提交
836
      pHandle->execHandle.pExecReader = qExtractReaderFromStreamScanner(scanner);
837
      ASSERT(pHandle->execHandle.pExecReader);
L
Liu Jicong 已提交
838
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
wmmhello's avatar
wmmhello 已提交
839
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
L
Liu Jicong 已提交
840
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
L
Liu Jicong 已提交
841
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
842
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
843 844
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
845

846
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, NULL, NULL);
L
Liu Jicong 已提交
847
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
wmmhello's avatar
wmmhello 已提交
848 849 850 851
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);

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

L
Liu Jicong 已提交
852
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
H
Hongze Cheng 已提交
853
      vnodeGetCtbIdList(pTq->pVnode, req.suid, tbUidList);
854
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pTq->pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
855 856
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
S
Shengliang Guan 已提交
857
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, TD_VID(pTq->pVnode), i, tbUid);
L
Liu Jicong 已提交
858
      }
L
Liu Jicong 已提交
859 860
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
      tqReaderSetTbUidList(pHandle->execHandle.pExecReader, tbUidList);
L
Liu Jicong 已提交
861
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
862

L
Liu Jicong 已提交
863 864 865
      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 已提交
866
    }
867
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
S
Shengliang Guan 已提交
868
    tqDebug("try to persist handle %s consumer %" PRId64, req.subKey, pHandle->consumerId);
L
Liu Jicong 已提交
869 870
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
      // TODO
871
      ASSERT(0);
L
Liu Jicong 已提交
872
    }
L
Liu Jicong 已提交
873
  } else {
874
    /*ASSERT(pExec->consumerId == req.oldConsumerId);*/
L
Liu Jicong 已提交
875
    // TODO handle qmsg and exec modification
L
Liu Jicong 已提交
876 877 878
    atomic_store_32(&pHandle->epoch, -1);
    atomic_store_64(&pHandle->consumerId, req.newConsumerId);
    atomic_add_fetch_32(&pHandle->epoch, 1);
L
Liu Jicong 已提交
879
    taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
880 881
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
      // TODO
882
      ASSERT(0);
L
Liu Jicong 已提交
883
    }
L
Liu Jicong 已提交
884
    // close handle
L
Liu Jicong 已提交
885
  }
L
Liu Jicong 已提交
886

L
Liu Jicong 已提交
887
  return 0;
L
Liu Jicong 已提交
888
}
889

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

L
Liu Jicong 已提交
895
  pTask->refCnt = 1;
L
Liu Jicong 已提交
896
  pTask->schedStatus = TASK_SCHED_STATUS__INACTIVE;
L
Liu Jicong 已提交
897 898 899

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

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

L
Liu Jicong 已提交
905 906 907
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;

908 909
  pTask->pMsgCb = &pTq->pVnode->msgCb;

910 911
  pTask->startVer = ver;

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

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

923 924 925 926
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTqReader = 1,
927
        .pStateBackend = pTask->pState,
928 929
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle);
930
    ASSERT(pTask->exec.executor);
931

932
  } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
933
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
934 935 936
    if (pTask->pState == NULL) {
      return -1;
    }
937 938 939
    SReadHandle mgHandle = {
        .vnode = NULL,
        .numOfVgroups = (int32_t)taosArrayGetSize(pTask->childEpInfo),
940
        .pStateBackend = pTask->pState,
941 942
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &mgHandle);
943
    ASSERT(pTask->exec.executor);
L
Liu Jicong 已提交
944
  }
L
Liu Jicong 已提交
945 946

  // sink
L
Liu Jicong 已提交
947
  /*pTask->ahandle = pTq->pVnode;*/
948
  if (pTask->outputType == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
949
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
950
    pTask->smaSink.smaSink = smaHandleRes;
951
  } else if (pTask->outputType == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
952
    pTask->tbSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
953
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline;
L
Liu Jicong 已提交
954

955 956
    ASSERT(pTask->tbSink.pSchemaWrapper);
    ASSERT(pTask->tbSink.pSchemaWrapper->pSchema);
L
Liu Jicong 已提交
957

L
Liu Jicong 已提交
958
    pTask->tbSink.pTSchema =
C
Cary Xu 已提交
959
        tdGetSTSChemaFromSSChema(pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols, 1);
960
    ASSERT(pTask->tbSink.pTSchema);
L
Liu Jicong 已提交
961
  }
962 963 964

  streamSetupTrigger(pTask);

965 966
  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 已提交
967
  return 0;
L
Liu Jicong 已提交
968
}
L
Liu Jicong 已提交
969

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
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 已提交
989
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
990 991 992 993 994 995
  if (pTask && atomic_load_8(&pTask->taskStatus) == TASK_STATUS__NORMAL) {
    rsp.status = 1;
  } else {
    rsp.status = 0;
  }

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

998 999 1000 1001 1002 1003 1004 1005
  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) {
1006
    ASSERT(0);
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  }
  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 已提交
1043
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId);
1044 1045 1046 1047
  if (pTask == NULL) {
    return -1;
  }

L
Liu Jicong 已提交
1048 1049 1050
  code = streamProcessTaskCheckRsp(pTask, &rsp, version);
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
1051 1052
}

1053
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
  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) {
1083
    streamTaskCheckDownstream(pTask, version);
1084 1085 1086 1087 1088
  }

  return 0;
}

L
Liu Jicong 已提交
1089 1090 1091 1092 1093
int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) {
  int32_t code;
  char*   msg = pMsg->pCont;
  int32_t msgLen = pMsg->contLen;

1094
  SStreamRecoverStep1Req* pReq = (SStreamRecoverStep1Req*)msg;
L
Liu Jicong 已提交
1095
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1096 1097 1098
  if (pTask == NULL) {
    return -1;
  }
1099
  ASSERT(pReq->taskId == pTask->taskId);
1100 1101 1102 1103

  // check param
  int64_t fillVer1 = pTask->startVer;
  if (fillVer1 <= 0) {
1104
    ASSERT(0);
L
Liu Jicong 已提交
1105
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
    return -1;
  }

  // do recovery step 1
  streamSourceRecoverScanStep1(pTask);

  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
1116
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1117 1118 1119
    return -1;
  }

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

1122
  // serialize msg
L
Liu Jicong 已提交
1123 1124 1125 1126 1127 1128 1129 1130
  int32_t len = sizeof(SStreamRecoverStep1Req);

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

  memcpy(serializedReq, &req, len);
1131 1132 1133 1134 1135

  // dispatch msg
  SRpcMsg rpcMsg = {
      .code = 0,
      .contLen = len,
L
Liu Jicong 已提交
1136
      .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE,
L
Liu Jicong 已提交
1137
      .pCont = serializedReq,
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  };

  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 已提交
1148
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1149 1150 1151 1152 1153 1154 1155
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
  code = streamSourceRecoverScanStep2(pTask, version);
  if (code < 0) {
L
Liu Jicong 已提交
1156
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1157 1158 1159 1160 1161 1162
    return -1;
  }

  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1163
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1164 1165 1166 1167 1168 1169
    return -1;
  }

  // set status normal
  code = streamSetStatusNormal(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1170
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1171 1172 1173 1174 1175 1176
    return -1;
  }

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

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

1183 1184 1185
  return 0;
}

L
Liu Jicong 已提交
1186 1187 1188
int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
1189 1190

  // deserialize
1191 1192 1193
  SStreamRecoverFinishReq req;

  SDecoder decoder;
L
Liu Jicong 已提交
1194
  tDecoderInit(&decoder, msg, msgLen);
1195 1196 1197
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

1198
  // find task
L
Liu Jicong 已提交
1199
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
1200 1201 1202
  if (pTask == NULL) {
    return -1;
  }
1203
  // do process request
1204
  if (streamProcessRecoverFinishReq(pTask, req.childId) < 0) {
L
Liu Jicong 已提交
1205
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1206 1207 1208
    return -1;
  }

L
Liu Jicong 已提交
1209
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1210
  return 0;
L
Liu Jicong 已提交
1211
}
L
Liu Jicong 已提交
1212

L
Liu Jicong 已提交
1213 1214 1215 1216 1217
int32_t tqProcessTaskRecoverFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}

L
Liu Jicong 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
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 已提交
1234
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    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 已提交
1259 1260
  taosArrayDestroy(pRes->uidList);

L
Liu Jicong 已提交
1261 1262 1263
  int32_t* pRef = taosMemoryMalloc(sizeof(int32_t));
  *pRef = 1;

L
Liu Jicong 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272
  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 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281
    if (!failed) {
      SStreamRefDataBlock* pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM);
      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 已提交
1282

L
Liu Jicong 已提交
1283
        atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1284
        taosFreeQitem(pRefBlock);
L
Liu Jicong 已提交
1285 1286
        continue;
      }
L
Liu Jicong 已提交
1287

L
Liu Jicong 已提交
1288 1289 1290 1291
      if (streamSchedExec(pTask) < 0) {
        qError("stream task launch failed, task id %d", pTask->taskId);
        continue;
      }
L
Liu Jicong 已提交
1292

L
Liu Jicong 已提交
1293 1294 1295 1296
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1297

L
Liu Jicong 已提交
1298
  int32_t ref = atomic_sub_fetch_32(pRef, 1);
1299
  ASSERT(ref >= 0);
L
Liu Jicong 已提交
1300
  if (ref == 0) {
L
Liu Jicong 已提交
1301
    blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1302 1303 1304 1305
    taosMemoryFree(pRef);
  }

#if 0
L
Liu Jicong 已提交
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM);
    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 已提交
1328
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1329
#endif
L
Liu Jicong 已提交
1330 1331 1332 1333 1334

  return 0;
}

int32_t tqProcessSubmitReq(STQ* pTq, SSubmitReq* pReq, int64_t ver) {
L
Liu Jicong 已提交
1335 1336 1337
  void*              pIter = NULL;
  bool               failed = false;
  SStreamDataSubmit* pSubmit = NULL;
L
Liu Jicong 已提交
1338

L
Liu Jicong 已提交
1339
  pSubmit = streamDataSubmitNew(pReq);
L
Liu Jicong 已提交
1340
  if (pSubmit == NULL) {
L
Liu Jicong 已提交
1341
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1342
    tqError("failed to create data submit for stream since out of memory");
L
Liu Jicong 已提交
1343 1344 1345 1346
    failed = true;
  }

  while (1) {
L
Liu Jicong 已提交
1347
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
L
Liu Jicong 已提交
1348
    if (pIter == NULL) break;
1349
    SStreamTask* pTask = *(SStreamTask**)pIter;
1350
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) continue;
1351
    if (pTask->taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
L
Liu Jicong 已提交
1352 1353 1354
      tqDebug("skip push task %d, task status %d", pTask->taskId, pTask->taskStatus);
      continue;
    }
L
Liu Jicong 已提交
1355

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

L
Liu Jicong 已提交
1358 1359
    if (!failed) {
      if (streamTaskInput(pTask, (SStreamQueueItem*)pSubmit) < 0) {
L
Liu Jicong 已提交
1360
        tqError("stream task input failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1361 1362 1363
        continue;
      }

L
Liu Jicong 已提交
1364
      if (streamSchedExec(pTask) < 0) {
L
Liu Jicong 已提交
1365
        tqError("stream task launch failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1366 1367
        continue;
      }
L
Liu Jicong 已提交
1368
    } else {
L
Liu Jicong 已提交
1369
      streamTaskInputFail(pTask);
L
Liu Jicong 已提交
1370 1371 1372
    }
  }

L
Liu Jicong 已提交
1373
  if (pSubmit) {
L
Liu Jicong 已提交
1374
    streamDataSubmitRefDec(pSubmit);
L
Liu Jicong 已提交
1375
    taosFreeQitem(pSubmit);
L
Liu Jicong 已提交
1376
  }
L
Liu Jicong 已提交
1377 1378

  return failed ? -1 : 0;
L
Liu Jicong 已提交
1379 1380
}

L
Liu Jicong 已提交
1381 1382 1383
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRunReq* pReq = pMsg->pCont;
  int32_t            taskId = pReq->taskId;
L
Liu Jicong 已提交
1384
  SStreamTask*       pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1385 1386
  if (pTask) {
    streamProcessRunReq(pTask);
L
Liu Jicong 已提交
1387
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1388
    return 0;
1389 1390
  } else {
    return -1;
L
Liu Jicong 已提交
1391
  }
L
Liu Jicong 已提交
1392 1393
}

L
Liu Jicong 已提交
1394
int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg, bool exec) {
1395 1396 1397 1398 1399
  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 已提交
1400
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1401
  tDecodeStreamDispatchReq(&decoder, &req);
L
Liu Jicong 已提交
1402 1403
  int32_t taskId = req.taskId;

L
Liu Jicong 已提交
1404
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1405
  if (pTask) {
1406 1407 1408 1409
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1410
    streamProcessDispatchReq(pTask, &req, &rsp, exec);
L
Liu Jicong 已提交
1411
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1412
    return 0;
1413 1414
  } else {
    return -1;
L
Liu Jicong 已提交
1415
  }
L
Liu Jicong 已提交
1416 1417
}

L
Liu Jicong 已提交
1418 1419
int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
1420
  int32_t             taskId = ntohl(pRsp->upstreamTaskId);
L
Liu Jicong 已提交
1421
  SStreamTask*        pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1422
  tqDebug("recv dispatch rsp, code: %x", pMsg->code);
L
Liu Jicong 已提交
1423
  if (pTask) {
1424
    streamProcessDispatchRsp(pTask, pRsp, pMsg->code);
L
Liu Jicong 已提交
1425
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1426
    return 0;
1427 1428
  } else {
    return -1;
L
Liu Jicong 已提交
1429
  }
L
Liu Jicong 已提交
1430
}
L
Liu Jicong 已提交
1431

1432
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t version, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1433
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1434
  streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId);
L
Liu Jicong 已提交
1435
  return 0;
L
Liu Jicong 已提交
1436
}
L
Liu Jicong 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445

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 已提交
1446
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1447
  int32_t      taskId = req.dstTaskId;
L
Liu Jicong 已提交
1448
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1449
  if (pTask) {
L
Liu Jicong 已提交
1450 1451 1452 1453
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1454
    streamProcessRetrieveReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
1455
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1456
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1457
    return 0;
L
Liu Jicong 已提交
1458 1459
  } else {
    return -1;
L
Liu Jicong 已提交
1460 1461 1462 1463 1464 1465 1466
  }
}

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

1468 1469 1470 1471 1472 1473
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 已提交
1474 1475 1476 1477 1478 1479

  SStreamDispatchReq req;
  SDecoder           decoder;
  tDecoderInit(&decoder, msgBody, msgLen);
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1480
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1481 1482
    goto FAIL;
  }
L
Liu Jicong 已提交
1483
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1484

L
Liu Jicong 已提交
1485
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1486

L
Liu Jicong 已提交
1487
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1488
  if (pTask) {
L
Liu Jicong 已提交
1489 1490 1491 1492
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1493
    streamProcessDispatchReq(pTask, &req, &rsp, false);
L
Liu Jicong 已提交
1494
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1495 1496
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
1497
    return 0;
L
Liu Jicong 已提交
1498
  }
L
Liu Jicong 已提交
1499

1500 1501
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1502
FAIL:
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
  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 已提交
1527 1528 1529
  SRpcMsg rsp = {
      .code = code,
      .info = pMsg->info,
1530 1531
      .contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp),
      .pCont = pRspHead,
L
Liu Jicong 已提交
1532
  };
1533
  tqDebug("send dispatch error rsp, code: %x", code);
L
Liu Jicong 已提交
1534
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1535 1536
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1537
  return -1;
L
Liu Jicong 已提交
1538
}