tq.c 53.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;
H
Haojun Liao 已提交
71 72 73 74 75 76 77
  if (p->pDataRsp->head.mqMsgType == TMQ_MSG_TYPE__POLL_RSP) {
    tDeleteSMqDataRsp(p->pDataRsp);
  } else if (p->pDataRsp->head.mqMsgType == TMQ_MSG_TYPE__TAOSX_RSP) {
    tDeleteSTaosxRsp((STaosxRsp*)p->pDataRsp);
  }

  taosMemoryFree(p->pDataRsp);
L
Liu Jicong 已提交
78 79 80
  taosMemoryFree(p);
}

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

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

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

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

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

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

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

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

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

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

  tqOffsetClose(pTq->pOffsetStore);
  taosHashCleanup(pTq->pHandle);
  taosHashCleanup(pTq->pPushMgr);
  taosHashCleanup(pTq->pCheckInfo);
  taosMemoryFree(pTq->path);
  tqMetaClose(pTq);
  streamMetaClose(pTq->pStreamMeta);
  taosMemoryFree(pTq);
L
Liu Jicong 已提交
135
}
L
Liu Jicong 已提交
136

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

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

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

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

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

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

  return 0;
}

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

  if (type == TMQ_MSG_TYPE__POLL_RSP) {
    tEncodeSize(tEncodeSMqDataRsp, pRsp, len, code);
  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
    tEncodeSize(tEncodeSTaosxRsp, (STaosxRsp*)pRsp, len, code);
  }
L
Liu Jicong 已提交
185 186 187 188 189 190 191 192 193 194 195

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

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

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

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

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

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

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

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

  tmsgSendRsp(&rsp);
  return 0;
}

H
Haojun Liao 已提交
224 225 226
int32_t tqPushDataRsp(STQ* pTq, STqPushEntry* pPushEntry) {
  SMqDataRsp* pRsp = pPushEntry->pDataRsp;

L
Liu Jicong 已提交
227 228 229
#if 0
  A(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
  A(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);
L
Liu Jicong 已提交
230

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

234
  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
H
Haojun Liao 已提交
235
    A(pRsp->rspOffset.version > pRsp->reqOffset.version);
L
Liu Jicong 已提交
236
  }
L
Liu Jicong 已提交
237
#endif
L
Liu Jicong 已提交
238

H
Haojun Liao 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
//  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;
//  }
//
//  memcpy(buf, &pPushEntry->dataRsp.head, sizeof(SMqRspHead));
//
//  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);
//

  SMqRspHead* pHeader = &pPushEntry->pDataRsp->head;
  doSendDataRsp(&pPushEntry->info, pRsp, pHeader->epoch, pHeader->consumerId, pHeader->mqMsgType);
L
Liu Jicong 已提交
273

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

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

H
Haojun Liao 已提交
288 289
  A(!pRsp->withSchema);
  A(taosArrayGetSize(pRsp->blockSchema) == 0);
290 291 292

  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
    if (pRsp->blockNum > 0) {
L
Liu Jicong 已提交
293
      A(pRsp->rspOffset.version > pRsp->reqOffset.version);
294
    } else {
L
Liu Jicong 已提交
295
      A(pRsp->rspOffset.version >= pRsp->reqOffset.version);
296 297
    }
  }
L
Liu Jicong 已提交
298
#endif
299

H
Haojun Liao 已提交
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 341 342 343 344
//  int32_t len = 0;
//  int32_t code = 0;
//
//  if (type == TMQ_MSG_TYPE__POLL_RSP) {
//    tEncodeSize(tEncodeSMqDataRsp, pRsp, len, code);
//  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
//    tEncodeSize(tEncodeSTaosxRsp, (STaosxRsp*)pRsp, len, code);
//  }
//
//  if (code < 0) {
//    return -1;
//  }
//
//  int32_t tlen = sizeof(SMqRspHead) + len;
//  void*   buf = rpcMallocCont(tlen);
//  if (buf == NULL) {
//    return -1;
//  }
//
//  ((SMqRspHead*)buf)->mqMsgType = type;
//  ((SMqRspHead*)buf)->epoch = pReq->epoch;
//  ((SMqRspHead*)buf)->consumerId = pReq->consumerId;
//
//  void* abuf = POINTER_SHIFT(buf, sizeof(SMqRspHead));
//
//  SEncoder encoder = {0};
//  tEncoderInit(&encoder, abuf, len);
//
//  if (type == TMQ_MSG_TYPE__POLL_RSP) {
//    tEncodeSMqDataRsp(&encoder, pRsp);
//  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
//    tEncodeSTaosxRsp(&encoder, (STaosxRsp*) pRsp);
//  }
//
//  tEncoderClear(&encoder);
//
//  SRpcMsg rsp = {
//      .info = pMsg->info,
//      .pCont = buf,
//      .contLen = tlen,
//      .code = 0,
//  };
//
//  tmsgSendRsp(&rsp);
  doSendDataRsp(&pMsg->info, pRsp, pReq->epoch, pReq->consumerId, type);
345 346 347 348 349 350

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

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

354 355 356
  return 0;
}

H
Haojun Liao 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
//int32_t tqSendTaosxRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const STaosxRsp* pRsp) {
//#if 0
//  A(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
//  A(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);
//
//  if (pRsp->withSchema) {
//    A(taosArrayGetSize(pRsp->blockSchema) == pRsp->blockNum);
//  } else {
//    A(taosArrayGetSize(pRsp->blockSchema) == 0);
//  }
//
//  if (pRsp->reqOffset.type == TMQ_OFFSET__LOG) {
//    if (pRsp->blockNum > 0) {
//      A(pRsp->rspOffset.version > pRsp->reqOffset.version);
//    } else {
//      A(pRsp->rspOffset.version >= pRsp->reqOffset.version);
//    }
//  }
//#endif
//
//  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) {
//    terrno = TSDB_CODE_OUT_OF_MEMORY;
//    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, consumer:0x%" PRIx64 " (epoch %d) send rsp, numOfBlks:%d, req:%s, rsp:%s",
//          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2);
//  return 0;
//}

421 422 423 424 425
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;
}

426
int32_t tqProcessOffsetCommitReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
427
  STqOffset offset = {0};
428

X
Xiaoyu Wang 已提交
429 430
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
431 432 433
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
    return -1;
  }
434

435 436
  tDecoderClear(&decoder);

wmmhello's avatar
wmmhello 已提交
437
  if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA || offset.val.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
438 439
    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 已提交
440
  } else if (offset.val.type == TMQ_OFFSET__LOG) {
S
Shengliang Guan 已提交
441
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey,
L
Liu Jicong 已提交
442
            TD_VID(pTq->pVnode), offset.val.version);
