executor.c 28.6 KB
Newer Older
H
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/>.
14 15 16
 */

#include "executor.h"
H
Haojun Liao 已提交
17
#include "executorimpl.h"
18
#include "planner.h"
L
Liu Jicong 已提交
19
#include "tdatablock.h"
L
Liu Jicong 已提交
20
#include "tref.h"
21
#include "tudf.h"
L
Liu Jicong 已提交
22
#include "vnode.h"
23 24 25 26 27 28 29 30 31

static TdThreadOnce initPoolOnce = PTHREAD_ONCE_INIT;
int32_t             exchangeObjRefPool = -1;

static void initRefPool() { exchangeObjRefPool = taosOpenRef(1024, doDestroyExchangeOperatorInfo); }
static void cleanupRefPool() {
  int32_t ref = atomic_val_compare_exchange_32(&exchangeObjRefPool, exchangeObjRefPool, 0);
  taosCloseRef(ref);
}
32

L
Liu Jicong 已提交
33
static int32_t doSetStreamBlock(SOperatorInfo* pOperator, void* input, size_t numOfBlocks, int32_t type, char* id) {
H
Haojun Liao 已提交
34
  ASSERT(pOperator != NULL);
X
Xiaoyu Wang 已提交
35
  if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
H
Haojun Liao 已提交
36
    if (pOperator->numOfDownstream == 0) {
37
      qError("failed to find stream scan operator to set the input data block, %s" PRIx64, id);
H
Haojun Liao 已提交
38 39
      return TSDB_CODE_QRY_APP_ERROR;
    }
H
Haojun Liao 已提交
40

H
Haojun Liao 已提交
41
    if (pOperator->numOfDownstream > 1) {  // not handle this in join query
42
      qError("join not supported for stream block scan, %s" PRIx64, id);
H
Haojun Liao 已提交
43
      return TSDB_CODE_QRY_APP_ERROR;
H
Haojun Liao 已提交
44
    }
L
Liu Jicong 已提交
45
    pOperator->status = OP_NOT_OPENED;
L
Liu Jicong 已提交
46
    return doSetStreamBlock(pOperator->pDownstream[0], input, numOfBlocks, type, id);
H
Haojun Liao 已提交
47
  } else {
48 49
    pOperator->status = OP_NOT_OPENED;

50
    SStreamScanInfo* pInfo = pOperator->info;
51

52 53
    // TODO: if a block was set but not consumed,
    // prevent setting a different type of block
54 55
    pInfo->validBlockIndex = 0;
    taosArrayClear(pInfo->pBlockLists);
56

L
Liu Jicong 已提交
57
    if (type == STREAM_INPUT__MERGED_SUBMIT) {
C
Cary Xu 已提交
58
      // ASSERT(numOfBlocks > 1);
L
Liu Jicong 已提交
59 60 61
      for (int32_t i = 0; i < numOfBlocks; i++) {
        SSubmitReq* pReq = *(void**)POINTER_SHIFT(input, i * sizeof(void*));
        taosArrayPush(pInfo->pBlockLists, &pReq);
62
      }
L
Liu Jicong 已提交
63 64
      pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
    } else if (type == STREAM_INPUT__DATA_SUBMIT) {
65 66 67 68
      /*if (tqReaderSetDataMsg(pInfo->tqReader, input, 0) < 0) {*/
      /*qError("submit msg messed up when initing stream block, %s" PRIx64, id);*/
      /*return TSDB_CODE_QRY_APP_ERROR;*/
      /*}*/
L
Liu Jicong 已提交
69 70 71 72 73 74
      ASSERT(numOfBlocks == 1);
      /*if (numOfBlocks == 1) {*/
      taosArrayPush(pInfo->pBlockLists, &input);
      pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
      /*} else {*/
      /*}*/
L
Liu Jicong 已提交
75
    } else if (type == STREAM_INPUT__DATA_BLOCK) {
H
Haojun Liao 已提交
76
      for (int32_t i = 0; i < numOfBlocks; ++i) {
L
Liu Jicong 已提交
77
        SSDataBlock* pDataBlock = &((SSDataBlock*)input)[i];
78

79
        // TODO optimize
80
        SSDataBlock* p = createOneDataBlock(pDataBlock, false);
H
Haojun Liao 已提交
81
        p->info = pDataBlock->info;
82

L
Liu Jicong 已提交
83
        taosArrayClear(p->pDataBlock);
H
Haojun Liao 已提交
84 85 86
        taosArrayAddAll(p->pDataBlock, pDataBlock->pDataBlock);
        taosArrayPush(pInfo->pBlockLists, &p);
      }
L
Liu Jicong 已提交
87
      pInfo->blockType = STREAM_INPUT__DATA_BLOCK;
88 89
    } else {
      ASSERT(0);
90 91
    }

H
Haojun Liao 已提交
92 93 94 95
    return TSDB_CODE_SUCCESS;
  }
}

