tq.c 47.5 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185
int32_t tqPushDataRsp(STQ* pTq, STqPushEntry* pPushEntry) {
  SMqDataRsp* pRsp = &pPushEntry->dataRsp;

  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 已提交
186
  memcpy(buf, &pPushEntry->dataRsp.head, sizeof(SMqRspHead));
L
Liu Jicong 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

  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};
206 207
  tFormatOffset(buf1, tListLen(buf1), &pRsp->reqOffset);
  tFormatOffset(buf2, tListLen(buf2), &pRsp->rspOffset);
208
  tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) push rsp, block num: %d, req:%s, rsp:%s",
L
Liu Jicong 已提交
209
          TD_VID(pTq->pVnode), pRsp->head.consumerId, pRsp->head.epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
210 211 212 213

  return 0;
}

L
Liu Jicong 已提交
214
int32_t tqSendDataRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqDataRsp* pRsp) {
wmmhello's avatar
wmmhello 已提交
215 216
  int32_t len = 0;
  int32_t code = 0;
L
Liu Jicong 已提交
217 218 219 220 221
  tEncodeSize(tEncodeSMqDataRsp, pRsp, len, code);
  if (code < 0) {
    return -1;
  }
  int32_t tlen = sizeof(SMqRspHead) + len;
L
Liu Jicong 已提交
222 223 224 225 226 227 228 229 230 231 232
  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 已提交
233
  SEncoder encoder = {0};
L
Liu Jicong 已提交
234
  tEncoderInit(&encoder, abuf, len);
L
Liu Jicong 已提交
235
  tEncodeSMqDataRsp(&encoder, pRsp);
wmmhello's avatar
wmmhello 已提交
236
  tEncoderClear(&encoder);
L
Liu Jicong 已提交
237 238

  SRpcMsg rsp = {
L
Liu Jicong 已提交
239 240 241 242 243
      .info = pMsg->info,
      .pCont = buf,
      .contLen = tlen,
      .code = 0,
  };
L
Liu Jicong 已提交
244
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
245

wmmhello's avatar
wmmhello 已提交
246 247
  char buf1[80] = {0};
  char buf2[80] = {0};
L
Liu Jicong 已提交
248 249
  tFormatOffset(buf1, 80, &pRsp->reqOffset);
  tFormatOffset(buf2, 80, &pRsp->rspOffset);
250
  tqDebug("vgId:%d consumer:0x%" PRIx64 " (epoch %d), block num:%d, req:%s, rsp:%s",
L
Liu Jicong 已提交
251
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
252 253 254 255

  return 0;
}

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
int32_t tqSendTaosxRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const STaosxRsp* pRsp) {
  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);
292
  tqDebug("taosx rsp, vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) send rsp, numOfBlks:%d, req:%s, rsp:%s",
293 294 295 296 297
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2);

  return 0;
}

298 299 300 301 302
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;
}

303
int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
304
  STqOffset offset = {0};
305

X
Xiaoyu Wang 已提交
306 307
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
308 309 310
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
    return -1;
  }
311

312 313
  tDecoderClear(&decoder);

wmmhello's avatar
wmmhello 已提交
314
  if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA || offset.val.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
315 316
    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 已提交
317
  } else if (offset.val.type == TMQ_OFFSET__LOG) {
S
Shengliang Guan 已提交
318
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey,
L
Liu Jicong 已提交
319
            TD_VID(pTq->pVnode), offset.val.version);
320
    if (offset.val.version + 1 == sversion) {
321 322
      offset.val.version += 1;
    }
323
  } else {
324 325
    tqError("invalid commit offset type:%d", offset.val.type);
    return -1;
326
  }
327 328 329 330

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

333
  // save the new offset value
334 335
  if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) {
    return -1;
336
  }
337 338

  if (offset.val.type == TMQ_OFFSET__LOG) {
339
    STqHandle* pHandle = taosHashGet(pTq->pHandle, offset.subKey, strlen(offset.subKey));
340 341
    if (pHandle && (walRefVer(pHandle->pRef, offset.val.version) < 0)) {
      return -1;
342 343 344
    }
  }

345 346 347
  return 0;
}

