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

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

L
Liu Jicong 已提交
18
int32_t tqInit() {
L
Liu Jicong 已提交
19 20 21 22 23 24
  int8_t old;
  while (1) {
    old = atomic_val_compare_exchange_8(&tqMgmt.inited, 0, 2);
    if (old != 2) break;
  }

25 26 27 28 29 30
  if (old == 0) {
    tqMgmt.timer = taosTmrInit(10000, 100, 10000, "TQ");
    if (tqMgmt.timer == NULL) {
      atomic_store_8(&tqMgmt.inited, 0);
      return -1;
    }
31 32 33
    if (streamInit() < 0) {
      return -1;
    }
L
Liu Jicong 已提交
34
    atomic_store_8(&tqMgmt.inited, 1);
35
  }
36

L
Liu Jicong 已提交
37 38
  return 0;
}
L
Liu Jicong 已提交
39

40
void tqCleanUp() {
L
Liu Jicong 已提交
41 42 43 44 45 46 47 48
  int8_t old;
  while (1) {
    old = atomic_val_compare_exchange_8(&tqMgmt.inited, 1, 2);
    if (old != 2) break;
  }

  if (old == 1) {
    taosTmrCleanUp(tqMgmt.timer);
L
Liu Jicong 已提交
49
    streamCleanUp();
L
Liu Jicong 已提交
50 51
    atomic_store_8(&tqMgmt.inited, 0);
  }
52
}
L
Liu Jicong 已提交
53

L
Liu Jicong 已提交
54
STQ* tqOpen(const char* path, SVnode* pVnode, SWal* pWal) {
55
  STQ* pTq = taosMemoryCalloc(1, sizeof(STQ));
L
Liu Jicong 已提交
56
  if (pTq == NULL) {
L
Liu Jicong 已提交
57
    terrno = TSDB_CODE_TQ_OUT_OF_MEMORY;
L
Liu Jicong 已提交
58 59
    return NULL;
  }
H
Hongze Cheng 已提交
60
  pTq->path = strdup(path);
L
Liu Jicong 已提交
61
  pTq->pVnode = pVnode;
L
Liu Jicong 已提交
62
  pTq->pWal = pWal;
63

L
Liu Jicong 已提交
64
  pTq->handles = taosHashInit(64, MurmurHash3_32, true, HASH_ENTRY_LOCK);
L
Liu Jicong 已提交
65

L
Liu Jicong 已提交
66 67
  pTq->pStreamTasks = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);

L
Liu Jicong 已提交
68 69
  pTq->pushMgr = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);

L
Liu Jicong 已提交
70
  if (tqMetaOpen(pTq) < 0) {
71 72 73
    ASSERT(0);
  }

74 75 76 77
  if (tqOffsetOpen(pTq) < 0) {
    ASSERT(0);
  }

L
Liu Jicong 已提交
78 79
  return pTq;
}
L
Liu Jicong 已提交
80

L
Liu Jicong 已提交
81
void tqClose(STQ* pTq) {
H
Hongze Cheng 已提交
82
  if (pTq) {
83
    tqOffsetClose(pTq->pOffsetStore);
L
Liu Jicong 已提交
84
    taosHashCleanup(pTq->handles);
L
Liu Jicong 已提交
85 86
    taosHashCleanup(pTq->pStreamTasks);
    taosHashCleanup(pTq->pushMgr);
87
    taosMemoryFree(pTq->path);
L
Liu Jicong 已提交
88
    tqMetaClose(pTq);
wafwerar's avatar
wafwerar 已提交
89
    taosMemoryFree(pTq);
H
Hongze Cheng 已提交
90
  }
L
Liu Jicong 已提交
91
}
L
Liu Jicong 已提交
92

L
Liu Jicong 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
int32_t tqSendMetaPollRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqMetaRsp* pRsp) {
  int32_t tlen = sizeof(SMqRspHead) + tEncodeSMqMetaRsp(NULL, pRsp);
  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));
  tEncodeSMqMetaRsp(&abuf, pRsp);

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

L
Liu Jicong 已提交
115 116
  tqDebug("vgId:%d from consumer:%" PRId64 ", (epoch %d) send rsp, res msg type %d, reqOffset:%" PRId64
          ", rspOffset:%" PRId64,
L
Liu Jicong 已提交
117 118 119 120 121
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->resMsgType, pRsp->reqOffset, pRsp->rspOffset);

  return 0;
}

L
Liu Jicong 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
int32_t tqSendDataRsp(STQ* pTq, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqDataRsp* pRsp) {
  ASSERT(taosArrayGetSize(pRsp->blockData) == pRsp->blockNum);
  ASSERT(taosArrayGetSize(pRsp->blockDataLen) == pRsp->blockNum);

  if (pRsp->withSchema) {
    ASSERT(taosArrayGetSize(pRsp->blockSchema) == pRsp->blockNum);
  } else {
    ASSERT(taosArrayGetSize(pRsp->blockSchema) == 0);
  }

  int32_t len;
  int32_t code;
  tEncodeSize(tEncodeSMqDataRsp, 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 149
  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));

L
Liu Jicong 已提交
150
  SEncoder encoder;