443
    if (offset.val.version + 1 == sversion) {
444 445
      offset.val.version += 1;
    }
446
  } else {
447 448
    tqError("invalid commit offset type:%d", offset.val.type);
    return -1;
449
  }
450 451 452 453

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

456
  // save the new offset value
457 458
  if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) {
    return -1;
459
  }
460 461

  if (offset.val.type == TMQ_OFFSET__LOG) {
462
    STqHandle* pHandle = taosHashGet(pTq->pHandle, offset.subKey, strlen(offset.subKey));
463 464
    if (pHandle && (walRefVer(pHandle->pRef, offset.val.version) < 0)) {
      return -1;
465 466 467
    }
  }

468 469 470
  return 0;
}

L
Liu Jicong 已提交
471
int32_t tqCheckColModifiable(STQ* pTq, int64_t tbUid, int32_t colId) {
L
Liu Jicong 已提交
472
  void* pIter = NULL;
473

L
Liu Jicong 已提交
474
  while (1) {
475
    pIter = taosHashIterate(pTq->pCheckInfo, pIter);
476 477 478 479
    if (pIter == NULL) {
      break;
    }

480
    STqCheckInfo* pCheck = (STqCheckInfo*)pIter;
481

L
Liu Jicong 已提交
482 483
    if (pCheck->ntbUid == tbUid) {
      int32_t sz = taosArrayGetSize(pCheck->colIdList);
L
Liu Jicong 已提交
484
      for (int32_t i = 0; i < sz; i++) {
L
Liu Jicong 已提交
485 486
        int16_t forbidColId = *(int16_t*)taosArrayGet(pCheck->colIdList, i);
        if (forbidColId == colId) {
487
          taosHashCancelIterate(pTq->pCheckInfo, pIter);
L
Liu Jicong 已提交
488 489 490 491 492
          return -1;
        }
      }
    }
  }
493

L
Liu Jicong 已提交
494 495 496
  return 0;
}

L
Liu Jicong 已提交
497 498 499 500 501 502 503 504 505 506
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 已提交
507 508
  pRsp->withTbName = 0;
#if 0
L
Liu Jicong 已提交
509 510 511 512 513 514 515 516
  pRsp->withTbName = pReq->withTbName;
  if (pRsp->withTbName) {
    pRsp->blockTbName = taosArrayInit(0, sizeof(void*));
    if (pRsp->blockTbName == NULL) {
      // TODO free
      return -1;
    }
  }
L
Liu Jicong 已提交
517
#endif
L
Liu Jicong 已提交
518

L
Liu Jicong 已提交
519
  pRsp->withSchema = false;
L
Liu Jicong 已提交
520 521 522
  return 0;
}

523 524 525 526 527 528 529 530 531 532 533 534 535
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;
  }
536

537 538 539
  return 0;
}

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
static int32_t extractResetOffsetVal(STqOffsetVal* pOffsetVal, STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest,
                                     SRpcMsg* pMsg, bool* pBlockReturned) {
  uint64_t     consumerId = pRequest->consumerId;
  STqOffsetVal reqOffset = pRequest->reqOffset;
  STqOffset*   pOffset = tqOffsetRead(pTq->pOffsetStore, pRequest->subKey);
  *pBlockReturned = false;

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

    char formatBuf[80];
    tFormatOffset(formatBuf, 80, pOffsetVal);
    tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, prev offset found, offset reset to %s and continue.",
            consumerId, pHandle->subKey, TD_VID(pTq->pVnode), formatBuf);
    return 0;
  } else {
    // no poll occurs in this vnode for this topic, let's seek to the right offset value.
    if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEAST) {
      if (pRequest->useSnapshot) {
        if (pHandle->fetchMeta) {
          tqOffsetResetToMeta(pOffsetVal, 0);
        } else {
          tqOffsetResetToData(pOffsetVal, 0, 0);
        }
      } else {
        pHandle->pRef = walRefFirstVer(pTq->pVnode->pWal, pHandle->pRef);
        if (pHandle->pRef == NULL) {
          terrno = TSDB_CODE_OUT_OF_MEMORY;
          return -1;
        }
D
dapan1121 已提交
571

572 573 574 575 576 577 578 579 580 581
        tqOffsetResetToLog(pOffsetVal, pHandle->pRef->refVer - 1);
      }
    } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
      if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
        SMqDataRsp dataRsp = {0};
        tqInitDataRsp(&dataRsp, pRequest, pHandle->execHandle.subType);

        tqOffsetResetToLog(&dataRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
        tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, offset reset to %" PRId64, consumerId,
                pHandle->subKey, TD_VID(pTq->pVnode), dataRsp.rspOffset.version);
H
Haojun Liao 已提交
582
        int32_t code = tqSendDataRsp(pTq, pMsg, pRequest, &dataRsp, TMQ_MSG_TYPE__POLL_RSP);
583 584 585 586 587 588 589 590
        tDeleteSMqDataRsp(&dataRsp);

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

595 596 597 598 599 600 601 602 603 604
        *pBlockReturned = true;
        return code;
      }
    } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) {
      tqError("tmq poll: subkey %s, no offset committed for consumer:0x%" PRIx64
              " in vg %d, subkey %s, reset none failed",
              pHandle->subKey, consumerId, TD_VID(pTq->pVnode), pRequest->subKey);
      terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
      return -1;
    }
L
Liu Jicong 已提交
605 606
  }

607 608
  return 0;
}
L
Liu Jicong 已提交
609

610 611
static int32_t extractDataForMq(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest, SRpcMsg* pMsg) {
  int32_t      code = -1;
612
  STqOffsetVal offset = {0};
613
  SWalCkHead*  pCkHead = NULL;
614 615 616
  int32_t      vgId = TD_VID(pTq->pVnode);

  STqOffsetVal reqOffset = pRequest->reqOffset;
617
  uint64_t     consumerId = pRequest->consumerId;
L
Liu Jicong 已提交
618

619
  // 1. reset the offset if needed
L
Liu Jicong 已提交
620
  if (reqOffset.type > 0) {
621
    offset = reqOffset;
622 623
  } else { // handle the reset offset cases, according to the consumer's choice.
    bool blockReturned = false;
624
    code = extractResetOffsetVal(&offset, pTq, pHandle, pRequest, pMsg, &blockReturned);
625 626 627 628 629 630 631
    if (code != 0) {
      return code;
    }

    // empty block returned, quit
    if (blockReturned) {
      return 0;
L
Liu Jicong 已提交
632 633 634
    }
  }

635
  // this is a normal subscription requirement
636 637
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
    SMqDataRsp dataRsp = {0};
638
    tqInitDataRsp(&dataRsp, pRequest, pHandle->execHandle.subType);
639

L
Liu Jicong 已提交
640 641
    // lock
    taosWLockLatch(&pTq->pushLock);
642
    code = tqScanData(pTq, pHandle, &dataRsp, &offset);
643

644
    // till now, all data has been transferred to consumer, new data needs to push client once arrived.
L
Liu Jicong 已提交
645
    if (dataRsp.blockNum == 0 && dataRsp.reqOffset.type == TMQ_OFFSET__LOG &&
646
        dataRsp.reqOffset.version == dataRsp.rspOffset.version && pHandle->consumerId == pRequest->consumerId) {
H
Haojun Liao 已提交
647
      code = tqRegisterPushEntry(pTq, pHandle, pRequest, pMsg, &dataRsp, TMQ_MSG_TYPE__POLL_RSP);
648 649
      taosWUnLockLatch(&pTq->pushLock);
      return code;
L
Liu Jicong 已提交
650 651
    }

652
    taosWUnLockLatch(&pTq->pushLock);
H
Haojun Liao 已提交
653
    code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&dataRsp, TMQ_MSG_TYPE__POLL_RSP);
