streamRecover.c 33.3 KB
Newer Older
L
Liu Jicong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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/>.
 */

16
#include "streamInt.h"
17
#include "ttimer.h"
18 19
#include "wal.h"

20 21
typedef struct SStreamTaskRetryInfo {
  SStreamMeta* pMeta;
22 23
  int32_t      taskId;
  int64_t      streamId;
24 25 26 27 28 29
} SStreamTaskRetryInfo;

static int32_t streamSetParamForScanHistory(SStreamTask* pTask);
static void    launchFillHistoryTask(SStreamTask* pTask);
static void    streamTaskSetRangeStreamCalc(SStreamTask* pTask);
static int32_t initScanHistoryReq(SStreamTask* pTask, SStreamScanHistoryReq* pReq, int8_t igUntreated);
30

31
static void streamTaskSetReady(SStreamTask* pTask, int32_t numOfReqs) {
32 33 34
  ASSERT(pTask->status.downstreamReady == 0);
  pTask->status.downstreamReady = 1;

35
  int64_t el = (taosGetTimestampMs() - pTask->tsInfo.init);
36
  qDebug("s-task:%s all %d downstream ready, init completed, elapsed time:%dms, task status:%s",
H
Haojun Liao 已提交
37
         pTask->id.idStr, numOfReqs, (int32_t) el, streamGetTaskStatusStr(pTask->status.taskStatus));
38 39
}

40
int32_t streamStartScanHistoryAsync(SStreamTask* pTask, int8_t igUntreated) {
L
liuyao 已提交
41
  SStreamScanHistoryReq req;
42
  initScanHistoryReq(pTask, &req, igUntreated);
L
liuyao 已提交
43

44
  int32_t len = sizeof(SStreamScanHistoryReq);
L
liuyao 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  void* serializedReq = rpcMallocCont(len);
  if (serializedReq == NULL) {
    return -1;
  }

  memcpy(serializedReq, &req, len);

  SRpcMsg rpcMsg = {.contLen = len, .pCont = serializedReq, .msgType = TDMT_VND_STREAM_SCAN_HISTORY};
  if (tmsgPutToQueue(pTask->pMsgCb, STREAM_QUEUE, &rpcMsg) < 0) {
    /*ASSERT(0);*/
  }

  return 0;
}

60 61 62
const char* streamGetTaskStatusStr(int32_t status) {
  switch(status) {
    case TASK_STATUS__NORMAL: return "normal";
63
    case TASK_STATUS__SCAN_HISTORY: return "scan-history";
64
    case TASK_STATUS__HALT: return "halt";
65
    case TASK_STATUS__PAUSE: return "paused";
66
    case TASK_STATUS__DROPPING: return "dropping";
67 68 69
    default:return "";
  }
}
70

71 72
static int32_t doLaunchScanHistoryTask(SStreamTask* pTask) {
  SVersionRange* pRange = &pTask->dataRange.range;
L
liuyao 已提交
73 74 75
  if (pTask->info.fillHistory) {
    streamSetParamForScanHistory(pTask);
  }
76

77 78
  streamSetParamForStreamScannerStep1(pTask, pRange, &pTask->dataRange.window);
  int32_t code = streamStartScanHistoryAsync(pTask, 0);
L
liuyao 已提交
79
  return code;
80
}
81

82 83 84
int32_t streamTaskLaunchScanHistory(SStreamTask* pTask) {
  if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
    if (pTask->status.taskStatus == TASK_STATUS__SCAN_HISTORY) {
85
      return doLaunchScanHistoryTask(pTask);
86 87 88 89 90 91
    } else {
      ASSERT(pTask->status.taskStatus == TASK_STATUS__NORMAL);
      qDebug("s-task:%s no need to scan-history-data, status:%s, sched-status:%d, ver:%" PRId64, pTask->id.idStr,
             streamGetTaskStatusStr(pTask->status.taskStatus), pTask->status.schedStatus,
             walReaderGetCurrentVer(pTask->exec.pWalReader));
    }
92
  } else if (pTask->info.taskLevel == TASK_LEVEL__AGG) {
L
liuyao 已提交
93 94 95
    if (pTask->info.fillHistory) {
      streamSetParamForScanHistory(pTask);
    }
96
    streamTaskEnablePause(pTask);
97
    streamTaskScanHistoryPrepare(pTask);
98
  } else if (pTask->info.taskLevel == TASK_LEVEL__SINK) {
99
    qDebug("s-task:%s sink task do nothing to handle scan-history", pTask->id.idStr);
100
    streamTaskScanHistoryPrepare(pTask);
101 102 103 104
  }
  return 0;
}