L
Liu Jicong 已提交
151
  tEncoderInit(&encoder, abuf, len);
L
Liu Jicong 已提交
152 153 154
  tEncodeSMqDataRsp(&encoder, pRsp);

  SRpcMsg rsp = {
L
Liu Jicong 已提交
155 156 157 158 159
      .info = pMsg->info,
      .pCont = buf,
      .contLen = tlen,
      .code = 0,
  };
L
Liu Jicong 已提交
160
  tmsgSendRsp(&rsp);
L
Liu Jicong 已提交
161

L
Liu Jicong 已提交
162 163 164 165
  char buf1[80];
  char buf2[80];
  tFormatOffset(buf1, 80, &pRsp->reqOffset);
  tFormatOffset(buf2, 80, &pRsp->rspOffset);
S
Shengliang Guan 已提交
166
  tqDebug("vgId:%d from consumer:%" PRId64 ", (epoch %d) send rsp, block num: %d, reqOffset:%s, rspOffset:%s",
L
Liu Jicong 已提交
167
          TD_VID(pTq->pVnode), pReq->consumerId, pReq->epoch, pRsp->blockNum, buf1, buf2);
L
Liu Jicong 已提交
168 169 170 171

  return 0;
}

172 173 174 175 176 177 178 179 180 181
int32_t tqProcessOffsetCommitReq(STQ* pTq, char* msg, int32_t msgLen) {
  STqOffset offset = {0};
  SDecoder  decoder;
  tDecoderInit(&decoder, msg, msgLen);
  if (tDecodeSTqOffset(&decoder, &offset) < 0) {
    ASSERT(0);
    return -1;
  }
  tDecoderClear(&decoder);

L
Liu Jicong 已提交
182
  if (offset.val.type == TMQ_OFFSET__SNAPSHOT_DATA) {
L
Liu Jicong 已提交
183 184
    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 已提交
185
  } else if (offset.val.type == TMQ_OFFSET__LOG) {
S
Shengliang Guan 已提交
186
    tqDebug("receive offset commit msg to %s on vgId:%d, offset(type:log) version:%" PRId64, offset.subKey,
L
Liu Jicong 已提交
187
            TD_VID(pTq->pVnode), offset.val.version);
188 189 190
  } else {
    ASSERT(0);
  }
191 192 193 194 195 196
  /*STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, offset.subKey);*/
  /*if (pOffset != NULL) {*/
  /*if (pOffset->val.type == TMQ_OFFSET__LOG && pOffset->val.version < offset.val.version) {*/
  if (tqOffsetWrite(pTq->pOffsetStore, &offset) < 0) {
    ASSERT(0);
    return -1;
197
  }
198 199
  /*}*/
  /*}*/
200 201 202 203

  return 0;
}

L
Liu Jicong 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
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;
  }

  pRsp->withTbName = pReq->withTbName;
  if (pRsp->withTbName) {
    pRsp->blockTbName = taosArrayInit(0, sizeof(void*));
    if (pRsp->blockTbName == NULL) {
      // TODO free
      return -1;
    }
  }

  if (subType == TOPIC_SUB_TYPE__COLUMN) {
    pRsp->withSchema = false;
  } else {
    pRsp->withSchema = true;
    pRsp->blockSchema = taosArrayInit(0, sizeof(void*));
    if (pRsp->blockSchema == NULL) {
      // TODO free
      return -1;
    }
  }
  return 0;
}

static int32_t tqInitMetaRsp(SMqMetaRsp* pRsp, const SMqPollReq* pReq) { return 0; }

