tscStream.c 18.9 KB
Newer Older
H
hzcheng 已提交
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/>.
 */

S
slguan 已提交
16
#include "os.h"
H
hzcheng 已提交
17
#include "tlog.h"
H
hjxilinx 已提交
18
#include "tscSQLParser.h"
H
hzcheng 已提交
19 20 21 22
#include "ttime.h"
#include "ttimer.h"
#include "tutil.h"

S
slguan 已提交
23
#include "taosmsg.h"
H
hzcheng 已提交
24
#include "tscUtil.h"
25
#include "tsclient.h"
H
hzcheng 已提交
26 27 28 29 30 31 32 33 34 35 36

#include "tscProfile.h"

static void tscProcessStreamQueryCallback(void *param, TAOS_RES *tres, int numOfRows);
static void tscProcessStreamRetrieveResult(void *param, TAOS_RES *res, int numOfRows);
static void tscSetNextLaunchTimer(SSqlStream *pStream, SSqlObj *pSql);
static void tscSetRetryTimer(SSqlStream *pStream, SSqlObj *pSql, int64_t timer);

static bool isProjectStream(SSqlCmd *pCmd) {
  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr *pExpr = tscSqlExprGet(pCmd, i);
S
slguan 已提交
37
    if (pExpr->functionId != TSDB_FUNC_PRJ) {
H
hzcheng 已提交
38 39 40 41 42 43 44
      return false;
    }
  }

  return true;
}

45 46 47 48 49 50 51
static int64_t tscGetRetryDelayTime(int64_t slidingTime, int16_t prec) {
  float retryRangeFactor = 0.3;

  // change to ms
  if (prec == TSDB_TIME_PRECISION_MICRO) {
    slidingTime = slidingTime / 1000;
  }
H
hzcheng 已提交
52

53
  int64_t retryDelta = (int64_t)tsStreamCompRetryDelay * retryRangeFactor;
H
hzcheng 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  retryDelta = ((rand() % retryDelta) + tsStreamCompRetryDelay) * 1000L;

  if (slidingTime < retryDelta) {
    return slidingTime;
  } else {
    return retryDelta;
  }
}

static void tscProcessStreamLaunchQuery(SSchedMsg *pMsg) {
  SSqlStream *pStream = (SSqlStream *)pMsg->ahandle;
  SSqlObj *   pSql = pStream->pSql;

  pSql->fp = tscProcessStreamQueryCallback;
  pSql->param = pStream;
S
slguan 已提交
69
  SMeterMetaInfo *pMeterMetaInfo = tscGetMeterMetaInfo(&pSql->cmd, 0);
H
hzcheng 已提交
70

S
slguan 已提交
71
  int code = tscGetMeterMeta(pSql, pMeterMetaInfo->name, 0);
H
hzcheng 已提交
72 73 74 75
  pSql->res.code = code;

  if (code == TSDB_CODE_ACTION_IN_PROGRESS) return;

S
slguan 已提交
76 77
  if (code == 0 && UTIL_METER_IS_METRIC(pMeterMetaInfo)) {
    code = tscGetMetricMeta(pSql);
H
hzcheng 已提交
78 79 80 81 82 83 84 85 86
    pSql->res.code = code;

    if (code == TSDB_CODE_ACTION_IN_PROGRESS) return;
  }

  tscTansformSQLFunctionForMetricQuery(&pSql->cmd);

  // failed to get meter/metric meta, retry in 10sec.
  if (code != TSDB_CODE_SUCCESS) {
87 88
    int64_t retryDelayTime = tscGetRetryDelayTime(pStream->slidingTime, pStream->precision);
    tscError("%p stream:%p,get metermeta failed, retry in %lldms", pStream->pSql, pStream, retryDelayTime);
H
hzcheng 已提交
89 90 91 92 93

    tscSetRetryTimer(pStream, pSql, retryDelayTime);
    return;
  }

S
slguan 已提交
94
  tscTrace("%p stream:%p start stream query on:%s", pSql, pStream, pMeterMetaInfo->name);
H
hzcheng 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107
  tscProcessSql(pStream->pSql);

  tscIncStreamExecutionCount(pStream);
}

