tqUtil.c 15.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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/>.
 */

#include "tq.h"

18 19
#define IS_OFFSET_RESET_TYPE(_t)  ((_t) < 0)

dengyihao's avatar
dengyihao 已提交
20 21
static int32_t tqSendMetaPollRsp(STqHandle* pHandle, const SRpcMsg* pMsg, const SMqPollReq* pReq,
                                 const SMqMetaRsp* pRsp, int32_t vgId);
22

23
int32_t tqAddInputBlockNLaunchTask(SStreamTask* pTask, SStreamQueueItem* pQueueItem) {
24
  int32_t code = tAppendDataToInputQueue(pTask, pQueueItem);
25
  if (code < 0) {
H
Haojun Liao 已提交
26
    tqError("s-task:%s failed to put into queue, too many", pTask->id.idStr);
27 28 29 30 31 32 33 34 35 36 37
    return -1;
  }

  if (streamSchedExec(pTask) < 0) {
    tqError("stream task:%d failed to be launched, code:%s", pTask->id.taskId, tstrerror(terrno));
    return -1;
  }

  return TSDB_CODE_SUCCESS;
}

38
int32_t tqInitDataRsp(SMqDataRsp* pRsp, const SMqPollReq* pReq) {
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
  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 = 0;
  pRsp->withSchema = false;
  return 0;
}

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) {
H
Haojun Liao 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    if (pRsp->blockData != NULL) {
      pRsp->blockData = taosArrayDestroy(pRsp->blockData);
    }

    if (pRsp->blockDataLen != NULL) {
      pRsp->blockDataLen = taosArrayDestroy(pRsp->blockDataLen);
    }

    if (pRsp->blockTbName != NULL) {
      pRsp->blockTbName = taosArrayDestroy(pRsp->blockTbName);
    }

    if (pRsp->blockSchema != NULL) {
      pRsp->blockSchema = taosArrayDestroy(pRsp->blockSchema);
    }
79 80 81 82 83 84
    return -1;
  }

  return 0;
}

85
static int32_t extractResetOffsetVal(STqOffsetVal* pOffsetVal, STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest, SRpcMsg* pMsg, bool* pBlockReturned) {
86 87 88 89 90
  uint64_t     consumerId = pRequest->consumerId;
  STqOffsetVal reqOffset = pRequest->reqOffset;
  STqOffset*   pOffset = tqOffsetRead(pTq->pOffsetStore, pRequest->subKey);
  int32_t      vgId = TD_VID(pTq->pVnode);

91
  *pBlockReturned = false;
92 93 94 95
  // 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;

96 97
    char formatBuf[TSDB_OFFSET_LEN];
    tFormatOffset(formatBuf, TSDB_OFFSET_LEN, pOffsetVal);
dengyihao's avatar
dengyihao 已提交
98 99
    tqDebug("tmq poll: consumer:0x%" PRIx64
            ", subkey %s, vgId:%d, existed offset found, offset reset to %s and continue. reqId:0x%" PRIx64,
100 101 102 103
            consumerId, pHandle->subKey, vgId, formatBuf, pRequest->reqId);
    return 0;
  } else {
    // no poll occurs in this vnode for this topic, let's seek to the right offset value.
104
    if (reqOffset.type == TMQ_OFFSET__RESET_EARLIEST) {
105 106 107 108 109 110 111 112 113 114
      if (pRequest->useSnapshot) {
        tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey:%s, vgId:%d, (earliest) set offset to be snapshot",
                consumerId, pHandle->subKey, vgId);

        if (pHandle->fetchMeta) {
          tqOffsetResetToMeta(pOffsetVal, 0);
        } else {
          tqOffsetResetToData(pOffsetVal, 0, 0);
        }
      } else {
115
        walRefFirstVer(pTq->pVnode->pWal, pHandle->pRef);
116 117 118
        tqOffsetResetToLog(pOffsetVal, pHandle->pRef->refVer - 1);
      }
    } else if (reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
119
      walRefLastVer(pTq->pVnode->pWal, pHandle->pRef);
120 121
      if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
        SMqDataRsp dataRsp = {0};
122
        tqInitDataRsp(&dataRsp, pRequest);
123 124 125 126

        tqOffsetResetToLog(&dataRsp.rspOffset, pHandle->pRef->refVer);
        tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, (latest) offset reset to %" PRId64, consumerId,
                pHandle->subKey, vgId, dataRsp.rspOffset.version);
127 128
        int32_t code = tqSendDataRsp(pHandle, pMsg, pRequest, &dataRsp, TMQ_MSG_TYPE__POLL_RSP, vgId);
        tDeleteMqDataRsp(&dataRsp);