105
// check status
106
int32_t streamTaskDoCheckDownstreamTasks(SStreamTask* pTask) {
107
  SHistDataRange* pRange = &pTask->dataRange;
108
  STimeWindow*    pWindow = &pRange->window;
109

110
  SStreamTaskCheckReq req = {
111 112
      .streamId = pTask->id.streamId,
      .upstreamTaskId = pTask->id.taskId,
113 114
      .upstreamNodeId = pTask->info.nodeId,
      .childId = pTask->info.selfChildId,
115
  };
116

117
  // serialize
118
  if (pTask->outputInfo.type == TASK_OUTPUT__FIXED_DISPATCH) {
119 120 121 122 123
    req.reqId = tGenIdPI64();
    req.downstreamNodeId = pTask->fixedEpDispatcher.nodeId;
    req.downstreamTaskId = pTask->fixedEpDispatcher.taskId;
    pTask->checkReqId = req.reqId;

124 125 126 127 128
    qDebug("s-task:%s check single downstream task:0x%x(vgId:%d) ver:%" PRId64 "-%" PRId64 " window:%" PRId64
           "-%" PRId64 ", req:0x%" PRIx64,
           pTask->id.idStr, req.downstreamTaskId, req.downstreamNodeId, pRange->range.minVer, pRange->range.maxVer,
           pWindow->skey, pWindow->ekey, req.reqId);

129
    streamDispatchCheckMsg(pTask, &req, pTask->fixedEpDispatcher.nodeId, &pTask->fixedEpDispatcher.epSet);
130
  } else if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
131
    SArray* vgInfo = pTask->shuffleDispatcher.dbInfo.pVgroupInfos;
132

133
    int32_t numOfVgs = taosArrayGetSize(vgInfo);
134
    pTask->notReadyTasks = numOfVgs;
135
    pTask->checkReqIds = taosArrayInit(numOfVgs, sizeof(int64_t));
136

137 138 139
    qDebug("s-task:%s check %d downstream tasks, ver:%" PRId64 "-%" PRId64 " window:%" PRId64 "-%" PRId64,
           pTask->id.idStr, numOfVgs, pRange->range.minVer, pRange->range.maxVer, pWindow->skey, pWindow->ekey);

140
    for (int32_t i = 0; i < numOfVgs; i++) {
141 142 143 144 145
      SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, i);
      req.reqId = tGenIdPI64();
      taosArrayPush(pTask->checkReqIds, &req.reqId);
      req.downstreamNodeId = pVgInfo->vgId;
      req.downstreamTaskId = pVgInfo->taskId;
146 147
      qDebug("s-task:%s (vgId:%d) check downstream task:0x%x (vgId:%d) (shuffle), idx:%d", pTask->id.idStr, pTask->info.nodeId,
             req.downstreamTaskId, req.downstreamNodeId, i);
148
      streamDispatchCheckMsg(pTask, &req, pVgInfo->vgId, &pVgInfo->epSet);
149 150
    }
  } else {
151 152
    qDebug("s-task:%s (vgId:%d) set downstream ready, since no downstream", pTask->id.idStr, pTask->info.nodeId);

153
    streamTaskSetReady(pTask, 0);
154
    streamTaskSetRangeStreamCalc(pTask);
155
    streamTaskLaunchScanHistory(pTask);
156

157
    launchFillHistoryTask(pTask);
158
  }
159

160 161 162
  return 0;
}

163
int32_t streamRecheckDownstream(SStreamTask* pTask, const SStreamTaskCheckRsp* pRsp) {
164 165 166 167 168 169 170 171 172
  SStreamTaskCheckReq req = {
      .reqId = pRsp->reqId,
      .streamId = pRsp->streamId,
      .upstreamTaskId = pRsp->upstreamTaskId,
      .upstreamNodeId = pRsp->upstreamNodeId,
      .downstreamTaskId = pRsp->downstreamTaskId,
      .downstreamNodeId = pRsp->downstreamNodeId,
      .childId = pRsp->childId,
  };
173

174
  qDebug("s-task:%s (vgId:%d) check downstream task:0x%x (vgId:%d) (recheck)", pTask->id.idStr, pTask->info.nodeId,
175
         req.downstreamTaskId, req.downstreamNodeId);
176

177
  if (pTask->outputInfo.type == TASK_OUTPUT__FIXED_DISPATCH) {
178
    streamDispatchCheckMsg(pTask, &req, pRsp->downstreamNodeId, &pTask->fixedEpDispatcher.epSet);
179
  } else if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
180
    SArray* vgInfo = pTask->shuffleDispatcher.dbInfo.pVgroupInfos;
181 182 183

    int32_t numOfVgs = taosArrayGetSize(vgInfo);
    for (int32_t i = 0; i < numOfVgs; i++) {
184 185
      SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, i);
      if (pVgInfo->taskId == req.downstreamTaskId) {
186
        streamDispatchCheckMsg(pTask, &req, pRsp->downstreamNodeId, &pVgInfo->epSet);
187 188 189
      }
    }
  }
190

191 192 193
  return 0;
}

194
int32_t streamTaskCheckStatus(SStreamTask* pTask) {
195 196 197 198
  return (pTask->status.downstreamReady == 1)? 1:0;
}

static void doProcessDownstreamReadyRsp(SStreamTask* pTask, int32_t numOfReqs) {
199
  streamTaskSetReady(pTask, numOfReqs);
200 201 202 203 204 205 206 207 208
  const char* id = pTask->id.idStr;

  int8_t      status = pTask->status.taskStatus;
  const char* str = streamGetTaskStatusStr(status);

  ASSERT(status == TASK_STATUS__SCAN_HISTORY || status == TASK_STATUS__NORMAL);
  streamTaskSetRangeStreamCalc(pTask);

  if (status == TASK_STATUS__SCAN_HISTORY) {
209
    qDebug("s-task:%s enter into scan-history data stage, status:%s", id, str);
210 211 212 213 214 215 216
    streamTaskLaunchScanHistory(pTask);
  } else {
    qDebug("s-task:%s downstream tasks are ready, now ready for data from wal, status:%s", id, str);
  }

  // when current stream task is ready, check the related fill history task.
  launchFillHistoryTask(pTask);
217 218
}

219
int32_t streamProcessCheckRsp(SStreamTask* pTask, const SStreamTaskCheckRsp* pRsp) {
220
  ASSERT(pTask->id.taskId == pRsp->upstreamTaskId);
221
  const char* id = pTask->id.idStr;
222

223
  if (pRsp->status == 1) {
224
    if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
225
      bool found = false;
226 227 228

      int32_t numOfReqs = taosArrayGetSize(pTask->checkReqIds);
      for (int32_t i = 0; i < numOfReqs; i++) {
229 230 231 232 233 234
        int64_t reqId = *(int64_t*)taosArrayGet(pTask->checkReqIds, i);
        if (reqId == pRsp->reqId) {
          found = true;
          break;
        }
      }
235 236 237 238 239

      if (!found) {
        return -1;
      }

240
      int32_t left = atomic_sub_fetch_32(&pTask->notReadyTasks, 1);
241
      ASSERT(left >= 0);
242

243 244
      if (left == 0) {
        taosArrayDestroy(pTask->checkReqIds);
L
Liu Jicong 已提交
245
        pTask->checkReqIds = NULL;
246 247

        doProcessDownstreamReadyRsp(pTask, numOfReqs);
248
      } else {
249 250 251
        int32_t total = taosArrayGetSize(pTask->shuffleDispatcher.dbInfo.pVgroupInfos);
        qDebug("s-task:%s (vgId:%d) recv check rsp from task:0x%x (vgId:%d) status:%d, total:%d not ready:%d", id,
               pRsp->upstreamNodeId, pRsp->downstreamTaskId, pRsp->downstreamNodeId, pRsp->status, total, left);
252
      }
253
    } else {
254
      ASSERT(pTask->outputInfo.type == TASK_OUTPUT__FIXED_DISPATCH);
255 256 257 258
      if (pRsp->reqId != pTask->checkReqId) {
        return -1;
      }

259
      doProcessDownstreamReadyRsp(pTask, 1);
260
    }
261 262 263
  } else {  // not ready, wait for 100ms and retry
    qDebug("s-task:%s downstream taskId:0x%x (vgId:%d) not ready, wait for 100ms and retry", id, pRsp->downstreamTaskId,
           pRsp->downstreamNodeId);
264
    taosMsleep(100);
265

266
    streamRecheckDownstream(pTask, pRsp);
267
  }
