tqUtil.c 14.7 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 24 25
int32_t tqInitDataRsp(SMqDataRsp* pRsp, STqOffsetVal pOffset) {
  pRsp->reqOffset = pOffset;
  pRsp->rspOffset = pOffset;
26 27 28 29 30 31 32 33 34 35 36 37 38

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

39 40 41
static int32_t tqInitTaosxRsp(STaosxRsp* pRsp, STqOffsetVal pOffset) {
  pRsp->reqOffset = pOffset;
  pRsp->rspOffset = pOffset;
42 43 44 45 46 47 48 49 50

  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 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    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);
    }
66 67 68 69 70 71
    return -1;
  }

  return 0;
}

72
static int32_t extractResetOffsetVal(STqOffsetVal* pOffsetVal, STQ* pTq, STqHandle* pHandle, const SMqPollReq* pRequest, SRpcMsg* pMsg, bool* pBlockReturned) {
73 74 75 76
  uint64_t     consumerId = pRequest->consumerId;
  STqOffset*   pOffset = tqOffsetRead(pTq->pOffsetStore, pRequest->subKey);
  int32_t      vgId = TD_VID(pTq->pVnode);

77
  *pBlockReturned = false;
78 79 80 81
  // 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;

wmmhello's avatar
wmmhello 已提交
82
    char formatBuf[TSDB_OFFSET_LEN] = {0};
83
    tFormatOffset(formatBuf, TSDB_OFFSET_LEN, pOffsetVal);
dengyihao's avatar
dengyihao 已提交
84 85
    tqDebug("tmq poll: consumer:0x%" PRIx64
            ", subkey %s, vgId:%d, existed offset found, offset reset to %s and continue. reqId:0x%" PRIx64,
86 87 88 89
            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.
90
    if (pRequest->reqOffset.type == TMQ_OFFSET__RESET_EARLIEST) {
91 92 93 94 95 96 97 98 99 100
      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 {
101
        walRefFirstVer(pTq->pVnode->pWal, pHandle->pRef);
102
        tqOffsetResetToLog(pOffsetVal, pHandle->pRef->refVer);
103
      }
104
    } else if (pRequest->reqOffset.type == TMQ_OFFSET__RESET_LATEST) {
105
      walRefLastVer(pTq->pVnode->pWal, pHandle->pRef);
106
      SMqDataRsp dataRsp = {0};
107
      tqOffsetResetToLog(pOffsetVal, pHandle->pRef->refVer + 1);
108

109
      tqInitDataRsp(&dataRsp, *pOffsetVal);
110 111 112 113 114 115 116
      tqDebug("tmq poll: consumer:0x%" PRIx64 ", subkey %s, vgId:%d, (latest) offset reset to %" PRId64, consumerId,
              pHandle->subKey, vgId, dataRsp.rspOffset.version);
      int32_t code = tqSendDataRsp(pHandle, pMsg, pRequest, &dataRsp, TMQ_MSG_TYPE__POLL_DATA_RSP, vgId);
      tDeleteMqDataRsp(&dataRsp);

      *pBlockReturned = true;
      return code;
117
    } else if (pRequest->reqOffset.type == TMQ_OFFSET__RESET_NONE) {
dengyihao's avatar
dengyihao 已提交
118 119
      tqError("tmq poll: subkey:%s, no offset committed for consumer:0x%" PRIx64
              " in vg %d, subkey %s, reset none failed",
120 121 122 123 124 125 126 127 128
              pHandle->subKey, consumerId, vgId, pRequest->subKey);
      terrno = TSDB_CODE_TQ_NO_COMMITTED_OFFSET;
      return -1;
    }
  }

  return 0;
}

129 130 131 132 133
//static void setRequestVersion(STqOffsetVal* offset, int64_t ver){
//  if(offset->type == TMQ_OFFSET__LOG){
//    offset->version = ver;
//  }
//}
134

135 136 137 138
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);
wmmhello's avatar
wmmhello 已提交
139
  terrno        = 0;
140 141

  SMqDataRsp dataRsp = {0};
142 143
  tqInitDataRsp(&dataRsp, *pOffset);
//  dataRsp.reqOffset.type = pOffset->type; // store origin type for getting offset in tmq_get_vgroup_offset
144 145

  qSetTaskId(pHandle->execHandle.task, consumerId, pRequest->reqId);
146
  int code = tqScanData(pTq, pHandle, &dataRsp, pOffset);
H
Haojun Liao 已提交
147
  if (code != 0 && terrno != TSDB_CODE_WAL_LOG_NOT_EXIST) {
148 149 150
    goto end;
  }

151
  //   till now, all data has been transferred to consumer, new data needs to push client once arrived.