129 130 131 132 133 134 135

        *pBlockReturned = true;
        return code;
      } else {
        STaosxRsp taosxRsp = {0};
        tqInitTaosxRsp(&taosxRsp, pRequest);
        tqOffsetResetToLog(&taosxRsp.rspOffset, pHandle->pRef->refVer);
136
        int32_t code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP, vgId);
137 138 139 140
        tDeleteSTaosxRsp(&taosxRsp);

        *pBlockReturned = true;
        return code;
wmmhello's avatar
wmmhello 已提交
141
      }
142
    } else if (reqOffset.type == TMQ_OFFSET__RESET_NONE) {
dengyihao's avatar
dengyihao 已提交
143 144
      tqError("tmq poll: subkey:%s, no offset committed for consumer:0x%" PRIx64
              " in vg %d, subkey %s, reset none failed",
145 146 147 148 149 150 151 152 153 154 155 156 157
              pHandle->subKey, consumerId, vgId, pRequest->subKey);
      terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
      return -1;
    }
  }

  return 0;
}

static int32_t extractDataAndRspForNormalSubscribe(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest,
                                                   SRpcMsg* pMsg, STqOffsetVal* pOffset) {
  uint64_t consumerId = pRequest->consumerId;
  int32_t  vgId = TD_VID(pTq->pVnode);
158
  int      code = 0;
159 160

  SMqDataRsp dataRsp = {0};
H
Haojun Liao 已提交
161
  tqInitDataRsp(&dataRsp, pRequest);
162 163

  qSetTaskId(pHandle->execHandle.task, consumerId, pRequest->reqId);
164
  code = tqScanData(pTq, pHandle, &dataRsp, pOffset);
H
Haojun Liao 已提交
165
  if (code != 0 && terrno != TSDB_CODE_WAL_LOG_NOT_EXIST) {
166 167 168
    goto end;
  }

169
  //   till now, all data has been transferred to consumer, new data needs to push client once arrived.
170
  if (terrno == TSDB_CODE_WAL_LOG_NOT_EXIST && dataRsp.blockNum == 0) {
171 172
    // lock
    taosWLockLatch(&pTq->lock);
Y
yihaoDeng 已提交
173
    int64_t ver = walGetCommittedVer(pTq->pVnode->pWal);
H
Haojun Liao 已提交
174 175
    if (pOffset->version >= ver ||
        dataRsp.rspOffset.version >= ver) {  // check if there are data again to avoid lost data
176 177 178
      code = tqRegisterPushHandle(pTq, pHandle, pMsg);
      taosWUnLockLatch(&pTq->lock);
      goto end;
H
Haojun Liao 已提交
179
    } else {
180 181
      taosWUnLockLatch(&pTq->lock);
    }
182
  }
183

H
Haojun Liao 已提交
184
  code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&dataRsp, TMQ_MSG_TYPE__POLL_RSP, vgId);
185

dengyihao's avatar
dengyihao 已提交
186
end : {
187 188
  char buf[TSDB_OFFSET_LEN] = {0};
  tFormatOffset(buf, TSDB_OFFSET_LEN, &dataRsp.rspOffset);
dengyihao's avatar
dengyihao 已提交
189 190 191 192
  tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, rsp block:%d, rsp offset type:%s, reqId:0x%" PRIx64
          " code:%d",
          consumerId, pHandle->subKey, vgId, dataRsp.blockNum, buf, pRequest->reqId, code);
  tDeleteMqDataRsp(&dataRsp);
193
  return code;
H
Haojun Liao 已提交
194
  }
195 196
}