268

269 270 271
  return 0;
}

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
int32_t streamSendCheckRsp(const SStreamMeta* pMeta, const SStreamTaskCheckReq* pReq, SStreamTaskCheckRsp* pRsp,
                           SRpcHandleInfo *pRpcInfo, int32_t taskId) {
  SEncoder encoder;
  int32_t  code;
  int32_t  len;

  tEncodeSize(tEncodeStreamTaskCheckRsp, pRsp, len, code);
  if (code < 0) {
    qError("vgId:%d failed to encode task check rsp, s-task:0x%x", pMeta->vgId, taskId);
    return -1;
  }

  void* buf = rpcMallocCont(sizeof(SMsgHead) + len);
  ((SMsgHead*)buf)->vgId = htonl(pReq->upstreamNodeId);

  void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
  tEncoderInit(&encoder, (uint8_t*)abuf, len);
  tEncodeStreamTaskCheckRsp(&encoder, pRsp);
  tEncoderClear(&encoder);

  SRpcMsg rspMsg = {.code = 0, .pCont = buf, .contLen = sizeof(SMsgHead) + len, .info = *pRpcInfo};

  tmsgSendRsp(&rspMsg);
  return 0;
}

298
// common
299
int32_t streamSetParamForScanHistory(SStreamTask* pTask) {
300
  qDebug("s-task:%s set operator option for scan-history data", pTask->id.idStr);
301
  return qSetStreamOperatorOptionForScanHistory(pTask->exec.pExecutor);
302
}
303

304
int32_t streamRestoreParam(SStreamTask* pTask) {
305
  qDebug("s-task:%s restore operator param after scan-history", pTask->id.idStr);
306
  return qRestoreStreamOperatorOption(pTask->exec.pExecutor);
307
}
308

309
int32_t streamSetStatusNormal(SStreamTask* pTask) {
310 311 312 313 314 315 316 317 318
  int32_t status = atomic_load_8(&pTask->status.taskStatus);
  if (status == TASK_STATUS__DROPPING) {
    qError("s-task:%s cannot be set normal, since in dropping state", pTask->id.idStr);
    return -1;
  } else {
    qDebug("s-task:%s set task status to be normal, prev:%s", pTask->id.idStr, streamGetTaskStatusStr(status));
    atomic_store_8(&pTask->status.taskStatus, TASK_STATUS__NORMAL);
    return 0;
  }
319 320 321
}

// source
L
liuyao 已提交
322 323 324 325 326 327
int32_t streamSetParamForStreamScannerStep1(SStreamTask* pTask, SVersionRange *pVerRange, STimeWindow* pWindow) {
  return qStreamSourceScanParamForHistoryScanStep1(pTask->exec.pExecutor, pVerRange, pWindow);
}

int32_t streamSetParamForStreamScannerStep2(SStreamTask* pTask, SVersionRange *pVerRange, STimeWindow* pWindow) {
  return qStreamSourceScanParamForHistoryScanStep2(pTask->exec.pExecutor, pVerRange, pWindow);
328 329
}

330
int32_t initScanHistoryReq(SStreamTask* pTask, SStreamScanHistoryReq* pReq, int8_t igUntreated) {
331
  pReq->msgHead.vgId = pTask->info.nodeId;
332 333
  pReq->streamId = pTask->id.streamId;
  pReq->taskId = pTask->id.taskId;
L
liuyao 已提交
334
  pReq->igUntreated = igUntreated;
335 336 337
  return 0;
}

338
int32_t streamSourceScanHistoryData(SStreamTask* pTask) {
339 340 341
  return streamScanExec(pTask, 100);
}

342
int32_t streamDispatchScanHistoryFinishMsg(SStreamTask* pTask) {
343 344 345 346 347 348
  SStreamScanHistoryFinishReq req = {
      .streamId = pTask->id.streamId,
      .childId = pTask->info.selfChildId,
      .upstreamTaskId = pTask->id.taskId,
      .upstreamNodeId = pTask->pMeta->vgId,
  };
H
Haojun Liao 已提交
349

L
Liu Jicong 已提交
350
  // serialize
351
  if (pTask->outputInfo.type == TASK_OUTPUT__FIXED_DISPATCH) {
352 353
    req.downstreamTaskId = pTask->fixedEpDispatcher.taskId;
    pTask->notReadyTasks = 1;
354
    streamDoDispatchScanHistoryFinishMsg(pTask, &req, pTask->fixedEpDispatcher.nodeId, &pTask->fixedEpDispatcher.epSet);
355
  } else if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
L
Liu Jicong 已提交
356
    SArray* vgInfo = pTask->shuffleDispatcher.dbInfo.pVgroupInfos;
357
    int32_t numOfVgs = taosArrayGetSize(vgInfo);
358
    pTask->notReadyTasks = numOfVgs;
359

360
    qDebug("s-task:%s send scan-history data complete msg to downstream (shuffle-dispatch) %d tasks, status:%s", pTask->id.idStr,
361 362
           numOfVgs, streamGetTaskStatusStr(pTask->status.taskStatus));
    for (int32_t i = 0; i < numOfVgs; i++) {
L
Liu Jicong 已提交
363
      SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, i);
364
      req.downstreamTaskId = pVgInfo->taskId;
365
      streamDoDispatchScanHistoryFinishMsg(pTask, &req, pVgInfo->vgId, &pVgInfo->epSet);
L
Liu Jicong 已提交
366
    }