L
Liu Jicong 已提交
348
int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) {
L
Liu Jicong 已提交
349
  void* pIter = NULL;
350

L
Liu Jicong 已提交
351
  while (1) {
352
    pIter = taosHashIterate(pTq->pCheckInfo, pIter);
353 354 355 356
    if (pIter == NULL) {
      break;
    }

357
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
358

L
Liu Jicong 已提交
359 360
    if (pCheck->ntbUid == tbUid) {
      int32_t sz = taosArrayGetSize(pCheck->colIdList);
L
Liu Jicong 已提交
361
      for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
362 363
        int16_t forbidColId = *(int16_t*)taosArrayGet(pCheck->colIdList, i);
        if (forbidColId == colId) {
364
          taosHashCancelIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
365 366 367 368 369
          return -1;
        }
      }
    }
  }
370

L
Liu Jicong 已提交
371 372 373
  return 0;
}

L
Liu Jicong 已提交
374 375 376 377 378 379 380 381 382 383
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 已提交
384
  pRsp->withTbName = 0;
L
Liu Jicong 已提交
385 386
  pRsp->withSchema = false;

L
Liu Jicong 已提交
387 388 389
  return 0;
}

390 391 392 393 394 395 396 397 398 399 400 401 402
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;
  }
403

404 405 406
  return 0;
}

L
Liu Jicong 已提交
407
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
D
dapan1121 已提交
408
  SMqPollReq   req = {0};
L
Liu Jicong 已提交
409 410
  int32_t      code = 0;
  STqOffsetVal fetchOffsetNew;
wmmhello's avatar
wmmhello 已提交
411
  SWalCkHead*  pCkHead = NULL;
L
Liu Jicong 已提交
412

D
dapan1121 已提交
413 414 415 416 417 418 419 420 421
  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;

422
  // 1. find handle
D
dapan1121 已提交
423
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
424
  if (pHandle == NULL) {
425 426
    tqError("tmq poll: consumer:0x%" PRIx64 " vgId:%d, subkey %s not found", consumerId, TD_VID(pTq->pVnode),
            req.subKey);
L
Liu Jicong 已提交
427 428 429
    return -1;
  }

430
  // 2. check rebalance
L
Liu Jicong 已提交
431
  if (pHandle->consumerId != consumerId) {
H
Haojun Liao 已提交
432
    tqDebug("ERROR tmq poll: consumer:0x%" PRIx64 " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64,
D
dapan1121 已提交
433
            consumerId, TD_VID(pTq->pVnode), req.subKey, pHandle->consumerId);
L
Liu Jicong 已提交
434
    terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
L
Liu Jicong 已提交
435 436 437 438
    return -1;
  }

  // update epoch if need
439 440 441 442
  int32_t savedEpoch = atomic_load_32(&pHandle->epoch);
  while (savedEpoch < reqEpoch) {
    tqDebug("tmq poll: consumer:0x%"PRIx64 " epoch update from %d to %d by poll req", consumerId, savedEpoch, reqEpoch);
    savedEpoch = atomic_val_compare_exchange_32(&pHandle->epoch, savedEpoch, reqEpoch);
L
Liu Jicong 已提交
443 444
  }

L
Liu Jicong 已提交
445 446
  char buf[80];
  tFormatOffset(buf, 80, &reqOffset);
447
  tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey %s, recv poll req vgId:%d, req:%s", consumerId,
D
dapan1121 已提交
448
          req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), buf);
L
Liu Jicong 已提交
449

L
Liu Jicong 已提交
450 451 452 453
  // 2.reset offset if needed
  if (reqOffset.type > 0) {
    fetchOffsetNew = reqOffset;
  } else {
D
dapan1121 已提交
454
    STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, req.subKey);
L
Liu Jicong 已提交
455 456
    if (pOffset != NULL) {
      fetchOffsetNew = pOffset->val;
L
Liu Jicong 已提交
457 458
      char formatBuf[80];
      tFormatOffset(formatBuf, 80, &fetchOffsetNew);
459
      tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vg %d, offset reset to %s", consumerId, pHandle->subKey,
L
Liu Jicong 已提交
460
              TD_VID(pTq->pVnode), formatBuf);
L
Liu Jicong 已提交
461 462
    } else {
      if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEAST) {
D
dapan1121 已提交
463
        if (req.useSnapshot) {
L
Liu Jicong 已提交
464
          if (pHandle->fetchMeta) {
wmmhello's avatar
wmmhello 已提交
465
            tqOffsetResetToMeta(&fetchOffsetNew, 0);
L
Liu Jicong 已提交
466
          } else {
467
            tqOffsetResetToData(&fetchOffsetNew, 0, 0);
L
Liu Jicong 已提交
468 469
          }
        } else {
L
Liu Jicong 已提交
470 471 472 473 474 475
          pHandle->pRef = walRefFirstVer(pTq->pVnode->pWal, pHandle->pRef);
          if (pHandle->pRef == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            return -1;
          }
          tqOffsetResetToLog(&fetchOffsetNew, pHandle->pRef->refVer - 1);
L
Liu Jicong 已提交
476 477
        }
      } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