96 97 98 99 100 101 102 103 104
void tdCleanupStreamInputDataBlock(qTaskInfo_t tinfo) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  if (!pTaskInfo || !pTaskInfo->pRoot || pTaskInfo->pRoot->numOfDownstream <= 0) {
    return;
  }
  SOperatorInfo* pOptrInfo = pTaskInfo->pRoot->pDownstream[0];

  if (pOptrInfo->operatorType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
    SStreamScanInfo* pInfo = pOptrInfo->info;
C
Cary Xu 已提交
105
    if (pInfo->blockType == STREAM_INPUT__DATA_BLOCK) {
106 107 108 109 110 111 112 113 114 115 116 117 118
      for (int32_t i = 0; i < taosArrayGetSize(pInfo->pBlockLists); ++i) {
        SSDataBlock* p = *(SSDataBlock**)taosArrayGet(pInfo->pBlockLists, i);
        taosArrayDestroy(p->pDataBlock);
        taosMemoryFreeClear(p);
      }
    } else {
      ASSERT(0);
    }
  } else {
    ASSERT(0);
  }
}

L
Liu Jicong 已提交
119
int32_t qSetMultiStreamInput(qTaskInfo_t tinfo, const void* pBlocks, size_t numOfBlocks, int32_t type) {
H
Haojun Liao 已提交
120 121 122 123
  if (tinfo == NULL) {
    return TSDB_CODE_QRY_APP_ERROR;
  }

H
Haojun Liao 已提交
124
  if (pBlocks == NULL || numOfBlocks == 0) {
H
Haojun Liao 已提交
125 126 127
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
128
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
H
Haojun Liao 已提交
129

C
Cary Xu 已提交
130
  int32_t code = doSetStreamBlock(pTaskInfo->pRoot, (void*)pBlocks, numOfBlocks, type, GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
131
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
132
    qError("%s failed to set the stream block data", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
133
  } else {
H
Haojun Liao 已提交
134
    qDebug("%s set the stream block successfully", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
135 136 137 138 139
  }

  return code;
}

H
Haojun Liao 已提交
140
qTaskInfo_t qCreateQueueExecTaskInfo(void* msg, SReadHandle* readers, int32_t* numOfCols, SSchemaWrapper** pSchema) {
L
Liu Jicong 已提交
141 142
  if (msg == NULL) {
    // TODO create raw scan
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

    SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
    if (NULL == pTaskInfo) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      return NULL;
    }
    setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);

    pTaskInfo->cost.created = taosGetTimestampMs();
    pTaskInfo->execModel = OPTR_EXEC_MODEL_QUEUE;
    pTaskInfo->pRoot = createRawScanOperatorInfo(readers, pTaskInfo);
    if(NULL == pTaskInfo->pRoot){
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      taosMemoryFree(pTaskInfo);
      return NULL;
    }
    return pTaskInfo;
L
Liu Jicong 已提交
160 161
  }

H
Haojun Liao 已提交
162 163
  struct SSubplan* pPlan = NULL;
  int32_t          code = qStringToSubplan(msg, &pPlan);
L
Liu Jicong 已提交
164 165 166 167 168 169
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return NULL;
  }

  qTaskInfo_t pTaskInfo = NULL;
H
Haojun Liao 已提交
170
  code = qCreateExecTask(readers, 0, 0, pPlan, &pTaskInfo, NULL, NULL, OPTR_EXEC_MODEL_QUEUE);
L
Liu Jicong 已提交
171
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
172 173
    nodesDestroyNode((SNode*)pPlan);
    qDestroyTask(pTaskInfo);
L
Liu Jicong 已提交
174 175 176 177
    terrno = code;
    return NULL;
  }

178
  // extract the number of output columns
H
Haojun Liao 已提交
179
  SDataBlockDescNode* pDescNode = pPlan->pNode->pOutputDataBlockDesc;
wmmhello's avatar
wmmhello 已提交
180
  *numOfCols = 0;
181

L
Liu Jicong 已提交
182
  SNode* pNode;
183 184 185
  FOREACH(pNode, pDescNode->pSlots) {
    SSlotDescNode* pSlotDesc = (SSlotDescNode*)pNode;
    if (pSlotDesc->output) {
wmmhello's avatar
wmmhello 已提交
186
      ++(*numOfCols);
187 188 189
    }
  }

H
Haojun Liao 已提交
190
  *pSchema = tCloneSSchemaWrapper(((SExecTaskInfo*)pTaskInfo)->schemaInfo.qsw);
L
Liu Jicong 已提交
191 192 193
  return pTaskInfo;
}

L
Liu Jicong 已提交
194
qTaskInfo_t qCreateStreamExecTaskInfo(void* msg, SReadHandle* readers) {
L
Liu Jicong 已提交
195
  if (msg == NULL) {
196 197 198
    return NULL;
  }

199
  /*qDebugL("stream task string %s", (const char*)msg);*/
X
bugfix  
Xiaoyu Wang 已提交
200

H
Haojun Liao 已提交
201 202
  struct SSubplan* pPlan = NULL;
  int32_t          code = qStringToSubplan(msg, &pPlan);
203 204 205 206 207 208
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return NULL;
  }

  qTaskInfo_t pTaskInfo = NULL;
H
Haojun Liao 已提交
209
  code = qCreateExecTask(readers, 0, 0, pPlan, &pTaskInfo, NULL, NULL, OPTR_EXEC_MODEL_STREAM);
210
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
211 212
    nodesDestroyNode((SNode*)pPlan);
    qDestroyTask(pTaskInfo);
213 214 215 216 217 218
    terrno = code;
    return NULL;
  }

  return pTaskInfo;
}
219