367
  } else {
368
    qDebug("s-task:%s no downstream tasks, invoke scan-history finish rsp directly", pTask->id.idStr);
369
    streamProcessScanHistoryFinishRsp(pTask);
370
  }
371

372 373 374
  return 0;
}

375 376 377 378 379 380 381 382 383 384 385 386
int32_t appendTranstateIntoInputQ(SStreamTask* pTask) {
  SStreamDataBlock* pTranstate = taosAllocateQitem(sizeof(SStreamDataBlock), DEF_QITEM, sizeof(SSDataBlock));
  if (pTranstate == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  if (pBlock == NULL) {
    taosFreeQitem(pTranstate);
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
387 388
  pTranstate->type = STREAM_INPUT__TRANS_STATE;

389 390 391 392 393 394 395 396 397 398 399 400 401
  pBlock->info.type = STREAM_TRANS_STATE;
  pBlock->info.rows = 1;
  pBlock->info.childId = pTask->info.selfChildId;

  pTranstate->blocks = taosArrayInit(4, sizeof(SSDataBlock));//pBlock;
  taosArrayPush(pTranstate->blocks, pBlock);

  taosMemoryFree(pBlock);
  if (tAppendDataToInputQueue(pTask, (SStreamQueueItem*)pTranstate) < 0) {
    taosFreeQitem(pTranstate);
    return TSDB_CODE_OUT_OF_MEMORY;
  }

402 403
  pTask->status.appendTranstateBlock = true;

H
Haojun Liao 已提交
404 405
  qDebug("s-task:%s set sched-status:%d, prev:%d", pTask->id.idStr, TASK_SCHED_STATUS__INACTIVE, pTask->status.schedStatus);
  pTask->status.schedStatus = TASK_SCHED_STATUS__INACTIVE;
406
  streamSchedExec(pTask);
H
Haojun Liao 已提交
407

408 409 410
  return TSDB_CODE_SUCCESS;
}

411
// agg
412
int32_t streamTaskScanHistoryPrepare(SStreamTask* pTask) {
413
  pTask->numOfWaitingUpstream = taosArrayGetSize(pTask->pUpstreamEpInfoList);
414 415 416
  qDebug("s-task:%s level:%d task wait for %d upstream tasks complete scan-history procedure, status:%s",
         pTask->id.idStr, pTask->info.taskLevel, pTask->numOfWaitingUpstream,
         streamGetTaskStatusStr(pTask->status.taskStatus));
417 418 419
  return 0;
}

420
int32_t streamAggUpstreamScanHistoryFinish(SStreamTask* pTask) {
421
  void* exec = pTask->exec.pExecutor;
L
liuyao 已提交
422
  if (pTask->info.fillHistory && qRestoreStreamOperatorOption(exec) < 0) {
423 424
    return -1;
  }
425

426 427 428 429 430 431
  if (qStreamRecoverFinish(exec) < 0) {
    return -1;
  }
  return 0;
}

432 433 434 435 436 437 438
int32_t streamProcessScanHistoryFinishReq(SStreamTask* pTask, SStreamScanHistoryFinishReq* pReq,
                                          SRpcHandleInfo* pRpcInfo) {
  int32_t taskLevel = pTask->info.taskLevel;
  ASSERT(taskLevel == TASK_LEVEL__AGG || taskLevel == TASK_LEVEL__SINK);

  // sink node do not send end of scan history msg to its upstream, which is agg task.
  streamAddEndScanHistoryMsg(pTask, pRpcInfo, pReq);
439

440 441
  int32_t left = atomic_sub_fetch_32(&pTask->numOfWaitingUpstream, 1);
  ASSERT(left >= 0);
442

443 444 445 446 447 448 449 450
  if (left == 0) {
    int32_t numOfTasks = taosArrayGetSize(pTask->pUpstreamEpInfoList);
    qDebug(
        "s-task:%s all %d upstream tasks finish scan-history data, set param for agg task for stream data and send "
        "rsp to all upstream tasks",
        pTask->id.idStr, numOfTasks);

    if (pTask->info.taskLevel == TASK_LEVEL__AGG) {
451
      streamAggUpstreamScanHistoryFinish(pTask);
L
Liu Jicong 已提交
452
    }
453

454
    streamNotifyUpstreamContinue(pTask);
H
Haojun Liao 已提交
455

456
    // sink node does not receive the pause msg from mnode, so does not need enable it
H
Haojun Liao 已提交
457 458 459
    if (pTask->info.taskLevel == TASK_LEVEL__AGG) {
      streamTaskEnablePause(pTask);
    }
460 461 462
  } else {
    qDebug("s-task:%s receive scan-history data finish msg from upstream:0x%x(index:%d), unfinished:%d",
           pTask->id.idStr, pReq->upstreamTaskId, pReq->childId, left);
463
  }
464

465 466 467
  return 0;
}

468 469 470 471 472 473 474 475 476 477
int32_t streamProcessScanHistoryFinishRsp(SStreamTask* pTask) {
  ASSERT(pTask->status.taskStatus == TASK_STATUS__SCAN_HISTORY);
  SStreamMeta* pMeta = pTask->pMeta;

  // execute in the scan history complete call back msg, ready to process data from inputQ
  streamSetStatusNormal(pTask);
  atomic_store_8(&pTask->status.schedStatus, TASK_SCHED_STATUS__INACTIVE);

  taosWLockLatch(&pMeta->lock);
  streamMetaSaveTask(pMeta, pTask);
478
  streamMetaCommit(pMeta);
479 480
  taosWUnLockLatch(&pMeta->lock);

481
  // history data scan in the stream time window finished, now let's enable the pause
H
Haojun Liao 已提交
482 483
  streamTaskEnablePause(pTask);

484
  // for source tasks, let's continue execute.
485 486 487 488 489 490 491
  if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
    streamSchedExec(pTask);
  }

  return TSDB_CODE_SUCCESS;
}

492 493 494 495
static void doCheckDownstreamStatus(SStreamTask* pTask, SStreamTask* pHTask) {
  pHTask->dataRange.range.minVer = 0;
  pHTask->dataRange.range.maxVer = pTask->chkInfo.currentVer;

496
  if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
497
    qDebug("s-task:%s set the launch condition for fill-history s-task:%s, window:%" PRId64 " - %" PRId64
498
           " ver range:%" PRId64 " - %" PRId64,
499 500 501 502 503
           pTask->id.idStr, pHTask->id.idStr, pHTask->dataRange.window.skey, pHTask->dataRange.window.ekey,
           pHTask->dataRange.range.minVer, pHTask->dataRange.range.maxVer);
  } else {
    qDebug("s-task:%s no fill history condition for non-source task:%s", pTask->id.idStr, pHTask->id.idStr);
  }
504 505

  // check if downstream tasks have been ready
506
  streamTaskDoCheckDownstreamTasks(pHTask);
507 508 509
}