int32_t tqProcessPollReq(STQ* pTq, SRpcMsg* pMsg, int32_t workerId) {
  SMqPollReq*  pReq = pMsg->pCont;
  int64_t      consumerId = pReq->consumerId;
  int64_t      timeout = pReq->timeout;
  int32_t      reqEpoch = pReq->epoch;
  int32_t      code = 0;
  STqOffsetVal reqOffset = pReq->reqOffset;
  STqOffsetVal fetchOffsetNew;

247 248 249
  // todo
  workerId = 0;

L
Liu Jicong 已提交
250 251 252 253
  // 1.find handle
  STqHandle* pHandle = taosHashGet(pTq->handles, pReq->subKey, strlen(pReq->subKey));
  /*ASSERT(pHandle);*/
  if (pHandle == NULL) {
S
Shengliang Guan 已提交
254 255
    tqError("tmq poll: no consumer handle for consumer:%" PRId64 ", in vgId:%d, subkey %s", consumerId,
            TD_VID(pTq->pVnode), pReq->subKey);
L
Liu Jicong 已提交
256 257 258 259 260
    return -1;
  }

  // check rebalance
  if (pHandle->consumerId != consumerId) {
S
Shengliang Guan 已提交
261 262
    tqError("tmq poll: consumer handle mismatch for consumer:%" PRId64
            ", in vgId:%d, subkey %s, handle consumer id %" PRId64,
L
Liu Jicong 已提交
263 264 265 266 267 268 269 270 271 272
            consumerId, TD_VID(pTq->pVnode), pReq->subKey, pHandle->consumerId);
    return -1;
  }

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

L
Liu Jicong 已提交
273 274 275 276 277
  char buf[80];
  tFormatOffset(buf, 80, &reqOffset);
  tqDebug("tmq poll: consumer %ld (epoch %d), subkey %s, recv poll req in vg %d, req offset %s", consumerId,
          pReq->epoch, pHandle->subKey, TD_VID(pTq->pVnode), buf);

L
Liu Jicong 已提交
278 279 280
  SMqDataRsp dataRsp = {0};
  tqInitDataRsp(&dataRsp, pReq, pHandle->execHandle.subType);

L
Liu Jicong 已提交
281 282 283 284 285 286 287
  // 2.reset offset if needed
  if (reqOffset.type > 0) {
    fetchOffsetNew = reqOffset;
  } else {
    STqOffset* pOffset = tqOffsetRead(pTq->pOffsetStore, pReq->subKey);
    if (pOffset != NULL) {
      fetchOffsetNew = pOffset->val;
L
Liu Jicong 已提交
288 289
      char formatBuf[80];
      tFormatOffset(formatBuf, 80, &fetchOffsetNew);
L
Liu Jicong 已提交
290 291
      tqDebug("tmq poll: consumer %" PRId64 ", subkey %s, vg %d, offset reset to %s", consumerId, pHandle->subKey,
              TD_VID(pTq->pVnode), formatBuf);
L
Liu Jicong 已提交
292 293
    } else {
      if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEAST) {
294
        if (pReq->useSnapshot && pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
295 296 297 298 299 300 301 302 303 304
          if (!pHandle->fetchMeta) {
            tqOffsetResetToData(&fetchOffsetNew, 0, 0);
          } else {
            // reset to meta
            ASSERT(0);
          }
        } else {
          tqOffsetResetToLog(&fetchOffsetNew, walGetFirstVer(pTq->pVnode->pWal));
        }
      } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
L
Liu Jicong 已提交
305
        tqOffsetResetToLog(&dataRsp.rspOffset, walGetLastVer(pTq->pVnode->pWal));
L
Liu Jicong 已提交
306 307
        tqDebug("tmq poll: consumer %ld, subkey %s, vg %d, offset reset to %ld", consumerId, pHandle->subKey,
                TD_VID(pTq->pVnode), dataRsp.rspOffset.version);
L
Liu Jicong 已提交
308 309 310
        if (tqSendDataRsp(pTq, pMsg, pReq, &dataRsp) < 0) {
          code = -1;
        }
L
Liu Jicong 已提交
311
        goto OVER;
L
Liu Jicong 已提交
312
      } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) {
313 314
        tqError("tmq poll: subkey %s, no offset committed for consumer %" PRId64
                " in vg %d, subkey %s, reset none failed",
L
Liu Jicong 已提交
315
                pHandle->subKey, consumerId, TD_VID(pTq->pVnode), pReq->subKey);
L
Liu Jicong 已提交
316
        terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
L
Liu Jicong 已提交
317 318
        code = -1;
        goto OVER;
L
Liu Jicong 已提交
319 320 321 322 323
      }
    }
  }

  // 3.query
L
Liu Jicong 已提交
324
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
325 326 327
    /*if (fetchOffsetNew.type == TMQ_OFFSET__LOG) {*/
    /*fetchOffsetNew.version++;*/
    /*}*/
L
Liu Jicong 已提交
328
    if (tqScan(pTq, pHandle, &dataRsp, &fetchOffsetNew) < 0) {
L
Liu Jicong 已提交
329 330 331 332 333
      ASSERT(0);
      code = -1;
      goto OVER;
    }
    if (dataRsp.blockNum == 0) {
L
Liu Jicong 已提交
334
      // TODO add to async task pool
L
Liu Jicong 已提交
335
      /*dataRsp.rspOffset.version--;*/
L
Liu Jicong 已提交
336 337 338 339 340 341 342
    }
    if (tqSendDataRsp(pTq, pMsg, pReq, &dataRsp) < 0) {
      code = -1;
    }
    goto OVER;
  }

L
Liu Jicong 已提交
343
  if (pHandle->execHandle.subType != TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
344 345 346
    int64_t     fetchVer = fetchOffsetNew.version + 1;
    SWalCkHead* pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
L
Liu Jicong 已提交
347 348
      code = -1;
      goto OVER;
L
Liu Jicong 已提交
349 350 351 352 353 354 355
    }

    walSetReaderCapacity(pHandle->pWalReader, 2048);

    while (1) {
      consumerEpoch = atomic_load_32(&pHandle->epoch);
      if (consumerEpoch > reqEpoch) {
356
        tqWarn("tmq poll: consumer %ld (epoch %d), subkey %s, vg %d offset %" PRId64
S
Shengliang Guan 已提交
357
               ", found new consumer epoch %d, discard req epoch %d",
358
               consumerId, pReq->epoch, pHandle->subKey, TD_VID(pTq->pVnode), fetchVer, consumerEpoch, reqEpoch);
L
Liu Jicong 已提交
359 360 361
        break;
      }

L
Liu Jicong 已提交
362
      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead) < 0) {
L
Liu Jicong 已提交
363 364
        // TODO add push mgr

L
Liu Jicong 已提交
365 366
        tqOffsetResetToLog(&dataRsp.rspOffset, fetchVer);
        ASSERT(dataRsp.rspOffset.version >= dataRsp.reqOffset.version);
L
Liu Jicong 已提交
367 368 369 370 371 372
        if (tqSendDataRsp(pTq, pMsg, pReq, &dataRsp) < 0) {
          code = -1;
        }
        goto OVER;
      }