152
  if (terrno == TSDB_CODE_WAL_LOG_NOT_EXIST && dataRsp.blockNum == 0) {
153 154
    // lock
    taosWLockLatch(&pTq->lock);
Y
yihaoDeng 已提交
155
    int64_t ver = walGetCommittedVer(pTq->pVnode->pWal);
156
    if (dataRsp.rspOffset.version > ver) {  // check if there are data again to avoid lost data
157 158 159 160
      code = tqRegisterPushHandle(pTq, pHandle, pMsg);
      taosWUnLockLatch(&pTq->lock);
      goto end;
    }
161
    taosWUnLockLatch(&pTq->lock);
162
  }
163

164
//  setRequestVersion(&dataRsp.reqOffset, pOffset->version);
165
  code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&dataRsp, TMQ_MSG_TYPE__POLL_DATA_RSP, vgId);
166

dengyihao's avatar
dengyihao 已提交
167
end : {
168 169
  char buf[TSDB_OFFSET_LEN] = {0};
  tFormatOffset(buf, TSDB_OFFSET_LEN, &dataRsp.rspOffset);
dengyihao's avatar
dengyihao 已提交
170 171 172 173
  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);
174
  return code;
H
Haojun Liao 已提交
175
  }
176 177
}

dengyihao's avatar
dengyihao 已提交
178 179 180 181 182 183
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);
  SMqMetaRsp  metaRsp = {0};
  STaosxRsp   taosxRsp = {0};
184 185
  tqInitTaosxRsp(&taosxRsp, *offset);
//  taosxRsp.reqOffset.type = offset->type;   // store origin type for getting offset in tmq_get_vgroup_offset
186 187 188

  if (offset->type != TMQ_OFFSET__LOG) {
    if (tqScanTaosx(pTq, pHandle, &taosxRsp, &metaRsp, offset) < 0) {
189 190
      code = -1;
      goto end;
191 192 193
    }

    if (metaRsp.metaRspLen > 0) {
194
      code = tqSendMetaPollRsp(pHandle, pMsg, pRequest, &metaRsp, vgId);
195 196 197 198
      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);
199
      taosMemoryFree(metaRsp.metaRsp);
200
      goto end;
201 202 203
    }

    tqDebug("taosx poll: consumer:0x%" PRIx64 " subkey:%s vgId:%d, send data blockNum:%d, offset type:%d,uid:%" PRId64
204 205 206
            ",ts:%" PRId64,
            pRequest->consumerId, pHandle->subKey, vgId, taosxRsp.blockNum, taosxRsp.rspOffset.type,
            taosxRsp.rspOffset.uid, taosxRsp.rspOffset.ts);
207
    if (taosxRsp.blockNum > 0) {
208
      code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__POLL_DATA_RSP, vgId);
209
      goto end;
210
    } else {
211 212 213 214 215
      *offset = taosxRsp.rspOffset;
    }
  }

  if (offset->type == TMQ_OFFSET__LOG) {
216
    walReaderVerifyOffset(pHandle->pWalReader, offset);
217
    int64_t fetchVer = offset->version;
218

219 220 221 222 223
    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
224 225
               ", found new consumer epoch %d, discard req epoch %d",
               pRequest->consumerId, pRequest->epoch, pHandle->subKey, vgId, fetchVer, savedEpoch, pRequest->epoch);
226 227 228
        break;
      }

wmmhello's avatar
wmmhello 已提交
229
      if (tqFetchLog(pTq, pHandle, &fetchVer, pRequest->reqId) < 0) {
230
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
231
//        setRequestVersion(&taosxRsp.reqOffset, offset->version);
232
        code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__POLL_DATA_RSP, vgId);
233
        goto end;
234 235
      }

wmmhello's avatar
wmmhello 已提交
236
      SWalCont* pHead = &pHandle->pWalReader->pHead->head;
dengyihao's avatar
dengyihao 已提交
237 238
      tqDebug("tmq poll: consumer:0x%" PRIx64 " (epoch %d) iter log, vgId:%d offset %" PRId64 " msgType %d",
              pRequest->consumerId, pRequest->epoch, vgId, fetchVer, pHead->msgType);
239 240 241

      // process meta
      if (pHead->msgType != TDMT_VND_SUBMIT) {
dengyihao's avatar
dengyihao 已提交
242
        if (totalRows > 0) {
wmmhello's avatar
wmmhello 已提交
243
          tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer);
244
//          setRequestVersion(&taosxRsp.reqOffset, offset->version);
245
          code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, TMQ_MSG_TYPE__POLL_DATA_RSP, vgId);
246
          goto end;
247 248 249
        }

        tqDebug("fetch meta msg, ver:%" PRId64 ", type:%s", pHead->version, TMSG_INFO(pHead->msgType));
250
        tqOffsetResetToLog(&metaRsp.rspOffset, fetchVer + 1);
251 252 253
        metaRsp.resMsgType = pHead->msgType;
        metaRsp.metaRspLen = pHead->bodyLen;
        metaRsp.metaRsp = pHead->body;
254
        code = tqSendMetaPollRsp(pHandle, pMsg, pRequest, &metaRsp, vgId);
255
        goto end;
256 257 258 259 260 261 262 263 264
      }

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