654

655
    // NOTE: this pHandle->consumerId may have been changed already.
656 657 658 659
    tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, rsp block:%d, offset type:%d, uid/version:%" PRId64
            ", ts:%" PRId64,
            consumerId, pHandle->subKey, vgId, dataRsp.blockNum, dataRsp.rspOffset.type, dataRsp.rspOffset.uid,
            dataRsp.rspOffset.ts);
660 661 662 663 664

    tDeleteSMqDataRsp(&dataRsp);
    return code;
  }

665
  // todo handle the case where re-balance occurs.
666 667 668
  // for taosx
  SMqMetaRsp metaRsp = {0};
  STaosxRsp taosxRsp = {0};
669
  tqInitTaosxRsp(&taosxRsp, pRequest);
670

671 672
  if (offset.type != TMQ_OFFSET__LOG) {
    if (tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, &offset) < 0) {
L
Liu Jicong 已提交
673 674
      return -1;
    }
L
Liu Jicong 已提交
675

L
Liu Jicong 已提交
676
    if (metaRsp.metaRspLen > 0) {
677
      code = tqSendMetaPollRsp(pTq, pMsg, pRequest, &metaRsp);
H
Haojun Liao 已提交
678
      tqDebug("tmq poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send meta offset type:%d,uid:%" PRId64
679 680
              ",version:%" PRId64,
              consumerId, pHandle->subKey, vgId, metaRsp.rspOffset.type, metaRsp.rspOffset.uid,
L
Liu Jicong 已提交
681
              metaRsp.rspOffset.version);
wmmhello's avatar
wmmhello 已提交
682
      taosMemoryFree(metaRsp.metaRsp);
683 684
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
wmmhello's avatar
wmmhello 已提交
685 686
    }

687
    if (taosxRsp.blockNum > 0) {
H
Haojun Liao 已提交
688
      code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
689 690
      tDeleteSTaosxRsp(&taosxRsp);
      return code;
L
Liu Jicong 已提交
691
    } else {
692
      offset = taosxRsp.rspOffset;
693
    }
wmmhello's avatar
wmmhello 已提交
694

H
Haojun Liao 已提交
695
    tqDebug("taosx poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send data blockNum:%d, offset type:%d,uid:%" PRId64
696
            ",version:%" PRId64,
697 698
            consumerId, pHandle->subKey, vgId, taosxRsp.blockNum, taosxRsp.rspOffset.type, taosxRsp.rspOffset.uid,
            taosxRsp.rspOffset.version);
H
Haojun Liao 已提交
699
  } else {
700

H
Haojun Liao 已提交
701
//  if (offset.type == TMQ_OFFSET__LOG) {
702
    int64_t fetchVer = offset.version + 1;
wmmhello's avatar
wmmhello 已提交
703 704
    pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
705
      tDeleteSTaosxRsp(&taosxRsp);
H
Haojun Liao 已提交
706
      terrno = TSDB_CODE_OUT_OF_MEMORY;
707
      return -1;
708 709
    }

wmmhello's avatar
wmmhello 已提交
710 711 712
    walSetReaderCapacity(pHandle->pWalReader, 2048);

    while (1) {
713 714 715
      // todo refactor: this is not correct.
      int32_t savedEpoch = atomic_load_32(&pHandle->epoch);
      if (savedEpoch > pRequest->epoch) {
H
Haojun Liao 已提交
716
        tqWarn("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey:%s vgId:%d offset %" PRId64
L
Liu Jicong 已提交
717
               ", found new consumer epoch %d, discard req epoch %d",
718
               consumerId, pRequest->epoch, pHandle->subKey, vgId, fetchVer, savedEpoch, pRequest->epoch);
wmmhello's avatar
wmmhello 已提交
719 720 721 722
        break;
      }

      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead) < 0) {
723
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
H
Haojun Liao 已提交
724 725 726 727 728 729 730 731 732
//        if (terrno == 0) {  // failed to seek to given ver, but no errors happen.
//          code = tqRegisterPushEntry(pTq, pHandle, pRequest, pMsg, (SMqDataRsp*) &taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
//          return code;
//        } else { // error happens, return to consumers
          code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
          tDeleteSTaosxRsp(&taosxRsp);
          taosMemoryFreeClear(pCkHead);
          return code;
//        }
wmmhello's avatar
wmmhello 已提交
733 734 735
      }

      SWalCont* pHead = &pCkHead->head;
736
      tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId,
737
              pRequest->epoch, vgId, fetchVer, pHead->msgType);
wmmhello's avatar
wmmhello 已提交
738 739

      if (pHead->msgType == TDMT_VND_SUBMIT) {
L
Liu Jicong 已提交
740
        SPackedData submit = {
741 742
            .msgStr = POINTER_SHIFT(pHead->body, sizeof(SSubmitReq2Msg)),
            .msgLen = pHead->bodyLen - sizeof(SSubmitReq2Msg),
L
Liu Jicong 已提交
743 744
            .ver = pHead->version,
        };
H
Haojun Liao 已提交
745

L
Liu Jicong 已提交
746
        if (tqTaosxScanLog(pTq, pHandle, submit, &taosxRsp) < 0) {
747
          tqError("tmq poll: tqTaosxScanLog error %" PRId64 ", in vgId:%d, subkey %s", consumerId, vgId,
748
                  pRequest->subKey);
749
          return -1;
wmmhello's avatar
wmmhello 已提交
750
        }
H
Haojun Liao 已提交
751 752

        if (taosxRsp.blockNum > 0) {
753
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
H
Haojun Liao 已提交
754
          code = tqSendDataRsp(pTq, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP);
755
          tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
756
          taosMemoryFreeClear(pCkHead);
757
          return code;
wmmhello's avatar
wmmhello 已提交
758 759 760 761 762
        } else {
          fetchVer++;
        }

      } else {
L
Liu Jicong 已提交
763 764
        /*A(pHandle->fetchMeta);*/
        /*A(IS_META_MSG(pHead->msgType));*/
765
        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%s", pHead->version, TMSG_INFO(pHead->msgType));
wmmhello's avatar
wmmhello 已提交
766 767 768 769
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer);
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
770
        if (tqSendMetaPollRsp(pTq, pMsg, pRequest, &metaRsp) < 0) {
wmmhello's avatar
wmmhello 已提交
771
          code = -1;
L
Liu Jicong 已提交
772
          taosMemoryFreeClear(pCkHead);
773
          tDeleteSTaosxRsp(&taosxRsp);
774
          return code;
wmmhello's avatar
wmmhello 已提交
775 776
        }
        code = 0;