static void tryLaunchHistoryTask(void* param, void* tmrId) {
H
Haojun Liao 已提交
510 511 512
  SStreamTaskRetryInfo* pInfo = param;
  SStreamMeta*          pMeta = pInfo->pMeta;

513
  qDebug("s-task:0x%x in timer to launch related history task", pInfo->taskId);
H
Haojun Liao 已提交
514 515

  taosWLockLatch(&pMeta->lock);
H
Haojun Liao 已提交
516 517 518
  int64_t keys[2] = {pInfo->streamId, pInfo->taskId};

  SStreamTask** ppTask = (SStreamTask**)taosHashGet(pMeta->pTasks, keys, sizeof(keys));
H
Haojun Liao 已提交
519 520
  if (ppTask) {
    ASSERT((*ppTask)->status.timerActive == 1);
H
Haojun Liao 已提交
521

H
Haojun Liao 已提交
522
    if (streamTaskShouldStop(&(*ppTask)->status)) {
H
Haojun Liao 已提交
523 524 525
      const char* pStatus = streamGetTaskStatusStr((*ppTask)->status.taskStatus);
      qDebug("s-task:%s status:%s quit timer task", (*ppTask)->id.idStr, pStatus);

H
Haojun Liao 已提交
526
      taosMemoryFree(pInfo);
H
Haojun Liao 已提交
527 528 529 530 531 532
      (*ppTask)->status.timerActive = 0;
      taosWUnLockLatch(&pMeta->lock);
      return;
    }
  }
  taosWUnLockLatch(&pMeta->lock);
533

534
  SStreamTask* pTask = streamMetaAcquireTask(pMeta, pInfo->streamId, pInfo->taskId);
H
Haojun Liao 已提交
535 536
  if (pTask != NULL) {
    ASSERT(pTask->status.timerActive == 1);
537

H
Haojun Liao 已提交
538
    // abort the timer if intend to stop task
539
    SStreamTask* pHTask = streamMetaAcquireTask(pMeta, pTask->historyTaskId.streamId, pTask->historyTaskId.taskId);
540 541 542
    if (pHTask == NULL && (!streamTaskShouldStop(&pTask->status))) {
      const char* pStatus = streamGetTaskStatusStr(pTask->status.taskStatus);
      qWarn(
543 544
          "s-task:%s vgId:%d status:%s failed to launch history task:0x%x, since it may not be built, or may have been "
          "destroyed, or should stop",
545
          pTask->id.idStr, pMeta->vgId, pStatus, pTask->historyTaskId.taskId);
546

547
      taosTmrReset(tryLaunchHistoryTask, 100, pInfo, streamEnv.timer, &pTask->launchTaskTimer);
548
      streamMetaReleaseTask(pMeta, pTask);
H
Haojun Liao 已提交
549 550 551
      return;
    }

552 553 554 555
    if (pHTask != NULL) {
      doCheckDownstreamStatus(pTask, pHTask);
      streamMetaReleaseTask(pMeta, pHTask);
    }
H
Haojun Liao 已提交
556 557 558 559 560

    // not in timer anymore
    pTask->status.timerActive = 0;
    streamMetaReleaseTask(pMeta, pTask);
  } else {
561
    qError("s-task:0x%x failed to load task, it may have been destroyed", pInfo->taskId);
H
Haojun Liao 已提交
562
  }
H
Haojun Liao 已提交
563 564

  taosMemoryFree(pInfo);
565 566 567 568
}

// todo fix the bug: 2. race condition
// an fill history task needs to be started.
569
int32_t streamLaunchFillHistoryTask(SStreamTask* pTask) {
570
  SStreamMeta* pMeta = pTask->pMeta;
H
Haojun Liao 已提交
571
  int32_t      hTaskId = pTask->historyTaskId.taskId;
572

H
Haojun Liao 已提交
573
  int64_t keys[2] = {pTask->historyTaskId.streamId, pTask->historyTaskId.taskId};
574
  // Set the execute conditions, including the query time window and the version range
H
Haojun Liao 已提交
575
  SStreamTask** pHTask = taosHashGet(pMeta->pTasks, keys, sizeof(keys));
576 577
  if (pHTask == NULL) {
    qWarn("s-task:%s vgId:%d failed to launch history task:0x%x, since it is not built yet", pTask->id.idStr,
H
Haojun Liao 已提交
578
          pMeta->vgId, hTaskId);
579

H
Haojun Liao 已提交
580 581
    SStreamTaskRetryInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamTaskRetryInfo));
    pInfo->taskId = pTask->id.taskId;