L
Liu Jicong 已提交
478 479
        if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
          SMqDataRsp dataRsp = {0};
D
dapan1121 已提交
480
          tqInitDataRsp(&dataRsp, &req, pHandle->execHandle.subType);
L
Liu Jicong 已提交
481 482

          tqOffsetResetToLog(&dataRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
483
          tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, offset reset to %" PRId64, consumerId,
L
Liu Jicong 已提交
484
                  pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.rspOffset.version);
D
dapan1121 已提交
485
          if (tqSendDataRsp(pTq, pMsg, &req, &dataRsp) < 0) {
L
Liu Jicong 已提交
486 487 488 489 490 491
            code = -1;
          }
          tDeleteSMqDataRsp(&dataRsp);
          return code;
        } else {
          STaosxRsp taosxRsp = {0};
D
dapan1121 已提交
492
          tqInitTaosxRsp(&taosxRsp, &req);
L
Liu Jicong 已提交
493
          tqOffsetResetToLog(&taosxRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
D
dapan1121 已提交
494
          if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
L
Liu Jicong 已提交
495 496 497 498
            code = -1;
          }
          tDeleteSTaosxRsp(&taosxRsp);
          return code;
L
Liu Jicong 已提交
499
        }
L
Liu Jicong 已提交
500
      } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) {
H
Haojun Liao 已提交
501
        tqError("tmq poll: subkey %s, no offset committed for consumer:0x%" PRIx64
502
                " in vg %d, subkey %s, reset none failed",
D
dapan1121 已提交
503
                pHandle->subKey, consumerId, TD_VID(pTq->pVnode), req.subKey);
L
Liu Jicong 已提交
504
        terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
505
        return -1;
L
Liu Jicong 已提交
506 507 508 509
      }
    }
  }

510 511
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
    SMqDataRsp dataRsp = {0};
D
dapan1121 已提交
512
    tqInitDataRsp(&dataRsp, &req, pHandle->execHandle.subType);
L
Liu Jicong 已提交
513 514
    // lock
    taosWLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
515 516 517
    if (tqScanData(pTq, pHandle, &dataRsp, &fetchOffsetNew) < 0) {
      return -1;
    }
518

519
    // till now, all data has been rsp to consumer, new data needs to push client once arrived.
L
Liu Jicong 已提交
520
    if (dataRsp.blockNum == 0 && dataRsp.reqOffset.type == TMQ_OFFSET__LOG &&
521
        dataRsp.reqOffset.version == dataRsp.rspOffset.version) {
L
Liu Jicong 已提交
522 523 524
      STqPushEntry* pPushEntry = taosMemoryCalloc(1, sizeof(STqPushEntry));
      if (pPushEntry != NULL) {
        pPushEntry->pInfo = pMsg->info;
L
Liu Jicong 已提交
525
        memcpy(pPushEntry->subKey, pHandle->subKey, TSDB_SUBSCRIBE_KEY_LEN);
L
Liu Jicong 已提交
526
        dataRsp.withTbName = 0;
L
Liu Jicong 已提交
527
        memcpy(&pPushEntry->dataRsp, &dataRsp, sizeof(SMqDataRsp));
L
Liu Jicong 已提交
528 529 530
        pPushEntry->dataRsp.head.consumerId = consumerId;
        pPushEntry->dataRsp.head.epoch = reqEpoch;
        pPushEntry->dataRsp.head.mqMsgType = TMQ_MSG_TYPE__POLL_RSP;
L
Liu Jicong 已提交
531
        taosHashPut(pTq->pPushMgr, pHandle->subKey, strlen(pHandle->subKey) + 1, &pPushEntry, sizeof(void*));
532 533 534

        tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s offset:%" PRId64 ", vgId:%d save handle to push mgr",
                consumerId, pHandle->subKey, dataRsp.reqOffset.version, TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
535 536 537 538 539
        // unlock
        taosWUnLockLatch(&pTq->pushLock);
        return 0;
      }
    }
L
Liu Jicong 已提交
540
    taosWUnLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
541