L
Liu Jicong 已提交
373
      SWalCont* pHead = &pCkHead->head;
L
Liu Jicong 已提交
374

S
Shengliang Guan 已提交
375 376
      tqDebug("tmq poll: consumer:%" PRId64 ", (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d", consumerId,
              pReq->epoch, TD_VID(pTq->pVnode), fetchVer, pHead->msgType);
L
Liu Jicong 已提交
377 378 379 380 381

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

        if (tqLogScanExec(pTq, &pHandle->execHandle, pCont, &dataRsp, workerId) < 0) {
L
Liu Jicong 已提交
382
          /*ASSERT(0);*/
L
Liu Jicong 已提交
383 384 385 386 387
        }
        // TODO batch optimization:
        // TODO continue scan until meeting batch requirement
        if (dataRsp.blockNum > 0 /* threshold */) {
          tqOffsetResetToLog(&dataRsp.rspOffset, fetchVer);
L
Liu Jicong 已提交
388
          ASSERT(dataRsp.rspOffset.version >= dataRsp.reqOffset.version);
L
Liu Jicong 已提交
389 390 391 392

          if (tqSendDataRsp(pTq, pMsg, pReq, &dataRsp) < 0) {
            code = -1;
          }
L
Liu Jicong 已提交
393
          goto OVER;
L
Liu Jicong 已提交
394 395 396 397 398 399 400
        } else {
          fetchVer++;
        }

      } else {
        ASSERT(pHandle->fetchMeta);
        ASSERT(IS_META_MSG(pHead->msgType));
L
Liu Jicong 已提交
401
        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%d", pHead->version, pHead->msgType);
L
Liu Jicong 已提交
402
        SMqMetaRsp metaRsp = {0};
403 404 405 406 407
        /*metaRsp.reqOffset = pReq->reqOffset.version;*/
        /*metaRsp.rspOffset = fetchVer;*/
        /*metaRsp.rspOffsetNew.version = fetchVer;*/
        tqOffsetResetToLog(&metaRsp.reqOffsetNew, pReq->reqOffset.version);
        tqOffsetResetToLog(&metaRsp.rspOffsetNew, fetchVer);
L
Liu Jicong 已提交
408 409 410 411 412 413 414 415 416 417 418 419
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
        if (tqSendMetaPollRsp(pTq, pMsg, pReq, &metaRsp) < 0) {
          code = -1;
          goto OVER;
        }
        code = 0;
        goto OVER;
      }
    }

L
Liu Jicong 已提交
420
    taosMemoryFree(pCkHead);
L
Liu Jicong 已提交
421
#if 0
L
Liu Jicong 已提交
422
  } else if (fetchOffsetNew.type == TMQ_OFFSET__SNAPSHOT_DATA) {
S
Shengliang Guan 已提交
423
    tqInfo("retrieve using snapshot actual offset: uid %" PRId64 " ts %" PRId64, fetchOffsetNew.uid, fetchOffsetNew.ts);
L
Liu Jicong 已提交
424
    if (tqScanSnapshot(pTq, &pHandle->execHandle, &dataRsp, fetchOffsetNew, workerId) < 0) {
L
Liu Jicong 已提交
425 426 427 428
      ASSERT(0);
    }

    // 4. send rsp
L
Liu Jicong 已提交
429 430
    if (tqSendDataRsp(pTq, pMsg, pReq, &dataRsp) < 0) {
      code = -1;
L
Liu Jicong 已提交
431
    }
L
Liu Jicong 已提交
432
#endif
L
Liu Jicong 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  } else if (fetchOffsetNew.type == TMQ_OFFSET__SNAPSHOT_META) {
    ASSERT(0);
  }

OVER:
  // TODO wrap in destroy func
  taosArrayDestroy(dataRsp.blockDataLen);
  taosArrayDestroyP(dataRsp.blockData, (FDelete)taosMemoryFree);

  if (dataRsp.withSchema) {
    taosArrayDestroyP(dataRsp.blockSchema, (FDelete)tDeleteSSchemaWrapper);
  }

  if (dataRsp.withTbName) {
    taosArrayDestroyP(dataRsp.blockTbName, (FDelete)taosMemoryFree);
  }

  return code;
}