582
    pInfo->streamId = pTask->id.streamId;
H
Haojun Liao 已提交
583
    pInfo->pMeta = pTask->pMeta;
H
Haojun Liao 已提交
584

585 586 587
    if (pTask->launchTaskTimer == NULL) {
      pTask->launchTaskTimer = taosTmrStart(tryLaunchHistoryTask,  100, pInfo, streamEnv.timer);
      if (pTask->launchTaskTimer == NULL) {
588
        // todo failed to create timer
H
Haojun Liao 已提交
589
        taosMemoryFree(pInfo);
H
Haojun Liao 已提交
590 591
      } else {
        pTask->status.timerActive = 1;  // timer is active
592
        qDebug("s-task:%s set timer active flag", pTask->id.idStr);
593
      }
H
Haojun Liao 已提交
594 595
    } else {  // timer exists
      pTask->status.timerActive = 1;
596 597
      qDebug("s-task:%s set timer active flag, task timer not null", pTask->id.idStr);
      taosTmrReset(tryLaunchHistoryTask, 100, pInfo, streamEnv.timer, &pTask->launchTaskTimer);
598 599 600 601 602 603 604 605 606 607
    }

    // try again in 500ms
    return TSDB_CODE_SUCCESS;
  }

  doCheckDownstreamStatus(pTask, *pHTask);
  return TSDB_CODE_SUCCESS;
}

608 609 610 611 612 613
int32_t streamTaskScanHistoryDataComplete(SStreamTask* pTask) {
  if (atomic_load_8(&pTask->status.taskStatus) == TASK_STATUS__DROPPING) {
    return 0;
  }

  // restore param
L
liuyao 已提交
614 615 616 617 618 619
  int32_t code = 0;
  if (pTask->info.fillHistory) {
    code = streamRestoreParam(pTask);
    if (code < 0) {
      return -1;
    }
620 621
  }

622
  // dispatch scan-history finish req to all related downstream task
623
  code = streamDispatchScanHistoryFinishMsg(pTask);
624 625 626 627 628 629 630
  if (code < 0) {
    return -1;
  }

  return 0;
}

631
int32_t streamTaskFillHistoryFinished(SStreamTask* pTask) {
L
liuyao 已提交
632
  void* exec = pTask->exec.pExecutor;
633
  return qStreamInfoResetTimewindowFilter(exec);
L
liuyao 已提交
634 635
}

636
bool streamHistoryTaskSetVerRangeStep2(SStreamTask* pTask, int64_t latestVer) {
637 638 639 640 641 642
  SVersionRange* pRange = &pTask->dataRange.range;
  ASSERT(latestVer >= pRange->maxVer);

  int64_t nextStartVer = pRange->maxVer + 1;
  if (nextStartVer > latestVer - 1) {
    // no input data yet. no need to execute the secondardy scan while stream task halt
643
    streamTaskFillHistoryFinished(pTask);
644
    qDebug(
645 646 647 648
        "s-task:%s no need to perform secondary scan-history data(step 2), since no data ingest during step1 scan, "
        "related stream task currentVer:%" PRId64,
        pTask->id.idStr, latestVer);
    return true;
649 650 651 652 653
  } else {
    // 2. do secondary scan of the history data, the time window remain, and the version range is updated to
    // [pTask->dataRange.range.maxVer, ver1]
    pRange->minVer = nextStartVer;
    pRange->maxVer = latestVer - 1;
654
    return false;
655 656 657
  }
}

658
int32_t tEncodeStreamTaskCheckReq(SEncoder* pEncoder, const SStreamTaskCheckReq* pReq) {
659
  if (tStartEncode(pEncoder) < 0) return -1;
660
  if (tEncodeI64(pEncoder, pReq->reqId) < 0) return -1;
661
  if (tEncodeI64(pEncoder, pReq->streamId) < 0) return -1;
L
Liu Jicong 已提交
662
  if (tEncodeI32(pEncoder, pReq->upstreamNodeId) < 0) return -1;
663 664 665 666
  if (tEncodeI32(pEncoder, pReq->upstreamTaskId) < 0) return -1;
  if (tEncodeI32(pEncoder, pReq->downstreamNodeId) < 0) return -1;
  if (tEncodeI32(pEncoder, pReq->downstreamTaskId) < 0) return -1;
  if (tEncodeI32(pEncoder, pReq->childId) < 0) return -1;
L
Liu Jicong 已提交
667 668 669 670
  tEndEncode(pEncoder);
  return pEncoder->pos;
}

671
int32_t tDecodeStreamTaskCheckReq(SDecoder* pDecoder, SStreamTaskCheckReq* pReq) {
L
Liu Jicong 已提交
672
  if (tStartDecode(pDecoder) < 0) return -1;
673
  if (tDecodeI64(pDecoder, &pReq->reqId) < 0) return -1;
L
Liu Jicong 已提交
674
  if (tDecodeI64(pDecoder, &pReq->streamId) < 0) return -1;
L
Liu Jicong 已提交
675
  if (tDecodeI32(pDecoder, &pReq->upstreamNodeId) < 0) return -1;
676 677 678 679
  if (tDecodeI32(pDecoder, &pReq->upstreamTaskId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pReq->downstreamNodeId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pReq->downstreamTaskId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pReq->childId) < 0) return -1;
L
Liu Jicong 已提交
680 681 682 683
  tEndDecode(pDecoder);
  return 0;
}

684
int32_t tEncodeStreamTaskCheckRsp(SEncoder* pEncoder, const SStreamTaskCheckRsp* pRsp) {
L
Liu Jicong 已提交
685
  if (tStartEncode(pEncoder) < 0) return -1;
686
  if (tEncodeI64(pEncoder, pRsp->reqId) < 0) return -1;
L
Liu Jicong 已提交
687
  if (tEncodeI64(pEncoder, pRsp->streamId) < 0) return -1;
688 689 690 691 692 693
  if (tEncodeI32(pEncoder, pRsp->upstreamNodeId) < 0) return -1;
  if (tEncodeI32(pEncoder, pRsp->upstreamTaskId) < 0) return -1;
  if (tEncodeI32(pEncoder, pRsp->downstreamNodeId) < 0) return -1;
  if (tEncodeI32(pEncoder, pRsp->downstreamTaskId) < 0) return -1;
  if (tEncodeI32(pEncoder, pRsp->childId) < 0) return -1;
  if (tEncodeI8(pEncoder, pRsp->status) < 0) return -1;
L
Liu Jicong 已提交
694 695 696 697
  tEndEncode(pEncoder);
  return pEncoder->pos;
}