D
dapan1121 已提交
542
    if (tqSendDataRsp(pTq, pMsg, &req, &dataRsp) < 0) {
543 544 545
      code = -1;
    }

546
    tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, rsp block:%d, offset type:%d, uid/version:%" PRId64 ", ts:%" PRId64 "",
547
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.blockNum, dataRsp.rspOffset.type,
548
            dataRsp.rspOffset.uid, dataRsp.rspOffset.ts);
549 550 551 552 553 554 555 556

    tDeleteSMqDataRsp(&dataRsp);
    return code;
  }

  // for taosx
  SMqMetaRsp metaRsp = {0};
  STaosxRsp taosxRsp = {0};
D
dapan1121 已提交
557
  tqInitTaosxRsp(&taosxRsp, &req);
558 559

  if (fetchOffsetNew.type != TMQ_OFFSET__LOG) {
L
Liu Jicong 已提交
560 561 562
    if (tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, &fetchOffsetNew) < 0) {
      return -1;
    }
L
Liu Jicong 已提交
563

L
Liu Jicong 已提交
564
    if (metaRsp.metaRspLen > 0) {
D
dapan1121 已提交
565
      if (tqSendMetaPollRsp(pTq, pMsg, &req, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
566 567
        code = -1;
      }
568 569
      tqDebug("tmq poll: consumer:0x%" PRIx64 " subkey %s, vg %d, send meta offset type:%d,uid:%" PRId64
              ",version:%" PRId64,
570
              consumerId, pHandle->subKey, TD_VID(pTq->pVnode), metaRsp.rspOffset.type, metaRsp.rspOffset.uid,
L
Liu Jicong 已提交
571
              metaRsp.rspOffset.version);
wmmhello's avatar
wmmhello 已提交
572
      taosMemoryFree(metaRsp.metaRsp);
573 574
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
wmmhello's avatar
wmmhello 已提交
575 576
    }

577
    if (taosxRsp.blockNum > 0) {
D
dapan1121 已提交
578
      if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
579 580
        code = -1;
      }
581 582
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
L
Liu Jicong 已提交
583
    } else {
584
      fetchOffsetNew = taosxRsp.rspOffset;
585
    }
wmmhello's avatar
wmmhello 已提交
586

587 588
    tqDebug("taosx poll: consumer:0x%" PRIx64 " subkey %s, vg %d, send data blockNum:%d, offset type:%d,uid:%" PRId64
            ",version:%" PRId64,
589 590
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), taosxRsp.blockNum, taosxRsp.rspOffset.type,
            taosxRsp.rspOffset.uid, taosxRsp.rspOffset.version);
591 592
  }

593
  if (fetchOffsetNew.type == TMQ_OFFSET__LOG) {
wmmhello's avatar
wmmhello 已提交
594 595 596
    int64_t fetchVer = fetchOffsetNew.version + 1;
    pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
597
      tDeleteSTaosxRsp(&taosxRsp);
598
      return -1;
599 600
    }

wmmhello's avatar
wmmhello 已提交
601 602 603
    walSetReaderCapacity(pHandle->pWalReader, 2048);

    while (1) {
604 605
      savedEpoch = atomic_load_32(&pHandle->epoch);
      if (savedEpoch > reqEpoch) {
H
Haojun Liao 已提交
606
        tqWarn("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey %s, vg %d offset %" PRId64
L
Liu Jicong 已提交
607
               ", found new consumer epoch %d, discard req epoch %d",
608
               consumerId, req.epoch, pHandle->subKey, TD_VID(pTq->pVnode), fetchVer, savedEpoch, reqEpoch);
wmmhello's avatar
wmmhello 已提交
609 610 611 612
        break;
      }

      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead) < 0) {
613
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
D
dapan1121 已提交
614
        if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
615 616
          code = -1;
        }
617
        tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
618
        taosMemoryFreeClear(pCkHead);
619
        return code;
wmmhello's avatar
wmmhello 已提交
620 621 622
      }

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

624
      tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId,
D
dapan1121 已提交
625
              req.epoch, TD_VID(pTq->pVnode), fetchVer, pHead->msgType);