L
Liu Jicong 已提交
453 454
int32_t tqProcessVgDeleteReq(STQ* pTq, char* msg, int32_t msgLen) {
  SMqVDeleteReq* pReq = (SMqVDeleteReq*)msg;
L
Liu Jicong 已提交
455

L
Liu Jicong 已提交
456
  int32_t code = taosHashRemove(pTq->handles, pReq->subKey, strlen(pReq->subKey));
L
Liu Jicong 已提交
457
  ASSERT(code == 0);
458

L
Liu Jicong 已提交
459 460
  tqOffsetDelete(pTq->pOffsetStore, pReq->subKey);

L
Liu Jicong 已提交
461
  if (tqMetaDeleteHandle(pTq, pReq->subKey) < 0) {
462 463
    ASSERT(0);
  }
L
Liu Jicong 已提交
464
  return 0;
L
Liu Jicong 已提交
465 466
}

L
Liu Jicong 已提交
467
int32_t tqProcessVgChangeReq(STQ* pTq, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
468
  SMqRebVgReq req = {0};
L
Liu Jicong 已提交
469 470
  tDecodeSMqRebVgReq(msg, &req);
  // todo lock
L
Liu Jicong 已提交
471 472
  STqHandle* pHandle = taosHashGet(pTq->handles, req.subKey, strlen(req.subKey));
  if (pHandle == NULL) {
L
Liu Jicong 已提交
473 474
    ASSERT(req.oldConsumerId == -1);
    ASSERT(req.newConsumerId != -1);
L
Liu Jicong 已提交
475 476
    STqHandle tqHandle = {0};
    pHandle = &tqHandle;
L
Liu Jicong 已提交
477 478
    /*taosInitRWLatch(&pExec->lock);*/

L
Liu Jicong 已提交
479 480 481
    memcpy(pHandle->subKey, req.subKey, TSDB_SUBSCRIBE_KEY_LEN);
    pHandle->consumerId = req.newConsumerId;
    pHandle->epoch = -1;
L
Liu Jicong 已提交
482

L
Liu Jicong 已提交
483
    pHandle->execHandle.subType = req.subType;
L
Liu Jicong 已提交
484
    pHandle->fetchMeta = req.withMeta;
L
Liu Jicong 已提交
485

L
Liu Jicong 已提交
486
    pHandle->pWalReader = walOpenReader(pTq->pVnode->pWal, NULL);
L
Liu Jicong 已提交
487 488

    // TODO version should be assigned in preprocess
489
    int64_t ver = walGetCommittedVer(pTq->pVnode->pWal);
L
Liu Jicong 已提交
490
    if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
L
Liu Jicong 已提交
491
      pHandle->execHandle.execCol.qmsg = req.qmsg;
L
Liu Jicong 已提交
492
      pHandle->snapshotVer = ver;
L
Liu Jicong 已提交
493
      req.qmsg = NULL;
494
      for (int32_t i = 0; i < 5; i++) {
L
Liu Jicong 已提交
495 496
        SReadHandle handle = {
            .meta = pTq->pVnode->pMeta,
L
Liu Jicong 已提交
497
            .vnode = pTq->pVnode,
498
            .initTableReader = true,
L
Liu Jicong 已提交
499
            .initTqReader = true,
500
            .version = ver,
L
Liu Jicong 已提交
501
        };
L
Liu Jicong 已提交
502
        pHandle->execHandle.execCol.task[i] = qCreateQueueExecTaskInfo(pHandle->execHandle.execCol.qmsg, &handle);
L
Liu Jicong 已提交
503
        ASSERT(pHandle->execHandle.execCol.task[i]);
L
Liu Jicong 已提交
504 505 506 507 508
        void* scanner = NULL;
        qExtractStreamScanner(pHandle->execHandle.execCol.task[i], &scanner);
        ASSERT(scanner);
        pHandle->execHandle.pExecReader[i] = qExtractReaderFromStreamScanner(scanner);
        ASSERT(pHandle->execHandle.pExecReader[i]);
509
      }
L
Liu Jicong 已提交
510
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__DB) {
L
Liu Jicong 已提交
511 512 513
      for (int32_t i = 0; i < 5; i++) {
        pHandle->execHandle.pExecReader[i] = tqOpenReader(pTq->pVnode);
      }
L
Liu Jicong 已提交
514
      pHandle->execHandle.execDb.pFilterOutTbUid =
L
Liu Jicong 已提交
515 516
          taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
    } else if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__TABLE) {
L
Liu Jicong 已提交
517
      pHandle->execHandle.execTb.suid = req.suid;
L
Liu Jicong 已提交
518
      SArray* tbUidList = taosArrayInit(0, sizeof(int64_t));
H
Hongze Cheng 已提交
519
      vnodeGetCtbIdList(pTq->pVnode, req.suid, tbUidList);
S
Shengliang Guan 已提交
520
      tqDebug("vgId:%d, tq try get suid:%" PRId64, pTq->pVnode->config.vgId, req.suid);
L
Liu Jicong 已提交
521 522
      for (int32_t i = 0; i < taosArrayGetSize(tbUidList); i++) {
        int64_t tbUid = *(int64_t*)taosArrayGet(tbUidList, i);
S
Shengliang Guan 已提交
523
        tqDebug("vgId:%d, idx %d, uid:%" PRId64, TD_VID(pTq->pVnode), i, tbUid);
L
Liu Jicong 已提交
524
      }
L
Liu Jicong 已提交
525
      for (int32_t i = 0; i < 5; i++) {
L
Liu Jicong 已提交
526
        pHandle->execHandle.pExecReader[i] = tqOpenReader(pTq->pVnode);
L
Liu Jicong 已提交
527
        tqReaderSetTbUidList(pHandle->execHandle.pExecReader[i], tbUidList);
L
Liu Jicong 已提交
528
      }
L
Liu Jicong 已提交
529
      taosArrayDestroy(tbUidList);
L
Liu Jicong 已提交
530
    }