dengyihao's avatar
dengyihao 已提交
197 198 199 200 201 202 203
static int32_t extractDataAndRspForDbStbSubscribe(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest,
                                                  SRpcMsg* pMsg, STqOffsetVal* offset) {
  int         code = 0;
  int32_t     vgId = TD_VID(pTq->pVnode);
  SWalCkHead* pCkHead = NULL;
  SMqMetaRsp  metaRsp = {0};
  STaosxRsp   taosxRsp = {0};
204 205 206 207
  tqInitTaosxRsp(&taosxRsp, pRequest);

  if (offset->type != TMQ_OFFSET__LOG) {
    if (tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, offset) < 0) {
208 209
      code = -1;
      goto end;
210 211 212
    }

    if (metaRsp.metaRspLen > 0) {
213
      code = tqSendMetaPollRsp(pHandle, pMsg, pRequest, &metaRsp, vgId);
214 215 216 217
      tqDebug("tmq poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send meta offset type:%d,uid:%" PRId64
              ",ts:%" PRId64,
              pRequest->consumerId, pHandle->subKey, vgId, metaRsp.rspOffset.type, metaRsp.rspOffset.uid,
              metaRsp.rspOffset.ts);
218
      taosMemoryFree(metaRsp.metaRsp);
219
      goto end;
220 221 222
    }

    tqDebug("taosx poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send data blockNum:%d, offset type:%d,uid:%" PRId64
223 224 225
            ",ts:%" PRId64,
            pRequest->consumerId, pHandle->subKey, vgId, taosxRsp.blockNum, taosxRsp.rspOffset.type,
            taosxRsp.rspOffset.uid, taosxRsp.rspOffset.ts);
226
    if (taosxRsp.blockNum > 0) {
227
      code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP, vgId);
228
      goto end;
229
    } else {
230 231 232 233 234
      *offset = taosxRsp.rspOffset;
    }
  }

  if (offset->type == TMQ_OFFSET__LOG) {
235
    walReaderVerifyOffset(pHandle->pWalReader, offset);
236 237 238 239
    int64_t fetchVer = offset->version + 1;
    pCkHead = taosMemoryMalloc(sizeof(SWalCkHead) + 2048);
    if (pCkHead == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
240 241
      code = -1;
      goto end;
242
    }
243

244 245 246 247 248 249
    walSetReaderCapacity(pHandle->pWalReader, 2048);
    int totalRows = 0;
    while (1) {
      int32_t savedEpoch = atomic_load_32(&pHandle->epoch);
      if (savedEpoch > pRequest->epoch) {
        tqWarn("tmq poll: consumer:0x%" PRIx64 " (epoch %d), subkey:%s vgId:%d offset %" PRId64
250 251
               ", found new consumer epoch %d, discard req epoch %d",
               pRequest->consumerId, pRequest->epoch, pHandle->subKey, vgId, fetchVer, savedEpoch, pRequest->epoch);
252 253 254 255 256
        break;
      }

      if (tqFetchLog(pTq, pHandle, &fetchVer, &pCkHead, pRequest->reqId) < 0) {
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
257
        code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP, vgId);
258
        goto end;
259 260 261
      }

      SWalCont* pHead = &pCkHead->head;
dengyihao's avatar
dengyihao 已提交
262 263
      tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d",
              pRequest->consumerId, pRequest->epoch, vgId, fetchVer, pHead->msgType);
264 265 266

      // process meta
      if (pHead->msgType != TDMT_VND_SUBMIT) {
dengyihao's avatar
dengyihao 已提交
267
        if (totalRows > 0) {
268
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer - 1);
269
          code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP, vgId);
270
          goto end;
271 272 273 274 275 276 277
        }

        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%s", pHead->version, TMSG_INFO(pHead->msgType));
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer);
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
278
        code = tqSendMetaPollRsp(pHandle, pMsg, pRequest, &metaRsp, vgId);
279
        goto end;
280 281 282 283 284 285 286 287 288
      }

      // process data
      SPackedData submit = {
          .msgStr = POINTER_SHIFT(pHead->body, sizeof(SSubmitReq2Msg)),
          .msgLen = pHead->bodyLen - sizeof(SSubmitReq2Msg),
          .ver = pHead->version,
      };

289 290
      code = tqTaosxScanLog(pTq, pHandle, submit, &taosxRsp, &totalRows);
      if (code < 0) {
dengyihao's avatar
dengyihao 已提交
291 292
        tqError("tmq poll: tqTaosxScanLog error %" PRId64 ", in vgId:%d, subkey %s", pRequest->consumerId, vgId,
                pRequest->subKey);
293
        goto end;
294 295 296 297
      }

      if (totalRows >= 4096 || taosxRsp.createTableNum > 0) {
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
298
        code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__TAOSX_RSP, vgId);
299
        goto end;
300 301 302 303 304 305
      } else {
        fetchVer++;
      }
    }
  }

306 307
end:

308 309
  tDeleteSTaosxRsp(&taosxRsp);
  taosMemoryFreeClear(pCkHead);
310
  return code;
311 312 313 314 315 316 317 318 319 320
}