wmmhello's avatar
wmmhello 已提交
626 627

      if (pHead->msgType == TDMT_VND_SUBMIT) {
L
Liu Jicong 已提交
628
        SPackedData submit = {
629 630
            .msgStr = POINTER_SHIFT(pHead->body, sizeof(SSubmitReq2Msg)),
            .msgLen = pHead->bodyLen - sizeof(SSubmitReq2Msg),
L
Liu Jicong 已提交
631 632 633
            .ver = pHead->version,
        };
        if (tqTaosxScanLog(pTq, pHandle, submit, &taosxRsp) < 0) {
634 635
          tqError("tmq poll: tqTaosxScanLog error %" PRId64 ", in vgId:%d, subkey %s", consumerId, TD_VID(pTq->pVnode),
                  req.subKey);
636
          return -1;
wmmhello's avatar
wmmhello 已提交
637
        }
638 639
        if (taosxRsp.blockNum > 0 /* threshold */) {
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
D
dapan1121 已提交
640
          if (tqSendTaosxRsp(pTq, pMsg, &req, &taosxRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
641 642
            code = -1;
          }
643
          tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
644
          taosMemoryFreeClear(pCkHead);
645
          return code;
wmmhello's avatar
wmmhello 已提交
646 647 648 649 650
        } else {
          fetchVer++;
        }

      } else {
L
Liu Jicong 已提交
651 652
        /*A(pHandle->fetchMeta);*/
        /*A(IS_META_MSG(pHead->msgType));*/
653
        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%s", pHead->version, TMSG_INFO(pHead->msgType));
wmmhello's avatar
wmmhello 已提交
654 655 656 657
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer);
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
D
dapan1121 已提交
658
        if (tqSendMetaPollRsp(pTq, pMsg, &req, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
659
          code = -1;
L
Liu Jicong 已提交
660
          taosMemoryFreeClear(pCkHead);
661
          tDeleteSTaosxRsp(&taosxRsp);
662
          return code;
wmmhello's avatar
wmmhello 已提交
663 664
        }
        code = 0;
L
Liu Jicong 已提交
665
        taosMemoryFreeClear(pCkHead);
666
        tDeleteSTaosxRsp(&taosxRsp);
667
        return code;
wmmhello's avatar
wmmhello 已提交
668 669 670
      }
    }
  }
671

672
  tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
673
  taosMemoryFreeClear(pCkHead);
674
  return 0;
L
Liu Jicong 已提交
675 676
}

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

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

L
Liu Jicong 已提交
682 683 684 685 686 687 688
  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 已提交
689 690
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
X
Xiaoyu Wang 已提交
691
    // walCloseRef(pHandle->pWalReader->pWal, pHandle->pRef->refId);
L
Liu Jicong 已提交
692 693 694 695 696 697 698
    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 已提交
699
  }
700

L
Liu Jicong 已提交
701 702
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
703
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
704
  }
L
Liu Jicong 已提交
705

L
Liu Jicong 已提交
706
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
707
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
708
  }
L
Liu Jicong 已提交
709
  return 0;
L
Liu Jicong 已提交
710 711
}

712
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
713 714
  STqCheckInfo info = {0};
  SDecoder     decoder;
X
Xiaoyu Wang 已提交
715
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
716
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
717 718 719 720
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
721 722 723 724 725
  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 已提交
726 727 728 729 730 731
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

732
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
733 734 735 736 737 738 739 740 741 742 743
  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;
}

744
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
745
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
746 747
  tDecodeSMqRebVgReq(msg, &req);
  // todo lock
L
Liu Jicong 已提交
748 749 750

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

751
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
752
  if (pHandle == NULL) {
L
Liu Jicong 已提交
753
    if (req.oldConsumerId != -1) {
H
Haojun Liao 已提交
754
      tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId is %" PRId64 "",
755
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
756
    }
L
Liu Jicong 已提交
757
    if (req.newConsumerId == -1) {
758
      tqError("vgId:%d, tq invalid rebalance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
759
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
760 761
      return 0;
    }
L
Liu Jicong 已提交
762 763
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
764 765
    /*taosInitRWLatch(&pExec->lock);*/

H
Haojun Liao 已提交
766
    uint64_t oldConsumerId = pHandle->consumerId;
L
Liu Jicong 已提交
767 768 769
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
770

L
Liu Jicong 已提交
771
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
772
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
773

774 775 776
    // TODO version should be assigned and refed during preprocess
    SWalRef* pRef = walRefCommittedVer(pTq->pVnode->pWal);
    if (pRef == NULL) {
L
Liu Jicong 已提交
777
      return -1;
778 779 780
    }
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
781

782 783 784 785 786 787 788
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTableReader = true,
        .initTqReader = true,
        .version = ver,
    };
wmmhello's avatar
wmmhello 已提交
789
    pHandle->snapshotVer = ver;
790

L
Liu Jicong 已提交
791
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
792
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
793
      req.qmsg = NULL;
794 795

      pHandle->execHandle.task =
L
Liu Jicong 已提交
796
          qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, &pHandle->execHandle.numOfCols, NULL);