L
Liu Jicong 已提交
777
        taosMemoryFreeClear(pCkHead);
778
        tDeleteSTaosxRsp(&taosxRsp);
779
        return code;
wmmhello's avatar
wmmhello 已提交
780 781 782
      }
    }
  }
783

784
  tDeleteSTaosxRsp(&taosxRsp);
L
Liu Jicong 已提交
785
  taosMemoryFreeClear(pCkHead);
786
  return 0;
L
Liu Jicong 已提交
787 788
}

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg) {
  SMqPollReq   req = {0};
  if (tDeserializeSMqPollReq(pMsg->pCont, pMsg->contLen, &req) < 0) {
    tqError("tDeserializeSMqPollReq %d failed", pMsg->contLen);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

  int64_t      consumerId = req.consumerId;
  int32_t      reqEpoch = req.epoch;
  STqOffsetVal reqOffset = req.reqOffset;
  int32_t      vgId = TD_VID(pTq->pVnode);

  // 1. find handle
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
  if (pHandle == NULL) {
    tqError("tmq poll: consumer:0x%" PRIx64 " vgId:%d subkey %s not found", consumerId, vgId, req.subKey);
    terrno = TSDB_CODE_INVALID_MSG;
    return -1;
  }

810 811
  // 2. check re-balance status
  taosRLockLatch(&pTq->pushLock);
812 813 814 815
  if (pHandle->consumerId != consumerId) {
    tqDebug("ERROR tmq poll: consumer:0x%" PRIx64 " vgId:%d, subkey %s, mismatch for saved handle consumer:0x%" PRIx64,
            consumerId, TD_VID(pTq->pVnode), req.subKey, pHandle->consumerId);
    terrno = TSDB_CODE_TMQ_CONSUMER_MISMATCH;
816
    taosRUnLockLatch(&pTq->pushLock);
817 818
    return -1;
  }
819 820 821
  taosRUnLockLatch(&pTq->pushLock);

  taosWLockLatch(&pTq->pushLock);
822
  // 3. update the epoch value
H
Haojun Liao 已提交
823 824
  int32_t savedEpoch = pHandle->epoch;
  if (savedEpoch < reqEpoch) {
825 826
    tqDebug("tmq poll: consumer:0x%" PRIx64 " epoch update from %d to %d by poll req", consumerId, savedEpoch, reqEpoch);
    pHandle->epoch = reqEpoch;
H
Haojun Liao 已提交
827
  }
828
  taosWUnLockLatch(&pTq->pushLock);
829 830 831

  char buf[80];
  tFormatOffset(buf, 80, &reqOffset);
H
Haojun Liao 已提交
832 833
  tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey %s, recv poll req vgId:%d, req:%s, reqId:0x%" PRIx64,
          consumerId, req.epoch, pHandle->subKey, vgId, buf, req.reqId);
834

835
  return extractDataForMq(pTq, pHandle, &req, pMsg);
836 837
}

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

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

L
Liu Jicong 已提交
843 844 845 846 847 848 849
  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 已提交
850 851
  STqHandle* pHandle = taosHashGet(pTq->pHandle, pReq->subKey, strlen(pReq->subKey));
  if (pHandle) {
X
Xiaoyu Wang 已提交
852
    // walCloseRef(pHandle->pWalReader->pWal, pHandle->pRef->refId);
L
Liu Jicong 已提交
853 854 855 856 857 858 859
    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 已提交
860
  }
861

L
Liu Jicong 已提交
862 863
  code = tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);
  if (code != 0) {
864
    tqError("cannot process tq delete req %s, since no such offset in cache", pReq->subKey);
L
Liu Jicong 已提交
865
  }
L
Liu Jicong 已提交
866

L
Liu Jicong 已提交
867
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
L
Liu Jicong 已提交
868
    tqError("cannot process tq delete req %s, since no such offset in tdb", pReq->subKey);
869
  }
L
Liu Jicong 已提交
870
  return 0;
L
Liu Jicong 已提交
871 872
}

873
int32_t tqProcessAddCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
874 875
  STqCheckInfo info = {0};
  SDecoder     decoder;
X
Xiaoyu Wang 已提交
876
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
877
  if (tDecodeSTqCheckInfo(&decoder, &info) < 0) {
L
Liu Jicong 已提交
878 879 880 881
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  tDecoderClear(&decoder);
882 883 884 885 886
  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 已提交
887 888 889 890 891 892
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }
  return 0;
}

893
int32_t tqProcessDelCheckInfoReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
894 895 896 897 898 899 900 901 902 903 904
  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;
}

905
int32_t tqProcessSubscribeReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
906
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
907
  tDecodeSMqRebVgReq(msg, &req);
L
Liu Jicong 已提交
908

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

912
  STqHandle* pHandle = taosHashGet(pTq->pHandle, req.subKey, strlen(req.subKey));
L
Liu Jicong 已提交
913
  if (pHandle == NULL) {
L
Liu Jicong 已提交
914
    if (req.oldConsumerId != -1) {
H
Haojun Liao 已提交
915
      tqError("vgId:%d, build new consumer handle %s for consumer:0x%" PRIx64 ", but old consumerId is %" PRId64 "",
916
              req.vgId, req.subKey, req.newConsumerId, req.oldConsumerId);
L
Liu Jicong 已提交
917
    }
918

L
Liu Jicong 已提交
919
    if (req.newConsumerId == -1) {
920
      tqError("vgId:%d, tq invalid rebalance request, new consumerId %" PRId64 "", req.vgId, req.newConsumerId);
L
Liu Jicong 已提交
921
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
922 923
      return 0;
    }
924

L
Liu Jicong 已提交
925 926
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
927 928
    /*taosInitRWLatch(&pExec->lock);*/

H
Haojun Liao 已提交
929
    uint64_t oldConsumerId = pHandle->consumerId;
L
Liu Jicong 已提交
930 931 932
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
933

L
Liu Jicong 已提交
934
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
935
    pHandle->fetchMeta = req.withMeta;
wmmhello's avatar
wmmhello 已提交
936

937 938 939
    // TODO version should be assigned and refed during preprocess
    SWalRef* pRef = walRefCommittedVer(pTq->pVnode->pWal);
    if (pRef == NULL) {
H
Haojun Liao 已提交
940
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
941
      return -1;
942
    }
H
Haojun Liao 已提交
943

944 945
    int64_t ver = pRef->refVer;
    pHandle->pRef = pRef;
L
Liu Jicong 已提交
946

947 948 949 950 951 952 953
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTableReader = true,
        .initTqReader = true,
        .version = ver,
    };