220
static SArray* filterUnqualifiedTables(const SStreamScanInfo* pScanInfo, const SArray* tableIdList, const char* idstr) {
221 222 223 224 225 226
  SArray* qa = taosArrayInit(4, sizeof(tb_uid_t));

  // let's discard the tables those are not created according to the queried super table.
  SMetaReader mr = {0};
  metaReaderInit(&mr, pScanInfo->readHandle.meta, 0);
  for (int32_t i = 0; i < taosArrayGetSize(tableIdList); ++i) {
227
    uint64_t* id = (uint64_t*)taosArrayGet(tableIdList, i);
228 229 230

    int32_t code = metaGetTableEntryByUid(&mr, *id);
    if (code != TSDB_CODE_SUCCESS) {
231
      qError("failed to get table meta, uid:%" PRIu64 " code:%s, %s", *id, tstrerror(terrno), idstr);
232 233 234
      continue;
    }

M
Minglei Jin 已提交
235 236
    tDecoderClear(&mr.coder);

237
    // TODO handle ntb case
L
Liu Jicong 已提交
238
    if (mr.me.type != TSDB_CHILD_TABLE || mr.me.ctbEntry.suid != pScanInfo->tableUid) {
239 240
      continue;
    }
241 242 243

    if (pScanInfo->pTagCond != NULL) {
      bool          qualified = false;
244
      STableKeyInfo info = {.groupId = 0, .uid = mr.me.uid};
H
Haojun Liao 已提交
245
      code = isQualifiedTable(&info, pScanInfo->pTagCond, pScanInfo->readHandle.meta, &qualified);
246 247 248 249 250 251 252 253 254 255
      if (code != TSDB_CODE_SUCCESS) {
        qError("failed to filter new table, uid:0x%" PRIx64 ", %s", info.uid, idstr);
        continue;
      }

      if (!qualified) {
        continue;
      }
    }

256
    // handle multiple partition
257 258 259 260 261 262 263
    taosArrayPush(qa, id);
  }

  metaReaderClear(&mr);
  return qa;
}