L
Liu Jicong 已提交
797
      void* scanner = NULL;
798
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
L
Liu Jicong 已提交
799
      pHandle->execHandle.pExecReader = qExtractReaderFromStreamScanner(scanner);
L
Liu Jicong 已提交
800
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
wmmhello's avatar
wmmhello 已提交
801
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
L
Liu Jicong 已提交
802
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
L
Liu Jicong 已提交
803
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
804
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
805 806
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
807

808
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, NULL, NULL);
L
Liu Jicong 已提交
809
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
wmmhello's avatar
wmmhello 已提交
810 811 812 813
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);

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

L
Liu Jicong 已提交
814
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
H
Hongze Cheng 已提交
815
      vnodeGetCtbIdList(pTq->pVnode, req.suid, tbUidList);
816
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pTq->pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
817 818
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
S
Shengliang Guan 已提交
819
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, TD_VID(pTq->pVnode), i, tbUid);
L
Liu Jicong 已提交
820
      }
L
Liu Jicong 已提交
821 822
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
      tqReaderSetTbUidList(pHandle->execHandle.pExecReader, tbUidList);
L
Liu Jicong 已提交
823
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
824

L
Liu Jicong 已提交
825 826 827
      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 已提交
828
    }
H
Haojun Liao 已提交
829

830
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
H
Haojun Liao 已提交
831 832
    tqDebug("try to persist handle %s consumer:0x%" PRIx64" , old consumer:0x%"PRIx64, req.subKey, pHandle->consumerId,
            oldConsumerId);
L
Liu Jicong 已提交
833
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
L
Liu Jicong 已提交
834
      return -1;
L
Liu Jicong 已提交
835
    }
L
Liu Jicong 已提交
836
  } else {
L
Liu Jicong 已提交
837
    // TODO handle qmsg and exec modification
H
Haojun Liao 已提交
838
    tqInfo("update the consumer info, old consumer id:0x%"PRIx64", new Id:0x%"PRIx64, pHandle->consumerId, req.newConsumerId);
L
Liu Jicong 已提交
839 840 841
    atomic_store_32(&pHandle->epoch, -1);
    atomic_store_64(&pHandle->consumerId, req.newConsumerId);
    atomic_add_fetch_32(&pHandle->epoch, 1);
L
Liu Jicong 已提交
842
    taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
843 844 845
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
      qStreamCloseTsdbReader(pHandle->execHandle.task);
    }
H
Haojun Liao 已提交
846

L
Liu Jicong 已提交
847
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
L
Liu Jicong 已提交
848
      return -1;
L
Liu Jicong 已提交
849
    }
L
Liu Jicong 已提交
850
    // close handle
L
Liu Jicong 已提交
851
  }
L
Liu Jicong 已提交
852

L
Liu Jicong 已提交
853
  return 0;
L
Liu Jicong 已提交
854
}
855

856
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
L
Liu Jicong 已提交
857
#if 0
858
  if (pTask->taskLevel == TASK_LEVEL__AGG) {
L
Liu Jicong 已提交
859
    A(taosArrayGetSize(pTask->childEpInfo) != 0);
L
Liu Jicong 已提交
860
  }
L
Liu Jicong 已提交
861
#endif
L
Liu Jicong 已提交
862

L
Liu Jicong 已提交
863
  pTask->refCnt = 1;
L
Liu Jicong 已提交
864
  pTask->schedStatus = TASK_SCHED_STATUS__INACTIVE;
L
Liu Jicong 已提交
865 866 867

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

  if (pTask->inputQueue == NULL || pTask->outputQueue == NULL) {
L
Liu Jicong 已提交
870
    return -1;
L
Liu Jicong 已提交
871 872
  }

L
Liu Jicong 已提交
873 874 875
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;

876 877
  pTask->pMsgCb = &pTq->pVnode->msgCb;

878 879
  pTask->startVer = ver;

880
  // expand executor
881 882 883 884
  if (pTask->fillHistory) {
    pTask->taskStatus = TASK_STATUS__WAIT_DOWNSTREAM;
  }

885
  if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
886
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
887 888 889 890
    if (pTask->pState == NULL) {
      return -1;
    }