954

wmmhello's avatar
wmmhello 已提交
955
    pHandle->snapshotVer = ver;
956

L
Liu Jicong 已提交
957
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
958
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
959
      req.qmsg = NULL;
960 961

      pHandle->execHandle.task =
L
Liu Jicong 已提交
962
          qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle, &pHandle->execHandle.numOfCols, NULL);
L
Liu Jicong 已提交
963
      void* scanner = NULL;
964
      qExtractStreamScanner(pHandle->execHandle.task, &scanner);
L
Liu Jicong 已提交
965
      pHandle->execHandle.pExecReader = qExtractReaderFromStreamScanner(scanner);
L
Liu Jicong 已提交
966
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
wmmhello's avatar
wmmhello 已提交
967
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
L
Liu Jicong 已提交
968
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
969

L
Liu Jicong 已提交
970
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
971
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
972 973
      buildSnapContext(handle.meta, handle.version, 0, pHandle->execHandle.subType, pHandle->fetchMeta,
                       (SSnapContext**)(&handle.sContext));
974

975
      pHandle->execHandle.task = qCreateQueueExecTaskInfo(NULL, &handle, NULL, NULL);
L
Liu Jicong 已提交
976
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
wmmhello's avatar
wmmhello 已提交
977 978 979
      pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
      pHandle->execHandle.execTb.suid = req.suid;

L
Liu Jicong 已提交
980
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
H
Hongze Cheng 已提交
981
      vnodeGetCtbIdList(pTq->pVnode, req.suid, tbUidList);
982
      tqDebug("vgId:%d, tq try to get all ctb, suid:%" PRId64, pTq->pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
983 984
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
S
Shengliang Guan 已提交
985
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, TD_VID(pTq->pVnode), i, tbUid);
L
Liu Jicong 已提交
986
      }
L
Liu Jicong 已提交
987 988
      pHandle->execHandle.pExecReader = tqOpenReader(pTq->pVnode);
      tqReaderSetTbUidList(pHandle->execHandle.pExecReader, tbUidList);
L
Liu Jicong 已提交
989
      taosArrayDestroy(tbUidList);
wmmhello's avatar
wmmhello 已提交
990

L
Liu Jicong 已提交
991 992 993
      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 已提交
994
    }
H
Haojun Liao 已提交
995

996
    taosHashPut(pTq->pHandle, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
997 998
    tqDebug("try to persist handle %s consumer:0x%" PRIx64 " , old consumer:0x%" PRIx64, req.subKey,
            pHandle->consumerId, oldConsumerId);
L
Liu Jicong 已提交
999
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
H
Haojun Liao 已提交
1000
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
1001
      return -1;
L
Liu Jicong 已提交
1002
    }
L
Liu Jicong 已提交
1003
  } else {
1004 1005 1006 1007
    if (pHandle->consumerId == req.newConsumerId) {  // do nothing
      tqInfo("vgId:%d consumer:0x%" PRIx64 " remains, no switch occurs", req.vgId, req.newConsumerId);
      atomic_store_32(&pHandle->epoch, -1);
      atomic_add_fetch_32(&pHandle->epoch, 1);
H
Haojun Liao 已提交
1008
      taosMemoryFree(req.qmsg);
1009 1010 1011 1012 1013 1014 1015
      return tqMetaSaveHandle(pTq, req.subKey, pHandle);
    }

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

    taosWLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
1016
    atomic_store_32(&pHandle->epoch, -1);
1017 1018 1019 1020

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

L
Liu Jicong 已提交
1021 1022
    atomic_store_64(&pHandle->consumerId, req.newConsumerId);
    atomic_add_fetch_32(&pHandle->epoch, 1);
1023

L
Liu Jicong 已提交
1024 1025 1026
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
      qStreamCloseTsdbReader(pHandle->execHandle.task);
    }
H
Haojun Liao 已提交
1027

1028
    taosWUnLockLatch(&pTq->pushLock);
L
Liu Jicong 已提交
1029
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
H
Haojun Liao 已提交
1030
      taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
1031
      return -1;
L
Liu Jicong 已提交
1032
    }
L
Liu Jicong 已提交
1033
  }
L
Liu Jicong 已提交
1034

H
Haojun Liao 已提交
1035
  taosMemoryFree(req.qmsg);
L
Liu Jicong 已提交
1036
  return 0;
L
Liu Jicong 已提交
1037
}
1038

1039
int32_t tqExpandTask(STQ* pTq, SStreamTask* pTask, int64_t ver) {
L
Liu Jicong 已提交
1040
#if 0
1041
  if (pTask->taskLevel == TASK_LEVEL__AGG) {
L
Liu Jicong 已提交
1042
    A(taosArrayGetSize(pTask->childEpInfo) != 0);
L
Liu Jicong 已提交
1043
  }
L
Liu Jicong 已提交
1044
#endif
L
Liu Jicong 已提交
1045

L
Liu Jicong 已提交
1046
  pTask->refCnt = 1;
L
Liu Jicong 已提交
1047
  pTask->schedStatus = TASK_SCHED_STATUS__INACTIVE;
L
Liu Jicong 已提交
1048 1049 1050

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

  if (pTask->inputQueue == NULL || pTask->outputQueue == NULL) {
L
Liu Jicong 已提交
1053
    return -1;
L
Liu Jicong 已提交
1054 1055
  }

L
Liu Jicong 已提交
1056 1057 1058
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;

1059 1060
  pTask->pMsgCb = &pTq->pVnode->msgCb;

1061 1062
  pTask->startVer = ver;

1063
  // expand executor
1064 1065 1066 1067
  if (pTask->fillHistory) {
    pTask->taskStatus = TASK_STATUS__WAIT_DOWNSTREAM;
  }

1068
  if (pTask->taskLevel == TASK_LEVEL__SOURCE) {
1069
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
1070 1071 1072 1073
    if (pTask->pState == NULL) {
      return -1;
    }

1074 1075 1076 1077
    SReadHandle handle = {
        .meta = pTq->pVnode->pMeta,
        .vnode = pTq->pVnode,
        .initTqReader = 1,
1078
        .pStateBackend = pTask->pState,
1079 1080
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle);
L
Liu Jicong 已提交
1081 1082 1083
    if (pTask->exec.executor == NULL) {
      return -1;
    }
1084

1085
  } else if (pTask->taskLevel == TASK_LEVEL__AGG) {
1086
    pTask->pState = streamStateOpen(pTq->pStreamMeta->path, pTask, false, -1, -1);
1087 1088 1089
    if (pTask->pState == NULL) {
      return -1;
    }
1090 1091 1092
    SReadHandle mgHandle = {
        .vnode = NULL,
        .numOfVgroups = (int32_t)taosArrayGetSize(pTask->childEpInfo),
1093
        .pStateBackend = pTask->pState,
1094 1095
    };
    pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &mgHandle);
L
Liu Jicong 已提交
1096 1097 1098
    if (pTask->exec.executor == NULL) {
      return -1;
    }
L
Liu Jicong 已提交
1099
  }