264
int32_t qUpdateQualifiedTableId(qTaskInfo_t tinfo, const SArray* tableIdList, bool isAdd) {
L
fix  
Liu Jicong 已提交
265
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
266

267
  // traverse to the stream scanner node to add this table id
268
  SOperatorInfo* pInfo = pTaskInfo->pRoot;
L
Liu Jicong 已提交
269
  while (pInfo->operatorType != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
270 271 272
    pInfo = pInfo->pDownstream[0];
  }

273 274
  int32_t          code = 0;
  SStreamScanInfo* pScanInfo = pInfo->info;
275
  if (isAdd) {  // add new table id
276
    SArray* qa = filterUnqualifiedTables(pScanInfo, tableIdList, GET_TASKID(pTaskInfo));
277

278
    qDebug(" %d qualified child tables added into stream scanner", (int32_t)taosArrayGetSize(qa));
L
Liu Jicong 已提交
279
    code = tqReaderAddTbUidList(pScanInfo->tqReader, qa);
280 281 282 283 284
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    // todo refactor STableList
M
Minglei Jin 已提交
285
    bool   assignUid = false;
L
Liu Jicong 已提交
286 287
    size_t bufLen = (pScanInfo->pGroupTags != NULL) ? getTableTagsBufLen(pScanInfo->pGroupTags) : 0;
    char*  keyBuf = NULL;
288
    if (bufLen > 0) {
289
      assignUid = groupbyTbname(pScanInfo->pGroupTags);
290 291 292 293 294
      keyBuf = taosMemoryMalloc(bufLen);
      if (keyBuf == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
    }
295

L
Liu Jicong 已提交
296
    for (int32_t i = 0; i < taosArrayGetSize(qa); ++i) {
297
      uint64_t*     uid = taosArrayGet(qa, i);
298
      STableKeyInfo keyInfo = {.uid = *uid, .groupId = 0};
299 300

      if (bufLen > 0) {
301 302 303 304 305 306 307 308
        if (assignUid) {
          keyInfo.groupId = keyInfo.uid;
        } else {
          code = getGroupIdFromTagsVal(pScanInfo->readHandle.meta, keyInfo.uid, pScanInfo->pGroupTags, keyBuf,
                                       &keyInfo.groupId);
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
309 310 311
        }
      }

312
      taosArrayPush(pTaskInfo->tableqinfoList.pTableList, &keyInfo);
313 314 315 316 317 318
      if (pTaskInfo->tableqinfoList.map == NULL) {
        pTaskInfo->tableqinfoList.map =
            taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
      }

      taosHashPut(pTaskInfo->tableqinfoList.map, uid, sizeof(uid), &keyInfo.groupId, sizeof(keyInfo.groupId));
319 320
    }

321 322 323 324
    if (keyBuf != NULL) {
      taosMemoryFree(keyBuf);
    }

325 326 327
    taosArrayDestroy(qa);
  } else {  // remove the table id in current list
    qDebug(" %d remove child tables from the stream scanner", (int32_t)taosArrayGetSize(tableIdList));
L
Liu Jicong 已提交
328
    code = tqReaderRemoveTbUidList(pScanInfo->tqReader, tableIdList);
329 330
  }

331
  return code;
L
fix  
Liu Jicong 已提交
332
}
333

334
int32_t qGetQueryTableSchemaVersion(qTaskInfo_t tinfo, char* dbName, char* tableName, int32_t* sversion,
L
Liu Jicong 已提交
335
                                    int32_t* tversion) {
336
  ASSERT(tinfo != NULL && dbName != NULL && tableName != NULL);
337
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
338

339
  if (pTaskInfo->schemaInfo.sw == NULL) {
H
Haojun Liao 已提交
340 341 342
    return TSDB_CODE_SUCCESS;
  }

343 344 345 346
  *sversion = pTaskInfo->schemaInfo.sw->version;
  *tversion = pTaskInfo->schemaInfo.tversion;
  if (pTaskInfo->schemaInfo.dbname) {
    strcpy(dbName, pTaskInfo->schemaInfo.dbname);
347 348 349
  } else {
    dbName[0] = 0;
  }
350 351
  if (pTaskInfo->schemaInfo.tablename) {
    strcpy(tableName, pTaskInfo->schemaInfo.tablename);
352 353 354
  } else {
    tableName[0] = 0;
  }
355 356

  return 0;
357
}
358 359

int32_t qCreateExecTask(SReadHandle* readHandle, int32_t vgId, uint64_t taskId, SSubplan* pSubplan,
D
dapan1121 已提交
360
                        qTaskInfo_t* pTaskInfo, DataSinkHandle* handle, char* sql, EOPTR_EXEC_MODEL model) {
361 362 363 364 365 366
  assert(pSubplan != NULL);
  SExecTaskInfo** pTask = (SExecTaskInfo**)pTaskInfo;

  taosThreadOnce(&initPoolOnce, initRefPool);
  atexit(cleanupRefPool);

367
  qDebug("start to create subplan task, TID:0x%" PRIx64 " QID:0x%" PRIx64, taskId, pSubplan->id.queryId);
368

369 370
  int32_t code = createExecTaskInfoImpl(pSubplan, pTask, readHandle, taskId, sql, model);
  if (code != TSDB_CODE_SUCCESS) {
371
    qError("failed to createExecTaskInfoImpl, code: %s", tstrerror(code));
372 373 374
    goto _error;
  }

375
  SDataSinkMgtCfg cfg = {.maxDataBlockNum = 10000, .maxDataBlockNumPerQuery = 5000};
376 377
  code = dsDataSinkMgtInit(&cfg);
  if (code != TSDB_CODE_SUCCESS) {
378
    qError("failed to dsDataSinkMgtInit, code: %s", tstrerror(code));
379 380 381 382 383 384 385
    goto _error;
  }

  if (handle) {
    void* pSinkParam = NULL;
    code = createDataSinkParam(pSubplan->pDataSink, &pSinkParam, pTaskInfo, readHandle);
    if (code != TSDB_CODE_SUCCESS) {
386
      qError("failed to createDataSinkParam, code: %s", tstrerror(code));
387 388 389 390
      goto _error;
    }

    code = dsCreateDataSinker(pSubplan->pDataSink, handle, pSinkParam);
L
Liu Jicong 已提交
391
    if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
392 393
      taosMemoryFreeClear(pSinkParam);
    }
394 395
  }

396
  qDebug("subplan task create completed, TID:0x%" PRIx64 " QID:0x%" PRIx64, taskId, pSubplan->id.queryId);
397

L
Liu Jicong 已提交
398
_error:
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
  // if failed to add ref for all tables in this query, abort current query
  return code;
}

#ifdef TEST_IMPL
// wait moment
int waitMoment(SQInfo* pQInfo) {
  if (pQInfo->sql) {
    int   ms = 0;
    char* pcnt = strstr(pQInfo->sql, " count(*)");
    if (pcnt) return 0;

    char* pos = strstr(pQInfo->sql, " t_");
    if (pos) {
      pos += 3;
      ms = atoi(pos);
      while (*pos >= '0' && *pos <= '9') {
        pos++;
      }
      char unit_char = *pos;
      if (unit_char == 'h') {
        ms *= 3600 * 1000;
      } else if (unit_char == 'm') {
        ms *= 60 * 1000;
      } else if (unit_char == 's') {
        ms *= 1000;
      }
    }
    if (ms == 0) return 0;
    printf("test wait sleep %dms. sql=%s ...\n", ms, pQInfo->sql);

    if (ms < 1000) {
      taosMsleep(ms);
    } else {
      int used_ms = 0;
      while (used_ms < ms) {
        taosMsleep(1000);
        used_ms += 1000;
        if (isTaskKilled(pQInfo)) {
          printf("test check query is canceled, sleep break.%s\n", pQInfo->sql);
          break;
        }
      }
    }
  }
  return 1;
}
#endif

H
Haojun Liao 已提交
448
static void freeBlock(void* param) {
449
  SSDataBlock* pBlock = *(SSDataBlock**)param;
H
Haojun Liao 已提交
450 451 452
  blockDataDestroy(pBlock);
}