int32_t tqExtractDataForMq(STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest, SRpcMsg* pMsg) {
  int32_t      code = -1;
  STqOffsetVal offset = {0};
  STqOffsetVal reqOffset = pRequest->reqOffset;

  // 1. reset the offset if needed
  if (IS_OFFSET_RESET_TYPE(reqOffset.type)) {
    // handle the reset offset cases, according to the consumer's choice.
321 322
    bool blockReturned = false;
    code = extractResetOffsetVal(&offset, pTq, pHandle, pRequest, pMsg, &blockReturned);
323 324 325 326
    if (code != 0) {
      return code;
    }

327 328 329 330
    // empty block returned, quit
    if (blockReturned) {
      return 0;
    }
dengyihao's avatar
dengyihao 已提交
331
  } else {  // use the consumer specified offset
332 333 334 335 336 337 338
    // the offset value can not be monotonious increase??
    offset = reqOffset;
  }

  // this is a normal subscribe requirement
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
    return extractDataAndRspForNormalSubscribe(pTq, pHandle, pRequest, pMsg, &offset);
dengyihao's avatar
dengyihao 已提交
339
  } else {  // todo handle the case where re-balance occurs.
340 341
    // for taosx
    return extractDataAndRspForDbStbSubscribe(pTq, pHandle, pRequest, pMsg, &offset);
342 343 344
  }
}

345 346 347 348 349 350 351 352 353
static void initMqRspHead(SMqRspHead* pMsgHead, int32_t type, int32_t epoch, int64_t consumerId, int64_t sver,
                          int64_t ever) {
  pMsgHead->consumerId = consumerId;
  pMsgHead->epoch = epoch;
  pMsgHead->mqMsgType = type;
  pMsgHead->walsver = sver;
  pMsgHead->walever = ever;
}

dengyihao's avatar
dengyihao 已提交
354 355
int32_t tqSendMetaPollRsp(STqHandle* pHandle, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqMetaRsp* pRsp,
                          int32_t vgId) {
356 357
  int32_t len = 0;
  int32_t code = 0;
358
  tEncodeSize(tEncodeMqMetaRsp, pRsp, len, code);
359 360 361 362 363 364 365 366 367
  if (code < 0) {
    return -1;
  }
  int32_t tlen = sizeof(SMqRspHead) + len;
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    return -1;
  }

368 369 370
  int64_t sver = 0, ever = 0;
  walReaderValidVersionRange(pHandle->execHandle.pTqReader->pWalReader, &sver, &ever);
  initMqRspHead(buf, TMQ_MSG_TYPE__POLL_META_RSP, pReq->epoch, pReq->consumerId, sver, ever);
371 372 373 374 375

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

  SEncoder encoder = {0};
  tEncoderInit(&encoder, abuf, len);
376
  tEncodeMqMetaRsp(&encoder, pRsp);
377 378
  tEncoderClear(&encoder);

dengyihao's avatar
dengyihao 已提交
379
  SRpcMsg resp = {.info = pMsg->info, .pCont = buf, .contLen = tlen, .code = 0};
380

381 382 383
  tmsgSendRsp(&resp);
  tqDebug("vgId:%d, from consumer:0x%" PRIx64 " (epoch %d) send rsp, res msg type %d, offset type:%d", vgId,
          pReq->consumerId, pReq->epoch, pRsp->resMsgType, pRsp->rspOffset.type);
384 385 386

  return 0;
}
387 388

int32_t tqDoSendDataRsp(const SRpcHandleInfo* pRpcHandleInfo, const SMqDataRsp* pRsp, int32_t epoch, int64_t consumerId,
dengyihao's avatar
dengyihao 已提交
389
                        int32_t type, int64_t sver, int64_t ever) {
390 391 392
  int32_t len = 0;
  int32_t code = 0;

393
  if (type == TMQ_MSG_TYPE__POLL_RSP || type == TMQ_MSG_TYPE__WALINFO_RSP) {
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    tEncodeSize(tEncodeMqDataRsp, 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* pHead = (SMqRspHead*)buf;
  initMqRspHead(pHead, type, epoch, consumerId, sver, ever);

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

  SEncoder encoder = {0};
  tEncoderInit(&encoder, abuf, len);

417
  if (type == TMQ_MSG_TYPE__POLL_RSP || type == TMQ_MSG_TYPE__WALINFO_RSP) {
418 419 420 421 422 423
    tEncodeMqDataRsp(&encoder, pRsp);
  } else if (type == TMQ_MSG_TYPE__TAOSX_RSP) {
    tEncodeSTaosxRsp(&encoder, (STaosxRsp*)pRsp);
  }

  tEncoderClear(&encoder);
dengyihao's avatar
dengyihao 已提交
424
  SRpcMsg rsp = {.info = *pRpcHandleInfo, .pCont = buf, .contLen = tlen, .code = 0};
425 426 427

  tmsgSendRsp(&rsp);
  return 0;
Y
yihaoDeng 已提交
428
}