static void tscProcessStreamTimer(void *handle, void *tmrId) {
  SSqlStream *pStream = (SSqlStream *)handle;
  if (pStream == NULL) return;
  if (pStream->pTimer != tmrId) return;
  pStream->pTimer = NULL;

  pStream->numOfRes = 0;  // reset the numOfRes.
  SSqlObj *pSql = pStream->pSql;
S
slguan 已提交
108
  tscTrace("%p add into timer", pSql);
H
hzcheng 已提交
109 110 111 112 113 114 115 116

  if (isProjectStream(&pSql->cmd)) {
    /*
     * pSql->cmd.etime, which is the start time, does not change in case of
     * repeat first execution, once the first execution failed.
     */
    pSql->cmd.stime = pStream->stime;  // start time

117
    pSql->cmd.etime = taosGetTimestamp(pStream->precision);  // end time
H
hzcheng 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    if (pSql->cmd.etime > pStream->etime) {
      pSql->cmd.etime = pStream->etime;
    }
  } else {
    pSql->cmd.stime = pStream->stime - pStream->interval;
    pSql->cmd.etime = pStream->stime - 1;
  }

  // launch stream computing in a new thread
  SSchedMsg schedMsg;
  schedMsg.fp = tscProcessStreamLaunchQuery;
  schedMsg.ahandle = pStream;
  schedMsg.thandle = (void *)1;
  schedMsg.msg = NULL;
  taosScheduleTask(tscQhandle, &schedMsg);
}

static void tscProcessStreamQueryCallback(void *param, TAOS_RES *tres, int numOfRows) {
  SSqlStream *pStream = (SSqlStream *)param;
  if (tres == NULL || numOfRows < 0) {
138 139 140
    int64_t retryDelay = tscGetRetryDelayTime(pStream->slidingTime, pStream->precision);
    tscError("%p stream:%p, query data failed, code:%d, retry in %lldms", pStream->pSql, pStream, numOfRows,
             retryDelay);
H
hzcheng 已提交
141

S
slguan 已提交
142 143 144
    SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(&pStream->pSql->cmd, 0);
    tscClearMeterMetaInfo(pMeterMetaInfo, true);

H
hzcheng 已提交
145 146 147 148 149 150 151
    tscSetRetryTimer(pStream, pStream->pSql, retryDelay);
    return;
  }

  taos_fetch_rows_a(tres, tscProcessStreamRetrieveResult, param);
}

S
slguan 已提交
152
static void tscSetTimestampForRes(SSqlStream *pStream, SSqlObj *pSql) {
H
hzcheng 已提交
153
  SSqlRes *pRes = &pSql->res;
S
slguan 已提交
154

H
hzcheng 已提交
155
  int64_t  timestamp = *(int64_t *)pRes->data;
S
slguan 已提交
156
  int64_t actualTimestamp = pStream->stime - pStream->interval;
H
hzcheng 已提交
157

S
slguan 已提交
158
  if (timestamp != actualTimestamp) {
H
hzcheng 已提交
159
    // reset the timestamp of each agg point by using start time of each interval
S
slguan 已提交
160 161
    *((int64_t *)pRes->data) = actualTimestamp;
    tscWarn("%p stream:%p, timestamp of points is:%lld, reset to %lld", pSql, pStream, timestamp, actualTimestamp);
H
hzcheng 已提交
162 163 164 165
  }
}

