smaRollup.c 42.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "sma.h"

C
Cary Xu 已提交
18 19
#define RSMA_QTASKINFO_BUFSIZE  32768
#define RSMA_QTASKINFO_HEAD_LEN (sizeof(int32_t) + sizeof(int8_t) + sizeof(int64_t))  // len + type + suid
C
Cary Xu 已提交
20

21 22 23 24
SSmaMgmt smaMgmt = {
    .smaRef = -1,
};

C
Cary Xu 已提交
25
#define TD_QTASKINFO_FNAME_PREFIX "qtaskinfo.ver"
26
typedef struct SRSmaQTaskInfoItem SRSmaQTaskInfoItem;
C
Cary Xu 已提交
27
typedef struct SRSmaQTaskInfoIter SRSmaQTaskInfoIter;
28

C
Cary Xu 已提交
29 30 31 32 33 34
static int32_t tdUidStorePut(STbUidStore *pStore, tb_uid_t suid, tb_uid_t *uid);
static int32_t tdUpdateTbUidListImpl(SSma *pSma, tb_uid_t *suid, SArray *tbUids);
static int32_t tdSetRSmaInfoItemParams(SSma *pSma, SRSmaParam *param, SRSmaInfo *pRSmaInfo, SReadHandle *handle,
                                       int8_t idx);
static int32_t tdExecuteRSmaImpl(SSma *pSma, const void *pMsg, int32_t inputType, SRSmaInfoItem *rsmaItem,
                                 tb_uid_t suid, int8_t level);
C
Cary Xu 已提交
35 36
static void    tdRSmaFetchTrigger(void *param, void *tmrId);
static void    tdRSmaPersistTrigger(void *param, void *tmrId);
37
static void   *tdRSmaPersistExec(void *param);
C
Cary Xu 已提交
38
static void    tdRSmaQTaskInfoGetFName(int32_t vid, int64_t version, char *outputName);
39

C
Cary Xu 已提交
40 41 42
static int32_t tdRSmaQTaskInfoIterInit(SRSmaQTaskInfoIter *pIter, STFile *pTFile);
static int32_t tdRSmaQTaskInfoIterNextBlock(SRSmaQTaskInfoIter *pIter, bool *isFinish);
static int32_t tdRSmaQTaskInfoRestore(SSma *pSma, SRSmaQTaskInfoIter *pIter);
43
static int32_t tdRSmaQTaskInfoItemRestore(SSma *pSma, const SRSmaQTaskInfoItem *infoItem);
44

C
Cary Xu 已提交
45
static int32_t tdRSmaRestoreQTaskInfoInit(SSma *pSma, int64_t *nTables);
C
Cary Xu 已提交
46 47
static int32_t tdRSmaRestoreQTaskInfoReload(SSma *pSma, int64_t *committed);
static int32_t tdRSmaRestoreTSDataReload(SSma *pSma, int64_t committed);
C
Cary Xu 已提交
48

49 50
struct SRSmaInfoItem {
  SRSmaInfo *pRsmaInfo;
51
  int64_t    refId;
52 53 54 55
  void      *taskInfo;  // qTaskInfo_t
  tmr_h      tmrId;
  int8_t     level;
  int8_t     tmrInitFlag;
C
Cary Xu 已提交
56
  int8_t     triggerStat;
57 58
  int32_t    maxDelay;
};
C
Cary Xu 已提交
59

60
struct SRSmaInfo {
61
  STSchema     *pTSchema;
62
  SRSmaStat    *pStat;
63 64
  int64_t       suid;
  SRSmaInfoItem items[TSDB_RETENTION_L2];
65 66
};

67 68 69
#define RSMA_INFO_SMA(r)  ((r)->pStat->pSma)
#define RSMA_INFO_STAT(r) ((r)->pStat)

70 71 72 73 74 75 76
struct SRSmaQTaskInfoItem {
  int32_t len;
  int8_t  type;
  int64_t suid;
  void   *qTaskInfo;
};

C
Cary Xu 已提交
77
struct SRSmaQTaskInfoIter {
78 79 80 81 82
  STFile *pTFile;
  int64_t offset;
  int64_t fsize;
  int32_t nBytes;
  int32_t nAlloc;
C
Cary Xu 已提交
83
  char   *pBuf;
84
  // ------------
C
Cary Xu 已提交
85
  char   *qBuf;  // for iterator
86 87 88
  int32_t nBufPos;
};

C
Cary Xu 已提交
89
static void tdRSmaQTaskInfoGetFName(int32_t vgId, int64_t version, char *outputName) {
C
Cary Xu 已提交
90
  tdGetVndFileName(vgId, NULL, VNODE_RSMA_DIR, TD_QTASKINFO_FNAME_PREFIX, version, outputName);
91 92
}

C
Cary Xu 已提交
93
static FORCE_INLINE int32_t tdRSmaQTaskInfoContLen(int32_t lenWithHead) {
C
Cary Xu 已提交
94
  return lenWithHead - RSMA_QTASKINFO_HEAD_LEN;
C
Cary Xu 已提交
95 96
}

C
Cary Xu 已提交
97
static FORCE_INLINE void tdRSmaQTaskInfoIterDestroy(SRSmaQTaskInfoIter *pIter) { taosMemoryFreeClear(pIter->pBuf); }
C
Cary Xu 已提交
98

C
Cary Xu 已提交
99
static FORCE_INLINE void tdFreeTaskHandle(qTaskInfo_t *taskHandle, int32_t vgId, int32_t level) {
100 101 102
  // Note: free/kill may in RC
  qTaskInfo_t otaskHandle = atomic_load_ptr(taskHandle);
  if (otaskHandle && atomic_val_compare_exchange_ptr(taskHandle, otaskHandle, NULL)) {
C
Cary Xu 已提交
103
    smaDebug("vgId:%d, free qTaskInfo_t %p of level %d", vgId, otaskHandle, level);
104
    qDestroyTask(otaskHandle);
C
Cary Xu 已提交
105
  } else {
C
Cary Xu 已提交
106
    smaDebug("vgId:%d, not free qTaskInfo_t %p of level %d", vgId, otaskHandle, level);
107 108 109 110
  }
}

void *tdFreeRSmaInfo(SRSmaInfo *pInfo) {
111
  if (pInfo) {
112
    SSma *pSma = RSMA_INFO_SMA(pInfo);
C
Cary Xu 已提交
113
    for (int32_t i = 0; i < TSDB_RETENTION_L2; ++i) {
114 115
      SRSmaInfoItem *pItem = &pInfo->items[i];
      if (pItem->taskInfo) {
C
Cary Xu 已提交
116 117 118 119 120
        if (pItem->tmrId) {
          smaDebug("vgId:%d, table %" PRIi64 " stop fetch timer %p level %d", SMA_VID(pSma), pInfo->suid, pItem->tmrId,
                   i + 1);
          taosTmrStopA(&pItem->tmrId);
        }
121
        tdFreeTaskHandle(&pItem->taskInfo, SMA_VID(pSma), i + 1);
C
Cary Xu 已提交
122
      } else {
C
Cary Xu 已提交
123
        smaDebug("vgId:%d, table %" PRIi64 " no need to destroy rsma info level %d since empty taskInfo", SMA_VID(pSma),
124
                 pInfo->suid, i + 1);
125
      }
126
    }
127 128
    taosMemoryFree(pInfo->pTSchema);
    taosMemoryFree(pInfo);
129
  }
130

131 132 133 134 135 136 137 138 139 140 141 142 143
  return NULL;
}

