schJob.c 52.1 KB
Newer Older
D
dapan1121 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * 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 "catalog.h"
#include "command.h"
#include "query.h"
#include "schedulerInt.h"
#include "tmsg.h"
#include "tref.h"
#include "trpc.h"

D
dapan1121 已提交
24
FORCE_INLINE SSchJob *schAcquireJob(int64_t refId) { qDebug("sch acquire jobId:0x%"PRIx64, refId); return (SSchJob *)taosAcquireRef(schMgmt.jobRef, refId); }
D
dapan1121 已提交
25

D
dapan1121 已提交
26
FORCE_INLINE int32_t schReleaseJob(int64_t refId) { qDebug("sch release jobId:0x%"PRIx64, refId); return taosReleaseRef(schMgmt.jobRef, refId); }
D
dapan1121 已提交
27 28 29 30

int32_t schInitTask(SSchJob *pJob, SSchTask *pTask, SSubplan *pPlan, SSchLevel *pLevel) {
  pTask->plan = pPlan;
  pTask->level = pLevel;
D
dapan1121 已提交
31
  pTask->execId = -1;
D
dapan1121 已提交
32
  pTask->maxExecTimes = SCH_TASK_MAX_EXEC_TIMES;
D
dapan1121 已提交
33
  pTask->timeoutUsec = SCH_DEFAULT_TASK_TIMEOUT_USEC;
D
dapan1121 已提交
34 35
  SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_NOT_START);
  pTask->taskId = schGenTaskId();
D
dapan1121 已提交
36
  pTask->execNodes = taosHashInit(SCH_MAX_CANDIDATE_EP_NUM, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);