891 892 893 894
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTqReader = 1,
895
        .pStateBackend = pTask->pState,
896 897
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle);
L
Liu Jicong 已提交
898 899 900
    if (pTask->exec.executor == NULL) {
      return -1;
    }
901

902
  } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
903
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
904 905 906
    if (pTask->pState == NULL) {
      return -1;
    }
907 908 909
    SReadHandle mgHandle = {
        .vnode = NULL,
        .numOfVgroups = (int32_t)taosArrayGetSize(pTask->childEpInfo),
910
        .pStateBackend = pTask->pState,
911 912
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &mgHandle);
L
Liu Jicong 已提交
913 914 915
    if (pTask->exec.executor == NULL) {
      return -1;
    }
L
Liu Jicong 已提交
916
  }
L
Liu Jicong 已提交
917 918

  // sink
L
Liu Jicong 已提交
919
  /*pTask->ahandle = pTq->pVnode;*/
920
  if (pTask->outputType == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
921
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
922
    pTask->smaSink.smaSink = smaHandleRes;
923
  } else if (pTask->outputType == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
924
    pTask->tbSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
925
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline2;
L
Liu Jicong 已提交
926

5
54liuyao 已提交
927 928 929 930 931 932
    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 已提交
933

L
Liu Jicong 已提交
934
    pTask->tbSink.pTSchema =
5
54liuyao 已提交
935
        tBuildTSchema(pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols, version);
wmmhello's avatar
wmmhello 已提交
936
    if(pTask->tbSink.pTSchema == NULL) {
wmmhello's avatar
wmmhello 已提交
937
      return -1;
wmmhello's avatar
wmmhello 已提交
938
    }
L
Liu Jicong 已提交
939
  }
940 941 942

  streamSetupTrigger(pTask);

943 944
  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 已提交
945
  return 0;
L
Liu Jicong 已提交
946
}
L
Liu Jicong 已提交
947

948 949 950 951 952 953
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 已提交
954
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
955 956 957 958 959 960 961 962 963 964 965 966
  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 已提交
967
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
968 969 970 971 972 973
  if (pTask && atomic_load_8(&pTask->taskStatus) == TASK_STATUS__NORMAL) {
    rsp.status = 1;
  } else {
    rsp.status = 0;
  }

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

976
  tqDebug("tq recv task check req(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d",
977 978 979 980 981 982 983
          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 已提交
984
    tqError("unable to encode rsp %d", __LINE__);
L
Liu Jicong 已提交
985
    return -1;
986
  }
L
Liu Jicong 已提交
987

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
  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;
}

1007
int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  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);

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

L
Liu Jicong 已提交
1023
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId);
1024 1025 1026 1027
  if (pTask == NULL) {
    return -1;
  }

1028
  code = streamProcessTaskCheckRsp(pTask, &rsp, sversion);
L
Liu Jicong 已提交
1029 1030
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
1031 1032
}

1033
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1034 1035 1036 1037 1038
  int32_t code;
#if 0
  code = streamMetaAddSerializedTask(pTq->pStreamMeta, version, msg, msgLen);
  if (code < 0) return code;
#endif
5
54liuyao 已提交
1039 1040 1041
  if (tsDisableStream) {
    return 0;
  }
1042 1043 1044 1045 1046 1047

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

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
  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
1060
  code = streamMetaAddTask(pTq->pStreamMeta, sversion, pTask);
1061 1062 1063 1064 1065 1066
  if (code < 0) {
    return -1;
  }

  // 3.go through recover steps to fill history
  if (pTask->fillHistory) {
1067
    streamTaskCheckDownstream(pTask, sversion);
1068 1069 1070 1071 1072
  }

  return 0;
}

L
Liu Jicong 已提交
1073 1074 1075 1076 1077
int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) {
  int32_t code;
  char*   msg = pMsg->pCont;
  int32_t msgLen = pMsg->contLen;

1078
  SStreamRecoverStep1Req* pReq = (SStreamRecoverStep1Req*)msg;
L
Liu Jicong 已提交
1079
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1080 1081 1082 1083 1084 1085 1086
  if (pTask == NULL) {
    return -1;
  }

  // check param
  int64_t fillVer1 = pTask->startVer;
  if (fillVer1 <= 0) {
L
Liu Jicong 已提交
1087
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1088 1089 1090 1091 1092 1093
    return -1;
  }

  // do recovery step 1
  streamSourceRecoverScanStep1(pTask);

L
Liu Jicong 已提交
1094 1095 1096 1097 1098
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1099 1100 1101 1102
  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
1103
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1104 1105 1106
    return -1;
  }

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