static void tscProcessStreamRetrieveResult(void *param, TAOS_RES *res, int numOfRows) {
S
slguan 已提交
166 167 168
  SSqlStream *    pStream = (SSqlStream *)param;
  SSqlObj *       pSql = (SSqlObj *)res;
  SMeterMetaInfo *pMeterMetaInfo = tscGetMeterMetaInfo(&pSql->cmd, 0);
H
hzcheng 已提交
169 170

  if (pSql == NULL || numOfRows < 0) {
171 172
    int64_t retryDelayTime = tscGetRetryDelayTime(pStream->slidingTime, pStream->precision);
    tscError("%p stream:%p, retrieve data failed, code:%d, retry in %lldms", pSql, pStream, numOfRows, retryDelayTime);
S
slguan 已提交
173
    tscClearMeterMetaInfo(pMeterMetaInfo, true);
H
hzcheng 已提交
174 175 176 177 178

    tscSetRetryTimer(pStream, pStream->pSql, retryDelayTime);
    return;
  }

S
slguan 已提交
179
  if (numOfRows > 0) { // when reaching here the first execution of stream computing is successful.
H
hzcheng 已提交
180
    pStream->numOfRes += numOfRows;
S
slguan 已提交
181 182 183

    for(int32_t i = 0; i < numOfRows; ++i) {
      TAOS_ROW row = taos_fetch_row(res);
H
hzcheng 已提交
184 185 186 187
      tscTrace("%p stream:%p fetch result", pSql, pStream);
      if (isProjectStream(&pSql->cmd)) {
        pStream->stime = *(TSKEY *)row[0];
      } else {
S
slguan 已提交
188
        tscSetTimestampForRes(pStream, pSql);
H
hzcheng 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
      }

      // user callback function
      (*pStream->fp)(pStream->param, res, row);
    }

    // actually only one row is returned. this following is not necessary
    taos_fetch_rows_a(res, tscProcessStreamRetrieveResult, pStream);
  } else {  // numOfRows == 0, all data has been retrieved
    pStream->useconds += pSql->res.useconds;

    if (pStream->numOfRes == 0) {
      if (pSql->cmd.interpoType == TSDB_INTERPO_SET_VALUE || pSql->cmd.interpoType == TSDB_INTERPO_NULL) {
        SSqlCmd *pCmd = &pSql->cmd;
        SSqlRes *pRes = &pSql->res;

        /* failed to retrieve any result in this retrieve */
        pSql->res.numOfRows = 1;
        void *row[TSDB_MAX_COLUMNS] = {0};
        char  tmpRes[TSDB_MAX_BYTES_PER_ROW] = {0};

        void *oldPtr = pSql->res.data;
        pSql->res.data = tmpRes;

        for (int32_t i = 1; i < pSql->cmd.fieldsInfo.numOfOutputCols; ++i) {
          int16_t     offset = tscFieldInfoGetOffset(pCmd, i);
          TAOS_FIELD *pField = tscFieldInfoGetField(pCmd, i);

          assignVal(pSql->res.data + offset, (char *)(&pCmd->defaultVal[i]), pField->bytes, pField->type);
          row[i] = pSql->res.data + offset;
        }

S
slguan 已提交
221
        tscSetTimestampForRes(pStream, pSql);
H
hzcheng 已提交
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
        row[0] = pRes->data;

        //            char result[512] = {0};
        //            taos_print_row(result, row, pSql->cmd.fieldsInfo.pFields, pSql->cmd.fieldsInfo.numOfOutputCols);
        //            tscPrint("%p stream:%p query result: %s", pSql, pStream, result);
        tscTrace("%p stream:%p fetch result", pSql, pStream);

        // user callback function
        (*pStream->fp)(pStream->param, res, row);

        pRes->numOfRows = 0;
        pRes->data = oldPtr;
      } else if (isProjectStream(&pSql->cmd)) {
        /* no resuls in the query range, retry */
        // todo set retry dynamic time
        int32_t retry = tsProjectExecInterval;
        tscError("%p stream:%p, retrieve no data, code:%d, retry in %lldms", pSql, pStream, numOfRows, retry);

        tscClearSqlMetaInfoForce(&(pStream->pSql->cmd));
        tscSetRetryTimer(pStream, pStream->pSql, retry);
        return;
      }
    } else {
      if (isProjectStream(&pSql->cmd)) {
        pStream->stime += 1;
      }
    }

S
slguan 已提交
250
    tscTrace("%p stream:%p, query on:%s, fetch result completed, fetched rows:%d", pSql, pStream, pMeterMetaInfo->name,
H
hzcheng 已提交
251 252
             pStream->numOfRes);

S
slguan 已提交
253 254
    // release the metric/meter meta information reference, so data in cache can be updated
    tscClearMeterMetaInfo(pMeterMetaInfo, false);
H
hzcheng 已提交
255 256 257 258 259 260
    tscSetNextLaunchTimer(pStream, pSql);
  }
}

static void tscSetRetryTimer(SSqlStream *pStream, SSqlObj *pSql, int64_t timer) {
  if (isProjectStream(&pSql->cmd)) {
261
    int64_t now = taosGetTimestamp(pStream->precision);
H
hzcheng 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    int64_t etime = now > pStream->etime ? pStream->etime : now;

    if (pStream->etime < now && now - pStream->etime > tsMaxRetentWindow) {
      /*
       * current time window will be closed, since it too early to exceed the maxRetentWindow value
       */
      tscTrace("%p stream:%p, etime:%lld is too old, exceeds the max retention time window:%lld, stop the stream",
               pStream->pSql, pStream, pStream->stime, pStream->etime);
      // TODO : How to terminate stream here
      taos_close_stream(pStream);
      if (pStream->callback) {
        // Callback function from upper level
        pStream->callback(pStream->param);
      }
      return;
    }

279 280
    tscTrace("%p stream:%p, next query start at %lld, in %lldms. query range %lld-%lld", pStream->pSql, pStream,
             now + timer, timer, pStream->stime, etime);
H
hzcheng 已提交
281
  } else {
282 283
    tscTrace("%p stream:%p, next query start at %lld, in %lldms. query range %lld-%lld", pStream->pSql, pStream,
             pStream->stime, timer, pStream->stime - pStream->interval, pStream->stime - 1);
H
hzcheng 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  }

  pSql->cmd.command = TSDB_SQL_SELECT;

  // start timer for next computing
  taosTmrReset(tscProcessStreamTimer, timer, pStream, tscTmr, &pStream->pTimer);
}