453
int32_t qExecTaskOpt(qTaskInfo_t tinfo, SArray* pResList, uint64_t* useconds) {
454 455 456
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  int64_t        threadId = taosGetSelfPthreadId();

H
Haojun Liao 已提交
457 458
  taosArrayClearEx(pResList, freeBlock);

459 460 461 462 463 464 465 466 467 468 469 470
  int64_t curOwner = 0;
  if ((curOwner = atomic_val_compare_exchange_64(&pTaskInfo->owner, 0, threadId)) != 0) {
    qError("%s-%p execTask is now executed by thread:%p", GET_TASKID(pTaskInfo), pTaskInfo, (void*)curOwner);
    pTaskInfo->code = TSDB_CODE_QRY_IN_EXEC;
    return pTaskInfo->code;
  }

  if (pTaskInfo->cost.start == 0) {
    pTaskInfo->cost.start = taosGetTimestampMs();
  }

  if (isTaskKilled(pTaskInfo)) {
471
    atomic_store_64(&pTaskInfo->owner, 0);
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    qDebug("%s already killed, abort", GET_TASKID(pTaskInfo));
    return TSDB_CODE_SUCCESS;
  }

  // error occurs, record the error code and return to client
  int32_t ret = setjmp(pTaskInfo->env);
  if (ret != TSDB_CODE_SUCCESS) {
    pTaskInfo->code = ret;
    cleanUpUdfs();
    qDebug("%s task abort due to error/cancel occurs, code:%s", GET_TASKID(pTaskInfo), tstrerror(pTaskInfo->code));
    atomic_store_64(&pTaskInfo->owner, 0);

    return pTaskInfo->code;
  }

  qDebug("%s execTask is launched", GET_TASKID(pTaskInfo));

489
  int32_t      current = 0;
H
Haojun Liao 已提交
490 491
  SSDataBlock* pRes = NULL;

492 493
  int64_t st = taosGetTimestampUs();

494
  while ((pRes = pTaskInfo->pRoot->fpSet.getNextFn(pTaskInfo->pRoot)) != NULL) {
H
Haojun Liao 已提交
495 496 497 498 499 500 501 502 503 504
    SSDataBlock* p = createOneDataBlock(pRes, true);
    current += p->info.rows;
    ASSERT(p->info.rows > 0);
    taosArrayPush(pResList, &p);

    if (current >= 4096) {
      break;
    }
  }

505 506 507
  uint64_t el = (taosGetTimestampUs() - st);

  pTaskInfo->cost.elapsedTime += el;
H
Haojun Liao 已提交
508
  if (NULL == pRes) {
509 510 511 512 513 514
    *useconds = pTaskInfo->cost.elapsedTime;
  }

  cleanUpUdfs();
  uint64_t total = pTaskInfo->pRoot->resultInfo.totalRows;

H
Haojun Liao 已提交
515
  qDebug("%s task suspended, %d rows in %d blocks returned, total:%" PRId64 " rows, in sinkNode:%d, elapsed:%.2f ms",
516
         GET_TASKID(pTaskInfo), current, (int32_t)taosArrayGetSize(pResList), total, 0, el / 1000.0);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

  atomic_store_64(&pTaskInfo->owner, 0);
  return pTaskInfo->code;
}

int32_t qExecTask(qTaskInfo_t tinfo, SSDataBlock** pRes, uint64_t* useconds) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  int64_t        threadId = taosGetSelfPthreadId();

  *pRes = NULL;
  int64_t curOwner = 0;
  if ((curOwner = atomic_val_compare_exchange_64(&pTaskInfo->owner, 0, threadId)) != 0) {
    qError("%s-%p execTask is now executed by thread:%p", GET_TASKID(pTaskInfo), pTaskInfo, (void*)curOwner);
    pTaskInfo->code = TSDB_CODE_QRY_IN_EXEC;
    return pTaskInfo->code;
  }

  if (pTaskInfo->cost.start == 0) {
    pTaskInfo->cost.start = taosGetTimestampMs();
  }

  if (isTaskKilled(pTaskInfo)) {
539
    atomic_store_64(&pTaskInfo->owner, 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 571 572 573 574 575 576 577 578 579 580 581 582 583
    qDebug("%s already killed, abort", GET_TASKID(pTaskInfo));
    return TSDB_CODE_SUCCESS;
  }

  // error occurs, record the error code and return to client
  int32_t ret = setjmp(pTaskInfo->env);
  if (ret != TSDB_CODE_SUCCESS) {
    pTaskInfo->code = ret;
    cleanUpUdfs();
    qDebug("%s task abort due to error/cancel occurs, code:%s", GET_TASKID(pTaskInfo), tstrerror(pTaskInfo->code));
    atomic_store_64(&pTaskInfo->owner, 0);
    return pTaskInfo->code;
  }

  qDebug("%s execTask is launched", GET_TASKID(pTaskInfo));

  int64_t st = taosGetTimestampUs();

  *pRes = pTaskInfo->pRoot->fpSet.getNextFn(pTaskInfo->pRoot);
  uint64_t el = (taosGetTimestampUs() - st);

  pTaskInfo->cost.elapsedTime += el;
  if (NULL == *pRes) {
    *useconds = pTaskInfo->cost.elapsedTime;
  }

  cleanUpUdfs();

  int32_t  current = (*pRes != NULL) ? (*pRes)->info.rows : 0;
  uint64_t total = pTaskInfo->pRoot->resultInfo.totalRows;

  qDebug("%s task suspended, %d rows returned, total:%" PRId64 " rows, in sinkNode:%d, elapsed:%.2f ms",
         GET_TASKID(pTaskInfo), current, total, 0, el / 1000.0);

  atomic_store_64(&pTaskInfo->owner, 0);
  return pTaskInfo->code;
}