L
Liu Jicong 已提交
1109 1110 1111 1112
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    return 0;
  }

1113
  // serialize msg
L
Liu Jicong 已提交
1114 1115 1116 1117 1118 1119 1120 1121
  int32_t len = sizeof(SStreamRecoverStep1Req);

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

  memcpy(serializedReq, &req, len);
1122 1123 1124 1125 1126

  // dispatch msg
  SRpcMsg rpcMsg = {
      .code = 0,
      .contLen = len,
L
Liu Jicong 已提交
1127
      .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE,
L
Liu Jicong 已提交
1128
      .pCont = serializedReq,
1129 1130 1131 1132 1133 1134 1135
  };

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

  return 0;
}

1136
int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1137 1138
  int32_t                 code;
  SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg;
L
Liu Jicong 已提交
1139
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1140 1141 1142 1143 1144
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
1145
  code = streamSourceRecoverScanStep2(pTask, sversion);
1146
  if (code < 0) {
L
Liu Jicong 已提交
1147
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1148 1149 1150
    return -1;
  }

L
Liu Jicong 已提交
1151 1152 1153 1154 1155
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1156 1157 1158
  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1159
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1160 1161 1162 1163 1164 1165
    return -1;
  }

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

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

L
Liu Jicong 已提交
1177 1178 1179
  atomic_store_8(&pTask->fillHistory, 0);
  streamMetaSaveTask(pTq->pStreamMeta, pTask);

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

1182 1183 1184
  return 0;
}

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

  // deserialize
1190 1191 1192
  SStreamRecoverFinishReq req;

  SDecoder decoder;
X
Xiaoyu Wang 已提交
1193
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
1194 1195 1196
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

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

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

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

L
Liu Jicong 已提交
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
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 已提交
1233
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    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);
1245
    colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
L
Liu Jicong 已提交
1246
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
1247
    colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false);
L
Liu Jicong 已提交
1248 1249 1250
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
1251
    colDataSetVal(pUidCol, i, (const char*)pUid, false);
L
Liu Jicong 已提交
1252

1253 1254 1255
    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 已提交
1256 1257
  }

L
Liu Jicong 已提交
1258 1259
  taosArrayDestroy(pRes->uidList);

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

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

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

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

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

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

#if 0
S
Shengliang Guan 已提交
1305
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, 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
    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 已提交
1327
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1328
#endif
L
Liu Jicong 已提交
1329 1330 1331 1332

  return 0;
}

L
Liu Jicong 已提交
1333
int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) {
L
Liu Jicong 已提交
1334 1335 1336
  void*               pIter = NULL;
  bool                failed = false;
  SStreamDataSubmit2* pSubmit = NULL;
L
Liu Jicong 已提交
1337

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

  while (1) {
L
Liu Jicong 已提交
1346
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
1347 1348 1349 1350
    if (pIter == NULL) {
      break;
    }

1351
    SStreamTask* pTask = *(SStreamTask**)pIter;
1352
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) continue;
1353
    if (pTask->taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
L
Liu Jicong 已提交
1354 1355 1356
      tqDebug("skip push task %d, task status %d", pTask->taskId, pTask->taskStatus);
      continue;
    }
L
Liu Jicong 已提交
1357

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

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

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

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

  return failed ? -1 : 0;
L
Liu Jicong 已提交
1381 1382
}

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

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

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

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

1434
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1435
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1436
  streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId);
L
Liu Jicong 已提交
1437
  return 0;
L
Liu Jicong 已提交
1438
}
L
Liu Jicong 已提交
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;
1446
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1447
  tDecodeStreamRetrieveReq(&decoder, &req);
L
Liu Jicong 已提交
1448
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1449
  int32_t      taskId = req.dstTaskId;
L
Liu Jicong 已提交
1450
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1451
  if (pTask) {
L
Liu Jicong 已提交
1452 1453 1454 1455
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1456
    streamProcessRetrieveReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
1457
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1458
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1459
    return 0;
L
Liu Jicong 已提交
1460 1461
  } else {
    return -1;
L
Liu Jicong 已提交
1462 1463 1464 1465 1466 1467 1468
  }
}

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

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

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

L
Liu Jicong 已提交
1487
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1488

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

1502 1503
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

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

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