L
Liu Jicong 已提交
1100 1101

  // sink
L
Liu Jicong 已提交
1102
  /*pTask->ahandle = pTq->pVnode;*/
1103
  if (pTask->outputType == TASK_OUTPUT__SMA) {
L
Liu Jicong 已提交
1104
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
1105
    pTask->smaSink.smaSink = smaHandleRes;
1106
  } else if (pTask->outputType == TASK_OUTPUT__TABLE) {
L
Liu Jicong 已提交
1107
    pTask->tbSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
1108
    pTask->tbSink.tbSinkFunc = tqSinkToTablePipeline2;
L
Liu Jicong 已提交
1109

H
Haojun Liao 已提交
1110
    int32_t ver1 = 1;
5
54liuyao 已提交
1111 1112 1113
    SMetaInfo info = {0};
    int32_t code = metaGetInfo(pTq->pVnode->pMeta, pTask->tbSink.stbUid, &info, NULL);
    if (code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1114
      ver1 = info.skmVer;
5
54liuyao 已提交
1115
    }
L
Liu Jicong 已提交
1116

L
Liu Jicong 已提交
1117
    pTask->tbSink.pTSchema =
H
Haojun Liao 已提交
1118
        tBuildTSchema(pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols, ver1);
wmmhello's avatar
wmmhello 已提交
1119
    if(pTask->tbSink.pTSchema == NULL) {
wmmhello's avatar
wmmhello 已提交
1120
      return -1;
wmmhello's avatar
wmmhello 已提交
1121
    }
L
Liu Jicong 已提交
1122
  }
1123 1124 1125

  streamSetupTrigger(pTask);

1126 1127
  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 已提交
1128
  return 0;
L
Liu Jicong 已提交
1129
}
L
Liu Jicong 已提交
1130

1131 1132 1133 1134 1135 1136
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 已提交
1137
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
  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 已提交
1150
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1151 1152 1153 1154 1155 1156
  if (pTask && atomic_load_8(&pTask->taskStatus) == TASK_STATUS__NORMAL) {
    rsp.status = 1;
  } else {
    rsp.status = 0;
  }

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

1159
  tqDebug("tq recv task check req(reqId:0x%" PRIx64 ") %d at node %d check req from task %d at node %d, status %d",
1160 1161 1162 1163 1164 1165 1166
          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 已提交
1167
    tqError("unable to encode rsp %d", __LINE__);
L
Liu Jicong 已提交
1168
    return -1;
1169
  }
L
Liu Jicong 已提交
1170

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
  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;
}

1190
int32_t tqProcessStreamTaskCheckRsp(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
  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);

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

L
Liu Jicong 已提交
1206
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, rsp.upstreamTaskId);
1207 1208 1209 1210
  if (pTask == NULL) {
    return -1;
  }

1211
  code = streamProcessTaskCheckRsp(pTask, &rsp, sversion);
L
Liu Jicong 已提交
1212 1213
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
  return code;
1214 1215
}

1216
int32_t tqProcessTaskDeployReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1217 1218 1219 1220 1221
  int32_t code;
#if 0
  code = streamMetaAddSerializedTask(pTq->pStreamMeta, version, msg, msgLen);
  if (code < 0) return code;
#endif
5
54liuyao 已提交
1222 1223 1224
  if (tsDisableStream) {
    return 0;
  }
1225 1226 1227 1228 1229 1230

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

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
  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
1243
  code = streamMetaAddTask(pTq->pStreamMeta, sversion, pTask);
1244 1245 1246 1247 1248 1249
  if (code < 0) {
    return -1;
  }

  // 3.go through recover steps to fill history
  if (pTask->fillHistory) {
1250
    streamTaskCheckDownstream(pTask, sversion);
1251 1252 1253 1254 1255
  }

  return 0;
}

L
Liu Jicong 已提交
1256 1257 1258 1259 1260
int32_t tqProcessTaskRecover1Req(STQ* pTq, SRpcMsg* pMsg) {
  int32_t code;
  char*   msg = pMsg->pCont;
  int32_t msgLen = pMsg->contLen;

1261
  SStreamRecoverStep1Req* pReq = (SStreamRecoverStep1Req*)msg;
L
Liu Jicong 已提交
1262
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1263 1264 1265 1266 1267 1268 1269
  if (pTask == NULL) {
    return -1;
  }

  // check param
  int64_t fillVer1 = pTask->startVer;
  if (fillVer1 <= 0) {
L
Liu Jicong 已提交
1270
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1271 1272 1273 1274 1275 1276
    return -1;
  }

  // do recovery step 1
  streamSourceRecoverScanStep1(pTask);

L
Liu Jicong 已提交
1277 1278 1279 1280 1281
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1282 1283 1284 1285
  // build msg to launch next step
  SStreamRecoverStep2Req req;
  code = streamBuildSourceRecover2Req(pTask, &req);
  if (code < 0) {
L
Liu Jicong 已提交
1286
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1287 1288 1289
    return -1;
  }

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

L
Liu Jicong 已提交
1292 1293 1294 1295
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    return 0;
  }

1296
  // serialize msg
L
Liu Jicong 已提交
1297 1298 1299 1300 1301 1302 1303 1304
  int32_t len = sizeof(SStreamRecoverStep1Req);

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

  memcpy(serializedReq, &req, len);