698
int32_t tDecodeStreamTaskCheckRsp(SDecoder* pDecoder, SStreamTaskCheckRsp* pRsp) {
L
Liu Jicong 已提交
699
  if (tStartDecode(pDecoder) < 0) return -1;
700 701 702 703 704 705 706 707
  if (tDecodeI64(pDecoder, &pRsp->reqId) < 0) return -1;
  if (tDecodeI64(pDecoder, &pRsp->streamId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pRsp->upstreamNodeId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pRsp->upstreamTaskId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pRsp->downstreamNodeId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pRsp->downstreamTaskId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pRsp->childId) < 0) return -1;
  if (tDecodeI8(pDecoder, &pRsp->status) < 0) return -1;
L
Liu Jicong 已提交
708 709 710 711
  tEndDecode(pDecoder);
  return 0;
}

712
int32_t tEncodeStreamScanHistoryFinishReq(SEncoder* pEncoder, const SStreamScanHistoryFinishReq* pReq) {
L
Liu Jicong 已提交
713 714
  if (tStartEncode(pEncoder) < 0) return -1;
  if (tEncodeI64(pEncoder, pReq->streamId) < 0) return -1;
715 716 717
  if (tEncodeI32(pEncoder, pReq->upstreamTaskId) < 0) return -1;
  if (tEncodeI32(pEncoder, pReq->upstreamNodeId) < 0) return -1;
  if (tEncodeI32(pEncoder, pReq->downstreamTaskId) < 0) return -1;
718
  if (tEncodeI32(pEncoder, pReq->childId) < 0) return -1;
L
Liu Jicong 已提交
719 720 721
  tEndEncode(pEncoder);
  return pEncoder->pos;
}
722

723
int32_t tDecodeStreamScanHistoryFinishReq(SDecoder* pDecoder, SStreamScanHistoryFinishReq* pReq) {
L
Liu Jicong 已提交
724 725
  if (tStartDecode(pDecoder) < 0) return -1;
  if (tDecodeI64(pDecoder, &pReq->streamId) < 0) return -1;
726 727 728
  if (tDecodeI32(pDecoder, &pReq->upstreamTaskId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pReq->upstreamNodeId) < 0) return -1;
  if (tDecodeI32(pDecoder, &pReq->downstreamTaskId) < 0) return -1;
729
  if (tDecodeI32(pDecoder, &pReq->childId) < 0) return -1;
L
Liu Jicong 已提交
730 731 732
  tEndDecode(pDecoder);
  return 0;
}
733

734 735 736
void streamTaskSetRangeStreamCalc(SStreamTask* pTask) {
  if (pTask->historyTaskId.taskId == 0) {
    SHistDataRange* pRange = &pTask->dataRange;
737 738 739 740 741 742 743 744 745
    if (pTask->info.fillHistory == 1) {
      qDebug("s-task:%s fill-history task, time window:%" PRId64 "-%" PRId64 ", verRange:%" PRId64
                 "-%" PRId64,
             pTask->id.idStr, pRange->window.skey, pRange->window.ekey, pRange->range.minVer, pRange->range.maxVer);
    } else {
      qDebug("s-task:%s no related fill-history task, stream time window:%" PRId64 "-%" PRId64 ", verRange:%" PRId64
             "-%" PRId64,
             pTask->id.idStr, pRange->window.skey, pRange->window.ekey, pRange->range.minVer, pRange->range.maxVer);
    }
746 747 748
  } else {
    SHistDataRange* pRange = &pTask->dataRange;

749 750 751 752 753 754 755
    int64_t ekey = 0;
    if (pRange->window.ekey < INT64_MAX) {
      ekey = pRange->window.ekey + 1;
    } else {
      ekey = pRange->window.ekey;
    }

756 757 758 759 760 761 762
    int64_t ver = pRange->range.minVer;

    pRange->window.skey = ekey;
    pRange->window.ekey = INT64_MAX;
    pRange->range.minVer = 0;
    pRange->range.maxVer = ver;

763
    qDebug("s-task:%s level:%d related fill-history task exists, update stream calc time window:%" PRId64 " - %" PRId64
764 765 766 767 768 769 770 771 772 773 774 775 776
           ", verRang:%" PRId64 " - %" PRId64,
           pTask->id.idStr, pTask->info.taskLevel, pRange->window.skey, pRange->window.ekey, pRange->range.minVer,
           pRange->range.maxVer);
  }
}

void launchFillHistoryTask(SStreamTask* pTask) {
  int32_t tId = pTask->historyTaskId.taskId;
  if (tId == 0) {
    return;
  }

  ASSERT(pTask->status.downstreamReady == 1);
H
Haojun Liao 已提交
777 778
  qDebug("s-task:%s start to launch related fill-history task:0x%" PRIx64 "-0x%x", pTask->id.idStr,
         pTask->historyTaskId.streamId, tId);
779 780 781 782 783 784

  // launch associated fill history task
  streamLaunchFillHistoryTask(pTask);
}

void streamTaskCheckDownstreamTasks(SStreamTask* pTask) {
785 786
  if (pTask->info.fillHistory) {
    qDebug("s-task:%s fill history task, wait for being launched", pTask->id.idStr);
787 788 789 790
    return;
  }

  ASSERT(pTask->status.downstreamReady == 0);
791

792 793
  // check downstream tasks for itself
  streamTaskDoCheckDownstreamTasks(pTask);
794
}
795