L
Liu Jicong 已提交
531
    taosHashPut(pTq->handles, req.subKey, strlen(req.subKey), pHandle, sizeof(STqHandle));
L
Liu Jicong 已提交
532 533 534
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
      // TODO
    }
L
Liu Jicong 已提交
535
  } else {
L
Liu Jicong 已提交
536
    /*ASSERT(pExec->consumerId == req.oldConsumerId);*/
L
Liu Jicong 已提交
537
    // TODO handle qmsg and exec modification
L
Liu Jicong 已提交
538 539 540
    atomic_store_32(&pHandle->epoch, -1);
    atomic_store_64(&pHandle->consumerId, req.newConsumerId);
    atomic_add_fetch_32(&pHandle->epoch, 1);
L
Liu Jicong 已提交
541 542 543
    if (tqMetaSaveHandle(pTq, req.subKey, pHandle) < 0) {
      // TODO
    }
L
Liu Jicong 已提交
544
  }
L
Liu Jicong 已提交
545

L
Liu Jicong 已提交
546
  return 0;
L
Liu Jicong 已提交
547
}
548

L
Liu Jicong 已提交
549
int32_t tqProcessTaskDeployReq(STQ* pTq, char* msg, int32_t msgLen) {
L
Liu Jicong 已提交
550 551 552 553 554 555 556 557 558 559
  SStreamTask* pTask = taosMemoryCalloc(1, sizeof(SStreamTask));
  if (pTask == NULL) {
    return -1;
  }
  SDecoder decoder;
  tDecoderInit(&decoder, (uint8_t*)msg, msgLen);
  if (tDecodeSStreamTask(&decoder, pTask) < 0) {
    ASSERT(0);
  }
  tDecoderClear(&decoder);
560
  ASSERT(pTask->isDataScan == 0 || pTask->isDataScan == 1);
L
Liu Jicong 已提交
561 562 563
  if (pTask->isDataScan == 0 && pTask->sinkType == TASK_SINK__NONE) {
    ASSERT(taosArrayGetSize(pTask->childEpInfo) != 0);
  }
L
Liu Jicong 已提交
564

L
Liu Jicong 已提交
565
  pTask->execStatus = TASK_EXEC_STATUS__IDLE;
L
Liu Jicong 已提交
566 567 568

  pTask->inputQueue = streamQueueOpen();
  pTask->outputQueue = streamQueueOpen();
L
Liu Jicong 已提交
569 570 571
  pTask->inputStatus = TASK_INPUT_STATUS__NORMAL;
  pTask->outputStatus = TASK_OUTPUT_STATUS__NORMAL;

L
Liu Jicong 已提交
572
  if (pTask->inputQueue == NULL || pTask->outputQueue == NULL) goto FAIL;
L
Liu Jicong 已提交
573

574 575
  pTask->pMsgCb = &pTq->pVnode->msgCb;

L
Liu Jicong 已提交
576
  // exec
L
Liu Jicong 已提交
577 578
  if (pTask->execType != TASK_EXEC__NONE) {
    // expand runners
L
Liu Jicong 已提交
579
    if (pTask->isDataScan) {
580 581 582
      SReadHandle handle = {
          .meta = pTq->pVnode->pMeta,
          .vnode = pTq->pVnode,
L
Liu Jicong 已提交
583
          .initTqReader = 1,
L
Liu Jicong 已提交
584 585 586 587 588
      };
      pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, &handle);
    } else {
      pTask->exec.executor = qCreateStreamExecTaskInfo(pTask->exec.qmsg, NULL);
    }
L
Liu Jicong 已提交
589
    ASSERT(pTask->exec.executor);
L
Liu Jicong 已提交
590
  }
L
Liu Jicong 已提交
591 592

  // sink
L
Liu Jicong 已提交
593
  /*pTask->ahandle = pTq->pVnode;*/
L
Liu Jicong 已提交
594
  if (pTask->sinkType == TASK_SINK__SMA) {
L
Liu Jicong 已提交
595
    pTask->smaSink.vnode = pTq->pVnode;
L
Liu Jicong 已提交
596
    pTask->smaSink.smaSink = smaHandleRes;
L
Liu Jicong 已提交
597
  } else if (pTask->sinkType == TASK_SINK__TABLE) {
L
Liu Jicong 已提交
598 599 600
    pTask->tbSink.vnode = pTq->pVnode;
    pTask->tbSink.tbSinkFunc = tqTableSink;

L
Liu Jicong 已提交
601 602
    ASSERT(pTask->tbSink.pSchemaWrapper);
    ASSERT(pTask->tbSink.pSchemaWrapper->pSchema);
L
Liu Jicong 已提交
603

L
Liu Jicong 已提交
604 605 606
    pTask->tbSink.pTSchema =
        tdGetSTSChemaFromSSChema(&pTask->tbSink.pSchemaWrapper->pSchema, pTask->tbSink.pSchemaWrapper->nCols);
    ASSERT(pTask->tbSink.pTSchema);
L
Liu Jicong 已提交
607
  }