1305 1306 1307 1308 1309

  // dispatch msg
  SRpcMsg rpcMsg = {
      .code = 0,
      .contLen = len,
L
Liu Jicong 已提交
1310
      .msgType = TDMT_VND_STREAM_RECOVER_BLOCKING_STAGE,
L
Liu Jicong 已提交
1311
      .pCont = serializedReq,
1312 1313 1314 1315 1316 1317 1318
  };

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

  return 0;
}

1319
int32_t tqProcessTaskRecover2Req(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
1320 1321
  int32_t                 code;
  SStreamRecoverStep2Req* pReq = (SStreamRecoverStep2Req*)msg;
L
Liu Jicong 已提交
1322
  SStreamTask*            pTask = streamMetaAcquireTask(pTq->pStreamMeta, pReq->taskId);
1323 1324 1325 1326 1327
  if (pTask == NULL) {
    return -1;
  }

  // do recovery step 2
1328
  code = streamSourceRecoverScanStep2(pTask, sversion);
1329
  if (code < 0) {
L
Liu Jicong 已提交
1330
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1331 1332 1333
    return -1;
  }

L
Liu Jicong 已提交
1334 1335 1336 1337 1338
  if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
    return 0;
  }

1339 1340 1341
  // restore param
  code = streamRestoreParam(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1342
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1343 1344 1345 1346 1347 1348
    return -1;
  }

  // set status normal
  code = streamSetStatusNormal(pTask);
  if (code < 0) {
L
Liu Jicong 已提交
1349
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1350 1351 1352 1353 1354 1355
    return -1;
  }

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

L
Liu Jicong 已提交
1360 1361 1362
  atomic_store_8(&pTask->fillHistory, 0);
  streamMetaSaveTask(pTq->pStreamMeta, pTask);

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

1365 1366 1367
  return 0;
}

L
Liu Jicong 已提交
1368 1369 1370
int32_t tqProcessTaskRecoverFinishReq(STQ* pTq, SRpcMsg* pMsg) {
  char*   msg = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
  int32_t msgLen = pMsg->contLen - sizeof(SMsgHead);
1371 1372

  // deserialize
1373 1374 1375
  SStreamRecoverFinishReq req;

  SDecoder decoder;
X
Xiaoyu Wang 已提交
1376
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
1377 1378 1379
  tDecodeSStreamRecoverFinishReq(&decoder, &req);
  tDecoderClear(&decoder);

1380
  // find task
L
Liu Jicong 已提交
1381
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, req.taskId);
1382 1383 1384
  if (pTask == NULL) {
    return -1;
  }
1385
  // do process request
1386
  if (streamProcessRecoverFinishReq(pTask, req.childId) < 0) {
L
Liu Jicong 已提交
1387
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1388 1389 1390
    return -1;
  }

L
Liu Jicong 已提交
1391
  streamMetaReleaseTask(pTq->pStreamMeta, pTask);
1392
  return 0;
L
Liu Jicong 已提交
1393
}
L
Liu Jicong 已提交
1394

L
Liu Jicong 已提交
1395 1396 1397 1398 1399
int32_t tqProcessTaskRecoverFinishRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}

L
Liu Jicong 已提交
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
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 已提交
1416
  if (sz == 0 || pRes->affectedRows == 0) {
L
Liu Jicong 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    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);
1428
    colDataSetVal(pStartCol, i, (const char*)&pRes->skey, false);  // end key column
L
Liu Jicong 已提交
1429
    SColumnInfoData* pEndCol = taosArrayGet(pDelBlock->pDataBlock, END_TS_COLUMN_INDEX);
1430
    colDataSetVal(pEndCol, i, (const char*)&pRes->ekey, false);
L
Liu Jicong 已提交
1431 1432 1433
    // uid column
    SColumnInfoData* pUidCol = taosArrayGet(pDelBlock->pDataBlock, UID_COLUMN_INDEX);
    int64_t*         pUid = taosArrayGet(pRes->uidList, i);
1434
    colDataSetVal(pUidCol, i, (const char*)pUid, false);
L
Liu Jicong 已提交
1435

1436 1437 1438
    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 已提交
1439 1440
  }

L
Liu Jicong 已提交
1441 1442
  taosArrayDestroy(pRes->uidList);

L
Liu Jicong 已提交
1443 1444 1445
  int32_t* pRef = taosMemoryMalloc(sizeof(int32_t));
  *pRef = 1;

L
Liu Jicong 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454
  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 已提交
1455
    if (!failed) {
S
Shengliang Guan 已提交
1456
      SStreamRefDataBlock* pRefBlock = taosAllocateQitem(sizeof(SStreamRefDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1457 1458 1459 1460 1461 1462 1463
      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 已提交
1464

L
Liu Jicong 已提交
1465
        atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1466
        taosFreeQitem(pRefBlock);
L
Liu Jicong 已提交
1467 1468
        continue;
      }
L
Liu Jicong 已提交
1469

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

L
Liu Jicong 已提交
1475 1476 1477 1478
    } else {
      streamTaskInputFail(pTask);
    }
  }
L
Liu Jicong 已提交
1479

L
Liu Jicong 已提交
1480
  int32_t ref = atomic_sub_fetch_32(pRef, 1);
L
Liu Jicong 已提交
1481
  /*A(ref >= 0);*/
L
Liu Jicong 已提交
1482
  if (ref == 0) {
L
Liu Jicong 已提交
1483
    blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1484 1485 1486 1487
    taosMemoryFree(pRef);
  }

#if 0
S
Shengliang Guan 已提交
1488
    SStreamDataBlock* pStreamBlock = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, 0);
L
Liu Jicong 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
    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 已提交
1510
  blockDataDestroy(pDelBlock);
L
Liu Jicong 已提交
1511
#endif
L
Liu Jicong 已提交
1512 1513 1514 1515

  return 0;
}