796
// normal -> pause, pause/stop/dropping -> pause, halt -> pause, scan-history -> pause
797 798 799 800
void streamTaskPause(SStreamTask* pTask) {
  SStreamMeta* pMeta = pTask->pMeta;

  int64_t st = taosGetTimestampMs();
801 802 803 804 805 806 807 808 809 810 811 812 813

  int8_t status = pTask->status.taskStatus;
  if (status == TASK_STATUS__DROPPING) {
    qDebug("vgId:%d s-task:%s task already dropped, do nothing", pMeta->vgId, pTask->id.idStr);
    return;
  }

  const char* str = streamGetTaskStatusStr(status);
  if (status == TASK_STATUS__STOP || status == TASK_STATUS__PAUSE) {
    qDebug("vgId:%d s-task:%s task already stopped/paused, status:%s, do nothing", pMeta->vgId, pTask->id.idStr, str);
    return;
  }

814
  while (!pTask->status.pauseAllowed || (pTask->status.taskStatus == TASK_STATUS__HALT)) {
815 816
    status = pTask->status.taskStatus;
    if (status == TASK_STATUS__DROPPING) {
817 818 819 820
      qDebug("vgId:%d s-task:%s task already dropped, do nothing", pMeta->vgId, pTask->id.idStr);
      return;
    }

821 822 823 824 825
    if (status == TASK_STATUS__STOP || status == TASK_STATUS__PAUSE) {
      qDebug("vgId:%d s-task:%s task already stopped/paused, status:%s, do nothing", pMeta->vgId, pTask->id.idStr, str);
      return;
    }

826 827
    const char* pStatus = streamGetTaskStatusStr(status);
    qDebug("s-task:%s wait for the task can be paused, status:%s, vgId:%d", pTask->id.idStr, pStatus, pMeta->vgId);
828 829 830
    taosMsleep(100);
  }

831
  // todo: use the task lock, stead of meta lock
832 833 834 835 836 837 838 839 840
  taosWLockLatch(&pMeta->lock);

  status = pTask->status.taskStatus;
  if (status == TASK_STATUS__DROPPING || status == TASK_STATUS__STOP) {
    taosWUnLockLatch(&pMeta->lock);
    qDebug("vgId:%d s-task:%s task already dropped/stopped/paused, do nothing", pMeta->vgId, pTask->id.idStr);
    return;
  }

841 842
  atomic_store_8(&pTask->status.keepTaskStatus, pTask->status.taskStatus);
  atomic_store_8(&pTask->status.taskStatus, TASK_STATUS__PAUSE);
843
  taosWUnLockLatch(&pMeta->lock);
844

845 846 847 848 849 850
  // in case of fill-history task, stop the tsdb file scan operation.
  if (pTask->info.fillHistory == 1) {
    void* pExecutor = pTask->exec.pExecutor;
    qKillTask(pExecutor, TSDB_CODE_SUCCESS);
  }

851 852
  int64_t el = taosGetTimestampMs() - st;
  qDebug("vgId:%d s-task:%s set pause flag, prev:%s, elapsed time:%dms", pMeta->vgId, pTask->id.idStr,
H
Haojun Liao 已提交
853
         streamGetTaskStatusStr(pTask->status.keepTaskStatus), (int32_t)el);
854 855
}

856 857 858 859 860 861 862 863 864 865 866
void streamTaskResume(SStreamTask* pTask) {
  int8_t status = pTask->status.taskStatus;
  if (status == TASK_STATUS__PAUSE) {
    pTask->status.taskStatus = pTask->status.keepTaskStatus;
    pTask->status.keepTaskStatus = TASK_STATUS__NORMAL;
    qDebug("s-task:%s resume from pause", pTask->id.idStr);
  } else {
    qError("s-task:%s not in pause, failed to resume, status:%s", pTask->id.idStr, streamGetTaskStatusStr(status));
  }
}

867 868 869
// todo fix race condition
void streamTaskDisablePause(SStreamTask* pTask) {
  // pre-condition check
870
  const char* id = pTask->id.idStr;
871
  while (pTask->status.taskStatus == TASK_STATUS__PAUSE) {
872
    qDebug("s-task:%s already in pause, wait for pause being cancelled, and set pause disabled, recheck in 100ms", id);
873
    taosMsleep(100);
874 875
  }

876
  qDebug("s-task:%s disable task pause", id);
877 878 879 880 881 882
  pTask->status.pauseAllowed = 0;
}

void streamTaskEnablePause(SStreamTask* pTask) {
  qDebug("s-task:%s enable task pause", pTask->id.idStr);
  pTask->status.pauseAllowed = 1;
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
}

void streamTaskHalt(SStreamTask* pTask) {
  int8_t status = pTask->status.taskStatus;
  if (status == TASK_STATUS__DROPPING || status == TASK_STATUS__STOP) {
    return;
  }

  if (status == TASK_STATUS__HALT) {
    return;
  }

  // upgrade to halt status
  if (status == TASK_STATUS__PAUSE) {
    qDebug("s-task:%s upgrade status to %s from %s", pTask->id.idStr, streamGetTaskStatusStr(TASK_STATUS__HALT),
           streamGetTaskStatusStr(TASK_STATUS__PAUSE));
  } else {
    qDebug("s-task:%s halt task", pTask->id.idStr);
  }

  pTask->status.keepTaskStatus = status;
  pTask->status.taskStatus = TASK_STATUS__HALT;
}

void streamTaskResumeFromHalt(SStreamTask* pTask) {
  const char* id = pTask->id.idStr;
  int8_t status = pTask->status.taskStatus;
  if (status != TASK_STATUS__HALT) {
    qError("s-task:%s not in halt status, status:%s", id, streamGetTaskStatusStr(status));
    return;
  }

  pTask->status.taskStatus = pTask->status.keepTaskStatus;
  pTask->status.keepTaskStatus = TASK_STATUS__NORMAL;
  qDebug("s-task:%s resume from halt, current status:%s", id, streamGetTaskStatusStr(pTask->status.taskStatus));
}