static FORCE_INLINE int32_t tdUidStoreInit(STbUidStore **pStore) {
  ASSERT(*pStore == NULL);
  *pStore = taosMemoryCalloc(1, sizeof(STbUidStore));
  if (*pStore == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return TSDB_CODE_FAILED;
  }
  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
144
static int32_t tdUpdateTbUidListImpl(SSma *pSma, tb_uid_t *suid, SArray *tbUids) {
145
  SSmaEnv   *pEnv = SMA_RSMA_ENV(pSma);
C
Cary Xu 已提交
146
  SRSmaStat *pStat = (SRSmaStat *)SMA_ENV_STAT(pEnv);
147 148 149 150
  SRSmaInfo *pRSmaInfo = NULL;

  if (!suid || !tbUids) {
    terrno = TSDB_CODE_INVALID_PTR;
S
Shengliang Guan 已提交
151
    smaError("vgId:%d, failed to get rsma info for uid:%" PRIi64 " since %s", SMA_VID(pSma), *suid, terrstr(terrno));
152 153 154
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
155
  pRSmaInfo = taosHashGet(RSMA_INFO_HASH(pStat), suid, sizeof(tb_uid_t));
156
  if (!pRSmaInfo || !(pRSmaInfo = *(SRSmaInfo **)pRSmaInfo)) {
S
Shengliang Guan 已提交
157
    smaError("vgId:%d, failed to get rsma info for uid:%" PRIi64, SMA_VID(pSma), *suid);
C
Cary Xu 已提交
158
    terrno = TSDB_CODE_RSMA_INVALID_STAT;
159 160 161
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
162 163 164 165 166 167 168 169
  if (pRSmaInfo->items[0].taskInfo) {
    if ((qUpdateQualifiedTableId(pRSmaInfo->items[0].taskInfo, tbUids, true) < 0)) {
      smaError("vgId:%d, update tbUidList failed for uid:%" PRIi64 " since %s", SMA_VID(pSma), *suid, terrstr(terrno));
      return TSDB_CODE_FAILED;
    } else {
      smaDebug("vgId:%d, update tbUidList succeed for qTaskInfo:%p with suid:%" PRIi64 ", uid:%" PRIi64, SMA_VID(pSma),
               pRSmaInfo->items[0].taskInfo, *suid, *(int64_t *)taosArrayGet(tbUids, 0));
    }
170 171
  }

C
Cary Xu 已提交
172 173 174 175 176 177 178 179
  if (pRSmaInfo->items[1].taskInfo) {
    if ((qUpdateQualifiedTableId(pRSmaInfo->items[1].taskInfo, tbUids, true) < 0)) {
      smaError("vgId:%d, update tbUidList failed for uid:%" PRIi64 " since %s", SMA_VID(pSma), *suid, terrstr(terrno));
      return TSDB_CODE_FAILED;
    } else {
      smaDebug("vgId:%d, update tbUidList succeed for qTaskInfo:%p with suid:%" PRIi64 ", uid:%" PRIi64, SMA_VID(pSma),
               pRSmaInfo->items[1].taskInfo, *suid, *(int64_t *)taosArrayGet(tbUids, 0));
    }
180 181 182 183 184 185 186 187 188 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 221 222 223 224 225
  }

  return TSDB_CODE_SUCCESS;
}

int32_t tdUpdateTbUidList(SSma *pSma, STbUidStore *pStore) {
  if (!pStore || (taosArrayGetSize(pStore->tbUids) == 0)) {
    return TSDB_CODE_SUCCESS;
  }

  if (tdUpdateTbUidListImpl(pSma, &pStore->suid, pStore->tbUids) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_FAILED;
  }

  void *pIter = taosHashIterate(pStore->uidHash, NULL);
  while (pIter) {
    tb_uid_t *pTbSuid = (tb_uid_t *)taosHashGetKey(pIter, NULL);
    SArray   *pTbUids = *(SArray **)pIter;

    if (tdUpdateTbUidListImpl(pSma, pTbSuid, pTbUids) != TSDB_CODE_SUCCESS) {
      taosHashCancelIterate(pStore->uidHash, pIter);
      return TSDB_CODE_FAILED;
    }

    pIter = taosHashIterate(pStore->uidHash, pIter);
  }
  return TSDB_CODE_SUCCESS;
}

/**
 * @brief fetch suid/uids when create child tables of rollup SMA
 *
 * @param pTsdb
 * @param ppStore
 * @param suid
 * @param uid
 * @return int32_t
 */
int32_t tdFetchTbUidList(SSma *pSma, STbUidStore **ppStore, tb_uid_t suid, tb_uid_t uid) {
  SSmaEnv *pEnv = SMA_RSMA_ENV(pSma);

  // only applicable to rollup SMA ctables
  if (!pEnv) {
    return TSDB_CODE_SUCCESS;
  }

C
Cary Xu 已提交
226 227 228
  SRSmaStat *pStat = (SRSmaStat *)SMA_ENV_STAT(pEnv);
  SHashObj  *infoHash = NULL;
  if (!pStat || !(infoHash = RSMA_INFO_HASH(pStat))) {
C
Cary Xu 已提交
229
    terrno = TSDB_CODE_RSMA_INVALID_STAT;
230 231 232 233 234 235 236 237 238 239 240
    return TSDB_CODE_FAILED;
  }

  // info cached when create rsma stable and return directly for non-rsma ctables
  if (!taosHashGet(infoHash, &suid, sizeof(tb_uid_t))) {
    return TSDB_CODE_SUCCESS;
  }

  ASSERT(ppStore != NULL);

  if (!(*ppStore)) {
241
    if (tdUidStoreInit(ppStore) < 0) {
242 243 244 245
      return TSDB_CODE_FAILED;
    }
  }

246
  if (tdUidStorePut(*ppStore, suid, &uid) < 0) {
247 248 249 250 251 252 253
    *ppStore = tdUidStoreFree(*ppStore);
    return TSDB_CODE_FAILED;
  }

  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
254 255 256 257 258 259
static int32_t tdSetRSmaInfoItemParams(SSma *pSma, SRSmaParam *param, SRSmaInfo *pRSmaInfo, SReadHandle *pReadHandle,
                                       int8_t idx) {
  SRetention *pRetention = SMA_RETENTION(pSma);
  STsdbCfg   *pTsdbCfg = SMA_TSDB_CFG(pSma);

  if (param->qmsg[idx]) {
C
Cary Xu 已提交
260
    SRSmaInfoItem *pItem = &(pRSmaInfo->items[idx]);
261
    pItem->refId = RSMA_REF_ID(pRSmaInfo->pStat);
C
Cary Xu 已提交
262
    pItem->pRsmaInfo = pRSmaInfo;
C
Cary Xu 已提交
263
    pItem->taskInfo = qCreateStreamExecTaskInfo(param->qmsg[idx], pReadHandle);
C
Cary Xu 已提交
264
    if (!pItem->taskInfo) {
C
Cary Xu 已提交
265
      terrno = TSDB_CODE_RSMA_QTASKINFO_CREATE;
C
Cary Xu 已提交
266 267
      goto _err;
    }
C
Cary Xu 已提交
268
    pItem->triggerStat = TASK_TRIGGER_STAT_INACTIVE;
C
Cary Xu 已提交
269 270 271
    if (param->maxdelay[idx] < TSDB_MIN_ROLLUP_MAX_DELAY) {
      int64_t msInterval =
          convertTimeFromPrecisionToUnit(pRetention[idx + 1].freq, pTsdbCfg->precision, TIME_UNIT_MILLISECOND);
C
Cary Xu 已提交
272
      pItem->maxDelay = (int32_t)msInterval;
C
Cary Xu 已提交
273
    } else {
C
Cary Xu 已提交
274
      pItem->maxDelay = (int32_t)param->maxdelay[idx];
C
Cary Xu 已提交
275
    }
C
Cary Xu 已提交
276 277
    if (pItem->maxDelay > TSDB_MAX_ROLLUP_MAX_DELAY) {
      pItem->maxDelay = TSDB_MAX_ROLLUP_MAX_DELAY;
C
Cary Xu 已提交
278
    }
C
Cary Xu 已提交
279
    pItem->level = (idx == 0 ? TSDB_RETENTION_L1 : TSDB_RETENTION_L2);
C
Cary Xu 已提交
280 281 282 283 284 285
  }
  return TSDB_CODE_SUCCESS;
_err:
  return TSDB_CODE_FAILED;
}

286
/**
287
 * @brief for rsam create or restore
288
 *
289 290 291 292
 * @param pSma
 * @param param
 * @param suid
 * @param tbName
293 294
 * @return int32_t
 */
295 296 297 298
int32_t tdProcessRSmaCreateImpl(SSma *pSma, SRSmaParam *param, int64_t suid, const char *tbName) {
  SVnode *pVnode = pSma->pVnode;
  SMeta  *pMeta = pVnode->pMeta;
  SMsgCb *pMsgCb = &pVnode->msgCb;
299

300
  if ((param->qmsgLen[0] == 0) && (param->qmsgLen[1] == 0)) {
301
    smaDebug("vgId:%d, no qmsg1/qmsg2 for rollup table %s %" PRIi64, SMA_VID(pSma), tbName, suid);
302 303 304
    return TSDB_CODE_SUCCESS;
  }

C
Cary Xu 已提交
305
  if (tdCheckAndInitSmaEnv(pSma, TSDB_SMA_TYPE_ROLLUP) != TSDB_CODE_SUCCESS) {
306 307 308 309 310
    terrno = TSDB_CODE_TDB_INIT_FAILED;
    return TSDB_CODE_FAILED;
  }

  SSmaEnv   *pEnv = SMA_RSMA_ENV(pSma);
C
Cary Xu 已提交
311
  SRSmaStat *pStat = (SRSmaStat *)SMA_ENV_STAT(pEnv);
312 313
  SRSmaInfo *pRSmaInfo = NULL;

314
  pRSmaInfo = taosHashGet(RSMA_INFO_HASH(pStat), &suid, sizeof(tb_uid_t));
315
  if (pRSmaInfo) {
C
Cary Xu 已提交
316
    ASSERT(0);  // TODO: free original pRSmaInfo if exists abnormally
317
    smaDebug("vgId:%d, rsma info already exists for table %s, %" PRIi64, SMA_VID(pSma), tbName, suid);
318 319 320
    return TSDB_CODE_SUCCESS;
  }

321
  // from write queue: single thead
322 323 324 325 326 327
  pRSmaInfo = (SRSmaInfo *)taosMemoryCalloc(1, sizeof(SRSmaInfo));
  if (!pRSmaInfo) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return TSDB_CODE_FAILED;
  }

L
Liu Jicong 已提交
328
  SStreamReader *pReadHandle = tqInitSubmitMsgScanner(pMeta);
329 330
  if (!pReadHandle) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
331
    goto _err;
332 333 334 335 336 337
  }

  SReadHandle handle = {
      .reader = pReadHandle,
      .meta = pMeta,
      .pMsgCb = pMsgCb,
5
54liuyao 已提交
338
      .vnode = pVnode,
339 340
  };

341
  STSchema *pTSchema = metaGetTbTSchema(SMA_META(pSma), suid, -1);
342 343 344 345 346
  if (!pTSchema) {
    terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION;
    goto _err;
  }
  pRSmaInfo->pTSchema = pTSchema;
347
  pRSmaInfo->pStat = pStat;
348
  pRSmaInfo->suid = suid;
349

C
Cary Xu 已提交
350 351 352
  if (tdSetRSmaInfoItemParams(pSma, param, pRSmaInfo, &handle, 0) < 0) {
    goto _err;
  }
C
Cary Xu 已提交
353

C
Cary Xu 已提交
354 355 356
  if (tdSetRSmaInfoItemParams(pSma, param, pRSmaInfo, &handle, 1) < 0) {
    goto _err;
  }
357

358
  if (taosHashPut(RSMA_INFO_HASH(pStat), &suid, sizeof(tb_uid_t), &pRSmaInfo, sizeof(pRSmaInfo)) < 0) {
359
    goto _err;
360 361
  }

C
Cary Xu 已提交
362
  smaDebug("vgId:%d, register rsma info succeed for table %" PRIi64, SMA_VID(pSma), suid);
C
Cary Xu 已提交
363

364
  return TSDB_CODE_SUCCESS;
365 366 367 368
_err:
  tdFreeRSmaInfo(pRSmaInfo);
  taosMemoryFree(pReadHandle);
  return TSDB_CODE_FAILED;
369 370
}

371
/**
C
Cary Xu 已提交
372
 * @brief Check and init qTaskInfo_t, only applicable to stable with SRSmaParam currently
373
 *
C
Cary Xu 已提交
374
 * @param pVnode
375 376 377 378 379 380 381 382 383 384 385 386 387
 * @param pReq
 * @return int32_t
 */
int32_t tdProcessRSmaCreate(SVnode *pVnode, SVCreateStbReq *pReq) {
  SSma *pSma = pVnode->pSma;
  if (!pReq->rollup) {
    smaTrace("vgId:%d, return directly since no rollup for stable %s %" PRIi64, SMA_VID(pSma), pReq->name, pReq->suid);
    return TSDB_CODE_SUCCESS;
  }

  return tdProcessRSmaCreateImpl(pSma, &pReq->rsmaParam, pReq->suid, pReq->name);
}

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
/**
 * @brief store suid/[uids], prefer to use array and then hash
 *
 * @param pStore
 * @param suid
 * @param uid
 * @return int32_t
 */
static int32_t tdUidStorePut(STbUidStore *pStore, tb_uid_t suid, tb_uid_t *uid) {
  // prefer to store suid/uids in array
  if ((suid == pStore->suid) || (pStore->suid == 0)) {
    if (pStore->suid == 0) {
      pStore->suid = suid;
    }
    if (uid) {
      if (!pStore->tbUids) {
        if (!(pStore->tbUids = taosArrayInit(1, sizeof(tb_uid_t)))) {
          terrno = TSDB_CODE_OUT_OF_MEMORY;
          return TSDB_CODE_FAILED;
        }
      }
      if (!taosArrayPush(pStore->tbUids, uid)) {
        return TSDB_CODE_FAILED;
      }
    }
  } else {
    // store other suid/uids in hash when multiple stable/table included in 1 batch of request
    if (!pStore->uidHash) {
      pStore->uidHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
      if (!pStore->uidHash) {
        return TSDB_CODE_FAILED;
      }
    }
    if (uid) {
      SArray *uidArray = taosHashGet(pStore->uidHash, &suid, sizeof(tb_uid_t));
      if (uidArray && ((uidArray = *(SArray **)uidArray))) {
        taosArrayPush(uidArray, uid);
      } else {
        SArray *pUidArray = taosArrayInit(1, sizeof(tb_uid_t));
        if (!pUidArray) {
          terrno = TSDB_CODE_OUT_OF_MEMORY;
          return TSDB_CODE_FAILED;
        }
        if (!taosArrayPush(pUidArray, uid)) {
          terrno = TSDB_CODE_OUT_OF_MEMORY;
          return TSDB_CODE_FAILED;
        }
435
        if (taosHashPut(pStore->uidHash, &suid, sizeof(suid), &pUidArray, sizeof(pUidArray)) < 0) {
436 437 438 439
          return TSDB_CODE_FAILED;
        }
      }
    } else {
440
      if (taosHashPut(pStore->uidHash, &suid, sizeof(suid), NULL, 0) < 0) {
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
        return TSDB_CODE_FAILED;
      }
    }
  }
  return TSDB_CODE_SUCCESS;
}

void tdUidStoreDestory(STbUidStore *pStore) {
  if (pStore) {
    if (pStore->uidHash) {
      if (pStore->tbUids) {
        // When pStore->tbUids not NULL, the pStore->uidHash has k/v; otherwise pStore->uidHash only has keys.
        void *pIter = taosHashIterate(pStore->uidHash, NULL);
        while (pIter) {
          SArray *arr = *(SArray **)pIter;
          taosArrayDestroy(arr);
          pIter = taosHashIterate(pStore->uidHash, pIter);
        }
      }
      taosHashCleanup(pStore->uidHash);
    }
    taosArrayDestroy(pStore->tbUids);
  }
}

void *tdUidStoreFree(STbUidStore *pStore) {
  if (pStore) {
    tdUidStoreDestory(pStore);
    taosMemoryFree(pStore);
  }
  return NULL;
}

static int32_t tdProcessSubmitReq(STsdb *pTsdb, int64_t version, void *pReq) {
  if (!pReq) {
    terrno = TSDB_CODE_INVALID_PTR;
    return TSDB_CODE_FAILED;
  }

  SSubmitReq *pSubmitReq = (SSubmitReq *)pReq;

  if (tsdbInsertData(pTsdb, version, pSubmitReq, NULL) < 0) {
    return TSDB_CODE_FAILED;
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t tdFetchSubmitReqSuids(SSubmitReq *pMsg, STbUidStore *pStore) {
  SSubmitMsgIter msgIter = {0};
  SSubmitBlk    *pBlock = NULL;
  SSubmitBlkIter blkIter = {0};
  STSRow        *row = NULL;

  terrno = TSDB_CODE_SUCCESS;

C
Cary Xu 已提交
497 498 499
  if (tInitSubmitMsgIter(pMsg, &msgIter) < 0) {
    return -1;
  }
500
  while (true) {
C
Cary Xu 已提交
501 502 503
    if (tGetSubmitMsgNext(&msgIter, &pBlock) < 0) {
      return -1;
    }
504 505 506 507 508

    if (!pBlock) break;
    tdUidStorePut(pStore, msgIter.suid, NULL);
  }

C
Cary Xu 已提交
509 510 511
  if (terrno != TSDB_CODE_SUCCESS) {
    return -1;
  }
512 513 514
  return 0;
}

C
Cary Xu 已提交
515
static void tdDestroySDataBlockArray(SArray *pArray) {
C
Cary Xu 已提交
516
  // TODO
C
Cary Xu 已提交
517 518 519 520 521 522 523 524 525
#if 0
  for (int32_t i = 0; i < taosArrayGetSize(pArray); ++i) {
    SSDataBlock *pDataBlock = taosArrayGet(pArray, i);
    blockDestroyInner(pDataBlock);
  }
#endif
  taosArrayDestroy(pArray);
}

526 527 528
static int32_t tdFetchAndSubmitRSmaResult(SRSmaInfoItem *pItem, int8_t blkType) {
  SArray    *pResult = NULL;
  SRSmaInfo *pRSmaInfo = pItem->pRsmaInfo;
529
  SSma      *pSma = RSMA_INFO_SMA(pRSmaInfo);
530 531 532 533

  while (1) {
    SSDataBlock *output = NULL;
    uint64_t     ts;
534
    if (qExecTask(pItem->taskInfo, &output, &ts) < 0) {
535 536 537 538 539
      ASSERT(false);
    }
    if (!output) {
      break;
    }
C
Cary Xu 已提交
540

541
    if (!pResult) {
C
Cary Xu 已提交
542
      pResult = taosArrayInit(1, sizeof(SSDataBlock));
543 544 545 546 547 548 549 550 551 552
      if (!pResult) {
        terrno = TSDB_CODE_OUT_OF_MEMORY;
        return TSDB_CODE_FAILED;
      }
    }

    taosArrayPush(pResult, output);
  }

  if (taosArrayGetSize(pResult) > 0) {
C
Cary Xu 已提交
553
#if 1
C
Cary Xu 已提交
554
    char flag[10] = {0};
555
    snprintf(flag, 10, "level %" PRIi8, pItem->level);
S
slzhou 已提交
556
    blockDebugShowDataBlocks(pResult, flag);
C
Cary Xu 已提交
557
#endif
558
    STsdb      *sinkTsdb = (pItem->level == TSDB_RETENTION_L1 ? pSma->pRSmaTsdb1 : pSma->pRSmaTsdb2);
559
    SSubmitReq *pReq = NULL;
C
Cary Xu 已提交
560
    // TODO: the schema update should be handled
561
    if (buildSubmitReqFromDataBlock(&pReq, pResult, pRSmaInfo->pTSchema, SMA_VID(pSma), pRSmaInfo->suid) < 0) {
C
Cary Xu 已提交
562
      goto _err;
563
    }
564

C
Cary Xu 已提交
565
    if (pReq && tdProcessSubmitReq(sinkTsdb, 1, pReq) < 0) {
566
      taosMemoryFreeClear(pReq);
C
Cary Xu 已提交
567
      goto _err;
568
    }
569

570
    taosMemoryFreeClear(pReq);
C
Cary Xu 已提交
571 572
  } else if (terrno == 0) {
    smaDebug("vgId:%d, no rsma %" PRIi8 " data fetched yet", SMA_VID(pSma), pItem->level);
573
  } else {
C
Cary Xu 已提交
574
    smaDebug("vgId:%d, no rsma %" PRIi8 " data fetched since %s", SMA_VID(pSma), pItem->level, tstrerror(terrno));
575 576
  }

C
Cary Xu 已提交
577
  tdDestroySDataBlockArray(pResult);
C
Cary Xu 已提交
578 579
  return TSDB_CODE_SUCCESS;
_err:
C
Cary Xu 已提交
580
  tdDestroySDataBlockArray(pResult);
C
Cary Xu 已提交
581
  return TSDB_CODE_FAILED;
582 583 584 585 586 587 588 589
}

/**
 * @brief trigger to get rsma result
 *
 * @param param
 * @param tmrId
 */
C
Cary Xu 已提交
590
static void tdRSmaFetchTrigger(void *param, void *tmrId) {
591
  SRSmaInfoItem *pItem = param;
592 593 594 595 596 597
  SSma          *pSma = NULL;
  SRSmaStat     *pStat = (SRSmaStat *)taosAcquireRef(smaMgmt.smaRef, pItem->refId);
  if (!pStat) {
    smaDebug("rsma fetch task not start since already destroyed");
    return;
  }
598

599 600
  pSma = RSMA_INFO_SMA(pItem->pRsmaInfo);

C
Cary Xu 已提交
601
  // if rsma trigger stat in paused, cancelled or finished, not start fetch task
C
Cary Xu 已提交
602
  int8_t rsmaTriggerStat = atomic_load_8(RSMA_TRIGGER_STAT(pStat));
C
Cary Xu 已提交
603 604 605 606 607 608 609 610 611 612 613
  switch (rsmaTriggerStat) {
    case TASK_TRIGGER_STAT_PAUSED:
    case TASK_TRIGGER_STAT_CANCELLED:
    case TASK_TRIGGER_STAT_FINISHED: {
      taosReleaseRef(smaMgmt.smaRef, pItem->refId);
      smaDebug("vgId:%d, not fetch rsma level %" PRIi8 " data for table:%" PRIi64 " since stat is cancelled",
               SMA_VID(pSma), pItem->level, pItem->pRsmaInfo->suid);
      return;
    }
    default:
      break;
C
Cary Xu 已提交
614
  }
615

C
Cary Xu 已提交
616 617
  int8_t fetchTriggerStat =
      atomic_val_compare_exchange_8(&pItem->triggerStat, TASK_TRIGGER_STAT_ACTIVE, TASK_TRIGGER_STAT_INACTIVE);
C
Cary Xu 已提交
618 619 620 621
  switch (fetchTriggerStat) {
    case TASK_TRIGGER_STAT_ACTIVE: {
      smaDebug("vgId:%d, fetch rsma level %" PRIi8 " data for table:%" PRIi64 " since stat is active", SMA_VID(pSma),
               pItem->level, pItem->pRsmaInfo->suid);
622

C
Cary Xu 已提交
623
      tdRefSmaStat(pSma, (SSmaStat *)pStat);
C
Cary Xu 已提交
624

C
Cary Xu 已提交
625 626 627
      SSDataBlock dataBlock = {.info.type = STREAM_GET_ALL};
      qSetStreamInput(pItem->taskInfo, &dataBlock, STREAM_INPUT__DATA_BLOCK, false);
      tdFetchAndSubmitRSmaResult(pItem, STREAM_INPUT__DATA_BLOCK);
C
Cary Xu 已提交
628

C
Cary Xu 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
      tdUnRefSmaStat(pSma, (SSmaStat *)pStat);
    } break;
    case TASK_TRIGGER_STAT_PAUSED: {
      smaDebug("vgId:%d, not fetch rsma level %" PRIi8 " data for table:%" PRIi64 " since stat is paused",
               SMA_VID(pSma), pItem->level, pItem->pRsmaInfo->suid);
    } break;
    case TASK_TRIGGER_STAT_INACTIVE: {
      smaDebug("vgId:%d, not fetch rsma level %" PRIi8 " data for table:%" PRIi64 " since stat is inactive",
               SMA_VID(pSma), pItem->level, pItem->pRsmaInfo->suid);
    } break;
    case TASK_TRIGGER_STAT_INIT: {
      smaDebug("vgId:%d, not fetch rsma level %" PRIi8 " data for table:%" PRIi64 " since stat is init", SMA_VID(pSma),
               pItem->level, pItem->pRsmaInfo->suid);
    } break;
    default: {
      smaWarn("vgId:%d, not fetch rsma level %" PRIi8 " data for table:%" PRIi64 " since stat is unknown",
              SMA_VID(pSma), pItem->level, pItem->pRsmaInfo->suid);
    } break;
647
  }
C
Cary Xu 已提交
648

649 650
_end:
  taosReleaseRef(smaMgmt.smaRef, pItem->refId);
651 652
}

C
Cary Xu 已提交
653 654
static int32_t tdExecuteRSmaImpl(SSma *pSma, const void *pMsg, int32_t inputType, SRSmaInfoItem *pItem, tb_uid_t suid,
                                 int8_t level) {
655 656 657 658 659 660 661 662
  if (!pItem || !pItem->taskInfo) {
    smaDebug("vgId:%d, no qTaskInfo to execute rsma %" PRIi8 " task for suid:%" PRIu64, SMA_VID(pSma), level, suid);
    return TSDB_CODE_SUCCESS;
  }

  smaDebug("vgId:%d, execute rsma %" PRIi8 " task for qTaskInfo:%p suid:%" PRIu64, SMA_VID(pSma), level,
           pItem->taskInfo, suid);

L
Liu Jicong 已提交
663
  if (qSetStreamInput(pItem->taskInfo, pMsg, inputType, true) < 0) {  // INPUT__DATA_SUBMIT
664 665 666 667
    smaError("vgId:%d, rsma % " PRIi8 " qSetStreamInput failed since %s", SMA_VID(pSma), level, tstrerror(terrno));
    return TSDB_CODE_FAILED;
  }

L
Liu Jicong 已提交
668
  tdFetchAndSubmitRSmaResult(pItem, STREAM_INPUT__DATA_SUBMIT);
C
Cary Xu 已提交
669
  atomic_store_8(&pItem->triggerStat, TASK_TRIGGER_STAT_ACTIVE);
C
Cary Xu 已提交
670 671 672 673

  SSmaEnv   *pEnv = SMA_RSMA_ENV(pSma);
  SRSmaStat *pStat = SMA_RSMA_STAT(pEnv->pStat);

C
Cary Xu 已提交
674 675 676 677 678
  if (pStat->tmrHandle) {
    taosTmrReset(tdRSmaFetchTrigger, pItem->maxDelay, pItem, pStat->tmrHandle, &pItem->tmrId);
  } else {
    ASSERT(0);
  }
679 680 681 682

  return TSDB_CODE_SUCCESS;
}

683
static int32_t tdExecuteRSma(SSma *pSma, const void *pMsg, int32_t inputType, tb_uid_t suid) {
684 685 686 687 688 689
  SSmaEnv *pEnv = SMA_RSMA_ENV(pSma);
  if (!pEnv) {
    // only applicable when rsma env exists
    return TSDB_CODE_SUCCESS;
  }

C
Cary Xu 已提交
690
  SRSmaStat *pStat = (SRSmaStat *)SMA_ENV_STAT(pEnv);
691 692
  SRSmaInfo *pRSmaInfo = NULL;

C
Cary Xu 已提交
693
  pRSmaInfo = taosHashGet(RSMA_INFO_HASH(pStat), &suid, sizeof(tb_uid_t));
694 695

  if (!pRSmaInfo || !(pRSmaInfo = *(SRSmaInfo **)pRSmaInfo)) {
696
    smaDebug("vgId:%d, return as no rsma info for suid:%" PRIu64, SMA_VID(pSma), suid);
697 698
    return TSDB_CODE_SUCCESS;
  }
699 700 701

  if (!pRSmaInfo->items[0].taskInfo) {
    smaDebug("vgId:%d, return as no rsma qTaskInfo for suid:%" PRIu64, SMA_VID(pSma), suid);
702 703 704
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
705
  if (inputType == STREAM_INPUT__DATA_SUBMIT) {
706 707
    tdExecuteRSmaImpl(pSma, pMsg, inputType, &pRSmaInfo->items[0], suid, TSDB_RETENTION_L1);
    tdExecuteRSmaImpl(pSma, pMsg, inputType, &pRSmaInfo->items[1], suid, TSDB_RETENTION_L2);
708 709 710 711 712 713 714 715 716 717 718 719
  }

  return TSDB_CODE_SUCCESS;
}

int32_t tdProcessRSmaSubmit(SSma *pSma, void *pMsg, int32_t inputType) {
  SSmaEnv *pEnv = SMA_RSMA_ENV(pSma);
  if (!pEnv) {
    // only applicable when rsma env exists
    return TSDB_CODE_SUCCESS;
  }

720 721 722 723 724 725
  SRetention *pRetention = SMA_RETENTION(pSma);
  if (!RETENTION_VALID(pRetention + 1)) {
    // return directly if retention level 1 is invalid
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
726
  if (inputType == STREAM_INPUT__DATA_SUBMIT) {
727 728 729 730
    STbUidStore uidStore = {0};
    tdFetchSubmitReqSuids(pMsg, &uidStore);

    if (uidStore.suid != 0) {
731
      tdExecuteRSma(pSma, pMsg, inputType, uidStore.suid);
732 733 734 735

      void *pIter = taosHashIterate(uidStore.uidHash, NULL);
      while (pIter) {
        tb_uid_t *pTbSuid = (tb_uid_t *)taosHashGetKey(pIter, NULL);
736
        tdExecuteRSma(pSma, pMsg, inputType, *pTbSuid);
737 738 739 740 741 742 743 744
        pIter = taosHashIterate(uidStore.uidHash, pIter);
      }

      tdUidStoreDestory(&uidStore);
    }
  }
  return TSDB_CODE_SUCCESS;
}
C
Cary Xu 已提交
745

C
Cary Xu 已提交
746
static int32_t tdRSmaRestoreQTaskInfoInit(SSma *pSma, int64_t *nTables) {
747 748 749 750
  SVnode *pVnode = pSma->pVnode;

  SArray *suidList = taosArrayInit(1, sizeof(tb_uid_t));
  if (tsdbGetStbIdList(SMA_META(pSma), 0, suidList) < 0) {
C
Cary Xu 已提交
751 752
    taosArrayDestroy(suidList);
    smaError("vgId:%d, failed to restore rsma env since get stb id list error: %s", TD_VID(pVnode), terrstr());
753 754 755
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
756 757 758 759 760 761
  int64_t arrSize = taosArrayGetSize(suidList);

  if (nTables) {
    *nTables = arrSize;
  }

C
Cary Xu 已提交
762 763 764
  if (arrSize == 0) {
    taosArrayDestroy(suidList);
    smaDebug("vgId:%d, no need to restore rsma env since empty stb id list", TD_VID(pVnode));
765 766 767 768 769
    return TSDB_CODE_SUCCESS;
  }

  SMetaReader mr = {0};
  metaReaderInit(&mr, SMA_META(pSma), 0);
C
Cary Xu 已提交
770
  for (int64_t i = 0; i < arrSize; ++i) {
771
    tb_uid_t suid = *(tb_uid_t *)taosArrayGet(suidList, i);
C
Cary Xu 已提交
772
    smaDebug("vgId:%d, rsma restore, suid is %" PRIi64, TD_VID(pVnode), suid);
773
    if (metaGetTableEntryByUid(&mr, suid) < 0) {
C
Cary Xu 已提交
774 775
      smaError("vgId:%d, rsma restore, failed to get table meta for %" PRIi64 " since %s", TD_VID(pVnode), suid,
               terrstr());
776 777 778 779 780 781
      goto _err;
    }
    ASSERT(mr.me.type == TSDB_SUPER_TABLE);
    ASSERT(mr.me.uid == suid);
    if (TABLE_IS_ROLLUP(mr.me.flags)) {
      SRSmaParam *param = &mr.me.stbEntry.rsmaParam;
C
Cary Xu 已提交
782 783 784 785
      for (int i = 0; i < TSDB_RETENTION_L2; ++i) {
        smaDebug("vgId:%d, rsma restore, table:%" PRIi64 " level:%d, maxdelay:%" PRIi64 " watermark:%" PRIi64
                 " qmsgLen:%" PRIi32,
                 TD_VID(pVnode), suid, i, param->maxdelay[i], param->watermark[i], param->qmsgLen[i]);
786 787
      }
      if (tdProcessRSmaCreateImpl(pSma, &mr.me.stbEntry.rsmaParam, suid, mr.me.name) < 0) {
C
Cary Xu 已提交
788
        smaError("vgId:%d, rsma restore env failed for %" PRIi64 " since %s", TD_VID(pVnode), suid, terrstr());
789 790
        goto _err;
      }
C
Cary Xu 已提交
791
      smaDebug("vgId:%d, rsma restore env success for %" PRIi64, TD_VID(pVnode), suid);
792 793 794
    }
  }

C
Cary Xu 已提交
795 796 797 798 799 800 801 802 803 804 805
  metaReaderClear(&mr);
  taosArrayDestroy(suidList);

  return TSDB_CODE_SUCCESS;
_err:
  metaReaderClear(&mr);
  taosArrayDestroy(suidList);

  return TSDB_CODE_FAILED;
}

C
Cary Xu 已提交
806
static int32_t tdRSmaRestoreQTaskInfoReload(SSma *pSma, int64_t *committed) {
C
Cary Xu 已提交
807
  SVnode *pVnode = pSma->pVnode;
C
Cary Xu 已提交
808
  STFile  tFile = {0};
C
Cary Xu 已提交
809
  char    qTaskInfoFName[TSDB_FILENAME_LEN] = {0};
810

C
Cary Xu 已提交
811 812
  tdRSmaQTaskInfoGetFName(TD_VID(pVnode), pVnode->state.committed, qTaskInfoFName);
  if (tdInitTFile(&tFile, tfsGetPrimaryPath(pVnode->pTfs), qTaskInfoFName) < 0) {
813 814
    goto _err;
  }
C
Cary Xu 已提交
815 816

  if (!taosCheckExistFile(TD_TFILE_FULL_NAME(&tFile))) {
C
Cary Xu 已提交
817 818 819
    if (pVnode->state.committed > 0) {
      smaWarn("vgId:%d, rsma restore for version %" PRIi64 ", not start as %s not exist", TD_VID(pVnode),
              pVnode->state.committed, TD_TFILE_FULL_NAME(&tFile));
C
Cary Xu 已提交
820 821 822 823
    } else {
      smaDebug("vgId:%d, rsma restore for version %" PRIi64 ", no need as %s not exist", TD_VID(pVnode),
               pVnode->state.committed, TD_TFILE_FULL_NAME(&tFile));
    }
C
Cary Xu 已提交
824
    return TSDB_CODE_SUCCESS;
825 826
  }

827 828 829
  if (tdOpenTFile(&tFile, TD_FILE_READ) < 0) {
    goto _err;
  }
C
Cary Xu 已提交
830

C
Cary Xu 已提交
831
  SRSmaQTaskInfoIter fIter = {0};
832
  if (tdRSmaQTaskInfoIterInit(&fIter, &tFile) < 0) {
C
Cary Xu 已提交
833 834
    tdRSmaQTaskInfoIterDestroy(&fIter);
    tdCloseTFile(&tFile);
C
Cary Xu 已提交
835
    tdDestroyTFile(&tFile);
836 837
    goto _err;
  }
C
Cary Xu 已提交
838

C
Cary Xu 已提交
839
  if (tdRSmaQTaskInfoRestore(pSma, &fIter) < 0) {
C
Cary Xu 已提交
840 841
    tdRSmaQTaskInfoIterDestroy(&fIter);
    tdCloseTFile(&tFile);
C
Cary Xu 已提交
842
    tdDestroyTFile(&tFile);
C
Cary Xu 已提交
843 844
    goto _err;
  }
845

C
Cary Xu 已提交
846
  tdRSmaQTaskInfoIterDestroy(&fIter);
C
Cary Xu 已提交
847
  tdCloseTFile(&tFile);
C
Cary Xu 已提交
848
  tdDestroyTFile(&tFile);
C
Cary Xu 已提交
849 850 851 852

  // restored successfully from committed
  *committed = pVnode->state.committed;

C
Cary Xu 已提交
853 854
  return TSDB_CODE_SUCCESS;
_err:
C
Cary Xu 已提交
855 856
  smaError("vgId:%d, rsma restore for version %" PRIi64 ", qtaskinfo reload failed since %s", TD_VID(pVnode),
           pVnode->state.committed, terrstr());
C
Cary Xu 已提交
857 858 859 860 861
  return TSDB_CODE_FAILED;
}

/**
 * @brief reload ts data from checkpoint
C
Cary Xu 已提交
862 863
 *
 * @param pSma
C
Cary Xu 已提交
864
 * @param committed restore from committed version
C
Cary Xu 已提交
865
 * @return int32_t
C
Cary Xu 已提交
866
 */
C
Cary Xu 已提交
867
static int32_t tdRSmaRestoreTSDataReload(SSma *pSma, int64_t committed) {
C
Cary Xu 已提交
868
  // TODO
C
Cary Xu 已提交
869
  smaDebug("vgId:%d, rsma restore from %" PRIi64 ", ts data reload success", SMA_VID(pSma), committed);
C
Cary Xu 已提交
870 871
  return TSDB_CODE_SUCCESS;
_err:
C
Cary Xu 已提交
872 873
  smaError("vgId:%d, rsma restore from %" PRIi64 ", ts data reload failed since %s", SMA_VID(pSma), committed,
           terrstr());
C
Cary Xu 已提交
874 875 876 877 878
  return TSDB_CODE_FAILED;
}

int32_t tdProcessRSmaRestoreImpl(SSma *pSma) {
  // step 1: iterate all stables to restore the rsma env
C
Cary Xu 已提交
879
  int64_t nTables = 0;
C
Cary Xu 已提交
880
  if (tdRSmaRestoreQTaskInfoInit(pSma, &nTables) < 0) {
C
Cary Xu 已提交
881 882
    goto _err;
  }
C
Cary Xu 已提交
883

C
Cary Xu 已提交
884 885 886 887
  if (nTables <= 0) {
    smaDebug("vgId:%d, no need to restore rsma task since no tables", SMA_VID(pSma));
    return TSDB_CODE_SUCCESS;
  }
C
Cary Xu 已提交
888 889

  // step 2: retrieve qtaskinfo items from the persistence file(rsma/qtaskinfo) and restore
C
Cary Xu 已提交
890 891
  int64_t committed = -1;
  if (tdRSmaRestoreQTaskInfoReload(pSma, &committed) < 0) {
C
Cary Xu 已提交
892 893 894 895
    goto _err;
  }

  // step 3: reload ts data from checkpoint
896
  if (tdRSmaRestoreTSDataReload(pSma, committed) < 0) {
C
Cary Xu 已提交
897 898 899
    goto _err;
  }

900 901
  return TSDB_CODE_SUCCESS;
_err:
C
Cary Xu 已提交
902
  smaError("vgId:%d failed to restore rsma task since %s", SMA_VID(pSma), terrstr());
903 904 905
  return TSDB_CODE_FAILED;
}

C
Cary Xu 已提交
906
static int32_t tdRSmaQTaskInfoItemRestore(SSma *pSma, const SRSmaQTaskInfoItem *pItem) {
907 908 909 910
  SRSmaStat *pStat = (SRSmaStat *)SMA_ENV_STAT((SSmaEnv *)pSma->pRSmaEnv);
  SRSmaInfo *pRSmaInfo = NULL;
  void      *qTaskInfo = NULL;

C
Cary Xu 已提交
911
  pRSmaInfo = taosHashGet(RSMA_INFO_HASH(pStat), &pItem->suid, sizeof(pItem->suid));
912 913

  if (!pRSmaInfo || !(pRSmaInfo = *(SRSmaInfo **)pRSmaInfo)) {
C
Cary Xu 已提交
914
    smaDebug("vgId:%d, no restore as no rsma info for table:%" PRIu64, SMA_VID(pSma), pItem->suid);
915 916 917
    return TSDB_CODE_SUCCESS;
  }

C
Cary Xu 已提交
918
  if (pItem->type == TSDB_RETENTION_L1) {
919
    qTaskInfo = pRSmaInfo->items[0].taskInfo;
C
Cary Xu 已提交
920
  } else if (pItem->type == TSDB_RETENTION_L2) {
921 922 923 924 925 926
    qTaskInfo = pRSmaInfo->items[1].taskInfo;
  } else {
    ASSERT(0);
  }

  if (!qTaskInfo) {
C
Cary Xu 已提交
927
    smaDebug("vgId:%d, no restore as NULL rsma qTaskInfo for table:%" PRIu64, SMA_VID(pSma), pItem->suid);
928 929 930
    return TSDB_CODE_SUCCESS;
  }

C
Cary Xu 已提交
931 932 933
  if (qDeserializeTaskStatus(qTaskInfo, pItem->qTaskInfo, pItem->len) < 0) {
    smaError("vgId:%d, restore rsma task failed for table:%" PRIi64 " level %d since %s", SMA_VID(pSma), pItem->suid,
             pItem->type, terrstr(terrno));
934 935
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
936 937
  smaDebug("vgId:%d, restore rsma task success for table:%" PRIi64 " level %d", SMA_VID(pSma), pItem->suid,
           pItem->type);
938 939 940 941

  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
942
static int32_t tdRSmaQTaskInfoIterInit(SRSmaQTaskInfoIter *pIter, STFile *pTFile) {
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
  memset(pIter, 0, sizeof(*pIter));
  pIter->pTFile = pTFile;
  pIter->offset = TD_FILE_HEAD_SIZE;

  if (tdGetTFileSize(pTFile, &pIter->fsize) < 0) {
    return TSDB_CODE_FAILED;
  }

  if ((pIter->fsize - TD_FILE_HEAD_SIZE) < RSMA_QTASKINFO_BUFSIZE) {
    pIter->nAlloc = pIter->fsize - TD_FILE_HEAD_SIZE;
  } else {
    pIter->nAlloc = RSMA_QTASKINFO_BUFSIZE;
  }

  if (pIter->nAlloc < TD_FILE_HEAD_SIZE) {
    pIter->nAlloc = TD_FILE_HEAD_SIZE;
  }

C
Cary Xu 已提交
961 962
  pIter->pBuf = taosMemoryMalloc(pIter->nAlloc);
  if (!pIter->pBuf) {
963 964 965
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
966
  pIter->qBuf = pIter->pBuf;
967 968 969 970

  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
971
static int32_t tdRSmaQTaskInfoIterNextBlock(SRSmaQTaskInfoIter *pIter, bool *isFinish) {
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
  STFile *pTFile = pIter->pTFile;
  int64_t nBytes = RSMA_QTASKINFO_BUFSIZE;

  if (pIter->offset >= pIter->fsize) {
    *isFinish = true;
    return TSDB_CODE_SUCCESS;
  }

  if ((pIter->fsize - pIter->offset) < RSMA_QTASKINFO_BUFSIZE) {
    nBytes = pIter->fsize - pIter->offset;
  }

  if (tdSeekTFile(pTFile, pIter->offset, SEEK_SET) < 0) {
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
988
  if (tdReadTFile(pTFile, pIter->qBuf, nBytes) != nBytes) {
989 990 991 992
    return TSDB_CODE_FAILED;
  }

  int32_t infoLen = 0;
C
Cary Xu 已提交
993
  taosDecodeFixedI32(pIter->qBuf, &infoLen);
994
  if (infoLen > nBytes) {
C
Cary Xu 已提交
995 996 997 998 999
    if (infoLen <= RSMA_QTASKINFO_BUFSIZE) {
      terrno = TSDB_CODE_RSMA_FILE_CORRUPTED;
      smaError("iterate rsma qtaskinfo file %s failed since %s", TD_TFILE_FULL_NAME(pIter->pTFile), terrstr());
      return TSDB_CODE_FAILED;
    }
1000
    pIter->nAlloc = infoLen;
C
Cary Xu 已提交
1001
    void *pBuf = taosMemoryRealloc(pIter->pBuf, infoLen);
1002 1003 1004 1005
    if (!pBuf) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      return TSDB_CODE_FAILED;
    }
C
Cary Xu 已提交
1006 1007
    pIter->pBuf = pBuf;
    pIter->qBuf = pIter->pBuf;
1008 1009 1010 1011 1012 1013
    nBytes = infoLen;

    if (tdSeekTFile(pTFile, pIter->offset, SEEK_SET)) {
      return TSDB_CODE_FAILED;
    }

C
Cary Xu 已提交
1014
    if (tdReadTFile(pTFile, pIter->pBuf, nBytes) != nBytes) {
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
      return TSDB_CODE_FAILED;
    }
  }

  pIter->offset += nBytes;
  pIter->nBytes = nBytes;
  pIter->nBufPos = 0;

  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
1026
static int32_t tdRSmaQTaskInfoRestore(SSma *pSma, SRSmaQTaskInfoIter *pIter) {
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
  while (1) {
    // block iter
    bool isFinish = false;
    if (tdRSmaQTaskInfoIterNextBlock(pIter, &isFinish) < 0) {
      return TSDB_CODE_FAILED;
    }
    if (isFinish) {
      return TSDB_CODE_SUCCESS;
    }

    // consume the block
    int32_t qTaskInfoLenWithHead = 0;
C
Cary Xu 已提交
1039 1040
    pIter->qBuf = taosDecodeFixedI32(pIter->qBuf, &qTaskInfoLenWithHead);
    if (qTaskInfoLenWithHead < RSMA_QTASKINFO_HEAD_LEN) {
1041
      terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
C
Cary Xu 已提交
1042 1043
      smaError("vgId:%d, restore rsma qtaskinfo file %s failed since %s", SMA_VID(pSma),
               TD_TFILE_FULL_NAME(pIter->pTFile), terrstr());
1044 1045
      return TSDB_CODE_FAILED;
    }
C
Cary Xu 已提交
1046

1047 1048
    while (1) {
      if ((pIter->nBufPos + qTaskInfoLenWithHead) <= pIter->nBytes) {
C
Cary Xu 已提交
1049 1050 1051 1052 1053
        SRSmaQTaskInfoItem infoItem = {0};
        pIter->qBuf = taosDecodeFixedI8(pIter->qBuf, &infoItem.type);
        pIter->qBuf = taosDecodeFixedI64(pIter->qBuf, &infoItem.suid);
        infoItem.qTaskInfo = pIter->qBuf;
        infoItem.len = tdRSmaQTaskInfoContLen(qTaskInfoLenWithHead);
1054
        // do the restore job
C
Cary Xu 已提交
1055 1056 1057
        smaDebug("vgId:%d, restore the qtask info %s offset:%" PRIi64 "\n", SMA_VID(pSma),
                 TD_TFILE_FULL_NAME(pIter->pTFile), pIter->offset - pIter->nBytes + pIter->nBufPos);
        tdRSmaQTaskInfoItemRestore(pSma, &infoItem);
1058

C
Cary Xu 已提交
1059
        pIter->qBuf = POINTER_SHIFT(pIter->qBuf, infoItem.len);
1060 1061
        pIter->nBufPos += qTaskInfoLenWithHead;

C
Cary Xu 已提交
1062 1063 1064 1065 1066 1067 1068
        if ((pIter->nBufPos + RSMA_QTASKINFO_HEAD_LEN) >= pIter->nBytes) {
          // prepare and load next block in the file
          pIter->offset -= (pIter->nBytes - pIter->nBufPos);
          break;
        }

        pIter->qBuf = taosDecodeFixedI32(pIter->qBuf, &qTaskInfoLenWithHead);
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
        continue;
      }
      // prepare and load next block in the file
      pIter->offset -= (pIter->nBytes - pIter->nBufPos);
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}
C
Cary Xu 已提交
1079

C
Cary Xu 已提交
1080
int32_t tdRSmaPersistExecImpl(SRSmaStat *pRSmaStat) {
C
Cary Xu 已提交
1081 1082 1083 1084 1085
  SSma   *pSma = pRSmaStat->pSma;
  SVnode *pVnode = pSma->pVnode;
  int32_t vid = SMA_VID(pSma);
  int64_t toffset = 0;
  bool    isFileCreated = false;
C
Cary Xu 已提交
1086

1087 1088 1089 1090
  if (taosHashGetSize(RSMA_INFO_HASH(pRSmaStat)) <= 0) {
    return TSDB_CODE_SUCCESS;
  }

C
Cary Xu 已提交
1091 1092
  void *infoHash = taosHashIterate(RSMA_INFO_HASH(pRSmaStat), NULL);
  if (!infoHash) {
C
Cary Xu 已提交
1093
    return TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
1094 1095 1096 1097 1098 1099 1100 1101
  }

  STFile tFile = {0};
  while (infoHash) {
    SRSmaInfo *pRSmaInfo = *(SRSmaInfo **)infoHash;
    for (int32_t i = 0; i < TSDB_RETENTION_L2; ++i) {
      qTaskInfo_t taskInfo = pRSmaInfo->items[i].taskInfo;
      if (!taskInfo) {
1102
        smaDebug("vgId:%d, rsma, table %" PRIi64 " level %d qTaskInfo is NULL", vid, pRSmaInfo->suid, i + 1);
C
Cary Xu 已提交
1103 1104 1105 1106 1107 1108 1109
        continue;
      }

      char   *pOutput = NULL;
      int32_t len = 0;
      int8_t  type = (int8_t)(i + 1);
      if (qSerializeTaskStatus(taskInfo, &pOutput, &len) < 0) {
1110 1111
        smaError("vgId:%d, rsma, table %" PRIi64 " level %d serialize qTaskInfo failed since %s", vid, pRSmaInfo->suid,
                 i + 1, terrstr(terrno));
C
Cary Xu 已提交
1112 1113 1114
        goto _err;
      }
      if (!pOutput || len <= 0) {
1115 1116
        smaDebug("vgId:%d, rsma, table %" PRIi64
                 " level %d serialize qTaskInfo success but no output(len %d), not persist",
C
Cary Xu 已提交
1117 1118 1119 1120 1121
                 vid, pRSmaInfo->suid, i + 1, len);
        taosMemoryFreeClear(pOutput);
        continue;
      }

1122
      smaDebug("vgId:%d, rsma, table %" PRIi64 " level %d serialize qTaskInfo success with len %d, need persist", vid,
C
Cary Xu 已提交
1123 1124 1125 1126
               pRSmaInfo->suid, i + 1, len);

      if (!isFileCreated) {
        char qTaskInfoFName[TSDB_FILENAME_LEN];
C
Cary Xu 已提交
1127 1128
        tdRSmaQTaskInfoGetFName(vid, pSma->pVnode->state.applied, qTaskInfoFName);
        if (tdInitTFile(&tFile, tfsGetPrimaryPath(pVnode->pTfs), qTaskInfoFName) < 0) {
C
Cary Xu 已提交
1129
          smaError("vgId:%d, rsma persit, init %s failed since %s", vid, qTaskInfoFName, terrstr());
C
Cary Xu 已提交
1130 1131 1132
          goto _err;
        }
        if (tdCreateTFile(&tFile, true, -1) < 0) {
C
Cary Xu 已提交
1133
          smaError("vgId:%d, rsma persit, create %s failed since %s", vid, TD_TFILE_FULL_NAME(&tFile), terrstr());
C
Cary Xu 已提交
1134 1135
          goto _err;
        }
C
Cary Xu 已提交
1136 1137
        smaDebug("vgId:%d, rsma, table %" PRIi64 " level %d serialize qTaskInfo, file %s created", vid, pRSmaInfo->suid,
                 i + 1, TD_TFILE_FULL_NAME(&tFile));
C
Cary Xu 已提交
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150

        isFileCreated = true;
      }

      char    tmpBuf[RSMA_QTASKINFO_HEAD_LEN] = {0};
      void   *pTmpBuf = &tmpBuf;
      int32_t headLen = 0;
      headLen += taosEncodeFixedI32(&pTmpBuf, len + RSMA_QTASKINFO_HEAD_LEN);
      headLen += taosEncodeFixedI8(&pTmpBuf, type);
      headLen += taosEncodeFixedI64(&pTmpBuf, pRSmaInfo->suid);

      ASSERT(headLen <= RSMA_QTASKINFO_HEAD_LEN);
      tdAppendTFile(&tFile, (void *)&tmpBuf, headLen, &toffset);
1151
      smaDebug("vgId:%d, rsma, table %" PRIi64 " level %d head part(len:%d) appended to offset:%" PRIi64, vid,
1152
               pRSmaInfo->suid, i + 1, headLen, toffset);
C
Cary Xu 已提交
1153
      tdAppendTFile(&tFile, pOutput, len, &toffset);
1154 1155
      smaDebug("vgId:%d, rsma, table %" PRIi64 " level %d body part len:%d appended to offset:%" PRIi64, vid,
               pRSmaInfo->suid, i + 1, len, toffset);
C
Cary Xu 已提交
1156 1157 1158 1159 1160 1161

      taosMemoryFree(pOutput);
    }

    infoHash = taosHashIterate(RSMA_INFO_HASH(pRSmaStat), infoHash);
  }
C
Cary Xu 已提交
1162

C
Cary Xu 已提交
1163 1164
  if (isFileCreated) {
    if (tdUpdateTFileHeader(&tFile) < 0) {
1165
      smaError("vgId:%d, rsma, failed to update tfile %s header since %s", vid, TD_TFILE_FULL_NAME(&tFile),
C
Cary Xu 已提交
1166 1167 1168
               tstrerror(terrno));
      goto _err;
    } else {
1169
      smaDebug("vgId:%d, rsma, succeed to update tfile %s header", vid, TD_TFILE_FULL_NAME(&tFile));
C
Cary Xu 已提交
1170 1171 1172
    }

    tdCloseTFile(&tFile);
C
Cary Xu 已提交
1173
    tdDestroyTFile(&tFile);
C
Cary Xu 已提交
1174
  }
C
Cary Xu 已提交
1175
  return TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
1176
_err:
C
Cary Xu 已提交
1177
  smaError("vgId:%d, rsma persit failed since %s", vid, terrstr());
C
Cary Xu 已提交
1178 1179
  if (isFileCreated) {
    tdRemoveTFile(&tFile);
C
Cary Xu 已提交
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    tdDestroyTFile(&tFile);
  }
  return TSDB_CODE_FAILED;
}

static void *tdRSmaPersistExec(void *param) {
  setThreadName("rsma-task-persist");
  SRSmaStat *pRSmaStat = param;
  SSma      *pSma = pRSmaStat->pSma;

  int8_t triggerStat = atomic_load_8(RSMA_TRIGGER_STAT(pRSmaStat));

  if (TASK_TRIGGER_STAT_CANCELLED == triggerStat || TASK_TRIGGER_STAT_PAUSED == triggerStat) {
    goto _end;
C
Cary Xu 已提交
1194
  }
C
Cary Xu 已提交
1195 1196 1197 1198

  // execution
  tdRSmaPersistExecImpl(pRSmaStat);

C
Cary Xu 已提交
1199 1200 1201 1202
_end:
  if (TASK_TRIGGER_STAT_INACTIVE == atomic_val_compare_exchange_8(RSMA_TRIGGER_STAT(pRSmaStat),
                                                                  TASK_TRIGGER_STAT_INACTIVE,
                                                                  TASK_TRIGGER_STAT_ACTIVE)) {
C
Cary Xu 已提交
1203
    smaDebug("vgId:%d, rsma persist task is active again", SMA_VID(pSma));
C
Cary Xu 已提交
1204 1205 1206
  } else if (TASK_TRIGGER_STAT_CANCELLED == atomic_val_compare_exchange_8(RSMA_TRIGGER_STAT(pRSmaStat),
                                                                          TASK_TRIGGER_STAT_CANCELLED,
                                                                          TASK_TRIGGER_STAT_FINISHED)) {
C
Cary Xu 已提交
1207
    smaDebug("vgId:%d, rsma persist task is cancelled", SMA_VID(pSma));
C
Cary Xu 已提交
1208
  } else {
C
Cary Xu 已提交
1209
    smaWarn("vgId:%d, rsma persist task in stat %" PRIi8, SMA_VID(pSma), atomic_load_8(RSMA_TRIGGER_STAT(pRSmaStat)));
C
Cary Xu 已提交
1210
  }
C
Cary Xu 已提交
1211

C
Cary Xu 已提交
1212
  atomic_store_8(RSMA_RUNNING_STAT(pRSmaStat), 0);
1213
  taosReleaseRef(smaMgmt.smaRef, pRSmaStat->refId);
C
Cary Xu 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
  taosThreadExit(NULL);
  return NULL;
}

static void tdRSmaPersistTask(SRSmaStat *pRSmaStat) {
  TdThreadAttr thAttr;
  taosThreadAttrInit(&thAttr);
  taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_DETACHED);
  TdThread tid;

  if (taosThreadCreate(&tid, &thAttr, tdRSmaPersistExec, pRSmaStat) != 0) {
    if (TASK_TRIGGER_STAT_INACTIVE == atomic_val_compare_exchange_8(RSMA_TRIGGER_STAT(pRSmaStat),
                                                                    TASK_TRIGGER_STAT_INACTIVE,
                                                                    TASK_TRIGGER_STAT_ACTIVE)) {
      smaDebug("vgId:%d, persist task is active again", SMA_VID(pRSmaStat->pSma));
    } else if (TASK_TRIGGER_STAT_CANCELLED == atomic_val_compare_exchange_8(RSMA_TRIGGER_STAT(pRSmaStat),
                                                                            TASK_TRIGGER_STAT_CANCELLED,
                                                                            TASK_TRIGGER_STAT_FINISHED)) {
      smaDebug("vgId:%d, persist task is cancelled and set finished", SMA_VID(pRSmaStat->pSma));
    } else {
C
Cary Xu 已提交
1234 1235
      smaWarn("vgId:%d, persist task in abnormal stat %" PRIi8, SMA_VID(pRSmaStat->pSma),
              atomic_load_8(RSMA_TRIGGER_STAT(pRSmaStat)));
C
Cary Xu 已提交
1236 1237
    }
    atomic_store_8(RSMA_RUNNING_STAT(pRSmaStat), 0);
1238
    taosReleaseRef(smaMgmt.smaRef, pRSmaStat->refId);
C
Cary Xu 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
  }

  taosThreadAttrDestroy(&thAttr);
}

/**
 * @brief trigger to persist rsma qTaskInfo
 *
 * @param param
 * @param tmrId
 */
static void tdRSmaPersistTrigger(void *param, void *tmrId) {
1251
  SRSmaStat *rsmaStat = param;
1252
  SRSmaStat *pRSmaStat = (SRSmaStat *)taosAcquireRef(smaMgmt.smaRef, rsmaStat->refId);
1253

C
Cary Xu 已提交
1254
  if (!pRSmaStat) {
1255 1256 1257
    smaDebug("rsma persistence task not start since already destroyed");
    return;
  }
C
Cary Xu 已提交
1258

C
Cary Xu 已提交
1259
  int8_t tmrStat =
C
Cary Xu 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
      atomic_val_compare_exchange_8(RSMA_TRIGGER_STAT(pRSmaStat), TASK_TRIGGER_STAT_ACTIVE, TASK_TRIGGER_STAT_INACTIVE);
  switch (tmrStat) {
    case TASK_TRIGGER_STAT_ACTIVE: {
      atomic_store_8(RSMA_RUNNING_STAT(pRSmaStat), 1);
      if (TASK_TRIGGER_STAT_CANCELLED != atomic_val_compare_exchange_8(RSMA_TRIGGER_STAT(pRSmaStat),
                                                                       TASK_TRIGGER_STAT_CANCELLED,
                                                                       TASK_TRIGGER_STAT_FINISHED)) {
        smaDebug("vgId:%d, rsma persistence start since active", SMA_VID(pRSmaStat->pSma));

        // start persist task
        tdRSmaPersistTask(pRSmaStat);

C
Cary Xu 已提交
1272 1273
        // taosTmrReset(tdRSmaPersistTrigger, 5000, pRSmaStat, pRSmaStat->tmrHandle,
        //              RSMA_TMR_ID(pRSmaStat));
C
Cary Xu 已提交
1274 1275 1276
      } else {
        atomic_store_8(RSMA_RUNNING_STAT(pRSmaStat), 0);
      }
1277
      return;
C
Cary Xu 已提交
1278 1279 1280 1281 1282
    } break;
    case TASK_TRIGGER_STAT_CANCELLED: {
      atomic_store_8(RSMA_TRIGGER_STAT(pRSmaStat), TASK_TRIGGER_STAT_FINISHED);
      smaDebug("rsma persistence not start since cancelled and finished");
    } break;
C
Cary Xu 已提交
1283 1284 1285
    case TASK_TRIGGER_STAT_PAUSED: {
      smaDebug("rsma persistence not start since paused");
    } break;
C
Cary Xu 已提交
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    case TASK_TRIGGER_STAT_INACTIVE: {
      smaDebug("rsma persistence not start since inactive");
    } break;
    case TASK_TRIGGER_STAT_INIT: {
      smaDebug("rsma persistence not start since init");
    } break;
    default: {
      smaWarn("rsma persistence not start since unknown stat %" PRIi8, tmrStat);
    } break;
  }
1296
  taosReleaseRef(smaMgmt.smaRef, rsmaStat->refId);
C
Cary Xu 已提交
1297
}