L
Liu Jicong 已提交
1516
int32_t tqProcessSubmitReq(STQ* pTq, SPackedData submit) {
L
Liu Jicong 已提交
1517 1518 1519
  void*               pIter = NULL;
  bool                failed = false;
  SStreamDataSubmit2* pSubmit = NULL;
L
Liu Jicong 已提交
1520

L
Liu Jicong 已提交
1521
  pSubmit = streamDataSubmitNew(submit);
L
Liu Jicong 已提交
1522
  if (pSubmit == NULL) {
L
Liu Jicong 已提交
1523
    terrno = TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
1524
    tqError("failed to create data submit for stream since out of memory");
L
Liu Jicong 已提交
1525 1526 1527 1528
    failed = true;
  }

  while (1) {
L
Liu Jicong 已提交
1529
    pIter = taosHashIterate(pTq->pStreamMeta->pTasks, pIter);
1530 1531 1532 1533
    if (pIter == NULL) {
      break;
    }

1534
    SStreamTask* pTask = *(SStreamTask**)pIter;
1535
    if (pTask->taskLevel != TASK_LEVEL__SOURCE) continue;
1536
    if (pTask->taskStatus == TASK_STATUS__RECOVER_PREPARE || pTask->taskStatus == TASK_STATUS__WAIT_DOWNSTREAM) {
L
Liu Jicong 已提交
1537 1538 1539
      tqDebug("skip push task %d, task status %d", pTask->taskId, pTask->taskStatus);
      continue;
    }
L
Liu Jicong 已提交
1540

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

L
Liu Jicong 已提交
1543 1544
    if (!failed) {
      if (streamTaskInput(pTask, (SStreamQueueItem*)pSubmit) < 0) {
L
Liu Jicong 已提交
1545
        tqError("stream task input failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1546 1547 1548
        continue;
      }

L
Liu Jicong 已提交
1549
      if (streamSchedExec(pTask) < 0) {
L
Liu Jicong 已提交
1550
        tqError("stream task launch failed, task id %d", pTask->taskId);
L
Liu Jicong 已提交
1551 1552
        continue;
      }
L
Liu Jicong 已提交
1553
    } else {
L
Liu Jicong 已提交
1554
      streamTaskInputFail(pTask);
L
Liu Jicong 已提交
1555 1556 1557
    }
  }

L
Liu Jicong 已提交
1558
  if (pSubmit) {
L
Liu Jicong 已提交
1559
    streamDataSubmitRefDec(pSubmit);
L
Liu Jicong 已提交
1560
    taosFreeQitem(pSubmit);
L
Liu Jicong 已提交
1561
  }
L
Liu Jicong 已提交
1562 1563

  return failed ? -1 : 0;
L
Liu Jicong 已提交
1564 1565
}

L
Liu Jicong 已提交
1566 1567 1568
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRunReq* pReq = pMsg->pCont;
  int32_t            taskId = pReq->taskId;
L
Liu Jicong 已提交
1569
  SStreamTask*       pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1570 1571
  if (pTask) {
    streamProcessRunReq(pTask);
L
Liu Jicong 已提交
1572
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1573
    return 0;
1574 1575
  } else {
    return -1;
L
Liu Jicong 已提交
1576
  }
L
Liu Jicong 已提交
1577 1578
}

L
Liu Jicong 已提交
1579
int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg, bool exec) {
1580 1581 1582 1583 1584
  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 已提交
1585
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
1586
  tDecodeStreamDispatchReq(&decoder, &req);
L
Liu Jicong 已提交
1587 1588
  int32_t taskId = req.taskId;

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

L
Liu Jicong 已提交
1603 1604
int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
1605
  int32_t             taskId = ntohl(pRsp->upstreamTaskId);
L
Liu Jicong 已提交
1606
  SStreamTask*        pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
1607
  tqDebug("recv dispatch rsp, code: %x", pMsg->code);
L
Liu Jicong 已提交
1608
  if (pTask) {
1609
    streamProcessDispatchRsp(pTask, pRsp, pMsg->code);
L
Liu Jicong 已提交
1610
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1611
    return 0;
1612 1613
  } else {
    return -1;
L
Liu Jicong 已提交
1614
  }
L
Liu Jicong 已提交
1615
}
L
Liu Jicong 已提交
1616

1617
int32_t tqProcessTaskDropReq(STQ* pTq, int64_t sversion, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
1618
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
1619
  streamMetaRemoveTask(pTq->pStreamMeta, pReq->taskId);
L
Liu Jicong 已提交
1620
  return 0;
L
Liu Jicong 已提交
1621
}
L
Liu Jicong 已提交
1622 1623 1624 1625 1626 1627 1628

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;
1629
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1630
  tDecodeStreamRetrieveReq(&decoder, &req);
L
Liu Jicong 已提交
1631
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1632
  int32_t      taskId = req.dstTaskId;
L
Liu Jicong 已提交
1633
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1634
  if (pTask) {
L
Liu Jicong 已提交
1635 1636 1637 1638
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1639
    streamProcessRetrieveReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
1640
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1641
    tDeleteStreamRetrieveReq(&req);
L
Liu Jicong 已提交
1642
    return 0;
L
Liu Jicong 已提交
1643 1644
  } else {
    return -1;
L
Liu Jicong 已提交
1645 1646 1647 1648 1649 1650 1651
  }
}

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

1653 1654 1655 1656 1657 1658
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 已提交
1659 1660 1661

  SStreamDispatchReq req;
  SDecoder           decoder;
1662
  tDecoderInit(&decoder, (uint8_t*)msgBody, msgLen);
L
Liu Jicong 已提交
1663 1664
  if (tDecodeStreamDispatchReq(&decoder, &req) < 0) {
    code = TSDB_CODE_MSG_DECODE_ERROR;
L
Liu Jicong 已提交
1665
    tDecoderClear(&decoder);
L
Liu Jicong 已提交
1666 1667
    goto FAIL;
  }
L
Liu Jicong 已提交
1668
  tDecoderClear(&decoder);
L
Liu Jicong 已提交
1669

L
Liu Jicong 已提交
1670
  int32_t taskId = req.taskId;
L
Liu Jicong 已提交
1671

L
Liu Jicong 已提交
1672
  SStreamTask* pTask = streamMetaAcquireTask(pTq->pStreamMeta, taskId);
L
Liu Jicong 已提交
1673
  if (pTask) {
L
Liu Jicong 已提交
1674 1675 1676 1677
    SRpcMsg rsp = {
        .info = pMsg->info,
        .code = 0,
    };
L
Liu Jicong 已提交
1678
    streamProcessDispatchReq(pTask, &req, &rsp, false);
L
Liu Jicong 已提交
1679
    streamMetaReleaseTask(pTq->pStreamMeta, pTask);
L
Liu Jicong 已提交
1680 1681
    rpcFreeCont(pMsg->pCont);
    taosFreeQitem(pMsg);
1682
    return 0;
L
Liu Jicong 已提交
1683
  }
L
Liu Jicong 已提交
1684

1685 1686
  code = TSDB_CODE_STREAM_TASK_NOT_EXIST;

L
Liu Jicong 已提交
1687
FAIL:
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
  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 已提交
1712 1713 1714
  SRpcMsg rsp = {
      .code = code,
      .info = pMsg->info,
1715 1716
      .contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp),
      .pCont = pRspHead,
L
Liu Jicong 已提交
1717
  };
1718
  tqDebug("send dispatch error rsp, code: %x", code);
L
Liu Jicong 已提交
1719
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
1720 1721
  rpcFreeCont(pMsg->pCont);
  taosFreeQitem(pMsg);
1722
  return -1;
L
Liu Jicong 已提交
1723
}
L
Liu Jicong 已提交
1724

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