265 266
      code = tqTaosxScanLog(pTq, pHandle, submit, &taosxRsp, &totalRows);
      if (code < 0) {
dengyihao's avatar
dengyihao 已提交
267 268
        tqError("tmq poll: tqTaosxScanLog error %" PRId64 ", in vgId:%d, subkey %s", pRequest->consumerId, vgId,
                pRequest->subKey);
269
        goto end;
270 271 272
      }

      if (totalRows >= 4096 || taosxRsp.createTableNum > 0) {
wmmhello's avatar
wmmhello 已提交
273
        tqOffsetResetToLog(&taosxRsp.rspOffset, fetchVer + 1);
274
//        setRequestVersion(&taosxRsp.reqOffset, offset->version);
275
        code = tqSendDataRsp(pHandle, pMsg, pRequest, (SMqDataRsp*)&taosxRsp, taosxRsp.createTableNum > 0 ? TMQ_MSG_TYPE__POLL_DATA_META_RSP : TMQ_MSG_TYPE__POLL_DATA_RSP, vgId);
276
        goto end;
277 278 279 280 281 282
      } else {
        fetchVer++;
      }
    }
  }

283 284
end:

285
  tDeleteSTaosxRsp(&taosxRsp);
286
  return code;
287 288 289 290 291 292
}

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

  // 1. reset the offset if needed
293
  if (IS_OFFSET_RESET_TYPE(pRequest->reqOffset.type)) {
294
    // handle the reset offset cases, according to the consumer's choice.
295
    bool blockReturned = false;
296
    int32_t code = extractResetOffsetVal(&reqOffset, pTq, pHandle, pRequest, pMsg, &blockReturned);
297 298 299 300
    if (code != 0) {
      return code;
    }

301 302 303 304
    // empty block returned, quit
    if (blockReturned) {
      return 0;
    }
305
  } else if(reqOffset.type == 0){  // use the consumer specified offset
306
    uError("req offset type is 0");
wmmhello's avatar
wmmhello 已提交
307
    return TSDB_CODE_TMQ_INVALID_MSG;
308 309 310 311
  }

  // this is a normal subscribe requirement
  if (pHandle->execHandle.subType == TOPIC_SUB_TYPE__COLUMN) {
312
    return extractDataAndRspForNormalSubscribe(pTq, pHandle, pRequest, pMsg, &reqOffset);
dengyihao's avatar
dengyihao 已提交
313
  } else {  // todo handle the case where re-balance occurs.
314
    // for taosx
315
    return extractDataAndRspForDbStbSubscribe(pTq, pHandle, pRequest, pMsg, &reqOffset);
316 317 318
  }
}

319 320 321 322 323 324 325 326 327
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 已提交
328 329
int32_t tqSendMetaPollRsp(STqHandle* pHandle, const SRpcMsg* pMsg, const SMqPollReq* pReq, const SMqMetaRsp* pRsp,
                          int32_t vgId) {
330 331
  int32_t len = 0;
  int32_t code = 0;
332
  tEncodeSize(tEncodeMqMetaRsp, pRsp, len, code);
333 334 335 336 337 338 339 340 341
  if (code < 0) {
    return -1;
  }
  int32_t tlen = sizeof(SMqRspHead) + len;
  void*   buf = rpcMallocCont(tlen);
  if (buf == NULL) {
    return -1;
  }

342 343 344
  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);
345 346 347 348 349

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

  SEncoder encoder = {0};
  tEncoderInit(&encoder, abuf, len);
350
  tEncodeMqMetaRsp(&encoder, pRsp);
351 352
  tEncoderClear(&encoder);

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

355 356 357
  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);
358 359 360

  return 0;
}
361 362

int32_t tqDoSendDataRsp(const SRpcHandleInfo* pRpcHandleInfo, const SMqDataRsp* pRsp, int32_t epoch, int64_t consumerId,
dengyihao's avatar
dengyihao 已提交
363
                        int32_t type, int64_t sver, int64_t ever) {
364 365 366
  int32_t len = 0;
  int32_t code = 0;

367
  if (type == TMQ_MSG_TYPE__POLL_DATA_RSP || type == TMQ_MSG_TYPE__WALINFO_RSP) {
368
    tEncodeSize(tEncodeMqDataRsp, pRsp, len, code);
369
  } else if (type == TMQ_MSG_TYPE__POLL_DATA_META_RSP) {
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    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);

391
  if (type == TMQ_MSG_TYPE__POLL_DATA_RSP || type == TMQ_MSG_TYPE__WALINFO_RSP) {
392
    tEncodeMqDataRsp(&encoder, pRsp);
393
  } else if (type == TMQ_MSG_TYPE__POLL_DATA_META_RSP) {
394 395 396 397
    tEncodeSTaosxRsp(&encoder, (STaosxRsp*)pRsp);
  }

  tEncoderClear(&encoder);
dengyihao's avatar
dengyihao 已提交
398
  SRpcMsg rsp = {.info = *pRpcHandleInfo, .pCont = buf, .contLen = tlen, .code = 0};
399 400 401

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