608 609 610

  streamSetupTrigger(pTask);

S
Shengliang Guan 已提交
611
  tqInfo("deploy stream task id %d child id %d on vgId:%d", pTask->taskId, pTask->selfChildId, TD_VID(pTq->pVnode));
L
Liu Jicong 已提交
612

613
  taosHashPut(pTq->pStreamTasks, &pTask->taskId, sizeof(int32_t), &pTask, sizeof(void*));
L
Liu Jicong 已提交
614

L
Liu Jicong 已提交
615 616
  return 0;
FAIL:
L
Liu Jicong 已提交
617 618
  if (pTask->inputQueue) streamQueueClose(pTask->inputQueue);
  if (pTask->outputQueue) streamQueueClose(pTask->outputQueue);
L
Liu Jicong 已提交
619
  if (pTask) taosMemoryFree(pTask);
L
Liu Jicong 已提交
620 621
  return -1;
}
L
Liu Jicong 已提交
622

L
Liu Jicong 已提交
623
int32_t tqProcessStreamTrigger(STQ* pTq, SSubmitReq* pReq) {
L
Liu Jicong 已提交
624 625 626
  void*              pIter = NULL;
  bool               failed = false;
  SStreamDataSubmit* pSubmit = NULL;
L
Liu Jicong 已提交
627

L
Liu Jicong 已提交
628
  pSubmit = streamDataSubmitNew(pReq);
L
Liu Jicong 已提交
629 630 631 632 633 634 635
  if (pSubmit == NULL) {
    failed = true;
  }

  while (1) {
    pIter = taosHashIterate(pTq->pStreamTasks, pIter);
    if (pIter == NULL) break;
636
    SStreamTask* pTask = *(SStreamTask**)pIter;
L
Liu Jicong 已提交
637 638 639
    if (atomic_load_8(&pTask->taskStatus) == TASK_STATUS__DROPPING) {
      continue;
    }
640
    if (!pTask->isDataScan) continue;
L
Liu Jicong 已提交
641

L
Liu Jicong 已提交
642 643
    if (!failed) {
      if (streamTaskInput(pTask, (SStreamQueueItem*)pSubmit) < 0) {
L
Liu Jicong 已提交
644 645 646
        continue;
      }

L
Liu Jicong 已提交
647
      if (streamLaunchByWrite(pTask, TD_VID(pTq->pVnode)) < 0) {
L
Liu Jicong 已提交
648 649
        continue;
      }
L
Liu Jicong 已提交
650
    } else {
L
Liu Jicong 已提交
651
      streamTaskInputFail(pTask);
L
Liu Jicong 已提交
652 653 654
    }
  }

L
Liu Jicong 已提交
655
  if (pSubmit) {
L
Liu Jicong 已提交
656
    streamDataSubmitRefDec(pSubmit);
L
Liu Jicong 已提交
657
    taosFreeQitem(pSubmit);
L
Liu Jicong 已提交
658
  }
L
Liu Jicong 已提交
659 660

  return failed ? -1 : 0;
L
Liu Jicong 已提交
661 662
}

L
Liu Jicong 已提交
663
int32_t tqProcessTaskRunReq(STQ* pTq, SRpcMsg* pMsg) {
L
Liu Jicong 已提交
664
  //
L
Liu Jicong 已提交
665 666
  SStreamTaskRunReq* pReq = pMsg->pCont;
  int32_t            taskId = pReq->taskId;
667
  SStreamTask*       pTask = *(SStreamTask**)taosHashGet(pTq->pStreamTasks, &taskId, sizeof(int32_t));
L
Liu Jicong 已提交
668
  if (atomic_load_8(&pTask->taskStatus) != TASK_STATUS__NORMAL) {
L
Liu Jicong 已提交
669 670
    return 0;
  }
L
Liu Jicong 已提交
671
  streamProcessRunReq(pTask);
L
Liu Jicong 已提交
672 673 674 675
  return 0;
}

int32_t tqProcessTaskDispatchReq(STQ* pTq, SRpcMsg* pMsg) {
676 677 678 679 680 681 682 683
  char*              msgStr = pMsg->pCont;
  char*              msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t            msgLen = pMsg->contLen - sizeof(SMsgHead);
  SStreamDispatchReq req;
  SDecoder           decoder;
  tDecoderInit(&decoder, msgBody, msgLen);
  tDecodeStreamDispatchReq(&decoder, &req);
  int32_t      taskId = req.taskId;
684
  SStreamTask* pTask = *(SStreamTask**)taosHashGet(pTq->pStreamTasks, &taskId, sizeof(int32_t));
L
Liu Jicong 已提交
685
  if (atomic_load_8(&pTask->taskStatus) != TASK_STATUS__NORMAL) {
L
Liu Jicong 已提交
686 687 688 689 690
    return 0;
  }
  SRpcMsg rsp = {
      .info = pMsg->info,
      .code = 0,
691
  };
L
Liu Jicong 已提交
692
  streamProcessDispatchReq(pTask, &req, &rsp);
L
Liu Jicong 已提交
693 694 695 696 697 698
  return 0;
}