D
dapan1121 已提交
37
  if (NULL == pTask->execNodes) {
D
dapan1121 已提交
38
    SCH_TASK_ELOG("taosHashInit %d execNodes failed", SCH_MAX_CANDIDATE_EP_NUM);
D
dapan1121 已提交
39 40 41 42 43 44
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
45
int32_t schInitJob(SSchedulerReq *pReq, SSchJob **pSchJob) {
D
dapan1121 已提交
46 47 48 49
  int32_t  code = 0;
  int64_t  refId = -1;
  SSchJob *pJob = taosMemoryCalloc(1, sizeof(SSchJob));
  if (NULL == pJob) {
D
dapan1121 已提交
50
    qError("QID:0x%" PRIx64 " calloc %d failed", pReq->pDag->queryId, (int32_t)sizeof(SSchJob));
D
dapan1121 已提交
51 52 53
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

D
dapan1121 已提交
54 55 56
  pJob->attr.explainMode = pReq->pDag->explainInfo.mode;
  pJob->conn = *pReq->pConn;
  pJob->sql = pReq->sql;
D
dapan1121 已提交
57
  pJob->pDag = pReq->pDag;
D
dapan1121 已提交
58 59 60 61
  pJob->chkKillFp = pReq->chkKillFp;
  pJob->chkKillParam = pReq->chkKillParam;
  pJob->userRes.execFp = pReq->execFp;
  pJob->userRes.userParam = pReq->execParam;
D
dapan1121 已提交
62 63 64 65

  if (pReq->pNodeList == NULL || taosArrayGetSize(pReq->pNodeList) <= 0) {
    qDebug("QID:0x%" PRIx64 " input exec nodeList is empty", pReq->pDag->queryId);
  } else {
D
dapan1121 已提交
66
    pJob->nodeList = taosArrayDup(pReq->pNodeList);
D
dapan1121 已提交
67
  }
D
dapan1121 已提交
68 69
  
  pJob->taskList =
D
dapan1121 已提交
70
      taosHashInit(pReq->pDag->numOfSubplans, taosGetDefaultHashFunction(TSDB_DATA_TYPE_UBIGINT), false, HASH_ENTRY_LOCK);
D
dapan1121 已提交
71
  if (NULL == pJob->taskList) {
D
dapan1121 已提交
72
    SCH_JOB_ELOG("taosHashInit %d taskList failed", pReq->pDag->numOfSubplans);
D
dapan1121 已提交
73 74
    SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }
D
dapan1121 已提交
75

D
dapan1121 已提交
76
  SCH_ERR_JRET(schValidateAndBuildJob(pReq->pDag, pJob));
D
dapan1121 已提交
77 78

  if (SCH_IS_EXPLAIN_JOB(pJob)) {
D
dapan1121 已提交
79
    SCH_ERR_JRET(qExecExplainBegin(pReq->pDag, &pJob->explainCtx, pReq->startTs));
D
dapan1121 已提交
80 81 82
  }

  pJob->execTasks =
D
dapan1121 已提交
83
      taosHashInit(pReq->pDag->numOfSubplans, taosGetDefaultHashFunction(TSDB_DATA_TYPE_UBIGINT), false, HASH_ENTRY_LOCK);
D
dapan1121 已提交
84
  if (NULL == pJob->execTasks) {
D
dapan1121 已提交
85
    SCH_JOB_ELOG("taosHashInit %d execTasks failed", pReq->pDag->numOfSubplans);
D
dapan1121 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99
    SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  tsem_init(&pJob->rspSem, 0, 0);

  refId = taosAddRef(schMgmt.jobRef, pJob);
  if (refId < 0) {
    SCH_JOB_ELOG("taosAddRef job failed, error:%s", tstrerror(terrno));
    SCH_ERR_JRET(terrno);
  }

  atomic_add_fetch_32(&schMgmt.jobNum, 1);

  if (NULL == schAcquireJob(refId)) {
D
dapan1121 已提交
100
    SCH_JOB_ELOG("schAcquireJob job failed, refId:0x%" PRIx64, refId);
D
dapan1121 已提交
101 102 103 104 105
    SCH_ERR_JRET(TSDB_CODE_SCH_STATUS_ERROR);
  }

  pJob->refId = refId;

106
  SCH_JOB_DLOG("job refId:0x%" PRIx64" created", pJob->refId);
D
dapan1121 已提交
107

D
dapan1121 已提交
108
  schUpdateJobStatus(pJob, JOB_TASK_STATUS_NOT_START);
D
dapan1121 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

  *pSchJob = pJob;

  return TSDB_CODE_SUCCESS;

_return:

  if (refId < 0) {
    schFreeJobImpl(pJob);
  } else {
    taosRemoveRef(schMgmt.jobRef, refId);
  }
  SCH_RET(code);
}

D
dapan1121 已提交
124 125 126 127

void schFreeTask(SSchJob *pJob, SSchTask *pTask) {
  schDeregisterTaskHb(pJob, pTask);
  
D
dapan1121 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  if (pTask->candidateAddrs) {
    taosArrayDestroy(pTask->candidateAddrs);
  }

  taosMemoryFreeClear(pTask->msg);

  if (pTask->children) {
    taosArrayDestroy(pTask->children);
  }

  if (pTask->parents) {
    taosArrayDestroy(pTask->parents);
  }

  if (pTask->execNodes) {
D
dapan1121 已提交
143
    taosHashCleanup(pTask->execNodes);
D
dapan1121 已提交
144 145 146
  }
}

D
dapan1121 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

void schUpdateJobErrCode(SSchJob *pJob, int32_t errCode) {
  if (TSDB_CODE_SUCCESS == errCode) {
    return;
  }

  int32_t origCode = atomic_load_32(&pJob->errCode);
  if (TSDB_CODE_SUCCESS == origCode) {
    if (origCode == atomic_val_compare_exchange_32(&pJob->errCode, origCode, errCode)) {
      goto _return;
    }

    origCode = atomic_load_32(&pJob->errCode);
  }

  if (NEED_CLIENT_HANDLE_ERROR(origCode)) {
    return;
  }

  if (NEED_CLIENT_HANDLE_ERROR(errCode)) {
    atomic_store_32(&pJob->errCode, errCode);
    goto _return;
  }

  return;

_return:

  SCH_JOB_DLOG("job errCode updated to %x - %s", errCode, tstrerror(errCode));
}



D
dapan1121 已提交
180 181 182 183 184 185
FORCE_INLINE bool schJobNeedToStop(SSchJob *pJob, int8_t *pStatus) {
  int8_t status = SCH_GET_JOB_STATUS(pJob);
  if (pStatus) {
    *pStatus = status;
  }

D
dapan1121 已提交
186
  if ((*pJob->chkKillFp)(pJob->chkKillParam)) {
D
dapan1121 已提交
187 188 189 190 191 192
    schUpdateJobStatus(pJob, JOB_TASK_STATUS_DROPPING);
    schUpdateJobErrCode(pJob, TSDB_CODE_TSC_QUERY_KILLED);

    return true;
  }  

D
dapan1121 已提交
193
  return (status == JOB_TASK_STATUS_FAILED || status == JOB_TASK_STATUS_DROPPING ||
D
dapan1121 已提交
194 195 196
          status == JOB_TASK_STATUS_SUCCEED);
}

D
dapan1121 已提交
197
int32_t schUpdateJobStatus(SSchJob *pJob, int8_t newStatus) {
D
dapan1121 已提交
198 199 200 201 202 203 204 205
  int32_t code = 0;

  int8_t oriStatus = 0;

  while (true) {
    oriStatus = SCH_GET_JOB_STATUS(pJob);

    if (oriStatus == newStatus) {
D
dapan1121 已提交
206 207 208 209 210
      if (newStatus == JOB_TASK_STATUS_DROPPING) {
        SCH_ERR_JRET(TSDB_CODE_SCH_JOB_IS_DROPPING);
      }
      
      SCH_ERR_JRET(TSDB_CODE_SCH_IGNORE_ERROR);
D
dapan1121 已提交
211 212 213 214 215 216 217 218 219 220
    }

    switch (oriStatus) {
      case JOB_TASK_STATUS_NULL:
        if (newStatus != JOB_TASK_STATUS_NOT_START) {
          SCH_ERR_JRET(TSDB_CODE_QRY_APP_ERROR);
        }

        break;
      case JOB_TASK_STATUS_NOT_START:
D
dapan1121 已提交
221
        if (newStatus != JOB_TASK_STATUS_EXECUTING && newStatus != JOB_TASK_STATUS_DROPPING) {
D
dapan1121 已提交
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
          SCH_ERR_JRET(TSDB_CODE_QRY_APP_ERROR);
        }

        break;
      case JOB_TASK_STATUS_EXECUTING:
        if (newStatus != JOB_TASK_STATUS_PARTIAL_SUCCEED && newStatus != JOB_TASK_STATUS_FAILED &&
            newStatus != JOB_TASK_STATUS_DROPPING) {
          SCH_ERR_JRET(TSDB_CODE_QRY_APP_ERROR);
        }

        break;
      case JOB_TASK_STATUS_PARTIAL_SUCCEED:
        if (newStatus != JOB_TASK_STATUS_FAILED && newStatus != JOB_TASK_STATUS_SUCCEED &&
            newStatus != JOB_TASK_STATUS_DROPPING) {
          SCH_ERR_JRET(TSDB_CODE_QRY_APP_ERROR);
        }

        break;
      case JOB_TASK_STATUS_SUCCEED:
      case JOB_TASK_STATUS_FAILED:
        if (newStatus != JOB_TASK_STATUS_DROPPING) {
          SCH_ERR_JRET(TSDB_CODE_QRY_APP_ERROR);
        }

        break;
      case JOB_TASK_STATUS_DROPPING:
        SCH_ERR_JRET(TSDB_CODE_QRY_JOB_FREED);
        break;

      default:
        SCH_JOB_ELOG("invalid job status:%s", jobTaskStatusStr(oriStatus));
        SCH_ERR_JRET(TSDB_CODE_QRY_APP_ERROR);
    }

    if (oriStatus != atomic_val_compare_exchange_8(&pJob->status, oriStatus, newStatus)) {
      continue;
    }

    SCH_JOB_DLOG("job status updated from %s to %s", jobTaskStatusStr(oriStatus), jobTaskStatusStr(newStatus));

    break;
  }

  return TSDB_CODE_SUCCESS;

_return:

  SCH_JOB_ELOG("invalid job status update, from %s to %s", jobTaskStatusStr(oriStatus), jobTaskStatusStr(newStatus));
D
dapan1121 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  SCH_RET(code);
}


void schEndOperation(SSchJob *pJob) {
  int32_t op = atomic_load_32(&pJob->opStatus.op);
  if (SCH_OP_NULL == op) {
    SCH_JOB_DLOG("job already not in any operation, status:%s", jobTaskStatusStr(pJob->status));
    return;
  }

  atomic_store_32(&pJob->opStatus.op, SCH_OP_NULL);
  
  SCH_JOB_DLOG("job end %s operation", schGetOpStr(op));
}

int32_t schBeginOperation(SSchJob *pJob, SCH_OP_TYPE type, bool sync) {
  int32_t code = 0;
D
dapan1121 已提交
288
  int8_t status = 0;
D
dapan1121 已提交
289
  
D
dapan1121 已提交
290
  if (schJobNeedToStop(pJob, &status)) {
D
dapan1121 已提交
291
    SCH_JOB_ELOG("abort op %s cause of job need to stop", schGetOpStr(type));
D
dapan1121 已提交
292 293 294
    SCH_ERR_JRET(pJob->errCode);
  }
      
D
dapan1121 已提交
295 296 297 298 299
  if (SCH_OP_NULL != atomic_val_compare_exchange_32(&pJob->opStatus.op, SCH_OP_NULL, type)) {
    SCH_JOB_ELOG("job already in %s operation", schGetOpStr(pJob->opStatus.op));
    SCH_ERR_JRET(TSDB_CODE_TSC_APP_ERROR);
  }

D
dapan1121 已提交
300
  SCH_JOB_DLOG("job start %s operation", schGetOpStr(pJob->opStatus.op));
D
dapan1121 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313

  pJob->opStatus.sync = sync;

  switch (type) {
    case SCH_OP_EXEC:
      SCH_ERR_JRET(schUpdateJobStatus(pJob, JOB_TASK_STATUS_EXECUTING));
      break;
    case SCH_OP_FETCH:
      if (!SCH_JOB_NEED_FETCH(pJob)) {
        SCH_JOB_ELOG("no need to fetch data, status:%s", SCH_GET_JOB_STATUS_STR(pJob));
        SCH_ERR_JRET(TSDB_CODE_QRY_APP_ERROR);
      }

D
dapan1121 已提交
314
      if (status != JOB_TASK_STATUS_PARTIAL_SUCCEED) {
D
dapan1121 已提交
315 316 317 318 319 320 321 322 323
        SCH_JOB_ELOG("job status error for fetch, status:%s", jobTaskStatusStr(status));
        SCH_ERR_JRET(TSDB_CODE_SCH_STATUS_ERROR);
      }
      break;
    default:
      SCH_JOB_ELOG("unknown operation type %d", type);
      SCH_ERR_JRET(TSDB_CODE_TSC_APP_ERROR);
  }

D
dapan1121 已提交
324
  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
325 326 327 328 329 330

_return:

  schEndOperation(pJob);

  SCH_RET(code);
D
dapan1121 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
}

int32_t schBuildTaskRalation(SSchJob *pJob, SHashObj *planToTask) {
  for (int32_t i = 0; i < pJob->levelNum; ++i) {
    SSchLevel *pLevel = taosArrayGet(pJob->levels, i);

    for (int32_t m = 0; m < pLevel->taskNum; ++m) {
      SSchTask *pTask = taosArrayGet(pLevel->subTasks, m);
      SSubplan *pPlan = pTask->plan;
      int32_t   childNum = pPlan->pChildren ? (int32_t)LIST_LENGTH(pPlan->pChildren) : 0;
      int32_t   parentNum = pPlan->pParents ? (int32_t)LIST_LENGTH(pPlan->pParents) : 0;

      if (childNum > 0) {
        if (pJob->levelIdx == pLevel->level) {
          SCH_JOB_ELOG("invalid query plan, lowest level, childNum:%d", childNum);
          SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
        }

        pTask->children = taosArrayInit(childNum, POINTER_BYTES);
        if (NULL == pTask->children) {
          SCH_TASK_ELOG("taosArrayInit %d children failed", childNum);
          SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
        }
      }

      for (int32_t n = 0; n < childNum; ++n) {
        SSubplan  *child = (SSubplan *)nodesListGetNode(pPlan->pChildren, n);
        SSchTask **childTask = taosHashGet(planToTask, &child, POINTER_BYTES);
        if (NULL == childTask || NULL == *childTask) {
          SCH_TASK_ELOG("subplan children relationship error, level:%d, taskIdx:%d, childIdx:%d", i, m, n);
          SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
        }

        if (NULL == taosArrayPush(pTask->children, childTask)) {
          SCH_TASK_ELOG("taosArrayPush childTask failed, level:%d, taskIdx:%d, childIdx:%d", i, m, n);
          SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
        }

D
dapan1121 已提交
369
        SCH_TASK_DLOG("children info, the %d child TID 0x%" PRIx64, n, (*childTask)->taskId);
D
dapan1121 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
      }

      if (parentNum > 0) {
        if (0 == pLevel->level) {
          SCH_TASK_ELOG("invalid task info, level:0, parentNum:%d", parentNum);
          SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
        }

        pTask->parents = taosArrayInit(parentNum, POINTER_BYTES);
        if (NULL == pTask->parents) {
          SCH_TASK_ELOG("taosArrayInit %d parents failed", parentNum);
          SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
        }
      } else {
        if (0 != pLevel->level) {
          SCH_TASK_ELOG("invalid task info, level:%d, parentNum:%d", pLevel->level, parentNum);
          SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
        }
      }

      for (int32_t n = 0; n < parentNum; ++n) {
        SSubplan  *parent = (SSubplan *)nodesListGetNode(pPlan->pParents, n);
        SSchTask **parentTask = taosHashGet(planToTask, &parent, POINTER_BYTES);
        if (NULL == parentTask || NULL == *parentTask) {
          SCH_TASK_ELOG("subplan parent relationship error, level:%d, taskIdx:%d, childIdx:%d", i, m, n);
          SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
        }

        if (NULL == taosArrayPush(pTask->parents, parentTask)) {
          SCH_TASK_ELOG("taosArrayPush parentTask failed, level:%d, taskIdx:%d, childIdx:%d", i, m, n);
          SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
        }

D
dapan1121 已提交
403
        SCH_TASK_DLOG("parents info, the %d parent TID 0x%" PRIx64, n, (*parentTask)->taskId);        
D
dapan1121 已提交
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
      }

      SCH_TASK_DLOG("level:%d, parentNum:%d, childNum:%d", i, parentNum, childNum);
    }
  }

  SSchLevel *pLevel = taosArrayGet(pJob->levels, 0);
  if (SCH_IS_QUERY_JOB(pJob) && pLevel->taskNum > 1) {
    SCH_JOB_ELOG("invalid query plan, level:0, taskNum:%d", pLevel->taskNum);
    SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
  }

  return TSDB_CODE_SUCCESS;
}

int32_t schRecordTaskSucceedNode(SSchJob *pJob, SSchTask *pTask) {
  SQueryNodeAddr *addr = taosArrayGet(pTask->candidateAddrs, pTask->candidateIdx);
  if (NULL == addr) {
    SCH_TASK_ELOG("taosArrayGet candidate addr failed, idx:%d, size:%d", pTask->candidateIdx,
                  (int32_t)taosArrayGetSize(pTask->candidateAddrs));
    SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
  }

  pTask->succeedAddr = *addr;

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
432
int32_t schAppendTaskExecNode(SSchJob *pJob, SSchTask *pTask, SQueryNodeAddr *addr, int32_t execId) {
D
dapan1121 已提交
433
  SSchNodeInfo nodeInfo = {.addr = *addr, .handle = NULL};
D
dapan1121 已提交
434

D
dapan1121 已提交
435
  if (taosHashPut(pTask->execNodes, &execId, sizeof(execId), &nodeInfo, sizeof(nodeInfo))) {
D
dapan1121 已提交
436
    SCH_TASK_ELOG("taosHashPut nodeInfo to execNodes failed, errno:%d", errno);
D
dapan1121 已提交
437 438 439
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

D
dapan1121 已提交
440
  SCH_TASK_DLOG("task execNode added, execId:%d", execId);
D
dapan1121 已提交
441 442 443 444

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
445
int32_t schDropTaskExecNode(SSchJob *pJob, SSchTask *pTask, void *handle, int32_t execId) {
446 447 448 449
  if (NULL == pTask->execNodes) {
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
450 451
  if (taosHashRemove(pTask->execNodes, &execId, sizeof(execId))) {
    SCH_TASK_ELOG("fail to remove execId %d from execNodeList", execId);
D
dapan1121 已提交
452
  } else {
D
dapan1121 已提交
453
    SCH_TASK_DLOG("execId %d removed from execNodeList", execId);
D
dapan1121 已提交
454 455
  }
  
D
dapan1121 已提交
456 457
  if (execId != pTask->execId) {     // ignore it
    SCH_TASK_DLOG("execId %d is not current execId %d", execId, pTask->execId);
D
dapan1121 已提交
458
    SCH_RET(TSDB_CODE_SCH_IGNORE_ERROR);
459 460 461 462 463
  }

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
464
int32_t schUpdateTaskExecNode(SSchJob *pJob, SSchTask *pTask, void *handle, int32_t execId) {
D
dapan1121 已提交
465
  if (taosHashGetSize(pTask->execNodes) <= 0) {
D
dapan1121 已提交
466 467 468
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
469
  SSchNodeInfo *nodeInfo = taosHashGet(pTask->execNodes, &execId, sizeof(execId));
D
dapan1121 已提交
470
  nodeInfo->handle = handle;
471

D
dapan1121 已提交
472
  SCH_TASK_DLOG("handle updated to %p for execId %d", handle, execId);
D
dapan1121 已提交
473

D
dapan1121 已提交
474 475
  return TSDB_CODE_SUCCESS;
}
476

D
dapan1121 已提交
477
int32_t schUpdateTaskHandle(SSchJob *pJob, SSchTask *pTask, bool dropExecNode, void *handle, int32_t execId) {
D
dapan1121 已提交
478
  if (dropExecNode) {
D
dapan1121 已提交
479
    SCH_RET(schDropTaskExecNode(pJob, pTask, handle, execId));
480 481
  }

D
dapan1121 已提交
482 483
  SCH_SET_TASK_HANDLE(pTask, handle);

D
dapan1121 已提交
484
  schUpdateTaskExecNode(pJob, pTask, handle, execId);
D
dapan1121 已提交
485

486 487 488 489
  return TSDB_CODE_SUCCESS;
}


D
dapan1121 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 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
int32_t schRecordQueryDataSrc(SSchJob *pJob, SSchTask *pTask) {
  if (!SCH_IS_DATA_SRC_QRY_TASK(pTask)) {
    return TSDB_CODE_SUCCESS;
  }

  taosArrayPush(pJob->dataSrcTasks, &pTask);

  return TSDB_CODE_SUCCESS;
}


int32_t schValidateAndBuildJob(SQueryPlan *pDag, SSchJob *pJob) {
  int32_t code = 0;
  pJob->queryId = pDag->queryId;

  if (pDag->numOfSubplans <= 0) {
    SCH_JOB_ELOG("invalid subplan num:%d", pDag->numOfSubplans);
    SCH_ERR_RET(TSDB_CODE_QRY_INVALID_INPUT);
  }

  pJob->dataSrcTasks = taosArrayInit(pDag->numOfSubplans, POINTER_BYTES);
  if (NULL == pJob->dataSrcTasks) {
    SCH_ERR_RET(TSDB_CODE_OUT_OF_MEMORY);
  }

  int32_t levelNum = (int32_t)LIST_LENGTH(pDag->pSubplans);
  if (levelNum <= 0) {
    SCH_JOB_ELOG("invalid level num:%d", levelNum);
    SCH_ERR_RET(TSDB_CODE_QRY_INVALID_INPUT);
  }

  SHashObj *planToTask = taosHashInit(
      SCHEDULE_DEFAULT_MAX_TASK_NUM,
      taosGetDefaultHashFunction(POINTER_BYTES == sizeof(int64_t) ? TSDB_DATA_TYPE_BIGINT : TSDB_DATA_TYPE_INT), false,
      HASH_NO_LOCK);
  if (NULL == planToTask) {
    SCH_JOB_ELOG("taosHashInit %d failed", SCHEDULE_DEFAULT_MAX_TASK_NUM);
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  pJob->levels = taosArrayInit(levelNum, sizeof(SSchLevel));
  if (NULL == pJob->levels) {
    SCH_JOB_ELOG("taosArrayInit %d failed", levelNum);
    SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  pJob->levelNum = levelNum;
  pJob->levelIdx = levelNum - 1;

  SSchLevel      level = {0};
  SNodeListNode *plans = NULL;
  int32_t        taskNum = 0;
  SSchLevel     *pLevel = NULL;

  level.status = JOB_TASK_STATUS_NOT_START;

  for (int32_t i = 0; i < levelNum; ++i) {
    if (NULL == taosArrayPush(pJob->levels, &level)) {
      SCH_JOB_ELOG("taosArrayPush level failed, level:%d", i);
      SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
    }

    pLevel = taosArrayGet(pJob->levels, i);
    pLevel->level = i;

    plans = (SNodeListNode *)nodesListGetNode(pDag->pSubplans, i);
    if (NULL == plans) {
      SCH_JOB_ELOG("empty level plan, level:%d", i);
      SCH_ERR_JRET(TSDB_CODE_QRY_INVALID_INPUT);
    }

    taskNum = (int32_t)LIST_LENGTH(plans->pNodeList);
    if (taskNum <= 0) {
      SCH_JOB_ELOG("invalid level plan number:%d, level:%d", taskNum, i);
      SCH_ERR_JRET(TSDB_CODE_QRY_INVALID_INPUT);
    }

    pLevel->taskNum = taskNum;

    pLevel->subTasks = taosArrayInit(taskNum, sizeof(SSchTask));
    if (NULL == pLevel->subTasks) {
      SCH_JOB_ELOG("taosArrayInit %d failed", taskNum);
      SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
    }

    for (int32_t n = 0; n < taskNum; ++n) {
      SSubplan *plan = (SSubplan *)nodesListGetNode(plans->pNodeList, n);

      SCH_SET_JOB_TYPE(pJob, plan->subplanType);

      SSchTask  task = {0};
      SCH_ERR_JRET(schInitTask(pJob, &task, plan, pLevel));

D
dapan1121 已提交
583 584
      SSchTask *pTask = taosArrayPush(pLevel->subTasks, &task);
      if (NULL == pTask) {
D
dapan1121 已提交
585 586 587 588
        SCH_TASK_ELOG("taosArrayPush task to level failed, level:%d, taskIdx:%d", pLevel->level, n);
        SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
      }

D
dapan1121 已提交
589
      SCH_ERR_JRET(schRecordQueryDataSrc(pJob, pTask));
D
dapan1121 已提交
590

D
dapan1121 已提交
591
      if (0 != taosHashPut(planToTask, &plan, POINTER_BYTES, &pTask, POINTER_BYTES)) {
D
dapan1121 已提交
592 593 594 595
        SCH_TASK_ELOG("taosHashPut to planToTaks failed, taskIdx:%d", n);
        SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
      }

D
dapan1121 已提交
596 597 598 599 600
      if (0 != taosHashPut(pJob->taskList, &pTask->taskId, sizeof(pTask->taskId), &pTask, POINTER_BYTES)) {
        SCH_TASK_ELOG("taosHashPut to taskList failed, taskIdx:%d", n);
        SCH_ERR_JRET(TSDB_CODE_QRY_OUT_OF_MEMORY);
      }

D
dapan1121 已提交
601 602 603
      ++pJob->taskNum;
    }

D
dapan1121 已提交
604
    SCH_JOB_DLOG("level %d initialized, taskNum:%d", i, taskNum);
D
dapan1121 已提交
605 606 607 608 609
  }

  SCH_ERR_JRET(schBuildTaskRalation(pJob, planToTask));

_return:
D
dapan1121 已提交
610
  
D
dapan1121 已提交
611 612 613 614 615 616 617
  if (planToTask) {
    taosHashCleanup(planToTask);
  }

  SCH_RET(code);
}

D
dapan1121 已提交
618 619 620 621 622 623 624 625
int32_t schSetAddrsFromNodeList(SSchJob *pJob, SSchTask *pTask) {
  int32_t addNum = 0;
  int32_t nodeNum = 0;
  
  if (pJob->nodeList) {
    nodeNum = taosArrayGetSize(pJob->nodeList);

    for (int32_t i = 0; i < nodeNum && addNum < SCH_MAX_CANDIDATE_EP_NUM; ++i) {
D
dapan1121 已提交
626 627 628
      SQueryNodeLoad *nload = taosArrayGet(pJob->nodeList, i);
      SQueryNodeAddr *naddr = &nload->addr;
      
D
dapan1121 已提交
629 630 631 632 633
      if (NULL == taosArrayPush(pTask->candidateAddrs, naddr)) {
        SCH_TASK_ELOG("taosArrayPush execNode to candidate addrs failed, addNum:%d, errno:%d", addNum, errno);
        SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
      }

H
Haojun Liao 已提交
634
      SCH_TASK_DLOG("set %dth candidate addr, id %d, fqdn:%s, port:%d", i, naddr->nodeId, SCH_GET_CUR_EP(naddr)->fqdn, SCH_GET_CUR_EP(naddr)->port);
D
dapan1121 已提交
635

D
dapan1121 已提交
636 637 638 639 640 641
      ++addNum;
    }
  }

  if (addNum <= 0) {
    SCH_TASK_ELOG("no available execNode as candidates, nodeNum:%d", nodeNum);
D
dapan1121 已提交
642
    SCH_ERR_RET(TSDB_CODE_TSC_NO_EXEC_NODE);
D
dapan1121 已提交
643 644 645 646 647 648
  }

  return TSDB_CODE_SUCCESS;
}


D
dapan1121 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
int32_t schSetTaskCandidateAddrs(SSchJob *pJob, SSchTask *pTask) {
  if (NULL != pTask->candidateAddrs) {
    return TSDB_CODE_SUCCESS;
  }

  pTask->candidateIdx = 0;
  pTask->candidateAddrs = taosArrayInit(SCH_MAX_CANDIDATE_EP_NUM, sizeof(SQueryNodeAddr));
  if (NULL == pTask->candidateAddrs) {
    SCH_TASK_ELOG("taosArrayInit %d condidate addrs failed", SCH_MAX_CANDIDATE_EP_NUM);
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  if (pTask->plan->execNode.epSet.numOfEps > 0) {
    if (NULL == taosArrayPush(pTask->candidateAddrs, &pTask->plan->execNode)) {
      SCH_TASK_ELOG("taosArrayPush execNode to candidate addrs failed, errno:%d", errno);
      SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
    }

D
dapan1121 已提交
667
    SCH_TASK_DLOG("use execNode in plan as candidate addr, numOfEps:%d", pTask->plan->execNode.epSet.numOfEps);
D
dapan1121 已提交
668 669 670 671

    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
672
  SCH_ERR_RET(schSetAddrsFromNodeList(pJob, pTask));
D
dapan1121 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685

  /*
    for (int32_t i = 0; i < job->dataSrcEps.numOfEps && addNum < SCH_MAX_CANDIDATE_EP_NUM; ++i) {
      strncpy(epSet->fqdn[epSet->numOfEps], job->dataSrcEps.fqdn[i], sizeof(job->dataSrcEps.fqdn[i]));
      epSet->port[epSet->numOfEps] = job->dataSrcEps.port[i];

      ++epSet->numOfEps;
    }
  */

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
686
int32_t schUpdateTaskCandidateAddr(SSchJob *pJob, SSchTask *pTask, SEpSet* pEpSet) {
D
dapan1121 已提交
687
  if (NULL == pTask->candidateAddrs || 1 != taosArrayGetSize(pTask->candidateAddrs)) {
D
dapan1121 已提交
688
    SCH_TASK_ELOG("not able to update cndidate addr, addr num %d", (int32_t)(pTask->candidateAddrs ? taosArrayGetSize(pTask->candidateAddrs): 0));
D
dapan1121 已提交
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    SCH_ERR_RET(TSDB_CODE_APP_ERROR);
  }

  SQueryNodeAddr* pAddr = taosArrayGet(pTask->candidateAddrs, 0);

  SEp* pOld = &pAddr->epSet.eps[pAddr->epSet.inUse];
  SEp* pNew = &pEpSet->eps[pEpSet->inUse];

  SCH_TASK_DLOG("update task ep from %s:%d to %s:%d", pOld->fqdn, pOld->port, pNew->fqdn, pNew->port);

  memcpy(&pAddr->epSet, pEpSet, sizeof(pAddr->epSet));

  return TSDB_CODE_SUCCESS;
}


D
dapan1121 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
int32_t schRemoveTaskFromExecList(SSchJob *pJob, SSchTask *pTask) {
  int32_t code = taosHashRemove(pJob->execTasks, &pTask->taskId, sizeof(pTask->taskId));
  if (code) {
    SCH_TASK_ELOG("task failed to rm from execTask list, code:%x", code);
    SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
  }

  return TSDB_CODE_SUCCESS;
}


int32_t schPushTaskToExecList(SSchJob *pJob, SSchTask *pTask) {
  int32_t code = taosHashPut(pJob->execTasks, &pTask->taskId, sizeof(pTask->taskId), &pTask, POINTER_BYTES);
  if (0 != code) {
    if (HASH_NODE_EXIST(code)) {
      SCH_TASK_ELOG("task already in execTask list, code:%x", code);
      SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
    }

    SCH_TASK_ELOG("taosHashPut task to execTask list failed, errno:%d", errno);
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  SCH_TASK_DLOG("task added to execTask list, numOfTasks:%d", taosHashGetSize(pJob->execTasks));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
733
/*
D
dapan1121 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 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 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
int32_t schMoveTaskToSuccList(SSchJob *pJob, SSchTask *pTask, bool *moved) {
  if (0 != taosHashRemove(pJob->execTasks, &pTask->taskId, sizeof(pTask->taskId))) {
    SCH_TASK_WLOG("remove task from execTask list failed, may not exist, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
  } else {
    SCH_TASK_DLOG("task removed from execTask list, numOfTasks:%d", taosHashGetSize(pJob->execTasks));
  }

  int32_t code = taosHashPut(pJob->succTasks, &pTask->taskId, sizeof(pTask->taskId), &pTask, POINTER_BYTES);
  if (0 != code) {
    if (HASH_NODE_EXIST(code)) {
      *moved = true;
      SCH_TASK_ELOG("task already in succTask list, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
      SCH_ERR_RET(TSDB_CODE_SCH_STATUS_ERROR);
    }

    SCH_TASK_ELOG("taosHashPut task to succTask list failed, errno:%d", errno);
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  *moved = true;

  SCH_TASK_DLOG("task moved to succTask list, numOfTasks:%d", taosHashGetSize(pJob->succTasks));

  return TSDB_CODE_SUCCESS;
}

int32_t schMoveTaskToFailList(SSchJob *pJob, SSchTask *pTask, bool *moved) {
  *moved = false;

  if (0 != taosHashRemove(pJob->execTasks, &pTask->taskId, sizeof(pTask->taskId))) {
    SCH_TASK_WLOG("remove task from execTask list failed, may not exist, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
  }

  int32_t code = taosHashPut(pJob->failTasks, &pTask->taskId, sizeof(pTask->taskId), &pTask, POINTER_BYTES);
  if (0 != code) {
    if (HASH_NODE_EXIST(code)) {
      *moved = true;

      SCH_TASK_WLOG("task already in failTask list, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
      SCH_ERR_RET(TSDB_CODE_SCH_STATUS_ERROR);
    }

    SCH_TASK_ELOG("taosHashPut task to failTask list failed, errno:%d", errno);
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  *moved = true;

  SCH_TASK_DLOG("task moved to failTask list, numOfTasks:%d", taosHashGetSize(pJob->failTasks));

  return TSDB_CODE_SUCCESS;
}

int32_t schMoveTaskToExecList(SSchJob *pJob, SSchTask *pTask, bool *moved) {
  if (0 != taosHashRemove(pJob->succTasks, &pTask->taskId, sizeof(pTask->taskId))) {
    SCH_TASK_WLOG("remove task from succTask list failed, may not exist, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
  }

  int32_t code = taosHashPut(pJob->execTasks, &pTask->taskId, sizeof(pTask->taskId), &pTask, POINTER_BYTES);
  if (0 != code) {
    if (HASH_NODE_EXIST(code)) {
      *moved = true;

      SCH_TASK_ELOG("task already in execTask list, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
      SCH_ERR_RET(TSDB_CODE_SCH_STATUS_ERROR);
    }

    SCH_TASK_ELOG("taosHashPut task to execTask list failed, errno:%d", errno);
    SCH_ERR_RET(TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

  *moved = true;

  SCH_TASK_DLOG("task moved to execTask list, numOfTasks:%d", taosHashGetSize(pJob->execTasks));

  return TSDB_CODE_SUCCESS;
}
D
dapan1121 已提交
811
*/
D
dapan1121 已提交
812 813 814 815 816 817 818 819 820 821

int32_t schTaskCheckSetRetry(SSchJob *pJob, SSchTask *pTask, int32_t errCode, bool *needRetry) {
  int8_t status = 0;

  if (schJobNeedToStop(pJob, &status)) {
    *needRetry = false;
    SCH_TASK_DLOG("task no more retry cause of job status, job status:%s", jobTaskStatusStr(status));
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
822 823 824 825 826 827 828 829 830 831
  if (TSDB_CODE_SCH_TIMEOUT_ERROR == errCode) {
    pTask->maxExecTimes++;
    if (pTask->timeoutUsec < SCH_MAX_TASK_TIMEOUT_USEC) {
      pTask->timeoutUsec *= 2;
      if (pTask->timeoutUsec > SCH_MAX_TASK_TIMEOUT_USEC) {
        pTask->timeoutUsec = SCH_MAX_TASK_TIMEOUT_USEC;
      }
    }
  }

D
dapan1121 已提交
832
  if ((pTask->execId + 1) >= pTask->maxExecTimes) {
D
dapan1121 已提交
833
    *needRetry = false;
D
dapan1121 已提交
834
    SCH_TASK_DLOG("task no more retry since reach max try times, execId:%d", pTask->execId);
D
dapan1121 已提交
835 836 837 838 839 840 841 842 843 844
    return TSDB_CODE_SUCCESS;
  }

  if (!NEED_SCHEDULER_RETRY_ERROR(errCode)) {
    *needRetry = false;
    SCH_TASK_DLOG("task no more retry cause of errCode, errCode:%x - %s", errCode, tstrerror(errCode));
    return TSDB_CODE_SUCCESS;
  }

  if (SCH_IS_DATA_SRC_TASK(pTask)) {
D
dapan1121 已提交
845
    if ((pTask->execId + 1) >= SCH_TASK_NUM_OF_EPS(&pTask->plan->execNode)) {
D
dapan1121 已提交
846
      *needRetry = false;
D
dapan1121 已提交
847
      SCH_TASK_DLOG("task no more retry since all ep tried, execId:%d, epNum:%d", pTask->execId,
D
dapan1121 已提交
848 849 850 851 852 853
                    SCH_TASK_NUM_OF_EPS(&pTask->plan->execNode));
      return TSDB_CODE_SUCCESS;
    }
  } else {
    int32_t candidateNum = taosArrayGetSize(pTask->candidateAddrs);

D
dapan1121 已提交
854
    if ((pTask->candidateIdx + 1) >= candidateNum && (TSDB_CODE_SCH_TIMEOUT_ERROR != errCode)) {
D
dapan1121 已提交
855 856 857 858 859 860 861 862
      *needRetry = false;
      SCH_TASK_DLOG("task no more retry since all candiates tried, candidateIdx:%d, candidateNum:%d",
                    pTask->candidateIdx, candidateNum);
      return TSDB_CODE_SUCCESS;
    }
  }

  *needRetry = true;
D
dapan1121 已提交
863
  SCH_TASK_DLOG("task need the %dth retry, errCode:%x - %s", pTask->execId + 1, errCode, tstrerror(errCode));
D
dapan1121 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876 877

  return TSDB_CODE_SUCCESS;
}

int32_t schHandleTaskRetry(SSchJob *pJob, SSchTask *pTask) {
  atomic_sub_fetch_32(&pTask->level->taskLaunchedNum, 1);

  SCH_ERR_RET(schRemoveTaskFromExecList(pJob, pTask));
  SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_NOT_START);
  
  if (SCH_TASK_NEED_FLOW_CTRL(pJob, pTask)) {
    SCH_ERR_RET(schLaunchTasksInFlowCtrlList(pJob, pTask));
  }

D
dapan1121 已提交
878 879
  schDeregisterTaskHb(pJob, pTask);

D
dapan1121 已提交
880 881 882
  if (SCH_IS_DATA_SRC_TASK(pTask)) {
    SCH_SWITCH_EPSET(&pTask->plan->execNode);
  } else {
D
dapan1121 已提交
883 884 885 886
    int32_t candidateNum = taosArrayGetSize(pTask->candidateAddrs);  
    if (++pTask->candidateIdx >= candidateNum) {
      pTask->candidateIdx = 0;
    }
D
dapan1121 已提交
887 888 889 890 891 892 893
  }

  SCH_ERR_RET(schLaunchTask(pJob, pTask));

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
894 895 896
int32_t schSetJobQueryRes(SSchJob* pJob, SQueryResult* pRes) {
  pRes->code = atomic_load_32(&pJob->errCode);
  pRes->numOfRows = pJob->resNumOfRows;
D
dapan1121 已提交
897 898
  pRes->res = pJob->execRes;
  pJob->execRes.res = NULL;
D
dapan1121 已提交
899 900 901 902 903 904 905

  return TSDB_CODE_SUCCESS;
}

int32_t schSetJobFetchRes(SSchJob* pJob, void** pData) {
  int32_t code = 0;
  if (pJob->resData && ((SRetrieveTableRsp *)pJob->resData)->completed) {
D
dapan1121 已提交
906
    SCH_ERR_RET(schUpdateJobStatus(pJob, JOB_TASK_STATUS_SUCCEED));
D
dapan1121 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
  }

  while (true) {
    *pData = atomic_load_ptr(&pJob->resData);
    if (*pData != atomic_val_compare_exchange_ptr(&pJob->resData, *pData, NULL)) {
      continue;
    }

    break;
  }

  if (NULL == *pData) {
    SRetrieveTableRsp *rsp = (SRetrieveTableRsp *)taosMemoryCalloc(1, sizeof(SRetrieveTableRsp));
    if (rsp) {
      rsp->completed = 1;
    }

    *pData = rsp;
    SCH_JOB_DLOG("empty res and set query complete, code:%x", code);
  }

  SCH_JOB_DLOG("fetch done, totalRows:%d", pJob->resNumOfRows);

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
933 934 935 936
int32_t schNotifyUserExecRes(SSchJob* pJob) {
  SQueryResult* pRes = taosMemoryCalloc(1, sizeof(SQueryResult));
  if (pRes) {
    schSetJobQueryRes(pJob, pRes);
D
dapan1121 已提交
937 938
  }

D
dapan1121 已提交
939
  schEndOperation(pJob);
D
dapan1121 已提交
940

D
dapan1121 已提交
941 942 943
  SCH_JOB_DLOG("sch start to invoke exec cb, code: %s", tstrerror(pJob->errCode));
  (*pJob->userRes.execFp)(pRes, pJob->userRes.userParam, atomic_load_32(&pJob->errCode));
  SCH_JOB_DLOG("sch end from query cb, code: %s", tstrerror(pJob->errCode));
D
dapan1121 已提交
944 945 946 947 948 949 950

  return TSDB_CODE_SUCCESS;
}

int32_t schNotifyUserFetchRes(SSchJob* pJob) {
  void* pRes = NULL;
  
D
dapan1121 已提交
951 952 953
  schSetJobFetchRes(pJob, &pRes);

  schEndOperation(pJob);
D
dapan1121 已提交
954

D
dapan1121 已提交
955
  SCH_JOB_DLOG("sch start to invoke fetch cb, code: %s", tstrerror(pJob->errCode));
D
dapan1121 已提交
956
  (*pJob->userRes.fetchFp)(pRes, pJob->userRes.userParam, atomic_load_32(&pJob->errCode));
D
dapan1121 已提交
957
  SCH_JOB_DLOG("sch end from fetch cb, code: %s", tstrerror(pJob->errCode));
D
dapan1121 已提交
958 959 960 961

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
void schPostJobRes(SSchJob *pJob, SCH_OP_TYPE op) {
  if (SCH_OP_NULL == pJob->opStatus.op) {
    SCH_JOB_DLOG("job not in any op, no need to post job res, status:%s", jobTaskStatusStr(pJob->status));
    return;
  }
  
  if (op && pJob->opStatus.op != op) {
    SCH_JOB_ELOG("job in op %s mis-match with expected %s", schGetOpStr(pJob->opStatus.op), schGetOpStr(op));
    return;
  }
  
  if (SCH_JOB_IN_SYNC_OP(pJob)) {
    tsem_post(&pJob->rspSem);
  } else if (SCH_JOB_IN_ASYNC_EXEC_OP(pJob)) {
    schNotifyUserExecRes(pJob);
  } else if (SCH_JOB_IN_ASYNC_FETCH_OP(pJob)) {
    schNotifyUserFetchRes(pJob);
  } else {
    SCH_JOB_ELOG("job not in any operation, status:%s", jobTaskStatusStr(pJob->status));
  }
}

D
dapan1121 已提交
984 985
int32_t schProcessOnJobFailureImpl(SSchJob *pJob, int32_t status, int32_t errCode) {
  // if already FAILED, no more processing
D
dapan1121 已提交
986
  SCH_ERR_RET(schUpdateJobStatus(pJob, status));
D
dapan1121 已提交
987 988

  schUpdateJobErrCode(pJob, errCode);
D
dapan1121 已提交
989
  
D
dapan1121 已提交
990
  int32_t code = atomic_load_32(&pJob->errCode);
D
dapan1121 已提交
991 992 993
  if (code) {
    SCH_JOB_DLOG("job failed with error: %s", tstrerror(code));
  }
D
dapan1121 已提交
994

D
dapan1121 已提交
995
  schPostJobRes(pJob, 0);
D
dapan1121 已提交
996

D
dapan1121 已提交
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
  SCH_RET(code);
}

// Note: no more task error processing, handled in function internal
int32_t schProcessOnJobFailure(SSchJob *pJob, int32_t errCode) {
  SCH_RET(schProcessOnJobFailureImpl(pJob, JOB_TASK_STATUS_FAILED, errCode));
}

// Note: no more error processing, handled in function internal
int32_t schProcessOnJobDropped(SSchJob *pJob, int32_t errCode) {
  SCH_RET(schProcessOnJobFailureImpl(pJob, JOB_TASK_STATUS_DROPPING, errCode));
}

// Note: no more task error processing, handled in function internal
int32_t schProcessOnJobPartialSuccess(SSchJob *pJob) {
  int32_t code = 0;

D
dapan1121 已提交
1014
  SCH_ERR_RET(schUpdateJobStatus(pJob, JOB_TASK_STATUS_PARTIAL_SUCCEED));
D
dapan1121 已提交
1015

D
dapan1121 已提交
1016
  schPostJobRes(pJob, SCH_OP_EXEC);
D
dapan1121 已提交
1017 1018 1019 1020 1021 1022 1023 1024

  return TSDB_CODE_SUCCESS;

_return:

  SCH_RET(schProcessOnJobFailure(pJob, code));
}

D
dapan1121 已提交
1025 1026
void schProcessOnDataFetched(SSchJob *pJob) {
  schPostJobRes(pJob, SCH_OP_FETCH);
D
dapan1121 已提交
1027 1028 1029 1030 1031 1032
}

// Note: no more task error processing, handled in function internal
int32_t schProcessOnTaskFailure(SSchJob *pJob, SSchTask *pTask, int32_t errCode) {
  int8_t status = 0;

D
dapan1121 已提交
1033 1034 1035 1036 1037 1038
  if (errCode == TSDB_CODE_SCH_TIMEOUT_ERROR) {
    SCH_LOG_TASK_WAIT_TS(pTask);
  } else {
    SCH_LOG_TASK_END_TS(pTask);
  }
  
D
dapan1121 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  if (schJobNeedToStop(pJob, &status)) {
    SCH_TASK_DLOG("task failed not processed cause of job status, job status:%s", jobTaskStatusStr(status));
    SCH_RET(atomic_load_32(&pJob->errCode));
  }

  bool    needRetry = false;
  bool    moved = false;
  int32_t taskDone = 0;
  int32_t code = 0;

  SCH_TASK_DLOG("taskOnFailure, code:%s", tstrerror(errCode));

  SCH_ERR_JRET(schTaskCheckSetRetry(pJob, pTask, errCode, &needRetry));

  if (!needRetry) {
    SCH_TASK_ELOG("task failed and no more retry, code:%s", tstrerror(errCode));

D
dapan1121 已提交
1056
    if (SCH_GET_TASK_STATUS(pTask) != JOB_TASK_STATUS_EXECUTING) {
D
dapan1121 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
      SCH_TASK_ELOG("task not in executing list, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
      SCH_ERR_JRET(TSDB_CODE_SCH_STATUS_ERROR);
    }

    SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_FAILED);

    if (SCH_IS_WAIT_ALL_JOB(pJob)) {
      SCH_LOCK(SCH_WRITE, &pTask->level->lock);
      pTask->level->taskFailed++;
      taskDone = pTask->level->taskSucceed + pTask->level->taskFailed;
      SCH_UNLOCK(SCH_WRITE, &pTask->level->lock);

      schUpdateJobErrCode(pJob, errCode);

      if (taskDone < pTask->level->taskNum) {
        SCH_TASK_DLOG("need to wait other tasks, doneNum:%d, allNum:%d", taskDone, pTask->level->taskNum);
        SCH_RET(errCode);
      }
    }
  } else {
    SCH_ERR_JRET(schHandleTaskRetry(pJob, pTask));

    return TSDB_CODE_SUCCESS;
  }

_return:

  SCH_RET(schProcessOnJobFailure(pJob, errCode));
}

int32_t schLaunchNextLevelTasks(SSchJob *pJob, SSchTask *pTask) {
  if (!SCH_IS_QUERY_JOB(pJob)) {
    return TSDB_CODE_SUCCESS;
  }

  SSchLevel *pLevel = pTask->level;
  int32_t doneNum = atomic_add_fetch_32(&pLevel->taskDoneNum, 1);
  if (doneNum == pLevel->taskNum) {
    pJob->levelIdx--;

    pLevel = taosArrayGet(pJob->levels, pJob->levelIdx);
    for (int32_t i = 0; i < pLevel->taskNum; ++i) {
      SSchTask *pTask = taosArrayGet(pLevel->subTasks, i);

      if (pTask->children && taosArrayGetSize(pTask->children) > 0) {
        continue;
      }
      
      SCH_ERR_RET(schLaunchTask(pJob, pTask));
    }
  }

  return TSDB_CODE_SUCCESS;
}


// Note: no more task error processing, handled in function internal
int32_t schProcessOnTaskSuccess(SSchJob *pJob, SSchTask *pTask) {
  bool    moved = false;
  int32_t code = 0;

  SCH_TASK_DLOG("taskOnSuccess, status:%s", SCH_GET_TASK_STATUS_STR(pTask));

D
dapan1121 已提交
1120 1121
  SCH_LOG_TASK_END_TS(pTask);

D
dapan1121 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
  SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_PARTIAL_SUCCEED);

  SCH_ERR_JRET(schRecordTaskSucceedNode(pJob, pTask));

  SCH_ERR_JRET(schLaunchTasksInFlowCtrlList(pJob, pTask));

  int32_t parentNum = pTask->parents ? (int32_t)taosArrayGetSize(pTask->parents) : 0;
  if (parentNum == 0) {
    int32_t taskDone = 0;
    if (SCH_IS_WAIT_ALL_JOB(pJob)) {
      SCH_LOCK(SCH_WRITE, &pTask->level->lock);
      pTask->level->taskSucceed++;
      taskDone = pTask->level->taskSucceed + pTask->level->taskFailed;
      SCH_UNLOCK(SCH_WRITE, &pTask->level->lock);

      if (taskDone < pTask->level->taskNum) {
        SCH_TASK_DLOG("wait all tasks, done:%d, all:%d", taskDone, pTask->level->taskNum);
        return TSDB_CODE_SUCCESS;
      } else if (taskDone > pTask->level->taskNum) {
        SCH_TASK_ELOG("taskDone number invalid, done:%d, total:%d", taskDone, pTask->level->taskNum);
      }

      if (pTask->level->taskFailed > 0) {
        SCH_RET(schProcessOnJobFailure(pJob, 0));
      } else {
        SCH_RET(schProcessOnJobPartialSuccess(pJob));
      }
    } else {
      pJob->resNode = pTask->succeedAddr;
    }

    pJob->fetchTask = pTask;

    SCH_RET(schProcessOnJobPartialSuccess(pJob));
  }

  /*
    if (SCH_IS_DATA_SRC_TASK(task) && job->dataSrcEps.numOfEps < SCH_MAX_CANDIDATE_EP_NUM) {
      strncpy(job->dataSrcEps.fqdn[job->dataSrcEps.numOfEps], task->execAddr.fqdn, sizeof(task->execAddr.fqdn));
      job->dataSrcEps.port[job->dataSrcEps.numOfEps] = task->execAddr.port;

      ++job->dataSrcEps.numOfEps;
    }
  */

  for (int32_t i = 0; i < parentNum; ++i) {
1168 1169
    SSchTask *parent = *(SSchTask **)taosArrayGet(pTask->parents, i);
    int32_t   readyNum = atomic_add_fetch_32(&parent->childReady, 1);
D
dapan1121 已提交
1170

1171
    SCH_LOCK(SCH_WRITE, &parent->lock);
D
dapan1121 已提交
1172 1173 1174
    SDownstreamSourceNode source = {.type = QUERY_NODE_DOWNSTREAM_SOURCE,
                                    .taskId = pTask->taskId,
                                    .schedId = schMgmt.sId,
D
dapan1121 已提交
1175
                                    .execId = pTask->execId,
D
dapan1121 已提交
1176
                                    .addr = pTask->succeedAddr};
1177 1178
    qSetSubplanExecutionNode(parent->plan, pTask->plan->id.groupId, &source);
    SCH_UNLOCK(SCH_WRITE, &parent->lock);
D
dapan1121 已提交
1179

1180
    if (SCH_TASK_READY_FOR_LAUNCH(readyNum, parent)) {
D
dapan1121 已提交
1181
      SCH_TASK_DLOG("all %d children task done, start to launch parent task 0x%" PRIx64, readyNum, parent->taskId);
1182
      SCH_ERR_RET(schLaunchTask(pJob, parent));
D
dapan1121 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    }
  }

  SCH_ERR_RET(schLaunchNextLevelTasks(pJob, pTask));

  return TSDB_CODE_SUCCESS;

_return:

  SCH_RET(schProcessOnJobFailure(pJob, code));
}

// Note: no more error processing, handled in function internal
int32_t schFetchFromRemote(SSchJob *pJob) {
  int32_t code = 0;

  void *resData = atomic_load_ptr(&pJob->resData);
  if (resData) {
    SCH_JOB_DLOG("res already fetched, res:%p", resData);
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
1205
  SCH_ERR_JRET(schBuildAndSendMsg(pJob, pJob->fetchTask, &pJob->resNode, TDMT_SCH_FETCH));
D
dapan1121 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

  return TSDB_CODE_SUCCESS;

_return:

  SCH_RET(schProcessOnTaskFailure(pJob, pJob->fetchTask, code));
}

int32_t schProcessOnExplainDone(SSchJob *pJob, SSchTask *pTask, SRetrieveTableRsp *pRsp) {
  SCH_TASK_DLOG("got explain rsp, rows:%d, complete:%d", htonl(pRsp->numOfRows), pRsp->completed);

  atomic_store_32(&pJob->resNumOfRows, htonl(pRsp->numOfRows));
  atomic_store_ptr(&pJob->resData, pRsp);

  SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_SUCCEED);

  schProcessOnDataFetched(pJob);

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
void schDropTaskOnExecNode(SSchJob *pJob, SSchTask *pTask) {
  if (NULL == pTask->execNodes) {
    SCH_TASK_DLOG("no exec address, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
    return;
  }

  int32_t size = (int32_t)taosHashGetSize(pTask->execNodes);

  if (size <= 0) {
    SCH_TASK_DLOG("task has no execNodes, no need to drop it, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
    return;
  }

  SSchNodeInfo *nodeInfo = taosHashIterate(pTask->execNodes, NULL);
  while (nodeInfo) {
    SCH_SET_TASK_HANDLE(pTask, nodeInfo->handle);

D
dapan1121 已提交
1244
    schBuildAndSendMsg(pJob, pTask, &nodeInfo->addr, TDMT_SCH_DROP_TASK);
D
dapan1121 已提交
1245 1246 1247 1248

    nodeInfo = taosHashIterate(pTask->execNodes, nodeInfo);
  }

D
dapan1121 已提交
1249
  SCH_TASK_DLOG("task has been dropped on %d exec nodes", size);
D
dapan1121 已提交
1250 1251 1252
}


D
dapan1121 已提交
1253 1254 1255 1256 1257
int32_t schRescheduleTask(SSchJob *pJob, SSchTask *pTask) {
  if (SCH_IS_DATA_SRC_QRY_TASK(pTask)) {
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
1258
  SCH_LOCK_TASK(pTask);
D
dapan1121 已提交
1259 1260
  if (SCH_TASK_TIMEOUT(pTask) && JOB_TASK_STATUS_EXECUTING == pTask->status && 
      pJob->fetchTask != pTask && taosArrayGetSize(pTask->candidateAddrs) > 1) {
D
dapan1121 已提交
1261
    SCH_TASK_DLOG("task execId %d will be rescheduled now", pTask->execId);
D
dapan1121 已提交
1262 1263 1264 1265 1266 1267 1268
    schDropTaskOnExecNode(pJob, pTask);
    taosHashClear(pTask->execNodes);
    schProcessOnTaskFailure(pJob, pTask, TSDB_CODE_SCH_TIMEOUT_ERROR);
  }
  SCH_UNLOCK_TASK(pTask);

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
}

int32_t schProcessOnTaskStatusRsp(SQueryNodeEpId* pEpId, SArray* pStatusList) {
  int32_t taskNum = (int32_t)taosArrayGetSize(pStatusList);
  SSchTask *pTask = NULL;

  qDebug("%d task status in hb rsp from nodeId:%d, fqdn:%s, port:%d", taskNum, pEpId->nodeId, pEpId->ep.fqdn, pEpId->ep.port);

  for (int32_t i = 0; i < taskNum; ++i) {
    STaskStatus *taskStatus = taosArrayGet(pStatusList, i);

D
dapan1121 已提交
1280 1281 1282
    qDebug("QID:%" PRIx64 ",TID:0x%" PRIx64 ",EID:%d task status in server: %s", 
      taskStatus->queryId, taskStatus->taskId, taskStatus->execId, jobTaskStatusStr(taskStatus->status));

D
dapan1121 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    SSchJob *pJob = schAcquireJob(taskStatus->refId);
    if (NULL == pJob) {
      qWarn("job not found, refId:0x%" PRIx64 ",QID:0x%" PRIx64 ",TID:0x%" PRIx64, taskStatus->refId,
            taskStatus->queryId, taskStatus->taskId);
      // TODO DROP TASK FROM SERVER!!!!
      continue;
    }

    pTask = NULL;
    schGetTaskInJob(pJob, taskStatus->taskId, &pTask);
    if (NULL == pTask) {
      // TODO DROP TASK FROM SERVER!!!!
      schReleaseJob(taskStatus->refId);
      continue;
    }
D
dapan1121 已提交
1298 1299 1300 1301 1302 1303 1304

    if (taskStatus->execId != pTask->execId) {
      // TODO DROP TASK FROM SERVER!!!!
      SCH_TASK_DLOG("EID %d in hb rsp mis-match", taskStatus->execId);
      schReleaseJob(taskStatus->refId);
      continue;      
    }
D
dapan1121 已提交
1305 1306 1307 1308 1309 1310 1311
    
    if (taskStatus->status == JOB_TASK_STATUS_FAILED) {
      // RECORD AND HANDLE ERROR!!!!
      schReleaseJob(taskStatus->refId);
      continue;
    }

D
dapan1121 已提交
1312
    if (taskStatus->status == JOB_TASK_STATUS_NOT_START) {
D
dapan1121 已提交
1313 1314 1315 1316 1317 1318
      schRescheduleTask(pJob, pTask);
    }

    schReleaseJob(taskStatus->refId);
  }

D
dapan1121 已提交
1319
  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
1320 1321 1322
}


D
dapan1121 已提交
1323
int32_t schSaveJobQueryRes(SSchJob *pJob, SQueryTableRsp *rsp) {
D
dapan1121 已提交
1324
  if (rsp->tbFName[0]) {
D
dapan1121 已提交
1325 1326 1327
    if (NULL == pJob->execRes.res) {
      pJob->execRes.res = taosArrayInit(pJob->taskNum, sizeof(STbVerInfo));
      if (NULL == pJob->execRes.res) {
D
dapan1121 已提交
1328 1329 1330 1331 1332 1333 1334 1335 1336
        SCH_ERR_RET(TSDB_CODE_OUT_OF_MEMORY);
      }
    }

    STbVerInfo tbInfo;
    strcpy(tbInfo.tbFName, rsp->tbFName);
    tbInfo.sversion = rsp->sversion;
    tbInfo.tversion = rsp->tversion;

D
dapan1121 已提交
1337
    taosArrayPush((SArray *)pJob->execRes.res, &tbInfo);
D
dapan1121 已提交
1338
    pJob->execRes.msgType = TDMT_SCH_QUERY;
D
dapan1121 已提交
1339 1340 1341 1342 1343
  }

  return TSDB_CODE_SUCCESS;
}

1344
int32_t schGetTaskFromList(SHashObj *pTaskList, uint64_t taskId, SSchTask **pTask) {
D
dapan1121 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
  int32_t s = taosHashGetSize(pTaskList);
  if (s <= 0) {
    return TSDB_CODE_SUCCESS;
  }

  SSchTask **task = taosHashGet(pTaskList, &taskId, sizeof(taskId));
  if (NULL == task || NULL == (*task)) {
    return TSDB_CODE_SUCCESS;
  }

  *pTask = *task;

  return TSDB_CODE_SUCCESS;
}

1360
int32_t schGetTaskInJob(SSchJob *pJob, uint64_t taskId, SSchTask **pTask) {
D
dapan1121 已提交
1361
  schGetTaskFromList(pJob->taskList, taskId, pTask);
1362
  if (NULL == *pTask) {
D
dapan1121 已提交
1363
    SCH_JOB_ELOG("task not found in job task list, taskId:0x%" PRIx64, taskId);
D
dapan1121 已提交
1364
    SCH_ERR_RET(TSDB_CODE_SCH_INTERNAL_ERROR);
1365 1366 1367 1368 1369
  }

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
1370 1371 1372 1373 1374
int32_t schLaunchTaskImpl(SSchJob *pJob, SSchTask *pTask) {
  int8_t  status = 0;
  int32_t code = 0;

  atomic_add_fetch_32(&pTask->level->taskLaunchedNum, 1);
D
dapan1121 已提交
1375
  pTask->execId++;
D
dapan1121 已提交
1376

D
dapan1121 已提交
1377
  SCH_TASK_DLOG("start to launch task's %dth exec", pTask->execId);
D
dapan1121 已提交
1378

D
dapan1121 已提交
1379 1380
  SCH_LOG_TASK_START_TS(pTask);

D
dapan1121 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
  if (schJobNeedToStop(pJob, &status)) {
    SCH_TASK_DLOG("no need to launch task cause of job status, job status:%s", jobTaskStatusStr(status));

    SCH_RET(atomic_load_32(&pJob->errCode));
  }

  // NOTE: race condition: the task should be put into the hash table before send msg to server
  if (SCH_GET_TASK_STATUS(pTask) != JOB_TASK_STATUS_EXECUTING) {
    SCH_ERR_RET(schPushTaskToExecList(pJob, pTask));
    SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_EXECUTING);
  }

  SSubplan *plan = pTask->plan;

  if (NULL == pTask->msg) {  // TODO add more detailed reason for failure
    code = qSubPlanToString(plan, &pTask->msg, &pTask->msgLen);
    if (TSDB_CODE_SUCCESS != code) {
      SCH_TASK_ELOG("failed to create physical plan, code:%s, msg:%p, len:%d", tstrerror(code), pTask->msg,
                    pTask->msgLen);
      SCH_ERR_RET(code);
    } else {
      SCH_TASK_DLOGL("physical plan len:%d, %s", pTask->msgLen, pTask->msg);
    }
  }

  SCH_ERR_RET(schSetTaskCandidateAddrs(pJob, pTask));

  if (SCH_IS_QUERY_JOB(pJob)) {
    SCH_ERR_RET(schEnsureHbConnection(pJob, pTask));
  }

  SCH_ERR_RET(schBuildAndSendMsg(pJob, pTask, NULL, plan->msgType));

  return TSDB_CODE_SUCCESS;
}

// Note: no more error processing, handled in function internal
int32_t schLaunchTask(SSchJob *pJob, SSchTask *pTask) {
  bool    enough = false;
  int32_t code = 0;

  SCH_SET_TASK_HANDLE(pTask, NULL);

  if (SCH_TASK_NEED_FLOW_CTRL(pJob, pTask)) {
    SCH_ERR_JRET(schCheckIncTaskFlowQuota(pJob, pTask, &enough));

    if (enough) {
      SCH_ERR_JRET(schLaunchTaskImpl(pJob, pTask));
    }
  } else {
    SCH_ERR_JRET(schLaunchTaskImpl(pJob, pTask));
  }

  return TSDB_CODE_SUCCESS;

_return:

  SCH_RET(schProcessOnTaskFailure(pJob, pTask, code));
}

int32_t schLaunchLevelTasks(SSchJob *pJob, SSchLevel *level) {
  for (int32_t i = 0; i < level->taskNum; ++i) {
    SSchTask *pTask = taosArrayGet(level->subTasks, i);

    SCH_ERR_RET(schLaunchTask(pJob, pTask));
  }

  return TSDB_CODE_SUCCESS;
}

int32_t schLaunchJob(SSchJob *pJob) {
  SSchLevel *level = taosArrayGet(pJob->levels, pJob->levelIdx);

  SCH_ERR_RET(schChkJobNeedFlowCtrl(pJob, level));

  SCH_ERR_RET(schLaunchLevelTasks(pJob, level));

  return TSDB_CODE_SUCCESS;
}


void schDropTaskInHashList(SSchJob *pJob, SHashObj *list) {
  if (!SCH_IS_NEED_DROP_JOB(pJob)) {
    return;
  }

  void *pIter = taosHashIterate(list, NULL);
  while (pIter) {
    SSchTask *pTask = *(SSchTask **)pIter;

    schDropTaskOnExecNode(pJob, pTask);

    pIter = taosHashIterate(list, pIter);
  }
}

void schDropJobAllTasks(SSchJob *pJob) {
  schDropTaskInHashList(pJob, pJob->execTasks);
D
dapan1121 已提交
1479 1480
//  schDropTaskInHashList(pJob, pJob->succTasks);
//  schDropTaskInHashList(pJob, pJob->failTasks);
D
dapan1121 已提交
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
}

int32_t schCancelJob(SSchJob *pJob) {
  // TODO
  return TSDB_CODE_SUCCESS;
  // TODO MOVE ALL TASKS FROM EXEC LIST TO FAIL LIST
}

void schFreeJobImpl(void *job) {
  if (NULL == job) {
    return;
  }

  SSchJob *pJob = job;
  uint64_t queryId = pJob->queryId;
  int64_t  refId = pJob->refId;

  if (pJob->status == JOB_TASK_STATUS_EXECUTING) {
    schCancelJob(pJob);
  }

  schDropJobAllTasks(pJob);

  int32_t numOfLevels = taosArrayGetSize(pJob->levels);
  for (int32_t i = 0; i < numOfLevels; ++i) {
    SSchLevel *pLevel = taosArrayGet(pJob->levels, i);

    int32_t numOfTasks = taosArrayGetSize(pLevel->subTasks);
    for (int32_t j = 0; j < numOfTasks; ++j) {
      SSchTask *pTask = taosArrayGet(pLevel->subTasks, j);
D
dapan1121 已提交
1511
      schFreeTask(pJob, pTask);
D
dapan1121 已提交
1512 1513 1514 1515 1516 1517 1518 1519
    }

    taosArrayDestroy(pLevel->subTasks);
  }

  schFreeFlowCtrl(pJob);

  taosHashCleanup(pJob->execTasks);
D
dapan1121 已提交
1520 1521
//  taosHashCleanup(pJob->failTasks);
//  taosHashCleanup(pJob->succTasks);
D
dapan1121 已提交
1522 1523
  taosHashCleanup(pJob->taskList);
  
D
dapan1121 已提交
1524 1525 1526 1527 1528 1529
  taosArrayDestroy(pJob->levels);
  taosArrayDestroy(pJob->nodeList);
  taosArrayDestroy(pJob->dataSrcTasks);

  qExplainFreeCtx(pJob->explainCtx);

D
dapan1121 已提交
1530
  destroyQueryExecRes(&pJob->execRes);
D
dapan1121 已提交
1531

D
dapan1121 已提交
1532 1533
  qDestroyQueryPlan(pJob->pDag);

D
dapan1121 已提交
1534
  taosMemoryFreeClear(pJob->userRes.queryRes);
D
dapan1121 已提交
1535
  taosMemoryFreeClear(pJob->resData);
D
dapan1121 已提交
1536
  taosMemoryFree(pJob);
D
dapan1121 已提交
1537

D
dapan1121 已提交
1538
  qDebug("QID:0x%" PRIx64 " sch job freed, refId:0x%" PRIx64 ", pointer:%p", queryId, refId, pJob);
D
dapan1121 已提交
1539

D
dapan1121 已提交
1540 1541 1542 1543
  int32_t jobNum = atomic_sub_fetch_32(&schMgmt.jobNum, 1);
  if (jobNum == 0) {
    schCloseJobRef();
  }
D
dapan1121 已提交
1544 1545
}

D
dapan1121 已提交
1546
int32_t schLaunchStaticExplainJob(SSchedulerReq *pReq, SSchJob *pJob, bool sync) {
D
dapan1121 已提交
1547
  qDebug("QID:0x%" PRIx64 " job started", pReq->pDag->queryId);
D
dapan1121 已提交
1548 1549

  int32_t  code = 0;
D
dapan1121 已提交
1550
/*  
D
dapan1121 已提交
1551 1552
  SSchJob *pJob = taosMemoryCalloc(1, sizeof(SSchJob));
  if (NULL == pJob) {
D
dapan1121 已提交
1553
    qError("QID:0x%" PRIx64 " calloc %d failed", pReq->pDag->queryId, (int32_t)sizeof(SSchJob));
D
dapan1121 已提交
1554 1555 1556
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    pReq->fp(NULL, pReq->cbParam, code);
    SCH_ERR_RET(code);
D
dapan1121 已提交
1557 1558
  }

D
dapan1121 已提交
1559
  pJob->sql = pReq->sql;
D
dapan1121 已提交
1560
  pJob->reqKilled = pReq->reqKilled;
D
dapan1121 已提交
1561
  pJob->pDag = pReq->pDag;
D
dapan1121 已提交
1562
  pJob->attr.queryJob = true;
D
dapan1121 已提交
1563 1564 1565 1566
  pJob->attr.explainMode = pReq->pDag->explainInfo.mode;
  pJob->queryId = pReq->pDag->queryId;
  pJob->userRes.execFp = pReq->fp;
  pJob->userRes.userParam = pReq->cbParam;
D
dapan1121 已提交
1567 1568
  
  schUpdateJobStatus(pJob, JOB_TASK_STATUS_NOT_START);
D
dapan1121 已提交
1569 1570 1571 1572

  code = schBeginOperation(pJob, SCH_OP_EXEC, sync);
  if (code) {
    pReq->fp(NULL, pReq->cbParam, code);
D
dapan1121 已提交
1573
    schFreeJobImpl(pJob);
D
dapan1121 已提交
1574 1575
    SCH_ERR_RET(code);
  }
D
dapan1121 已提交
1576 1577
*/

D
dapan1121 已提交
1578
  SCH_ERR_JRET(qExecStaticExplain(pReq->pDag, (SRetrieveTableRsp **)&pJob->resData));
D
dapan1121 已提交
1579

D
dapan1121 已提交
1580
/*
D
dapan1121 已提交
1581 1582 1583 1584 1585 1586 1587
  int64_t refId = taosAddRef(schMgmt.jobRef, pJob);
  if (refId < 0) {
    SCH_JOB_ELOG("taosAddRef job failed, error:%s", tstrerror(terrno));
    SCH_ERR_JRET(terrno);
  }

  if (NULL == schAcquireJob(refId)) {
D
dapan1121 已提交
1588
    SCH_JOB_ELOG("schAcquireJob job failed, refId:0x%" PRIx64, refId);
D
dapan1121 已提交
1589
    SCH_ERR_JRET(TSDB_CODE_SCH_STATUS_ERROR);
D
dapan1121 已提交
1590 1591 1592 1593
  }

  pJob->refId = refId;

D
dapan1121 已提交
1594
  SCH_JOB_DLOG("job refId:0x%" PRIx64, pJob->refId);
D
dapan1121 已提交
1595
*/
D
dapan1121 已提交
1596 1597

  pJob->status = JOB_TASK_STATUS_PARTIAL_SUCCEED;
D
dapan1121 已提交
1598
  
D
dapan1121 已提交
1599
  SCH_JOB_DLOG("job exec done, job status:%s", SCH_GET_JOB_STATUS_STR(pJob));
D
dapan1121 已提交
1600 1601 1602 1603 1604
  
  if (!sync) {
    schPostJobRes(pJob, SCH_OP_EXEC);
  } else {
    schEndOperation(pJob);
D
dapan1121 已提交
1605 1606
  }

D
dapan1121 已提交
1607
//  schReleaseJob(pJob->refId);
D
dapan1121 已提交
1608

D
dapan1121 已提交
1609
  SCH_RET(code);
D
dapan1121 已提交
1610 1611 1612

_return:

D
dapan1121 已提交
1613 1614
  schEndOperation(pJob);
  if (!sync) {
D
dapan1121 已提交
1615
    pReq->execFp(NULL, pReq->execParam, code);
D
dapan1121 已提交
1616 1617
  }
  
D
dapan1121 已提交
1618
  schFreeJobImpl(pJob);
D
dapan1121 已提交
1619
  
D
dapan1121 已提交
1620 1621 1622
  SCH_RET(code);
}

D
dapan1121 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
int32_t schFetchRows(SSchJob *pJob) {
  int32_t  code = 0;

  if (!(pJob->attr.explainMode == EXPLAIN_MODE_STATIC)) {
    SCH_ERR_JRET(schFetchFromRemote(pJob));
    tsem_wait(&pJob->rspSem);
  }

  SCH_ERR_JRET(schSetJobFetchRes(pJob, pJob->userRes.fetchRes));

_return:

D
dapan1121 已提交
1635
  schEndOperation(pJob);
D
dapan1121 已提交
1636 1637 1638 1639 1640 1641 1642 1643

  SCH_RET(code);
}

int32_t schAsyncFetchRows(SSchJob *pJob) {
  int32_t  code = 0;

  if (pJob->attr.explainMode == EXPLAIN_MODE_STATIC) {
D
dapan1121 已提交
1644 1645
    schPostJobRes(pJob, SCH_OP_FETCH);
    return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
1646
  }
D
dapan1121 已提交
1647 1648
  
  SCH_ERR_RET(schFetchFromRemote(pJob));
D
dapan1121 已提交
1649 1650 1651 1652

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
1653

D
dapan1121 已提交
1654 1655 1656 1657 1658 1659 1660 1661
int32_t schExecJobImpl(SSchedulerReq *pReq, SSchJob *pJob, bool sync) {
  int32_t  code = 0;

  qDebug("QID:0x%" PRIx64 " sch job refId 0x%"PRIx64 " started", pReq->pDag->queryId, pJob->refId);

  SCH_ERR_JRET(schBeginOperation(pJob, SCH_OP_EXEC, sync));

  if (EXPLAIN_MODE_STATIC == pReq->pDag->explainInfo.mode) {
D
dapan1121 已提交
1662
    code = schLaunchStaticExplainJob(pReq, pJob, sync);
D
dapan1121 已提交
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
  } else {
    code = schLaunchJob(pJob);
    if (sync) {
      SCH_JOB_DLOG("will wait for rsp now, job status:%s", SCH_GET_JOB_STATUS_STR(pJob));
      tsem_wait(&pJob->rspSem);
      
      schEndOperation(pJob);
    } else if (code) {
      schPostJobRes(pJob, SCH_OP_EXEC);
    }
  }

  SCH_JOB_DLOG("job exec done, job status:%s, jobId:0x%" PRIx64, SCH_GET_JOB_STATUS_STR(pJob), pJob->refId);
  
  SCH_RET(code);

_return:

  if (!sync) {
D
dapan1121 已提交
1682
    pReq->execFp(NULL, pReq->execParam, code);
D
dapan1121 已提交
1683 1684 1685 1686 1687
  }
  
  SCH_RET(code);
}

D
dapan1121 已提交
1688
int32_t schDoTaskRedirect(SSchJob *pJob, SSchTask *pTask, SDataBuf* pData, int32_t rspCode) {
D
dapan1121 已提交
1689
  int32_t code = 0;
D
dapan1121 已提交
1690 1691 1692 1693 1694
  int8_t  status = 0;
  if (schJobNeedToStop(pJob, &status)) {
    SCH_TASK_ELOG("redirect will no continue cause of job status %s", jobTaskStatusStr(status));
    SCH_RET(atomic_load_32(&pJob->errCode));
  }
D
dapan1121 已提交
1695
  
D
dapan1121 已提交
1696 1697
  if ((pTask->execId + 1) >= pTask->maxExecTimes) {
    SCH_TASK_DLOG("task no more retry since reach max try times, execId:%d", pTask->execId);
D
dapan1121 已提交
1698 1699 1700 1701
    schProcessOnJobFailure(pJob, rspCode);
    return TSDB_CODE_SUCCESS;
  }

D
dapan1121 已提交
1702
  SCH_TASK_DLOG("task will be redirected now, status:%s", SCH_GET_TASK_STATUS_STR(pTask));
D
dapan1121 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
  
  schDropTaskOnExecNode(pJob, pTask);
  taosHashClear(pTask->execNodes);
  SCH_ERR_JRET(schRemoveTaskFromExecList(pJob, pTask));
  schDeregisterTaskHb(pJob, pTask);
  atomic_sub_fetch_32(&pTask->level->taskLaunchedNum, 1);
  taosMemoryFreeClear(pTask->msg);
  pTask->msgLen = 0;
  pTask->lastMsgType = 0;
  memset(&pTask->succeedAddr, 0, sizeof(pTask->succeedAddr));

  if (SCH_IS_DATA_SRC_QRY_TASK(pTask)) {
D
dapan1121 已提交
1715 1716 1717 1718
    if (pData) {
      SCH_ERR_JRET(schUpdateTaskCandidateAddr(pJob, pTask, pData->pEpSet));
    }
  
D
dapan1121 已提交
1719 1720 1721 1722 1723
    if (SCH_TASK_NEED_FLOW_CTRL(pJob, pTask)) {
      if (JOB_TASK_STATUS_EXECUTING == SCH_GET_TASK_STATUS(pTask)) {
        SCH_ERR_JRET(schLaunchTasksInFlowCtrlList(pJob, pTask));
      }
    }    
D
dapan1121 已提交
1724 1725

    SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_NOT_START);
D
dapan1121 已提交
1726
    
D
dapan1121 已提交
1727 1728 1729
    SCH_ERR_JRET(schLaunchTask(pJob, pTask));

    return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
1730 1731
  }

D
dapan1121 已提交
1732 1733 1734 1735

  // merge plan
  
  pTask->childReady = 0;
D
dapan1121 已提交
1736
  
D
dapan1121 已提交
1737
  qClearSubplanExecutionNode(pTask->plan);
D
dapan1121 已提交
1738

D
dapan1121 已提交
1739 1740 1741 1742 1743 1744
  SCH_SET_TASK_STATUS(pTask, JOB_TASK_STATUS_NOT_START);
  
  int32_t childrenNum = taosArrayGetSize(pTask->children);
  for (int32_t i = 0; i < childrenNum; ++i) {
    SSchTask* pChild = taosArrayGetP(pTask->children, i);
    SCH_LOCK_TASK(pChild);
D
dapan1121 已提交
1745
    schDoTaskRedirect(pJob, pChild, NULL, rspCode);
D
dapan1121 已提交
1746 1747
    SCH_UNLOCK_TASK(pChild);
  }
D
dapan1121 已提交
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757

  return TSDB_CODE_SUCCESS;

_return:

  code = schProcessOnTaskFailure(pJob, pTask, code);

  SCH_RET(code);  
}

D
dapan1121 已提交
1758
int32_t schHandleRedirect(SSchJob *pJob, SSchTask *pTask, SDataBuf* pData, int32_t rspCode) {
D
dapan1121 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767
  int32_t code = 0;

  if (SCH_IS_DATA_SRC_QRY_TASK(pTask)) {
    if (NULL == pData->pEpSet) {
      SCH_TASK_ELOG("no epset updated while got error %s", tstrerror(rspCode));
      SCH_ERR_JRET(rspCode);
    }
  }

D
dapan1121 已提交
1768
  SCH_RET(schDoTaskRedirect(pJob, pTask, pData, rspCode));
D
dapan1121 已提交
1769 1770 1771 1772 1773 1774 1775 1776

_return:

  schProcessOnTaskFailure(pJob, pTask, code);
  
  SCH_RET(code);
}

D
dapan1121 已提交
1777 1778