int32_t qKillTask(qTaskInfo_t qinfo) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)qinfo;
  if (pTaskInfo == NULL) {
    return TSDB_CODE_QRY_INVALID_QHANDLE;
  }

H
Haojun Liao 已提交
584
  qAsyncKillTask(qinfo);
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618

  // Wait for the query executing thread being stopped/
  // Once the query is stopped, the owner of qHandle will be cleared immediately.
  while (pTaskInfo->owner != 0) {
    taosMsleep(100);
  }

  return TSDB_CODE_SUCCESS;
}

int32_t qAsyncKillTask(qTaskInfo_t qinfo) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)qinfo;

  if (pTaskInfo == NULL) {
    return TSDB_CODE_QRY_INVALID_QHANDLE;
  }

  qDebug("%s execTask async killed", GET_TASKID(pTaskInfo));
  setTaskKilled(pTaskInfo);
  return TSDB_CODE_SUCCESS;
}

void qDestroyTask(qTaskInfo_t qTaskHandle) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)qTaskHandle;
  if (pTaskInfo == NULL) {
    return;
  }

  qDebug("%s execTask completed, numOfRows:%" PRId64, GET_TASKID(pTaskInfo), pTaskInfo->pRoot->resultInfo.totalRows);

  queryCostStatis(pTaskInfo);  // print the query cost summary
  doDestroyTask(pTaskInfo);
}

H
Haojun Liao 已提交
619
int32_t qGetExplainExecInfo(qTaskInfo_t tinfo, SArray* pExecInfoList) {
620
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
H
Haojun Liao 已提交
621
  return getOperatorExplainExecInfo(pTaskInfo->pRoot, pExecInfoList);
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
}

int32_t qSerializeTaskStatus(qTaskInfo_t tinfo, char** pOutput, int32_t* len) {
  SExecTaskInfo* pTaskInfo = (struct SExecTaskInfo*)tinfo;
  if (pTaskInfo->pRoot == NULL) {
    return TSDB_CODE_INVALID_PARA;
  }

  int32_t nOptrWithVal = 0;
  int32_t code = encodeOperator(pTaskInfo->pRoot, pOutput, len, &nOptrWithVal);
  if ((code == TSDB_CODE_SUCCESS) && (nOptrWithVal = 0)) {
    taosMemoryFreeClear(*pOutput);
    *len = 0;
  }
  return code;
}

int32_t qDeserializeTaskStatus(qTaskInfo_t tinfo, const char* pInput, int32_t len) {
  SExecTaskInfo* pTaskInfo = (struct SExecTaskInfo*)tinfo;

  if (pTaskInfo == NULL || pInput == NULL || len == 0) {
    return TSDB_CODE_INVALID_PARA;
  }

  return decodeOperator(pTaskInfo->pRoot, pInput, len);
}

int32_t qExtractStreamScanner(qTaskInfo_t tinfo, void** scanner) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  SOperatorInfo* pOperator = pTaskInfo->pRoot;

  while (1) {
654
    uint16_t type = pOperator->operatorType;
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    if (type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
      *scanner = pOperator->info;
      return 0;
    } else {
      ASSERT(pOperator->numOfDownstream == 1);
      pOperator = pOperator->pDownstream[0];
    }
  }
}

#if 0
int32_t qStreamInput(qTaskInfo_t tinfo, void* pItem) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  ASSERT(pTaskInfo->execModel == OPTR_EXEC_MODEL_STREAM);
  taosWriteQitem(pTaskInfo->streamInfo.inputQueue->queue, pItem);
  return 0;
}
#endif

int32_t qStreamPrepareRecover(qTaskInfo_t tinfo, int64_t startVer, int64_t endVer) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  ASSERT(pTaskInfo->execModel == OPTR_EXEC_MODEL_STREAM);
  pTaskInfo->streamInfo.recoverStartVer = startVer;
  pTaskInfo->streamInfo.recoverEndVer = endVer;
  pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__PREPARE;
  return 0;
}

void* qExtractReaderFromStreamScanner(void* scanner) {
  SStreamScanInfo* pInfo = scanner;
  return (void*)pInfo->tqReader;
}

wmmhello's avatar
wmmhello 已提交
688 689 690 691 692 693 694 695
const SSchemaWrapper* qExtractSchemaFromTask(qTaskInfo_t tinfo) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  return pTaskInfo->streamInfo.schema;
}

const char* qExtractTbnameFromTask(qTaskInfo_t tinfo) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  return pTaskInfo->streamInfo.tbName;
696 697
}

wmmhello's avatar
wmmhello 已提交
698
SMqMetaRsp* qStreamExtractMetaMsg(qTaskInfo_t tinfo) {
699 700
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  ASSERT(pTaskInfo->execModel == OPTR_EXEC_MODEL_QUEUE);
wmmhello's avatar
wmmhello 已提交
701
  return &pTaskInfo->streamInfo.metaRsp;
702 703
}