static void tscSetNextLaunchTimer(SSqlStream *pStream, SSqlObj *pSql) {
  int64_t timer = 0;

  if (isProjectStream(&pSql->cmd)) {
    /*
     * for project query, no mater fetch data successfully or not, next launch will issue
     * more than the sliding time window
     */
    timer = pStream->slidingTime;
    if (pStream->stime > pStream->etime) {
302 303
      tscTrace("%p stream:%p, stime:%lld is larger than end time: %lld, stop the stream", pStream->pSql, pStream,
               pStream->stime, pStream->etime);
H
hzcheng 已提交
304 305 306 307 308 309 310 311 312 313 314
      // TODO : How to terminate stream here
      taos_close_stream(pStream);
      if (pStream->callback) {
        // Callback function from upper level
        pStream->callback(pStream->param);
      }
      return;
    }
  } else {
    pStream->stime += pStream->slidingTime;
    if ((pStream->stime - pStream->interval) >= pStream->etime) {
315 316
      tscTrace("%p stream:%p, stime:%ld is larger than end time: %ld, stop the stream", pStream->pSql, pStream,
               pStream->stime, pStream->etime);
H
hzcheng 已提交
317 318 319 320 321 322 323 324 325
      // TODO : How to terminate stream here
      taos_close_stream(pStream);
      if (pStream->callback) {
        // Callback function from upper level
        pStream->callback(pStream->param);
      }
      return;
    }

326
    timer = pStream->stime - taosGetTimestamp(pStream->precision);
H
hzcheng 已提交
327 328 329 330 331 332 333
    if (timer < 0) {
      timer = 0;
    }
  }

  int64_t delayDelta = (int64_t)(pStream->slidingTime * 0.1);
  delayDelta = (rand() % delayDelta);
334 335 336 337 338 339

  int64_t maxDelay =
      (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? tsMaxStreamComputDelay * 1000L : tsMaxStreamComputDelay;

  if (delayDelta > maxDelay) {
    delayDelta = maxDelay;
H
hzcheng 已提交
340 341 342
  }

  timer += delayDelta;  // a random number
343 344 345 346
  if (pStream->precision == TSDB_TIME_PRECISION_MICRO) {
    timer = timer / 1000L;
  }

H
hzcheng 已提交
347 348 349
  tscSetRetryTimer(pStream, pSql, timer);
}

350
static void tscSetSlidingWindowInfo(SSqlObj *pSql, SSqlStream *pStream) {
H
hzcheng 已提交
351 352
  SSqlCmd *pCmd = &pSql->cmd;

353 354 355 356 357 358
  int64_t minIntervalTime =
      (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? tsMinIntervalTime * 1000L : tsMinIntervalTime;
  if (pCmd->nAggTimeInterval < minIntervalTime) {
    tscWarn("%p stream:%p, original sample interval:%ld too small, reset to:%lld", pSql, pStream,
            pCmd->nAggTimeInterval, minIntervalTime);
    pCmd->nAggTimeInterval = minIntervalTime;
H
hzcheng 已提交
359 360 361 362 363 364 365 366
  }

  pStream->interval = pCmd->nAggTimeInterval;  // it shall be derived from sql string

  if (pCmd->nSlidingTime == 0) {
    pCmd->nSlidingTime = pCmd->nAggTimeInterval;
  }

367 368 369 370 371 372
  int64_t minSlidingTime =
      (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? tsMinSlidingTime * 1000L : tsMinSlidingTime;

  if (pCmd->nSlidingTime < minSlidingTime) {
    tscWarn("%p stream:%p, original sliding value:%lld too small, reset to:%lld", pSql, pStream, pCmd->nSlidingTime,
            minSlidingTime);
H
hzcheng 已提交
373

374
    pCmd->nSlidingTime = minSlidingTime;
H
hzcheng 已提交
375 376 377
  }

  if (pCmd->nSlidingTime > pCmd->nAggTimeInterval) {
378 379
    tscWarn("%p stream:%p, sliding value:%lld can not be larger than interval range, reset to:%lld", pSql, pStream,
            pCmd->nSlidingTime, pCmd->nAggTimeInterval);
H
hzcheng 已提交
380 381 382 383 384

    pCmd->nSlidingTime = pCmd->nAggTimeInterval;
  }

  pStream->slidingTime = pCmd->nSlidingTime;
385 386 387 388
}

static int64_t tscGetStreamStartTimestamp(SSqlObj *pSql, SSqlStream *pStream, int64_t stime) {
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
389 390 391 392 393 394 395

  if (isProjectStream(pCmd)) {
    // no data in table, flush all data till now to destination meter, 10sec delay
    pStream->interval = tsProjectExecInterval;
    pStream->slidingTime = tsProjectExecInterval;

    if (stime != 0) {  // first projection start from the latest event timestamp
396
      assert(stime >= pCmd->stime);
H
hzcheng 已提交
397 398
      stime += 1;  // exclude the last records from table
    } else {
399
      stime = pCmd->stime;
H
hzcheng 已提交
400
    }
401
  } else {             // timewindow based aggregation stream
H
hzcheng 已提交
402
    if (stime == 0) {  // no data in meter till now
403
      stime = ((int64_t)taosGetTimestamp(pStream->precision) / pStream->interval) * pStream->interval;
S
slguan 已提交
404
      tscWarn("%p stream:%p, last timestamp:0, reset to:%lld", pSql, pStream, stime);
H
hzcheng 已提交
405 406 407 408 409 410 411 412 413
    } else {
      int64_t newStime = (stime / pStream->interval) * pStream->interval;
      if (newStime != stime) {
        tscWarn("%p stream:%p, last timestamp:%lld, reset to:%lld", pSql, pStream, stime, newStime);
        stime = newStime;
      }
    }
  }

414 415
  return stime;
}
H
hzcheng 已提交
416

417 418
static int64_t tscGetLaunchTimestamp(const SSqlStream *pStream) {
  int64_t timer = pStream->stime - taosGetTimestamp(pStream->precision);
H
hzcheng 已提交
419 420 421
  if (timer < 0) timer = 0;

  int64_t delayDelta = (int64_t)(pStream->interval * 0.1);
422 423 424 425 426

  int64_t maxDelay =
      (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? tsMaxStreamComputDelay * 1000L : tsMaxStreamComputDelay;
  if (delayDelta > maxDelay) {
    delayDelta = maxDelay;
H
hzcheng 已提交
427 428
  }

429 430 431
  int64_t startDelay =
      (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? tsStreamCompStartDelay * 1000L : tsStreamCompStartDelay;

H
hzcheng 已提交
432 433 434
  srand(time(NULL));
  timer += (rand() % delayDelta);  // a random number

435 436
  if (timer < startDelay || timer > maxDelay) {
    timer = (timer % startDelay) + startDelay;
H
hzcheng 已提交
437 438
  }

439 440 441
  return (pStream->precision == TSDB_TIME_PRECISION_MICRO) ? timer / 1000L : timer;
}

S
slguan 已提交
442 443 444 445 446 447 448 449 450 451 452
static void setErrorInfo(STscObj* pObj, int32_t code, char* info) {
  if (pObj == NULL) {
    return;
  }

  SSqlCmd* pCmd = &pObj->pSql->cmd;

  pObj->pSql->res.code = code;
  strncpy(pCmd->payload, info, pCmd->payloadLen);
}

S
slguan 已提交
453
TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sqlstr, void (*fp)(void *param, TAOS_RES *, TAOS_ROW row),
454 455 456 457 458
                              int64_t stime, void *param, void (*callback)(void *)) {
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) return NULL;

  SSqlObj *pSql = (SSqlObj *)calloc(1, sizeof(SSqlObj));
S
slguan 已提交
459 460
  if (pSql == NULL) {
    setErrorInfo(pObj, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL);
461 462 463 464 465 466 467
    return NULL;
  }

  pSql->signature = pSql;
  pSql->pTscObj = pObj;
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
S
slguan 已提交
468 469 470 471 472 473
  int ret = tscAllocPayload(pCmd, TSDB_DEFAULT_PAYLOAD_SIZE);
  if (TSDB_CODE_SUCCESS != ret) {
    setErrorInfo(pObj, ret, NULL);
    free(pSql);
    return NULL;
  }
474

S
slguan 已提交
475 476 477 478
  pSql->sqlstr = strdup(sqlstr);
  if (pSql->sqlstr == NULL) {
    setErrorInfo(pObj, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL);

479 480 481 482
    tfree(pSql);
    return NULL;
  }

S
slguan 已提交
483 484
  tsem_init(&pSql->rspSem, 0, 0);
  tsem_init(&pSql->emptyRspSem, 0, 1);
485 486 487

  SSqlInfo SQLInfo = {0};
  tSQLParse(&SQLInfo, pSql->sqlstr);
S
slguan 已提交
488 489

  tscCleanSqlCmd(&pSql->cmd);
S
slguan 已提交
490 491 492 493 494 495 496 497 498 499
  ret = tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE);
  if (TSDB_CODE_SUCCESS != ret) {
    setErrorInfo(pObj, ret, NULL);
    tscError("%p open stream failed, sql:%s, code:%d", pSql, sqlstr, TSDB_CODE_CLI_OUT_OF_MEMORY);
    tscFreeSqlObj(pSql);
    return NULL;
  }
  
  // TODO later refactor use enum
  pSql->cmd.count = 1;  // 1 means sql in stream, allowed the sliding clause.
500 501 502 503
  pRes->code = tscToSQLCmd(pSql, &SQLInfo);
  SQLInfoDestroy(&SQLInfo);

  if (pRes->code != TSDB_CODE_SUCCESS) {
S
slguan 已提交
504 505
    setErrorInfo(pObj, pRes->code, pCmd->payload);

506 507 508 509 510 511 512
    tscError("%p open stream failed, sql:%s, reason:%s, code:%d", pSql, sqlstr, pCmd->payload, pRes->code);
    tscFreeSqlObj(pSql);
    return NULL;
  }

  SSqlStream *pStream = (SSqlStream *)calloc(1, sizeof(SSqlStream));
  if (pStream == NULL) {
S
slguan 已提交
513 514
    setErrorInfo(pObj, TSDB_CODE_CLI_OUT_OF_MEMORY, NULL);

515 516 517 518 519
    tscError("%p open stream failed, sql:%s, reason:%s, code:%d", pSql, sqlstr, pCmd->payload, pRes->code);
    tscFreeSqlObj(pSql);
    return NULL;
  }

S
slguan 已提交
520 521
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, 0);

522 523 524 525
  pStream->fp = fp;
  pStream->callback = callback;
  pStream->param = param;
  pStream->pSql = pSql;
S
slguan 已提交
526 527 528
  pStream->precision = pMeterMetaInfo->pMeterMeta->precision;

  pStream->ctime = taosGetTimestamp(pStream->precision);
529 530 531 532 533 534 535 536 537 538 539 540
  pStream->etime = pCmd->etime;

  pSql->pStream = pStream;
  tscAddIntoStreamList(pStream);

  tscSetSlidingWindowInfo(pSql, pStream);
  pStream->stime = tscGetStreamStartTimestamp(pSql, pStream, stime);

  int64_t starttime = tscGetLaunchTimestamp(pStream);
  taosTmrReset(tscProcessStreamTimer, starttime, pStream, tscTmr, &pStream->pTimer);

  tscTrace("%p stream:%p is opened, query on:%s, interval:%lld, sliding:%lld, first launched in:%lld, sql:%s", pSql,
S
slguan 已提交
541
           pStream, pMeterMetaInfo->name, pStream->interval, pStream->slidingTime, starttime, sqlstr);
H
hzcheng 已提交
542 543 544 545 546 547 548

  return pStream;
}

void taos_close_stream(TAOS_STREAM *handle) {
  SSqlStream *pStream = (SSqlStream *)handle;

weixin_48148422's avatar
weixin_48148422 已提交
549
  SSqlObj *pSql = (SSqlObj *)atomic_exchange_ptr(&pStream->pSql, 0);
H
hzcheng 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
  if (pSql == NULL) {
    return;
  }

  /*
   * stream may be closed twice, 1. drop dst table, 2. kill stream
   * Here, we need a check before release memory
   */
  if (pSql->signature == pSql) {
    tscRemoveFromStreamList(pStream, pSql);

    taosTmrStopA(&(pStream->pTimer));
    tscFreeSqlObj(pSql);
    pStream->pSql = NULL;

    tscTrace("%p stream:%p is closed", pSql, pStream);
    tfree(pStream);
  }
}