int32_t tqProcessTaskRecoverReq(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRecoverReq* pReq = pMsg->pCont;
  int32_t                taskId = pReq->taskId;
699
  SStreamTask*           pTask = *(SStreamTask**)taosHashGet(pTq->pStreamTasks, &taskId, sizeof(int32_t));
L
Liu Jicong 已提交
700
  if (atomic_load_8(&pTask->taskStatus) != TASK_STATUS__NORMAL) {
L
Liu Jicong 已提交
701 702
    return 0;
  }
L
Liu Jicong 已提交
703
  streamProcessRecoverReq(pTask, pReq, pMsg);
L
Liu Jicong 已提交
704 705 706 707
  return 0;
}

int32_t tqProcessTaskDispatchRsp(STQ* pTq, SRpcMsg* pMsg) {
L
Liu Jicong 已提交
708
  SStreamDispatchRsp* pRsp = POINTER_SHIFT(pMsg->pCont, sizeof(SMsgHead));
L
Liu Jicong 已提交
709
  int32_t             taskId = pRsp->taskId;
710
  SStreamTask*        pTask = *(SStreamTask**)taosHashGet(pTq->pStreamTasks, &taskId, sizeof(int32_t));
L
Liu Jicong 已提交
711
  if (atomic_load_8(&pTask->taskStatus) != TASK_STATUS__NORMAL) {
L
Liu Jicong 已提交
712 713
    return 0;
  }
L
Liu Jicong 已提交
714
  streamProcessDispatchRsp(pTask, pRsp);
L
Liu Jicong 已提交
715 716 717 718 719 720
  return 0;
}

int32_t tqProcessTaskRecoverRsp(STQ* pTq, SRpcMsg* pMsg) {
  SStreamTaskRecoverRsp* pRsp = pMsg->pCont;
  int32_t                taskId = pRsp->taskId;
721
  SStreamTask*           pTask = *(SStreamTask**)taosHashGet(pTq->pStreamTasks, &taskId, sizeof(int32_t));
L
Liu Jicong 已提交
722
  if (atomic_load_8(&pTask->taskStatus) != TASK_STATUS__NORMAL) {
L
Liu Jicong 已提交
723 724
    return 0;
  }
L
Liu Jicong 已提交
725
  streamProcessRecoverRsp(pTask, pRsp);
L
Liu Jicong 已提交
726 727
  return 0;
}
L
Liu Jicong 已提交
728 729 730

int32_t tqProcessTaskDropReq(STQ* pTq, char* msg, int32_t msgLen) {
  SVDropStreamTaskReq* pReq = (SVDropStreamTaskReq*)msg;
L
Liu Jicong 已提交
731 732 733 734 735 736 737 738 739 740 741

  SStreamTask* pTask = *(SStreamTask**)taosHashGet(pTq->pStreamTasks, &pReq->taskId, sizeof(int32_t));
  atomic_store_8(&pTask->taskStatus, TASK_STATUS__DROPPING);
  // todo
  // clear queue
  // push drop req into queue
  // launch exec to free memory
  // remove from hash
  return 0;

#if 0
L
Liu Jicong 已提交
742
  int32_t              code = taosHashRemove(pTq->pStreamTasks, &pReq->taskId, sizeof(int32_t));
L
Liu Jicong 已提交
743
  // set status dropping
L
Liu Jicong 已提交
744
  ASSERT(code == 0);
L
Liu Jicong 已提交
745 746 747 748
  if (code == 0) {
    // sendrsp
  }
  return code;
L
Liu Jicong 已提交
749
#endif
L
Liu Jicong 已提交
750
}
L
Liu Jicong 已提交
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776

int32_t tqProcessTaskRetrieveReq(STQ* pTq, SRpcMsg* pMsg) {
  char*              msgStr = pMsg->pCont;
  char*              msgBody = POINTER_SHIFT(msgStr, sizeof(SMsgHead));
  int32_t            msgLen = pMsg->contLen - sizeof(SMsgHead);
  SStreamRetrieveReq req;
  SDecoder           decoder;
  tDecoderInit(&decoder, msgBody, msgLen);
  tDecodeStreamRetrieveReq(&decoder, &req);
  int32_t      taskId = req.dstTaskId;
  SStreamTask* pTask = *(SStreamTask**)taosHashGet(pTq->pStreamTasks, &taskId, sizeof(int32_t));
  if (atomic_load_8(&pTask->taskStatus) != TASK_STATUS__NORMAL) {
    return 0;
  }
  SRpcMsg rsp = {
      .info = pMsg->info,
      .code = 0,
  };
  streamProcessRetrieveReq(pTask, &req, &rsp);
  return 0;
}

int32_t tqProcessTaskRetrieveRsp(STQ* pTq, SRpcMsg* pMsg) {
  //
  return 0;
}