wmmhello's avatar
wmmhello 已提交
704 705 706 707 708 709
int64_t qStreamExtractPrepareUid(qTaskInfo_t tinfo) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  ASSERT(pTaskInfo->execModel == OPTR_EXEC_MODEL_QUEUE);
  return pTaskInfo->streamInfo.prepareStatus.uid;
}

710 711 712 713 714 715 716
int32_t qStreamExtractOffset(qTaskInfo_t tinfo, STqOffsetVal* pOffset) {
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  ASSERT(pTaskInfo->execModel == OPTR_EXEC_MODEL_QUEUE);
  memcpy(pOffset, &pTaskInfo->streamInfo.lastStatus, sizeof(STqOffsetVal));
  return 0;
}

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
int32_t initQueryTableDataCondForTmq(SQueryTableDataCond* pCond, SSnapContext* sContext, SMetaTableInfo mtInfo) {
  memset(pCond, 0, sizeof(SQueryTableDataCond));
  pCond->order = TSDB_ORDER_ASC;
  pCond->numOfCols = mtInfo.schema->nCols;
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
  if (pCond->colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return terrno;
  }

  pCond->twindows = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
  pCond->suid = mtInfo.suid;
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
  pCond->startVersion = -1;
  pCond->endVersion = sContext->snapVersion;
wmmhello's avatar
wmmhello 已提交
732
  pCond->schemaVersion = sContext->snapVersion;
733 734 735 736 737 738 739 740 741 742 743

  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
    pCond->colList[i].type = mtInfo.schema->pSchema[i].type;
    pCond->colList[i].bytes = mtInfo.schema->pSchema[i].bytes;
    pCond->colList[i].colId = mtInfo.schema->pSchema[i].colId;
  }

  return TSDB_CODE_SUCCESS;
}

int32_t qStreamPrepareScan(qTaskInfo_t tinfo, STqOffsetVal* pOffset, int8_t subType) {
744 745 746 747
  SExecTaskInfo* pTaskInfo = (SExecTaskInfo*)tinfo;
  SOperatorInfo* pOperator = pTaskInfo->pRoot;
  ASSERT(pTaskInfo->execModel == OPTR_EXEC_MODEL_QUEUE);
  pTaskInfo->streamInfo.prepareStatus = *pOffset;
748 749 750 751
  if (tOffsetEqual(pOffset, &pTaskInfo->streamInfo.lastStatus)) {
    return 0;
  }
  if (subType == TOPIC_SUB_TYPE__COLUMN) {
wmmhello's avatar
wmmhello 已提交
752
    uint16_t type = pOperator->operatorType;
753 754 755 756 757 758
    pOperator->status = OP_OPENED;
    // TODO add more check
    if (type != QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
      ASSERT(pOperator->numOfDownstream == 1);
      pOperator = pOperator->pDownstream[0];
    }
L
Liu Jicong 已提交
759

760 761 762 763 764
    SStreamScanInfo* pInfo = pOperator->info;
    if (pOffset->type == TMQ_OFFSET__LOG) {
      STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
      tsdbReaderClose(pTSInfo->dataReader);
      pTSInfo->dataReader = NULL;
765
#if 0
wmmhello's avatar
wmmhello 已提交
766 767 768 769 770 771
      if (tOffsetEqual(pOffset, &pTaskInfo->streamInfo.lastStatus) &&
          pInfo->tqReader->pWalReader->curVersion != pOffset->version) {
        qError("prepare scan ver %" PRId64 " actual ver %" PRId64 ", last %" PRId64, pOffset->version,
               pInfo->tqReader->pWalReader->curVersion, pTaskInfo->streamInfo.lastStatus.version);
        ASSERT(0);
      }
772
#endif
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
      if (tqSeekVer(pInfo->tqReader, pOffset->version + 1) < 0) {
        return -1;
      }
      ASSERT(pInfo->tqReader->pWalReader->curVersion == pOffset->version + 1);
    } else if (pOffset->type == TMQ_OFFSET__SNAPSHOT_DATA) {
      /*pInfo->blockType = STREAM_INPUT__TABLE_SCAN;*/
      int64_t uid = pOffset->uid;
      int64_t ts = pOffset->ts;

      if (uid == 0) {
        if (taosArrayGetSize(pTaskInfo->tableqinfoList.pTableList) != 0) {
          STableKeyInfo* pTableInfo = taosArrayGet(pTaskInfo->tableqinfoList.pTableList, 0);
          uid = pTableInfo->uid;
          ts = INT64_MIN;
        } else {
L
Liu Jicong 已提交
788 789
          return -1;
        }
790
      }
H
Haojun Liao 已提交
791

792 793 794 795
      /*if (pTaskInfo->streamInfo.lastStatus.type != TMQ_OFFSET__SNAPSHOT_DATA ||*/
      /*pTaskInfo->streamInfo.lastStatus.uid != uid || pTaskInfo->streamInfo.lastStatus.ts != ts) {*/
      STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
      int32_t         tableSz = taosArrayGetSize(pTaskInfo->tableqinfoList.pTableList);
H
Haojun Liao 已提交
796 797

#ifndef NDEBUG
wmmhello's avatar
wmmhello 已提交
798 799
      qDebug("switch to next table %" PRId64 " (cursor %d), %" PRId64 " rows returned", uid,
             pTableScanInfo->currentTable, pInfo->pTableScanOp->resultInfo.totalRows);
800
      pInfo->pTableScanOp->resultInfo.totalRows = 0;
H
Haojun Liao 已提交
801 802
#endif

803 804 805 806 807 808 809
      bool found = false;
      for (int32_t i = 0; i < tableSz; i++) {
        STableKeyInfo* pTableInfo = taosArrayGet(pTaskInfo->tableqinfoList.pTableList, i);
        if (pTableInfo->uid == uid) {
          found = true;
          pTableScanInfo->currentTable = i;
          break;
L
Liu Jicong 已提交
810
        }
811
      }
812

813 814
      // TODO after dropping table, table may be not found
      ASSERT(found);
815

816 817 818 819 820
      if (pTableScanInfo->dataReader == NULL) {
        if (tsdbReaderOpen(pTableScanInfo->readHandle.vnode, &pTableScanInfo->cond,
                           pTaskInfo->tableqinfoList.pTableList, &pTableScanInfo->dataReader, NULL) < 0 ||
            pTableScanInfo->dataReader == NULL) {
          ASSERT(0);
L
Liu Jicong 已提交
821
        }
822
      }
H
Haojun Liao 已提交
823

824 825 826 827 828 829
      tsdbSetTableId(pTableScanInfo->dataReader, uid);
      int64_t oldSkey = pTableScanInfo->cond.twindows.skey;
      pTableScanInfo->cond.twindows.skey = ts + 1;
      tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
      pTableScanInfo->cond.twindows.skey = oldSkey;
      pTableScanInfo->scanTimes = 0;
830

wmmhello's avatar
wmmhello 已提交
831 832
      qDebug("tsdb reader offset seek to uid %" PRId64 " ts %" PRId64 ", table cur set to %d , all table num %d", uid,
             ts, pTableScanInfo->currentTable, tableSz);
833 834 835
      /*}*/
    } else {
      ASSERT(0);
836
    }
837 838 839
  }else if (pOffset->type == TMQ_OFFSET__SNAPSHOT_DATA){
    SStreamRawScanInfo* pInfo = pOperator->info;
    SSnapContext* sContext = pInfo->sContext;
wmmhello's avatar
wmmhello 已提交
840
    if(setForSnapShot(sContext, pOffset->uid) != 0) {
841 842 843 844 845 846 847 848 849
      qError("setDataForSnapShot error. uid:%"PRIi64, pOffset->uid);
      return -1;
    }

    SMetaTableInfo mtInfo = getUidfromSnapShot(sContext);
    tsdbReaderClose(pInfo->dataReader);
    pInfo->dataReader = NULL;
    cleanupQueryTableDataCond(&pTaskInfo->streamInfo.tableCond);
    taosArrayDestroy(pTaskInfo->tableqinfoList.pTableList);
850 851
    if(mtInfo.uid == 0) return 0;   // no data

852 853 854 855
    initQueryTableDataCondForTmq(&pTaskInfo->streamInfo.tableCond, sContext, mtInfo);
    pTaskInfo->streamInfo.tableCond.twindows.skey = pOffset->ts;
    pTaskInfo->tableqinfoList.pTableList = taosArrayInit(1, sizeof(STableKeyInfo));
    taosArrayPush(pTaskInfo->tableqinfoList.pTableList, &(STableKeyInfo){.uid = mtInfo.uid, .groupId = 0});
wmmhello's avatar
wmmhello 已提交
856
    tsdbReaderOpen(pInfo->vnode, &pTaskInfo->streamInfo.tableCond, pTaskInfo->tableqinfoList.pTableList, &pInfo->dataReader, NULL);
857

wmmhello's avatar
wmmhello 已提交
858 859 860 861
    strcpy(pTaskInfo->streamInfo.tbName, mtInfo.tbName);
    tDeleteSSchemaWrapper(pTaskInfo->streamInfo.schema);
    pTaskInfo->streamInfo.schema = mtInfo.schema;
    qDebug("tmqsnap qStreamPrepareScan snapshot data uid %ld ts %ld", mtInfo.uid, pOffset->ts);
wmmhello's avatar
wmmhello 已提交
862 863 864 865 866 867 868
  }else if(pOffset->type == TMQ_OFFSET__SNAPSHOT_META){
    SStreamRawScanInfo* pInfo = pOperator->info;
    SSnapContext* sContext = pInfo->sContext;
    if(setForSnapShot(sContext, pOffset->uid) != 0) {
      qError("setForSnapShot error. uid:%"PRIi64" ,version:%"PRIi64, pOffset->uid);
      return -1;
    }
wmmhello's avatar
wmmhello 已提交
869
    qDebug("tmqsnap qStreamPrepareScan snapshot meta uid %ld ts %ld", pOffset->uid);
wmmhello's avatar
wmmhello 已提交
870 871 872 873
  }else if (pOffset->type == TMQ_OFFSET__LOG) {
    SStreamRawScanInfo* pInfo = pOperator->info;
    tsdbReaderClose(pInfo->dataReader);
    pInfo->dataReader = NULL;
wmmhello's avatar
wmmhello 已提交
874
    qDebug("tmqsnap qStreamPrepareScan snapshot log");
875 876 877
  }
  return 0;
}