tsdbSma.c 51.1 KB
Newer Older
C
Cary Xu 已提交
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 "tsdbDef.h"

C
Cary Xu 已提交
18 19 20 21 22
static const char *TSDB_SMA_DNAME[] = {
    "",      // TSDB_SMA_TYPE_BLOCK
    "tsma",  // TSDB_SMA_TYPE_TIME_RANGE
    "rsma",  // TSDB_SMA_TYPE_ROLLUP
};
C
Cary Xu 已提交
23

C
Cary Xu 已提交
24
#undef _TEST_SMA_PRINT_DEBUG_LOG_
C
Cary Xu 已提交
25
#define SMA_STORAGE_TSDB_DAYS   30
C
Cary Xu 已提交
26
#define SMA_STORAGE_TSDB_TIMES  10
C
Cary Xu 已提交
27
#define SMA_STORAGE_SPLIT_HOURS 24
C
Cary Xu 已提交
28
#define SMA_KEY_LEN             16  // TSKEY+groupId 8+8
C
Cary Xu 已提交
29
#define SMA_DROP_EXPIRED_TIME   10  // default is 10 seconds
C
Cary Xu 已提交
30

31 32 33 34
#define SMA_STATE_HASH_SLOT      4
#define SMA_STATE_ITEM_HASH_SLOT 32

#define SMA_TEST_INDEX_NAME "smaTestIndexName"  // TODO: just for test
35
#define SMA_TEST_INDEX_UID  2000000001          // TODO: just for test
C
Cary Xu 已提交
36
typedef enum {
C
Cary Xu 已提交
37 38
  SMA_STORAGE_LEVEL_TSDB = 0,     // use days of self-defined  e.g. vnode${N}/tsdb/tsma/sma_index_uid/v2f200.tsma
  SMA_STORAGE_LEVEL_DFILESET = 1  // use days of TS data       e.g. vnode${N}/tsdb/tsma/sma_index_uid/v2f1906.tsma
C
Cary Xu 已提交
39 40 41
} ESmaStorageLevel;

typedef struct {
C
Cary Xu 已提交
42 43 44 45
  STsdb        *pTsdb;
  SDBFile       dFile;
  const SArray *pDataBlocks;  // sma data
  int32_t       interval;     // interval with the precision of DB
C
Cary Xu 已提交
46 47 48 49
} STSmaWriteH;

typedef struct {
  int32_t iter;
C
Cary Xu 已提交
50
  int32_t fid;
C
Cary Xu 已提交
51
} SmaFsIter;
C
Cary Xu 已提交
52

C
Cary Xu 已提交
53
typedef struct {
C
Cary Xu 已提交
54
  STsdb    *pTsdb;
C
Cary Xu 已提交
55
  SDBFile   dFile;
C
Cary Xu 已提交
56 57 58 59 60 61 62
  int32_t   interval;   // interval with the precision of DB
  int32_t   blockSize;  // size of SMA block item
  int8_t    storageLevel;
  int8_t    days;
  SmaFsIter smaFsIter;
} STSmaReadH;

63 64 65 66 67
typedef struct {
  /**
   * @brief The field 'state' is here to demonstrate if one smaIndex is ready to provide service.
   *    - TSDB_SMA_STAT_OK: 1) The sma calculation of history data is finished; 2) Or recevied information from
   * Streaming Module or TSDB local persistence.
C
Cary Xu 已提交
68 69 70
   *    - TSDB_SMA_STAT_EXPIRED: 1) If sma calculation of history TS data is not finished; 2) Or if the TSDB is open,
   * without information about its previous state.
   *    - TSDB_SMA_STAT_DROPPED: 1)sma dropped
71 72 73
   */
  int8_t    state;           // ETsdbSmaStat
  SHashObj *expiredWindows;  // key: skey of time window, value: N/A
C
Cary Xu 已提交
74
  STSma    *pSma;            // cache schema
75 76 77
} SSmaStatItem;

struct SSmaStat {
C
Cary Xu 已提交
78
  SHashObj *smaStatItems;  // key: indexUid, value: SSmaStatItem
79
  T_REF_DECLARE()
80 81
};

C
Cary Xu 已提交
82
// declaration of static functions
C
Cary Xu 已提交
83

84
// expired window
C
Cary Xu 已提交
85
static int32_t  tsdbUpdateExpiredWindowImpl(STsdb *pTsdb, SSubmitReq *pMsg);
C
update  
Cary Xu 已提交
86
static int32_t  tsdbSetExpiredWindow(STsdb *pTsdb, SHashObj *pItemsHash, int64_t indexUid, int64_t winSKey);
C
Cary Xu 已提交
87
static int32_t  tsdbInitSmaStat(SSmaStat **pSmaStat);
C
Cary Xu 已提交
88
static void    *tsdbFreeSmaStatItem(SSmaStatItem *pSmaStatItem);
C
Cary Xu 已提交
89
static int32_t  tsdbDestroySmaState(SSmaStat *pSmaStat);
90 91
static SSmaEnv *tsdbNewSmaEnv(const STsdb *pTsdb, const char *path, SDiskID did);
static int32_t  tsdbInitSmaEnv(STsdb *pTsdb, const char *path, SDiskID did, SSmaEnv **pEnv);
92 93 94 95 96 97
static int32_t  tsdbResetExpiredWindow(STsdb *pTsdb, SSmaStat *pStat, int64_t indexUid, TSKEY skey);
static int32_t  tsdbRefSmaStat(STsdb *pTsdb, SSmaStat *pStat);
static int32_t  tsdbUnRefSmaStat(STsdb *pTsdb, SSmaStat *pStat);

// read data
// TODO: This is the basic params, and should wrap the params to a queryHandle.
C
Cary Xu 已提交
98
static int32_t tsdbGetTSmaDataImpl(STsdb *pTsdb, char *pData, int64_t indexUid, TSKEY querySKey, int32_t nMaxResult);
C
Cary Xu 已提交
99

100
// insert data
C
Cary Xu 已提交
101
static int32_t tsdbInitTSmaWriteH(STSmaWriteH *pSmaH, STsdb *pTsdb, const SArray *pDataBlocks, int64_t interval,
C
Cary Xu 已提交
102
                                  int8_t intervalUnit);
103 104 105
static void    tsdbDestroyTSmaWriteH(STSmaWriteH *pSmaH);
static int32_t tsdbInitTSmaReadH(STSmaReadH *pSmaH, STsdb *pTsdb, int64_t interval, int8_t intervalUnit);
static int32_t tsdbGetSmaStorageLevel(int64_t interval, int8_t intervalUnit);
C
Cary Xu 已提交
106
static int32_t tsdbSetRSmaDataFile(STSmaWriteH *pSmaH, int32_t fid);
107
static int32_t tsdbInsertTSmaBlocks(STSmaWriteH *pSmaH, void *smaKey, uint32_t keyLen, void *pData, uint32_t dataLen);
C
Cary Xu 已提交
108
static int64_t tsdbGetIntervalByPrecision(int64_t interval, uint8_t intervalUnit, int8_t precision, bool adjusted);
C
Cary Xu 已提交
109
static int32_t tsdbGetTSmaDays(STsdb *pTsdb, int64_t interval, int32_t storageLevel);
C
Cary Xu 已提交
110
static int32_t tsdbSetTSmaDataFile(STSmaWriteH *pSmaH, int64_t indexUid, int32_t fid);
111
static int32_t tsdbInitTSmaFile(STSmaReadH *pSmaH, int64_t indexUid, TSKEY skey);
C
Cary Xu 已提交
112
static bool    tsdbSetAndOpenTSmaFile(STSmaReadH *pReadH, TSKEY *queryKey);
C
Cary Xu 已提交
113
static void    tsdbGetSmaDir(int32_t vgId, ETsdbSmaType smaType, char dirName[]);
C
Cary Xu 已提交
114 115
static int32_t tsdbInsertTSmaDataImpl(STsdb *pTsdb, int64_t indexUid, const char *msg);
static int32_t tsdbInsertRSmaDataImpl(STsdb *pTsdb, const char *msg);
C
Cary Xu 已提交
116

C
Cary Xu 已提交
117 118 119
// mgmt interface
static int32_t tsdbDropTSmaDataImpl(STsdb *pTsdb, int64_t indexUid);

120
// implementation
C
Cary Xu 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133
static FORCE_INLINE int16_t tsdbTSmaAdd(STsdb *pTsdb, int16_t n) { return atomic_add_fetch_16(&REPO_TSMA_NUM(pTsdb), n); }
static FORCE_INLINE int16_t tsdbTSmaSub(STsdb *pTsdb, int16_t n) { return atomic_sub_fetch_16(&REPO_TSMA_NUM(pTsdb), n); }

int32_t tsdbInitSma(STsdb *pTsdb) {
  // tSma
  int32_t numOfTSma = taosArrayGetSize(metaGetSmaTbUids(pTsdb->pMeta, false));
  if (numOfTSma > 0) {
    atomic_store_16(&REPO_TSMA_NUM(pTsdb), (int16_t)numOfTSma);
  }
  // TODO: rSma
  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
134 135 136 137 138 139 140 141
static FORCE_INLINE int8_t tsdbSmaStat(SSmaStatItem *pStatItem) {
  if (pStatItem) {
    return atomic_load_8(&pStatItem->state);
  }
  return TSDB_SMA_STAT_UNKNOWN;
}

static FORCE_INLINE bool tsdbSmaStatIsOK(SSmaStatItem *pStatItem, int8_t *state) {
C
Cary Xu 已提交
142
  if (!pStatItem) {
C
Cary Xu 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    return false;
  }

  if (state) {
    *state = atomic_load_8(&pStatItem->state);
    return *state == TSDB_SMA_STAT_OK;
  }
  return atomic_load_8(&pStatItem->state) == TSDB_SMA_STAT_OK;
}

static FORCE_INLINE bool tsdbSmaStatIsExpired(SSmaStatItem *pStatItem) {
  return pStatItem ? (atomic_load_8(&pStatItem->state) & TSDB_SMA_STAT_EXPIRED) : true;
}

static FORCE_INLINE bool tsdbSmaStatIsDropped(SSmaStatItem *pStatItem) {
  return pStatItem ? (atomic_load_8(&pStatItem->state) & TSDB_SMA_STAT_DROPPED) : true;
}

static FORCE_INLINE void tsdbSmaStatSetOK(SSmaStatItem *pStatItem) {
  if (pStatItem) {
    atomic_store_8(&pStatItem->state, TSDB_SMA_STAT_OK);
  }
}

static FORCE_INLINE void tsdbSmaStatSetExpired(SSmaStatItem *pStatItem) {
  if (pStatItem) {
    atomic_or_fetch_8(&pStatItem->state, TSDB_SMA_STAT_EXPIRED);
  }
}

static FORCE_INLINE void tsdbSmaStatSetDropped(SSmaStatItem *pStatItem) {
  if (pStatItem) {
    atomic_or_fetch_8(&pStatItem->state, TSDB_SMA_STAT_DROPPED);
  }
}

C
Cary Xu 已提交
179
static void tsdbGetSmaDir(int32_t vgId, ETsdbSmaType smaType, char dirName[]) {
180 181
  snprintf(dirName, TSDB_FILENAME_LEN, "vnode%svnode%d%stsdb%s%s", TD_DIRSEP, vgId, TD_DIRSEP, TD_DIRSEP,
           TSDB_SMA_DNAME[smaType]);
C
Cary Xu 已提交
182
}
C
Cary Xu 已提交
183

184
static SSmaEnv *tsdbNewSmaEnv(const STsdb *pTsdb, const char *path, SDiskID did) {
C
Cary Xu 已提交
185 186
  SSmaEnv *pEnv = NULL;

wafwerar's avatar
wafwerar 已提交
187
  pEnv = (SSmaEnv *)taosMemoryCalloc(1, sizeof(SSmaEnv));
C
Cary Xu 已提交
188 189 190 191 192
  if (pEnv == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
193
  int code = taosThreadRwlockInit(&(pEnv->lock), NULL);
C
Cary Xu 已提交
194 195
  if (code) {
    terrno = TAOS_SYSTEM_ERROR(code);
wafwerar's avatar
wafwerar 已提交
196
    taosMemoryFree(pEnv);
C
Cary Xu 已提交
197 198 199 200 201 202 203 204 205 206
    return NULL;
  }

  ASSERT(path && (strlen(path) > 0));
  pEnv->path = strdup(path);
  if (pEnv->path == NULL) {
    tsdbFreeSmaEnv(pEnv);
    return NULL;
  }

207 208
  pEnv->did = did;

C
Cary Xu 已提交
209 210 211 212 213
  if (tsdbInitSmaStat(&pEnv->pStat) != TSDB_CODE_SUCCESS) {
    tsdbFreeSmaEnv(pEnv);
    return NULL;
  }

214 215 216
  char aname[TSDB_FILENAME_LEN] = {0};
  tfsAbsoluteName(pTsdb->pTfs, did, path, aname);
  if (tsdbOpenBDBEnv(&pEnv->dbEnv, aname) != TSDB_CODE_SUCCESS) {
217 218 219 220
    tsdbFreeSmaEnv(pEnv);
    return NULL;
  }

C
Cary Xu 已提交
221 222 223
  return pEnv;
}

224
static int32_t tsdbInitSmaEnv(STsdb *pTsdb, const char *path, SDiskID did, SSmaEnv **pEnv) {
C
Cary Xu 已提交
225 226 227 228 229
  if (!pEnv) {
    terrno = TSDB_CODE_INVALID_PTR;
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
230
  if (*pEnv == NULL) {
231
    if ((*pEnv = tsdbNewSmaEnv(pTsdb, path, did)) == NULL) {
C
Cary Xu 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
      return TSDB_CODE_FAILED;
    }
  }

  return TSDB_CODE_SUCCESS;
}

/**
 * @brief Release resources allocated for its member fields, not including itself.
 *
 * @param pSmaEnv
 * @return int32_t
 */
void tsdbDestroySmaEnv(SSmaEnv *pSmaEnv) {
  if (pSmaEnv) {
    tsdbDestroySmaState(pSmaEnv->pStat);
wafwerar's avatar
wafwerar 已提交
248 249
    taosMemoryFreeClear(pSmaEnv->pStat);
    taosMemoryFreeClear(pSmaEnv->path);
wafwerar's avatar
wafwerar 已提交
250
    taosThreadRwlockDestroy(&(pSmaEnv->lock));
251
    tsdbCloseBDBEnv(pSmaEnv->dbEnv);
C
Cary Xu 已提交
252 253 254 255 256
  }
}

void *tsdbFreeSmaEnv(SSmaEnv *pSmaEnv) {
  tsdbDestroySmaEnv(pSmaEnv);
wafwerar's avatar
wafwerar 已提交
257
  taosMemoryFreeClear(pSmaEnv);
C
Cary Xu 已提交
258 259 260
  return NULL;
}

261 262
static int32_t tsdbRefSmaStat(STsdb *pTsdb, SSmaStat *pStat) {
  if (pStat == NULL) return 0;
C
Cary Xu 已提交
263

264
  int ref = T_REF_INC(pStat);
C
Cary Xu 已提交
265
  tsdbDebug("vgId:%d ref sma stat:%p, val:%d", REPO_ID(pTsdb), pStat, ref);
266 267 268 269 270 271 272
  return 0;
}

static int32_t tsdbUnRefSmaStat(STsdb *pTsdb, SSmaStat *pStat) {
  if (pStat == NULL) return 0;

  int ref = T_REF_DEC(pStat);
C
Cary Xu 已提交
273
  tsdbDebug("vgId:%d unref sma stat:%p, val:%d", REPO_ID(pTsdb), pStat, ref);
274 275 276
  return 0;
}

277 278
static int32_t tsdbInitSmaStat(SSmaStat **pSmaStat) {
  ASSERT(pSmaStat != NULL);
C
Cary Xu 已提交
279 280 281 282 283

  if (*pSmaStat != NULL) {  // no lock
    return TSDB_CODE_SUCCESS;
  }

284 285 286 287 288
  /**
   *  1. Lazy mode utilized when init SSmaStat to update expired window(or hungry mode when tsdbNew).
   *  2. Currently, there is mutex lock when init SSmaEnv, thus no need add lock on SSmaStat, and please add lock if
   * tsdbInitSmaStat invoked in other multithread environment later.
   */
289
  if (*pSmaStat == NULL) {
wafwerar's avatar
wafwerar 已提交
290
    *pSmaStat = (SSmaStat *)taosMemoryCalloc(1, sizeof(SSmaStat));
291 292 293 294 295 296 297 298 299
    if (*pSmaStat == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      return TSDB_CODE_FAILED;
    }

    (*pSmaStat)->smaStatItems =
        taosHashInit(SMA_STATE_HASH_SLOT, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);

    if ((*pSmaStat)->smaStatItems == NULL) {
wafwerar's avatar
wafwerar 已提交
300
      taosMemoryFreeClear(*pSmaStat);
301 302 303 304 305 306 307 308 309
      return TSDB_CODE_FAILED;
    }
  }
  return TSDB_CODE_SUCCESS;
}

static SSmaStatItem *tsdbNewSmaStatItem(int8_t state) {
  SSmaStatItem *pItem = NULL;

wafwerar's avatar
wafwerar 已提交
310
  pItem = (SSmaStatItem *)taosMemoryCalloc(1, sizeof(SSmaStatItem));
311 312 313 314 315
  if (pItem) {
    pItem->state = state;
    pItem->expiredWindows = taosHashInit(SMA_STATE_ITEM_HASH_SLOT, taosGetDefaultHashFunction(TSDB_DATA_TYPE_TIMESTAMP),
                                         true, HASH_ENTRY_LOCK);
    if (!pItem->expiredWindows) {
wafwerar's avatar
wafwerar 已提交
316
      taosMemoryFreeClear(pItem);
317 318 319 320 321
    }
  }
  return pItem;
}

C
Cary Xu 已提交
322 323 324
static void *tsdbFreeSmaStatItem(SSmaStatItem *pSmaStatItem) {
  if (pSmaStatItem != NULL) {
    tdDestroyTSma(pSmaStatItem->pSma);
wafwerar's avatar
wafwerar 已提交
325
    taosMemoryFreeClear(pSmaStatItem->pSma);
C
Cary Xu 已提交
326
    taosHashCleanup(pSmaStatItem->expiredWindows);
wafwerar's avatar
wafwerar 已提交
327
    taosMemoryFreeClear(pSmaStatItem);
C
Cary Xu 已提交
328 329 330 331
  }
  return NULL;
}

C
Cary Xu 已提交
332 333
/**
 * @brief Release resources allocated for its member fields, not including itself.
334 335 336
 *
 * @param pSmaStat
 * @return int32_t
C
Cary Xu 已提交
337
 */
C
Cary Xu 已提交
338
int32_t tsdbDestroySmaState(SSmaStat *pSmaStat) {
339 340
  if (pSmaStat) {
    // TODO: use taosHashSetFreeFp when taosHashSetFreeFp is ready.
341
    void *item = taosHashIterate(pSmaStat->smaStatItems, NULL);
342
    while (item != NULL) {
343
      SSmaStatItem *pItem = *(SSmaStatItem **)item;
C
Cary Xu 已提交
344
      tsdbFreeSmaStatItem(pItem);
345 346 347 348 349 350
      item = taosHashIterate(pSmaStat->smaStatItems, item);
    }
    taosHashCleanup(pSmaStat->smaStatItems);
  }
}

C
Cary Xu 已提交
351
static int32_t tsdbCheckAndInitSmaEnv(STsdb *pTsdb, int8_t smaType) {
352 353
  SSmaEnv *pEnv = NULL;

C
Cary Xu 已提交
354
  // return if already init
C
Cary Xu 已提交
355 356
  switch (smaType) {
    case TSDB_SMA_TYPE_TIME_RANGE:
C
Cary Xu 已提交
357
      if ((pEnv = (SSmaEnv *)atomic_load_ptr(&REPO_TSMA_ENV(pTsdb))) != NULL) {
C
Cary Xu 已提交
358 359 360 361
        return TSDB_CODE_SUCCESS;
      }
      break;
    case TSDB_SMA_TYPE_ROLLUP:
C
Cary Xu 已提交
362
      if ((pEnv = (SSmaEnv *)atomic_load_ptr(&REPO_RSMA_ENV(pTsdb))) != NULL) {
C
Cary Xu 已提交
363 364 365 366 367 368 369 370
        return TSDB_CODE_SUCCESS;
      }
      break;
    default:
      terrno = TSDB_CODE_INVALID_PARA;
      return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
371 372
  // init sma env
  tsdbLockRepo(pTsdb);
C
Cary Xu 已提交
373 374
  pEnv = (smaType == TSDB_SMA_TYPE_TIME_RANGE) ? atomic_load_ptr(&REPO_TSMA_ENV(pTsdb))
                                               : atomic_load_ptr(&REPO_RSMA_ENV(pTsdb));
375
  if (pEnv == NULL) {
C
Cary Xu 已提交
376
    char rname[TSDB_FILENAME_LEN] = {0};
C
Cary Xu 已提交
377

C
Cary Xu 已提交
378 379 380 381 382 383 384 385 386 387 388 389 390
    SDiskID did = {0};
    tfsAllocDisk(pTsdb->pTfs, TFS_PRIMARY_LEVEL, &did);
    if (did.level < 0 || did.id < 0) {
      tsdbUnlockRepo(pTsdb);
      return TSDB_CODE_FAILED;
    }
    tsdbGetSmaDir(REPO_ID(pTsdb), smaType, rname);

    if (tfsMkdirRecurAt(pTsdb->pTfs, rname, did) != TSDB_CODE_SUCCESS) {
      tsdbUnlockRepo(pTsdb);
      return TSDB_CODE_FAILED;
    }

391
    if (tsdbInitSmaEnv(pTsdb, rname, did, &pEnv) != TSDB_CODE_SUCCESS) {
C
Cary Xu 已提交
392 393 394 395
      tsdbUnlockRepo(pTsdb);
      return TSDB_CODE_FAILED;
    }

C
Cary Xu 已提交
396 397
    (smaType == TSDB_SMA_TYPE_TIME_RANGE) ? atomic_store_ptr(&REPO_TSMA_ENV(pTsdb), pEnv)
                                          : atomic_store_ptr(&REPO_RSMA_ENV(pTsdb), pEnv);
C
Cary Xu 已提交
398
  }
C
Cary Xu 已提交
399
  tsdbUnlockRepo(pTsdb);
C
Cary Xu 已提交
400 401 402 403

  return TSDB_CODE_SUCCESS;
};

C
Cary Xu 已提交
404
static int32_t tsdbSetExpiredWindow(STsdb *pTsdb, SHashObj *pItemsHash, int64_t indexUid, int64_t winSKey) {
405
  SSmaStatItem *pItem = taosHashGet(pItemsHash, &indexUid, sizeof(indexUid));
C
Cary Xu 已提交
406
  if (pItem == NULL) {
C
Cary Xu 已提交
407 408
    // TODO: use TSDB_SMA_STAT_EXPIRED and update by stream computing later
    pItem = tsdbNewSmaStatItem(TSDB_SMA_STAT_OK);  // TODO use the real state
C
Cary Xu 已提交
409
    if (pItem == NULL) {
410
      // Response to stream computing: OOM
411
      // For query, if the indexUid not found, the TSDB should tell query module to query raw TS data.
412 413 414
      return TSDB_CODE_FAILED;
    }

C
Cary Xu 已提交
415 416 417
    // cache smaMeta
    STSma *pSma = metaGetSmaInfoByIndex(pTsdb->pMeta, indexUid);
    if (pSma == NULL) {
418
      terrno = TSDB_CODE_TDB_NO_SMA_INDEX_IN_META;
C
Cary Xu 已提交
419
      taosHashCleanup(pItem->expiredWindows);
wafwerar's avatar
wafwerar 已提交
420
      taosMemoryFree(pItem);
421 422
      tsdbWarn("vgId:%d update expired window failed for smaIndex %" PRIi64 " since %s", REPO_ID(pTsdb), indexUid,
               tstrerror(terrno));
C
Cary Xu 已提交
423 424 425 426
      return TSDB_CODE_FAILED;
    }
    pItem->pSma = pSma;

C
Cary Xu 已提交
427
    if (taosHashPut(pItemsHash, &indexUid, sizeof(indexUid), &pItem, sizeof(pItem)) != 0) {
428 429
      // If error occurs during put smaStatItem, free the resources of pItem
      taosHashCleanup(pItem->expiredWindows);
wafwerar's avatar
wafwerar 已提交
430
      taosMemoryFree(pItem);
431 432
      return TSDB_CODE_FAILED;
    }
C
Cary Xu 已提交
433 434 435
  } else if ((pItem = *(SSmaStatItem **)pItem) == NULL) {
    terrno = TSDB_CODE_INVALID_PTR;
    return TSDB_CODE_FAILED;
436 437 438
  }

  int8_t state = TSDB_SMA_STAT_EXPIRED;
C
Cary Xu 已提交
439 440 441 442 443 444 445 446
  if (taosHashPut(pItem->expiredWindows, &winSKey, sizeof(TSKEY), &state, sizeof(state)) != 0) {
    // If error occurs during taosHashPut expired windows, remove the smaIndex from pTsdb->pSmaStat, thus TSDB would
    // tell query module to query raw TS data.
    // N.B.
    //  1) It is assumed to be extemely little probability event of fail to taosHashPut.
    //  2) This would solve the inconsistency to some extent, but not completely, unless we record all expired
    // windows failed to put into hash table.
    taosHashCleanup(pItem->expiredWindows);
wafwerar's avatar
wafwerar 已提交
447
    taosMemoryFreeClear(pItem->pSma);
C
Cary Xu 已提交
448
    taosHashRemove(pItemsHash, &indexUid, sizeof(indexUid));
C
Cary Xu 已提交
449 450
    tsdbWarn("vgId:%d smaIndex %" PRIi64 ", put skey %" PRIi64 " to expire window fail", REPO_ID(pTsdb), indexUid,
             winSKey);
C
Cary Xu 已提交
451 452
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
453 454
  tsdbDebug("vgId:%d smaIndex %" PRIi64 ", put skey %" PRIi64 " to expire window succeed", REPO_ID(pTsdb), indexUid,
            winSKey);
C
Cary Xu 已提交
455 456 457 458 459 460 461 462 463
}

/**
 * @brief Update expired window according to msg from stream computing module.
 *
 * @param pTsdb
 * @param msg SSubmitReq
 * @return int32_t
 */
C
Cary Xu 已提交
464
int32_t tsdbUpdateExpiredWindowImpl(STsdb *pTsdb, SSubmitReq *pMsg) {
C
Cary Xu 已提交
465 466 467 468 469
  if (!pTsdb->pMeta) {
    terrno = TSDB_CODE_INVALID_PTR;
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
470 471 472 473 474 475 476 477 478
  if (atomic_load_16(&REPO_TSMA_NUM(pTsdb)) <= 0) {
    tsdbWarn("vgId:%d not update expire window since no tSma", REPO_ID(pTsdb));
    return TSDB_CODE_SUCCESS;
  }

  if (tdScanAndConvertSubmitMsg(pMsg) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
479 480 481 482 483 484
// TODO: decode the msg from Stream Computing module => start
#ifdef TSDB_SMA_TESTx
  int64_t       indexUid = SMA_TEST_INDEX_UID;
  const int32_t SMA_TEST_EXPIRED_WINDOW_SIZE = 10;
  TSKEY         expiredWindows[SMA_TEST_EXPIRED_WINDOW_SIZE];
  TSKEY         skey1 = 1646987196 * 1e3;
485
  for (int32_t i = 0; i < SMA_TEST_EXPIRED_WINDOW_SIZE; ++i) {
C
Cary Xu 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    expiredWindows[i] = skey1 + i;
  }
#else

#endif
  // TODO: decode the msg <= end

  if (tsdbCheckAndInitSmaEnv(pTsdb, TSDB_SMA_TYPE_TIME_RANGE) != TSDB_CODE_SUCCESS) {
    terrno = TSDB_CODE_TDB_INIT_FAILED;
    return TSDB_CODE_FAILED;
  }

#ifndef TSDB_SMA_TEST
  TSKEY expiredWindows[SMA_TEST_EXPIRED_WINDOW_SIZE];
#endif

  // Firstly, assume that tSma can only be created on super table/normal table.
  // getActiveTimeWindow

C
Cary Xu 已提交
505
  SSmaEnv  *pEnv = REPO_TSMA_ENV(pTsdb);
C
Cary Xu 已提交
506 507 508 509 510
  SSmaStat *pStat = SMA_ENV_STAT(pEnv);
  SHashObj *pItemsHash = SMA_ENV_STAT_ITEMS(pEnv);

  TASSERT(pEnv != NULL && pStat != NULL && pItemsHash != NULL);

C
Cary Xu 已提交
511 512 513
  // basic procedure
  // TODO: optimization
  tsdbRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

  SSubmitMsgIter msgIter = {0};
  SSubmitBlk    *pBlock = NULL;
  SInterval      interval = {0};

  if (tInitSubmitMsgIter(pMsg, &msgIter) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_FAILED;
  }

  while (true) {
    tGetSubmitMsgNext(&msgIter, &pBlock);
    if (pBlock == NULL) break;

    STSmaWrapper *pSW = NULL;
    STSma        *pTSma = NULL;

C
Cary Xu 已提交
530 531 532 533 534 535
    SSubmitBlkIter blkIter = {0};
    if (tInitSubmitBlkIter(pBlock, &blkIter) != TSDB_CODE_SUCCESS) {
      tdFreeTSmaWrapper(pSW);
      break;
    }

C
Cary Xu 已提交
536 537 538 539 540 541
    while (true) {
      STSRow *row = tGetSubmitBlkNext(&blkIter);
      if (row == NULL) {
        tdFreeTSmaWrapper(pSW);
        break;
      }
C
Cary Xu 已提交
542 543
      if (pSW == NULL) {
        if ((pSW = metaGetSmaInfoByTable(REPO_META(pTsdb), pBlock->suid)) == NULL) {
C
Cary Xu 已提交
544 545
          break;
        }
C
Cary Xu 已提交
546
        if ((pSW->number) <= 0 || (pSW->tSma == NULL)) {
C
Cary Xu 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559
          tdFreeTSmaWrapper(pSW);
          break;
        }
        pTSma = pSW->tSma;
      }

      interval.interval = pTSma->interval;
      interval.intervalUnit = pTSma->intervalUnit;
      interval.offset = pTSma->offset;
      interval.precision = REPO_CFG(pTsdb)->precision;
      interval.sliding = pTSma->sliding;
      interval.slidingUnit = pTSma->slidingUnit;

C
update  
Cary Xu 已提交
560 561 562
      TSKEY winSKey = taosTimeTruncate(TD_ROW_KEY(row), &interval, interval.precision);

      tsdbSetExpiredWindow(pTsdb, pItemsHash, pTSma->indexUid, winSKey);
563 564 565
    }
  }

566
  tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
567

568 569 570
  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
571 572 573 574 575 576 577 578 579
/**
 * @brief When sma data received from stream computing, make the relative expired window valid.
 *
 * @param pTsdb
 * @param pStat
 * @param indexUid
 * @param skey
 * @return int32_t
 */
580
static int32_t tsdbResetExpiredWindow(STsdb *pTsdb, SSmaStat *pStat, int64_t indexUid, TSKEY skey) {
C
Cary Xu 已提交
581 582
  SSmaStatItem *pItem = NULL;

583 584
  tsdbRefSmaStat(pTsdb, pStat);

C
Cary Xu 已提交
585
  if (pStat && pStat->smaStatItems) {
586
    pItem = taosHashGet(pStat->smaStatItems, &indexUid, sizeof(indexUid));
C
Cary Xu 已提交
587
  }
588
  if ((pItem != NULL) && ((pItem = *(SSmaStatItem **)pItem) != NULL)) {
589 590
    // pItem resides in hash buffer all the time unless drop sma index
    // TODO: multithread protect
C
Cary Xu 已提交
591 592
    if (taosHashRemove(pItem->expiredWindows, &skey, sizeof(TSKEY)) != 0) {
      // error handling
593
      tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
594
      tsdbWarn("vgId:%d remove skey %" PRIi64 " from expired window for sma index %" PRIi64 " fail", REPO_ID(pTsdb),
595 596
               skey, indexUid);
      return TSDB_CODE_FAILED;
C
Cary Xu 已提交
597
    }
C
Cary Xu 已提交
598 599
    tsdbDebug("vgId:%d remove skey %" PRIi64 " from expired window for sma index %" PRIi64 " succeed", REPO_ID(pTsdb),
              skey, indexUid);
C
Cary Xu 已提交
600 601 602 603 604 605 606 607 608
    // TODO: use a standalone interface to received state upate notification from stream computing module.
    /**
     * @brief state
     *  - When SMA env init in TSDB, its status is TSDB_SMA_STAT_OK.
     *  - In startup phase of stream computing module, it should notify the SMA env in TSDB to expired if needed(e.g.
     * when batch data caculation not finised)
     *  - When TSDB_SMA_STAT_OK, the stream computing module should also notify that to the SMA env in TSDB.
     */
    pItem->state = TSDB_SMA_STAT_OK;
C
Cary Xu 已提交
609 610
  } else {
    // error handling
611 612 613
    tsdbUnRefSmaStat(pTsdb, pStat);
    tsdbWarn("vgId:%d expired window %" PRIi64 " not exists for sma index %" PRIi64, REPO_ID(pTsdb), skey, indexUid);
    return TSDB_CODE_FAILED;
C
Cary Xu 已提交
614
  }
615 616

  tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
617 618 619
  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
620 621 622 623 624 625 626
/**
 * @brief Judge the tSma storage level
 *
 * @param interval
 * @param intervalUnit
 * @return int32_t
 */
C
Cary Xu 已提交
627
static int32_t tsdbGetSmaStorageLevel(int64_t interval, int8_t intervalUnit) {
C
Cary Xu 已提交
628 629
  // TODO: configurable for SMA_STORAGE_SPLIT_HOURS?
  switch (intervalUnit) {
C
Cary Xu 已提交
630
    case TIME_UNIT_HOUR:
C
Cary Xu 已提交
631 632 633 634
      if (interval < SMA_STORAGE_SPLIT_HOURS) {
        return SMA_STORAGE_LEVEL_DFILESET;
      }
      break;
C
Cary Xu 已提交
635
    case TIME_UNIT_MINUTE:
C
Cary Xu 已提交
636 637 638 639
      if (interval < 60 * SMA_STORAGE_SPLIT_HOURS) {
        return SMA_STORAGE_LEVEL_DFILESET;
      }
      break;
C
Cary Xu 已提交
640
    case TIME_UNIT_SECOND:
C
Cary Xu 已提交
641 642 643 644
      if (interval < 3600 * SMA_STORAGE_SPLIT_HOURS) {
        return SMA_STORAGE_LEVEL_DFILESET;
      }
      break;
C
Cary Xu 已提交
645
    case TIME_UNIT_MILLISECOND:
C
Cary Xu 已提交
646 647 648 649
      if (interval < 3600 * 1e3 * SMA_STORAGE_SPLIT_HOURS) {
        return SMA_STORAGE_LEVEL_DFILESET;
      }
      break;
C
Cary Xu 已提交
650
    case TIME_UNIT_MICROSECOND:
C
Cary Xu 已提交
651 652 653 654
      if (interval < 3600 * 1e6 * SMA_STORAGE_SPLIT_HOURS) {
        return SMA_STORAGE_LEVEL_DFILESET;
      }
      break;
C
Cary Xu 已提交
655
    case TIME_UNIT_NANOSECOND:
C
Cary Xu 已提交
656 657 658 659 660 661 662 663 664 665 666
      if (interval < 3600 * 1e9 * SMA_STORAGE_SPLIT_HOURS) {
        return SMA_STORAGE_LEVEL_DFILESET;
      }
      break;
    default:
      break;
  }
  return SMA_STORAGE_LEVEL_TSDB;
}

/**
C
Cary Xu 已提交
667
 * @brief Insert TSma data blocks to DB File build by B+Tree
C
Cary Xu 已提交
668
 *
C
Cary Xu 已提交
669
 * @param pSmaH
670
 * @param smaKey  tableUid-colId-skeyOfWindow(8-2-8)
C
Cary Xu 已提交
671
 * @param keyLen
C
Cary Xu 已提交
672 673 674 675
 * @param pData
 * @param dataLen
 * @return int32_t
 */
676
static int32_t tsdbInsertTSmaBlocks(STSmaWriteH *pSmaH, void *smaKey, uint32_t keyLen, void *pData, uint32_t dataLen) {
C
Cary Xu 已提交
677
  SDBFile *pDBFile = &pSmaH->dFile;
678
  // TODO: insert sma data blocks into B+Tree(TDB)
C
Cary Xu 已提交
679
  if (tsdbSaveSmaToDB(pDBFile, smaKey, keyLen, pData, dataLen) != 0) {
C
Cary Xu 已提交
680 681
    tsdbWarn("vgId:%d insert sma data blocks into %s: smaKey %" PRIx64 "-%" PRIx64 ", dataLen %" PRIu32 " fail",
             REPO_ID(pSmaH->pTsdb), pDBFile->path, *(int64_t *)smaKey, *(int64_t *)POINTER_SHIFT(smaKey, 8), dataLen);
682 683
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
684 685
  tsdbDebug("vgId:%d insert sma data blocks into %s: smaKey %" PRIx64 "-%" PRIx64 ", dataLen %" PRIu32 " succeed",
            REPO_ID(pSmaH->pTsdb), pDBFile->path, *(int64_t *)smaKey, *(int64_t *)POINTER_SHIFT(smaKey, 8), dataLen);
686

C
Cary Xu 已提交
687
#ifdef _TEST_SMA_PRINT_DEBUG_LOG_
C
Cary Xu 已提交
688
  uint32_t valueSize = 0;
C
Cary Xu 已提交
689
  void    *data = tsdbGetSmaDataByKey(pDBFile, smaKey, keyLen, &valueSize);
C
Cary Xu 已提交
690 691
  ASSERT(data != NULL);
  for (uint32_t v = 0; v < valueSize; v += 8) {
C
Cary Xu 已提交
692
    tsdbWarn("vgId:%d insert sma data val[%d] %" PRIi64, REPO_ID(pSmaH->pTsdb), v, *(int64_t *)POINTER_SHIFT(data, v));
C
Cary Xu 已提交
693 694
  }
#endif
C
Cary Xu 已提交
695 696 697
  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
698 699 700 701 702 703
/**
 * @brief Approximate value for week/month/year.
 *
 * @param interval
 * @param intervalUnit
 * @param precision
C
Cary Xu 已提交
704
 * @param adjusted Interval already adjusted according to DB precision
C
Cary Xu 已提交
705 706
 * @return int64_t
 */
C
Cary Xu 已提交
707 708 709 710 711
static int64_t tsdbGetIntervalByPrecision(int64_t interval, uint8_t intervalUnit, int8_t precision, bool adjusted) {
  if (adjusted) {
    return interval;
  }

C
Cary Xu 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  switch (intervalUnit) {
    case TIME_UNIT_YEAR:  // approximate value
      interval *= 365 * 86400 * 1e3;
      break;
    case TIME_UNIT_MONTH:  // approximate value
      interval *= 30 * 86400 * 1e3;
      break;
    case TIME_UNIT_WEEK:  // approximate value
      interval *= 7 * 86400 * 1e3;
      break;
    case TIME_UNIT_DAY:  // the interval for tSma calculation must <= day
      interval *= 86400 * 1e3;
      break;
    case TIME_UNIT_HOUR:
      interval *= 3600 * 1e3;
      break;
    case TIME_UNIT_MINUTE:
      interval *= 60 * 1e3;
      break;
    case TIME_UNIT_SECOND:
      interval *= 1e3;
      break;
    default:
      break;
C
Cary Xu 已提交
736 737
  }

C
Cary Xu 已提交
738 739
  switch (precision) {
    case TSDB_TIME_PRECISION_MILLI:
C
Cary Xu 已提交
740
      if (TIME_UNIT_MICROSECOND == intervalUnit) {  // us
C
Cary Xu 已提交
741
        return interval / 1e3;
C
Cary Xu 已提交
742
      } else if (TIME_UNIT_NANOSECOND == intervalUnit) {  //  nano second
C
Cary Xu 已提交
743
        return interval / 1e6;
744
      } else {  // ms
C
Cary Xu 已提交
745 746 747
        return interval;
      }
      break;
C
Cary Xu 已提交
748
    case TSDB_TIME_PRECISION_MICRO:
C
Cary Xu 已提交
749
      if (TIME_UNIT_MICROSECOND == intervalUnit) {  // us
C
Cary Xu 已提交
750
        return interval;
751
      } else if (TIME_UNIT_NANOSECOND == intervalUnit) {  //  ns
C
Cary Xu 已提交
752
        return interval / 1e3;
753
      } else {  // ms
C
Cary Xu 已提交
754 755 756
        return interval * 1e3;
      }
      break;
C
Cary Xu 已提交
757
    case TSDB_TIME_PRECISION_NANO:
758
      if (TIME_UNIT_MICROSECOND == intervalUnit) {  // us
C
Cary Xu 已提交
759
        return interval * 1e3;
760
      } else if (TIME_UNIT_NANOSECOND == intervalUnit) {  // ns
C
Cary Xu 已提交
761
        return interval;
762
      } else {  // ms
C
Cary Xu 已提交
763
        return interval * 1e6;
C
Cary Xu 已提交
764 765
      }
      break;
C
Cary Xu 已提交
766
    default:                                        // ms
C
Cary Xu 已提交
767
      if (TIME_UNIT_MICROSECOND == intervalUnit) {  // us
C
Cary Xu 已提交
768
        return interval / 1e3;
769
      } else if (TIME_UNIT_NANOSECOND == intervalUnit) {  //  ns
C
Cary Xu 已提交
770
        return interval / 1e6;
771
      } else {  // ms
C
Cary Xu 已提交
772
        return interval;
C
Cary Xu 已提交
773 774 775 776 777 778
      }
      break;
  }
  return interval;
}

C
Cary Xu 已提交
779 780
static int32_t tsdbInitTSmaWriteH(STSmaWriteH *pSmaH, STsdb *pTsdb, const SArray *pDataBlocks, int64_t interval,
                                  int8_t intervalUnit) {
C
Cary Xu 已提交
781
  pSmaH->pTsdb = pTsdb;
C
Cary Xu 已提交
782 783 784
  pSmaH->interval = tsdbGetIntervalByPrecision(interval, intervalUnit, REPO_CFG(pTsdb)->precision, true);
  pSmaH->pDataBlocks = pDataBlocks;
  pSmaH->dFile.fid = TSDB_IVLD_FID;
785 786 787 788 789
  return TSDB_CODE_SUCCESS;
}

static void tsdbDestroyTSmaWriteH(STSmaWriteH *pSmaH) {
  if (pSmaH) {
C
Cary Xu 已提交
790
    tsdbCloseDBF(&pSmaH->dFile);
791
  }
C
Cary Xu 已提交
792 793
}

C
Cary Xu 已提交
794
static int32_t tsdbSetTSmaDataFile(STSmaWriteH *pSmaH, int64_t indexUid, int32_t fid) {
C
Cary Xu 已提交
795
  STsdb *pTsdb = pSmaH->pTsdb;
C
Cary Xu 已提交
796
  ASSERT(pSmaH->dFile.path == NULL && pSmaH->dFile.pDB == NULL);
797 798

  pSmaH->dFile.fid = fid;
799
  char tSmaFile[TSDB_FILENAME_LEN] = {0};
800
  snprintf(tSmaFile, TSDB_FILENAME_LEN, "%" PRIi64 "%sv%df%d.tsma", indexUid, TD_DIRSEP, REPO_ID(pTsdb), fid);
C
Cary Xu 已提交
801
  pSmaH->dFile.path = strdup(tSmaFile);
802

C
Cary Xu 已提交
803
  return TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
804
}
C
Cary Xu 已提交
805

C
Cary Xu 已提交
806 807 808 809 810 811 812 813 814 815
/**
 * @brief
 *
 * @param pTsdb
 * @param interval Interval calculated by DB's precision
 * @param storageLevel
 * @return int32_t
 */
static int32_t tsdbGetTSmaDays(STsdb *pTsdb, int64_t interval, int32_t storageLevel) {
  STsdbCfg *pCfg = REPO_CFG(pTsdb);
C
Cary Xu 已提交
816 817 818
  int32_t   daysPerFile = pCfg->daysPerFile;

  if (storageLevel == SMA_STORAGE_LEVEL_TSDB) {
C
Cary Xu 已提交
819
    int32_t days = SMA_STORAGE_TSDB_TIMES * (interval / tsTickPerDay[pCfg->precision]);
C
Cary Xu 已提交
820 821 822 823 824
    daysPerFile = days > SMA_STORAGE_TSDB_DAYS ? days : SMA_STORAGE_TSDB_DAYS;
  }

  return daysPerFile;
}
C
Cary Xu 已提交
825 826 827 828 829 830 831 832 833 834

/**
 * @brief Insert/Update Time-range-wise SMA data.
 *  - If interval < SMA_STORAGE_SPLIT_HOURS(e.g. 24), save the SMA data as a part of DFileSet to e.g.
 * v3f1900.tsma.${sma_index_name}. The days is the same with that for TS data files.
 *  - If interval >= SMA_STORAGE_SPLIT_HOURS, save the SMA data to e.g. vnode3/tsma/v3f632.tsma.${sma_index_name}. The
 * days is 30 times of the interval, and the minimum days is SMA_STORAGE_TSDB_DAYS(30d).
 *  - The destination file of one data block for some interval is determined by its start TS key.
 *
 * @param pTsdb
C
Cary Xu 已提交
835
 * @param msg
C
Cary Xu 已提交
836 837
 * @return int32_t
 */
C
Cary Xu 已提交
838 839 840
static int32_t tsdbInsertTSmaDataImpl(STsdb *pTsdb, int64_t indexUid, const char *msg) {
  STsdbCfg     *pCfg = REPO_CFG(pTsdb);
  const SArray *pDataBlocks = (const SArray *)msg;
C
Cary Xu 已提交
841
  SSmaEnv      *pEnv = atomic_load_ptr(&REPO_TSMA_ENV(pTsdb));
C
Cary Xu 已提交
842

843
  if (pEnv == NULL) {
844 845 846 847
    terrno = TSDB_CODE_INVALID_PTR;
    tsdbWarn("vgId:%d insert tSma data failed since pTSmaEnv is NULL", REPO_ID(pTsdb));
    return terrno;
  }
C
Cary Xu 已提交
848

C
Cary Xu 已提交
849
  if (pDataBlocks == NULL) {
C
Cary Xu 已提交
850
    terrno = TSDB_CODE_INVALID_PTR;
C
Cary Xu 已提交
851
    tsdbWarn("vgId:%d insert tSma data failed since pDataBlocks is NULL", REPO_ID(pTsdb));
C
Cary Xu 已提交
852
    return terrno;
C
Cary Xu 已提交
853 854
  }

C
Cary Xu 已提交
855
  if (taosArrayGetSize(pDataBlocks) <= 0) {
C
Cary Xu 已提交
856
    terrno = TSDB_CODE_INVALID_PARA;
C
Cary Xu 已提交
857
    tsdbWarn("vgId:%d insert tSma data failed since pDataBlocks is empty", REPO_ID(pTsdb));
858
    return TSDB_CODE_FAILED;
C
Cary Xu 已提交
859
  }
C
Cary Xu 已提交
860

C
Cary Xu 已提交
861
  SSmaStat     *pStat = SMA_ENV_STAT(pEnv);
C
Cary Xu 已提交
862 863 864 865 866 867 868
  SSmaStatItem *pItem = NULL;

  tsdbRefSmaStat(pTsdb, pStat);

  if (pStat && pStat->smaStatItems) {
    pItem = taosHashGet(pStat->smaStatItems, &indexUid, sizeof(indexUid));
  }
C
Cary Xu 已提交
869

C
Cary Xu 已提交
870 871 872 873 874 875
  if ((pItem == NULL) || ((pItem = *(SSmaStatItem **)pItem) == NULL) || tsdbSmaStatIsDropped(pItem)) {
    terrno = TSDB_CODE_TDB_INVALID_SMA_STAT;
    tsdbUnRefSmaStat(pTsdb, pStat);
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
876
  STSma      *pSma = pItem->pSma;
C
Cary Xu 已提交
877 878
  STSmaWriteH tSmaH = {0};

C
Cary Xu 已提交
879
  if (tsdbInitTSmaWriteH(&tSmaH, pTsdb, pDataBlocks, pSma->interval, pSma->intervalUnit) != 0) {
C
Cary Xu 已提交
880 881 882
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
883 884
  char rPath[TSDB_FILENAME_LEN] = {0};
  char aPath[TSDB_FILENAME_LEN] = {0};
885 886 887 888
  snprintf(rPath, TSDB_FILENAME_LEN, "%s%s%" PRIi64, SMA_ENV_PATH(pEnv), TD_DIRSEP, indexUid);
  tfsAbsoluteName(REPO_TFS(pTsdb), SMA_ENV_DID(pEnv), rPath, aPath);
  if (!taosCheckExistFile(aPath)) {
    if (tfsMkdirRecurAt(REPO_TFS(pTsdb), rPath, SMA_ENV_DID(pEnv)) != TSDB_CODE_SUCCESS) {
C
Cary Xu 已提交
889
      tsdbUnRefSmaStat(pTsdb, pStat);
890 891 892 893
      return TSDB_CODE_FAILED;
    }
  }

C
Cary Xu 已提交
894
  // Step 1: Judge the storage level and days
C
Cary Xu 已提交
895
  int32_t storageLevel = tsdbGetSmaStorageLevel(pSma->interval, pSma->intervalUnit);
C
Cary Xu 已提交
896
  int32_t daysPerFile = tsdbGetTSmaDays(pTsdb, tSmaH.interval, storageLevel);
C
Cary Xu 已提交
897

C
Cary Xu 已提交
898 899 900
  // key: skey + groupId
  char    smaKey[SMA_KEY_LEN] = {0};
  char    dataBuf[512] = {0};
C
Cary Xu 已提交
901
  void   *pDataBuf = NULL;
C
Cary Xu 已提交
902 903
  int32_t sz = taosArrayGetSize(pDataBlocks);
  for (int32_t i = 0; i < sz; ++i) {
C
Cary Xu 已提交
904
    SSDataBlock *pDataBlock = taosArrayGet(pDataBlocks, i);
C
Cary Xu 已提交
905 906 907 908 909 910
    int32_t      colNum = pDataBlock->info.numOfCols;
    int32_t      rows = pDataBlock->info.rows;
    int32_t      rowSize = pDataBlock->info.rowSize;
    int64_t      groupId = pDataBlock->info.groupId;
    for (int32_t j = 0; j < rows; ++j) {
      printf("|");
C
Cary Xu 已提交
911 912 913 914 915 916 917 918 919 920
      TSKEY skey = 1649295200000;  // TSKEY_INITIAL_VAL;  // the start key of TS window by interval
      void *pSmaKey = &smaKey;
      bool  isStartKey = false;
      {
        // just for debugging
        isStartKey = true;
        tsdbEncodeTSmaKey(groupId, skey, &pSmaKey);
      }
      int32_t tlen = 0;     // reset the len
      pDataBuf = &dataBuf;  // reset the buf
C
Cary Xu 已提交
921
      for (int32_t k = 0; k < colNum; ++k) {
C
Cary Xu 已提交
922
        SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
C
Cary Xu 已提交
923 924 925
        void            *var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
C
Cary Xu 已提交
926 927 928 929 930 931 932 933 934 935
            if (!isStartKey) {
              isStartKey = true;
              skey = *(TSKEY *)var;
              printf("==> skey = %" PRIi64 " groupId = %" PRIi64 "|", skey, groupId);
              tsdbEncodeTSmaKey(groupId, skey, &pSmaKey);
            } else {
              printf(" %" PRIi64 " |", *(int64_t *)var);
              tlen += taosEncodeFixedI64(&pDataBuf, *(int64_t *)var);
              break;
            }
C
Cary Xu 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
            break;
          case TSDB_DATA_TYPE_BOOL:
          case TSDB_DATA_TYPE_UTINYINT:
            printf(" %15d |", *(uint8_t *)var);
            tlen += taosEncodeFixedU8(&pDataBuf, *(uint8_t *)var);
            break;
          case TSDB_DATA_TYPE_TINYINT:
            printf(" %15d |", *(int8_t *)var);
            tlen += taosEncodeFixedI8(&pDataBuf, *(int8_t *)var);
            break;
          case TSDB_DATA_TYPE_SMALLINT:
            printf(" %15d |", *(int16_t *)var);
            tlen += taosEncodeFixedI16(&pDataBuf, *(int16_t *)var);
            break;
          case TSDB_DATA_TYPE_USMALLINT:
            printf(" %15d |", *(uint16_t *)var);
            tlen += taosEncodeFixedU16(&pDataBuf, *(uint16_t *)var);
            break;
          case TSDB_DATA_TYPE_INT:
            printf(" %15d |", *(int32_t *)var);
            tlen += taosEncodeFixedI32(&pDataBuf, *(int32_t *)var);
            break;
          case TSDB_DATA_TYPE_FLOAT:
C
Cary Xu 已提交
959 960 961
            printf(" %15f |", *(float *)var);
            tlen += taosEncodeBinary(&pDataBuf, var, sizeof(float));
            break;
C
Cary Xu 已提交
962 963 964 965 966 967 968 969 970
          case TSDB_DATA_TYPE_UINT:
            printf(" %15u |", *(uint32_t *)var);
            tlen += taosEncodeFixedU32(&pDataBuf, *(uint32_t *)var);
            break;
          case TSDB_DATA_TYPE_BIGINT:
            printf(" %15ld |", *(int64_t *)var);
            tlen += taosEncodeFixedI64(&pDataBuf, *(int64_t *)var);
            break;
          case TSDB_DATA_TYPE_DOUBLE:
C
Cary Xu 已提交
971 972
            printf(" %15lf |", *(double *)var);
            tlen += taosEncodeBinary(&pDataBuf, var, sizeof(double));
C
Cary Xu 已提交
973 974 975 976 977 978 979 980 981 982 983
          case TSDB_DATA_TYPE_UBIGINT:
            printf(" %15lu |", *(uint64_t *)var);
            tlen += taosEncodeFixedU64(&pDataBuf, *(uint64_t *)var);
            break;
          case TSDB_DATA_TYPE_NCHAR: {
            char tmpChar[100] = {0};
            strncpy(tmpChar, varDataVal(var), varDataLen(var));
            printf(" %s |", tmpChar);
            tlen += taosEncodeBinary(&pDataBuf, varDataVal(var), varDataLen(var));
            break;
          }
C
Cary Xu 已提交
984 985
          case TSDB_DATA_TYPE_VARCHAR: {  // TSDB_DATA_TYPE_BINARY
            char tmpChar[100] = {0};
C
Cary Xu 已提交
986 987 988 989 990 991 992 993 994 995 996 997 998 999
            strncpy(tmpChar, varDataVal(var), varDataLen(var));
            printf(" %s |", tmpChar);
            tlen += taosEncodeBinary(&pDataBuf, varDataVal(var), varDataLen(var));
            break;
          }
          case TSDB_DATA_TYPE_VARBINARY:
            // TODO: add binary/varbinary
            TASSERT(0);
          default:
            printf("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type);
            TASSERT(0);
            break;
        }
      }
C
Cary Xu 已提交
1000 1001
      // if ((tlen > 0) && (skey != TSKEY_INITIAL_VAL)) {
      if (tlen > 0) {
C
Cary Xu 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        int32_t fid = (int32_t)(TSDB_KEY_FID(skey, daysPerFile, pCfg->precision));

        // Step 2: Set the DFile for storage of SMA index, and iterate/split the TSma data and store to B+Tree index
        // file
        //         - Set and open the DFile or the B+Tree file
        // TODO: tsdbStartTSmaCommit();
        if (fid != tSmaH.dFile.fid) {
          if (tSmaH.dFile.fid != TSDB_IVLD_FID) {
            tsdbCloseDBF(&tSmaH.dFile);
          }
          tsdbSetTSmaDataFile(&tSmaH, indexUid, fid);
C
Cary Xu 已提交
1013
          if (tsdbOpenDBF(pEnv->dbEnv, &tSmaH.dFile) != 0) {
C
Cary Xu 已提交
1014 1015 1016 1017 1018 1019 1020
            tsdbWarn("vgId:%d open DB file %s failed since %s", REPO_ID(pTsdb),
                     tSmaH.dFile.path ? tSmaH.dFile.path : "path is NULL", tstrerror(terrno));
            tsdbDestroyTSmaWriteH(&tSmaH);
            tsdbUnRefSmaStat(pTsdb, pStat);
            return TSDB_CODE_FAILED;
          }
        }
C
Cary Xu 已提交
1021

C
Cary Xu 已提交
1022 1023
        if (tsdbInsertTSmaBlocks(&tSmaH, &smaKey, SMA_KEY_LEN, dataBuf, tlen) != 0) {
          tsdbWarn("vgId:%d insert tSma data blocks fail for index %" PRIi64 ", skey %" PRIi64 ", groupId %" PRIi64
C
Cary Xu 已提交
1024 1025 1026 1027 1028 1029
                   " since %s",
                   REPO_ID(pTsdb), indexUid, skey, groupId, tstrerror(terrno));
          tsdbDestroyTSmaWriteH(&tSmaH);
          tsdbUnRefSmaStat(pTsdb, pStat);
          return TSDB_CODE_FAILED;
        }
C
Cary Xu 已提交
1030 1031
        tsdbDebug("vgId:%d insert tSma data blocks success for index %" PRIi64 ", skey %" PRIi64 ", groupId %" PRIi64,
                  REPO_ID(pTsdb), indexUid, skey, groupId);
C
Cary Xu 已提交
1032
        // TODO:tsdbEndTSmaCommit();
C
Cary Xu 已提交
1033

C
Cary Xu 已提交
1034
        // Step 3: reset the SSmaStat
C
Cary Xu 已提交
1035
        tsdbResetExpiredWindow(pTsdb, pStat, indexUid, skey);
C
Cary Xu 已提交
1036 1037 1038 1039
      } else {
        tsdbWarn("vgId:%d invalid data skey:%" PRIi64 ", tlen %" PRIi32 " during insert tSma data for %" PRIi64,
                 REPO_ID(pTsdb), skey, tlen, indexUid);
      }
C
Cary Xu 已提交
1040

C
Cary Xu 已提交
1041 1042
      printf("\n");
    }
1043
  }
C
Cary Xu 已提交
1044

1045
  tsdbDestroyTSmaWriteH(&tSmaH);
C
Cary Xu 已提交
1046
  tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
1047 1048 1049
  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
1050 1051 1052
/**
 * @brief Drop tSma data and local cache
 *        - insert/query reference
C
Cary Xu 已提交
1053 1054 1055
 * @param pTsdb
 * @param msg
 * @return int32_t
C
Cary Xu 已提交
1056 1057
 */
static int32_t tsdbDropTSmaDataImpl(STsdb *pTsdb, int64_t indexUid) {
C
Cary Xu 已提交
1058
  SSmaEnv *pEnv = atomic_load_ptr(&REPO_TSMA_ENV(pTsdb));
C
Cary Xu 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067

  // clear local cache
  if (pEnv) {
    tsdbDebug("vgId:%d drop tSma local cache for %" PRIi64, REPO_ID(pTsdb), indexUid);

    SSmaStatItem *pItem = taosHashGet(SMA_ENV_STAT_ITEMS(pEnv), &indexUid, sizeof(indexUid));
    if ((pItem != NULL) || ((pItem = *(SSmaStatItem **)pItem) != NULL)) {
      if (tsdbSmaStatIsDropped(pItem)) {
        tsdbDebug("vgId:%d tSma stat is already dropped for %" PRIi64, REPO_ID(pTsdb), indexUid);
C
Cary Xu 已提交
1068
        return TSDB_CODE_TDB_INVALID_ACTION;  // TODO: duplicate drop msg would be intercepted by mnode
C
Cary Xu 已提交
1069 1070 1071 1072 1073 1074
      }

      tsdbWLockSma(pEnv);
      if (tsdbSmaStatIsDropped(pItem)) {
        tsdbUnLockSma(pEnv);
        tsdbDebug("vgId:%d tSma stat is already dropped for %" PRIi64, REPO_ID(pTsdb), indexUid);
C
Cary Xu 已提交
1075
        return TSDB_CODE_TDB_INVALID_ACTION;  // TODO: duplicate drop msg would be intercepted by mnode
C
Cary Xu 已提交
1076 1077 1078 1079 1080
      }
      tsdbSmaStatSetDropped(pItem);
      tsdbUnLockSma(pEnv);

      int32_t nSleep = 0;
C
Cary Xu 已提交
1081
      int32_t refVal = INT32_MAX;
C
Cary Xu 已提交
1082
      while (true) {
C
Cary Xu 已提交
1083 1084
        if ((refVal = T_REF_VAL_GET(SMA_ENV_STAT(pEnv))) <= 0) {
          tsdbDebug("vgId:%d drop index %" PRIi64 " since refVal=%d", REPO_ID(pTsdb), indexUid, refVal);
C
Cary Xu 已提交
1085 1086
          break;
        }
C
Cary Xu 已提交
1087
        tsdbDebug("vgId:%d wait 1s to drop index %" PRIi64 " since refVal=%d", REPO_ID(pTsdb), indexUid, refVal);
C
Cary Xu 已提交
1088 1089
        taosSsleep(1);
        if (++nSleep > SMA_DROP_EXPIRED_TIME) {
C
Cary Xu 已提交
1090 1091
          tsdbDebug("vgId:%d drop index %" PRIi64 " after wait %d (refVal=%d)", REPO_ID(pTsdb), indexUid, nSleep,
                    refVal);
C
Cary Xu 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100
          break;
        };
      }

      tsdbFreeSmaStatItem(pItem);
      tsdbDebug("vgId:%d getTSmaDataImpl failed since no index %" PRIi64 " in local cache", REPO_ID(pTsdb), indexUid);
    }
  }
  // clear sma data files
C
Cary Xu 已提交
1101
  // TODO:
C
Cary Xu 已提交
1102 1103
}

C
Cary Xu 已提交
1104
static int32_t tsdbSetRSmaDataFile(STSmaWriteH *pSmaH, int32_t fid) {
1105 1106 1107 1108
  STsdb *pTsdb = pSmaH->pTsdb;

  char tSmaFile[TSDB_FILENAME_LEN] = {0};
  snprintf(tSmaFile, TSDB_FILENAME_LEN, "v%df%d.rsma", REPO_ID(pTsdb), fid);
C
Cary Xu 已提交
1109
  pSmaH->dFile.path = strdup(tSmaFile);
C
Cary Xu 已提交
1110 1111 1112 1113

  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
1114 1115 1116
static int32_t tsdbInsertRSmaDataImpl(STsdb *pTsdb, const char *msg) {
  STsdbCfg     *pCfg = REPO_CFG(pTsdb);
  const SArray *pDataBlocks = (const SArray *)msg;
C
Cary Xu 已提交
1117
  SSmaEnv      *pEnv = atomic_load_ptr(&REPO_RSMA_ENV(pTsdb));
C
Cary Xu 已提交
1118
  int64_t       indexUid = SMA_TEST_INDEX_UID;
C
Cary Xu 已提交
1119

C
Cary Xu 已提交
1120 1121
  if (pEnv == NULL) {
    terrno = TSDB_CODE_INVALID_PTR;
C
Cary Xu 已提交
1122 1123 1124 1125 1126 1127 1128
    tsdbWarn("vgId:%d insert rSma data failed since pTSmaEnv is NULL", REPO_ID(pTsdb));
    return terrno;
  }

  if (pEnv == NULL) {
    terrno = TSDB_CODE_INVALID_PTR;
    tsdbWarn("vgId:%d insert rSma data failed since pTSmaEnv is NULL", REPO_ID(pTsdb));
C
Cary Xu 已提交
1129 1130
    return terrno;
  }
C
Cary Xu 已提交
1131

C
Cary Xu 已提交
1132
  if (pDataBlocks == NULL) {
C
Cary Xu 已提交
1133
    terrno = TSDB_CODE_INVALID_PTR;
C
Cary Xu 已提交
1134
    tsdbWarn("vgId:%d insert rSma data failed since pDataBlocks is NULL", REPO_ID(pTsdb));
C
Cary Xu 已提交
1135 1136 1137
    return terrno;
  }

C
Cary Xu 已提交
1138
  if (taosArrayGetSize(pDataBlocks) <= 0) {
C
Cary Xu 已提交
1139
    terrno = TSDB_CODE_INVALID_PARA;
C
Cary Xu 已提交
1140
    tsdbWarn("vgId:%d insert rSma data failed since pDataBlocks is empty", REPO_ID(pTsdb));
C
Cary Xu 已提交
1141 1142 1143
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
1144
  SSmaStat     *pStat = SMA_ENV_STAT(pEnv);
C
Cary Xu 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
  SSmaStatItem *pItem = NULL;

  tsdbRefSmaStat(pTsdb, pStat);

  if (pStat && pStat->smaStatItems) {
    pItem = taosHashGet(pStat->smaStatItems, &indexUid, sizeof(indexUid));
  }

  if ((pItem == NULL) || ((pItem = *(SSmaStatItem **)pItem) == NULL) || tsdbSmaStatIsDropped(pItem)) {
    terrno = TSDB_CODE_TDB_INVALID_SMA_STAT;
    tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
1156
    return TSDB_CODE_FAILED;
C
Cary Xu 已提交
1157
  }
C
Cary Xu 已提交
1158

C
Cary Xu 已提交
1159 1160
  STSma *pSma = pItem->pSma;

C
Cary Xu 已提交
1161
  STSmaWriteH tSmaH = {0};
C
Cary Xu 已提交
1162

C
Cary Xu 已提交
1163
  if (tsdbInitTSmaWriteH(&tSmaH, pTsdb, pDataBlocks, pSma->interval, pSma->intervalUnit) != 0) {
C
Cary Xu 已提交
1164 1165
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
1166

C
Cary Xu 已提交
1167 1168
  char rPath[TSDB_FILENAME_LEN] = {0};
  char aPath[TSDB_FILENAME_LEN] = {0};
C
Cary Xu 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177
  snprintf(rPath, TSDB_FILENAME_LEN, "%s%s%" PRIi64, SMA_ENV_PATH(pEnv), TD_DIRSEP, indexUid);
  tfsAbsoluteName(REPO_TFS(pTsdb), SMA_ENV_DID(pEnv), rPath, aPath);
  if (!taosCheckExistFile(aPath)) {
    if (tfsMkdirRecurAt(REPO_TFS(pTsdb), rPath, SMA_ENV_DID(pEnv)) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_FAILED;
    }
  }

  // Step 1: Judge the storage level and days
C
Cary Xu 已提交
1178
  int32_t storageLevel = tsdbGetSmaStorageLevel(pSma->interval, pSma->intervalUnit);
C
Cary Xu 已提交
1179
  int32_t daysPerFile = tsdbGetTSmaDays(pTsdb, tSmaH.interval, storageLevel);
C
Cary Xu 已提交
1180
#if 0
C
Cary Xu 已提交
1181 1182
  int32_t fid = (int32_t)(TSDB_KEY_FID(pData->skey, daysPerFile, pCfg->precision));

C
Cary Xu 已提交
1183 1184
  // Step 2: Set the DFile for storage of SMA index, and iterate/split the TSma data and store to B+Tree index file
  //         - Set and open the DFile or the B+Tree file
C
Cary Xu 已提交
1185
  // TODO: tsdbStartTSmaCommit();
C
Cary Xu 已提交
1186 1187 1188 1189 1190 1191 1192
  tsdbSetTSmaDataFile(&tSmaH, pData, indexUid, fid);
  if (tsdbOpenDBF(pTsdb->pTSmaEnv->dbEnv, &tSmaH.dFile) != 0) {
    tsdbWarn("vgId:%d open DB file %s failed since %s", REPO_ID(pTsdb),
             tSmaH.dFile.path ? tSmaH.dFile.path : "path is NULL", tstrerror(terrno));
    tsdbDestroyTSmaWriteH(&tSmaH);
    return TSDB_CODE_FAILED;
  }
1193

C
Cary Xu 已提交
1194 1195 1196 1197 1198
  if (tsdbInsertTSmaDataSection(&tSmaH, pData) != 0) {
    tsdbWarn("vgId:%d insert tSma data section failed since %s", REPO_ID(pTsdb), tstrerror(terrno));
    tsdbDestroyTSmaWriteH(&tSmaH);
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
1199 1200
  // TODO:tsdbEndTSmaCommit();

C
Cary Xu 已提交
1201 1202
  // Step 3: reset the SSmaStat
  tsdbResetExpiredWindow(pTsdb, SMA_ENV_STAT(pTsdb->pTSmaEnv), pData->indexUid, pData->skey);
C
Cary Xu 已提交
1203
#endif
C
Cary Xu 已提交
1204

C
Cary Xu 已提交
1205
  tsdbDestroyTSmaWriteH(&tSmaH);
C
Cary Xu 已提交
1206
  tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
1207 1208 1209 1210
  return TSDB_CODE_SUCCESS;
}

/**
C
Cary Xu 已提交
1211
 * @brief
C
Cary Xu 已提交
1212 1213 1214
 *
 * @param pSmaH
 * @param pTsdb
C
Cary Xu 已提交
1215 1216
 * @param interval
 * @param intervalUnit
C
Cary Xu 已提交
1217 1218
 * @return int32_t
 */
C
Cary Xu 已提交
1219
static int32_t tsdbInitTSmaReadH(STSmaReadH *pSmaH, STsdb *pTsdb, int64_t interval, int8_t intervalUnit) {
C
Cary Xu 已提交
1220
  pSmaH->pTsdb = pTsdb;
C
Cary Xu 已提交
1221
  pSmaH->interval = tsdbGetIntervalByPrecision(interval, intervalUnit, REPO_CFG(pTsdb)->precision, true);
C
Cary Xu 已提交
1222 1223
  pSmaH->storageLevel = tsdbGetSmaStorageLevel(interval, intervalUnit);
  pSmaH->days = tsdbGetTSmaDays(pTsdb, pSmaH->interval, pSmaH->storageLevel);
C
Cary Xu 已提交
1224 1225 1226 1227 1228 1229
}

/**
 * @brief Init of tSma FS
 *
 * @param pReadH
1230
 * @param indexUid
C
Cary Xu 已提交
1231
 * @param skey
C
Cary Xu 已提交
1232 1233
 * @return int32_t
 */
1234 1235 1236 1237
static int32_t tsdbInitTSmaFile(STSmaReadH *pSmaH, int64_t indexUid, TSKEY skey) {
  STsdb *pTsdb = pSmaH->pTsdb;

  int32_t fid = (int32_t)(TSDB_KEY_FID(skey, pSmaH->days, REPO_CFG(pTsdb)->precision));
C
Cary Xu 已提交
1238
  char    tSmaFile[TSDB_FILENAME_LEN] = {0};
1239
  snprintf(tSmaFile, TSDB_FILENAME_LEN, "%" PRIi64 "%sv%df%d.tsma", indexUid, TD_DIRSEP, REPO_ID(pTsdb), fid);
C
Cary Xu 已提交
1240 1241 1242
  pSmaH->dFile.path = strdup(tSmaFile);
  pSmaH->smaFsIter.iter = 0;
  pSmaH->smaFsIter.fid = fid;
C
Cary Xu 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
}

/**
 * @brief Set and open tSma file if it has key locates in queryWin.
 *
 * @param pReadH
 * @param param
 * @param queryWin
 * @return true
 * @return false
 */
C
Cary Xu 已提交
1254
static bool tsdbSetAndOpenTSmaFile(STSmaReadH *pReadH, TSKEY *queryKey) {
C
Cary Xu 已提交
1255
  SArray *smaFs = pReadH->pTsdb->fs->cstatus->sf;
C
Cary Xu 已提交
1256 1257
  int32_t nSmaFs = taosArrayGetSize(smaFs);

C
Cary Xu 已提交
1258
  tsdbCloseDBF(&pReadH->dFile);
C
Cary Xu 已提交
1259

C
Cary Xu 已提交
1260
#if 0
C
Cary Xu 已提交
1261 1262 1263 1264
  while (pReadH->smaFsIter.iter < nSmaFs) {
    void *pSmaFile = taosArrayGet(smaFs, pReadH->smaFsIter.iter);
    if (pSmaFile) {  // match(indexName, queryWindow)
      // TODO: select the file by index_name ...
C
Cary Xu 已提交
1265
      pReadH->dFile = pSmaFile;
C
Cary Xu 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
      ++pReadH->smaFsIter.iter;
      break;
    }
    ++pReadH->smaFsIter.iter;
  }

  if (pReadH->pDFile != NULL) {
    tsdbDebug("vg%d: smaFile %s matched", REPO_ID(pReadH->pTsdb), "[pSmaFile dir]");
    return true;
  }
C
Cary Xu 已提交
1276
#endif
C
Cary Xu 已提交
1277 1278 1279 1280 1281

  return false;
}

/**
C
Cary Xu 已提交
1282
 * @brief
C
Cary Xu 已提交
1283
 *
C
Cary Xu 已提交
1284
 * @param pTsdb Return the data between queryWin and fill the pData.
C
Cary Xu 已提交
1285
 * @param pData
C
Cary Xu 已提交
1286 1287
 * @param indexUid
 * @param pQuerySKey
C
Cary Xu 已提交
1288 1289 1290
 * @param nMaxResult The query invoker should control the nMaxResult need to return to avoid OOM.
 * @return int32_t
 */
C
Cary Xu 已提交
1291
static int32_t tsdbGetTSmaDataImpl(STsdb *pTsdb, char *pData, int64_t indexUid, TSKEY querySKey, int32_t nMaxResult) {
C
Cary Xu 已提交
1292 1293
  SSmaEnv  *pEnv = atomic_load_ptr(&REPO_TSMA_ENV(pTsdb));
  SSmaStat *pStat = NULL;
1294 1295

  if (!pEnv) {
C
Cary Xu 已提交
1296 1297 1298 1299 1300
    terrno = TSDB_CODE_INVALID_PTR;
    tsdbWarn("vgId:%d getTSmaDataImpl failed since pTSmaEnv is NULL", REPO_ID(pTsdb));
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
1301 1302 1303
  pStat = SMA_ENV_STAT(pEnv);

  tsdbRefSmaStat(pTsdb, pStat);
1304
  SSmaStatItem *pItem = taosHashGet(SMA_ENV_STAT_ITEMS(pEnv), &indexUid, sizeof(indexUid));
1305
  if ((pItem == NULL) || ((pItem = *(SSmaStatItem **)pItem) == NULL)) {
C
Cary Xu 已提交
1306 1307
    // Normally pItem should not be NULL, mark all windows as expired and notify query module to fetch raw TS data if
    // it's NULL.
C
Cary Xu 已提交
1308
    tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
1309
    terrno = TSDB_CODE_TDB_INVALID_ACTION;
1310
    tsdbDebug("vgId:%d getTSmaDataImpl failed since no index %" PRIi64, REPO_ID(pTsdb), indexUid);
C
Cary Xu 已提交
1311
    return TSDB_CODE_FAILED;
C
Cary Xu 已提交
1312 1313
  }

C
Cary Xu 已提交
1314 1315
#if 0
  int32_t nQueryWin = taosArrayGetSize(pQuerySKey);
C
Cary Xu 已提交
1316
  for (int32_t n = 0; n < nQueryWin; ++n) {
C
Cary Xu 已提交
1317 1318
    TSKEY skey = taosArrayGet(pQuerySKey, n);
    if (taosHashGet(pItem->expiredWindows, &skey, sizeof(TSKEY)) != NULL) {
C
Cary Xu 已提交
1319 1320 1321
      // TODO: mark this window as expired.
    }
  }
C
Cary Xu 已提交
1322
#endif
C
Cary Xu 已提交
1323

1324
#if 1
C
Cary Xu 已提交
1325 1326
  int8_t smaStat = 0;
  if (!tsdbSmaStatIsOK(pItem, &smaStat)) {  // TODO: multiple check for large scale sma query
C
Cary Xu 已提交
1327
    tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
1328
    terrno = TSDB_CODE_TDB_INVALID_SMA_STAT;
C
Cary Xu 已提交
1329 1330
    tsdbWarn("vgId:%d getTSmaDataImpl failed from index %" PRIi64 " since %s %" PRIi8, REPO_ID(pTsdb), indexUid,
             tstrerror(terrno), smaStat);
C
Cary Xu 已提交
1331 1332 1333
    return TSDB_CODE_FAILED;
  }

1334
  if (taosHashGet(pItem->expiredWindows, &querySKey, sizeof(TSKEY)) != NULL) {
C
Cary Xu 已提交
1335
    // TODO: mark this window as expired.
1336 1337 1338 1339 1340
    tsdbDebug("vgId:%d skey %" PRIi64 " of window exists in expired window for index %" PRIi64, REPO_ID(pTsdb),
              querySKey, indexUid);
  } else {
    tsdbDebug("vgId:%d skey %" PRIi64 " of window not in expired window for index %" PRIi64, REPO_ID(pTsdb), querySKey,
              indexUid);
C
Cary Xu 已提交
1341
  }
C
Cary Xu 已提交
1342 1343 1344

  STSma *pTSma = pItem->pSma;

C
Cary Xu 已提交
1345
#endif
1346

C
Cary Xu 已提交
1347
  STSmaReadH tReadH = {0};
C
Cary Xu 已提交
1348
  tsdbInitTSmaReadH(&tReadH, pTsdb, pTSma->interval, pTSma->intervalUnit);
C
Cary Xu 已提交
1349
  tsdbCloseDBF(&tReadH.dFile);
C
Cary Xu 已提交
1350 1351

  tsdbUnRefSmaStat(pTsdb, pStat);
C
Cary Xu 已提交
1352

1353
  tsdbInitTSmaFile(&tReadH, indexUid, querySKey);
C
Cary Xu 已提交
1354
  if (tsdbOpenDBF(pEnv->dbEnv, &tReadH.dFile) != 0) {
C
Cary Xu 已提交
1355 1356 1357 1358
    tsdbWarn("vgId:%d open DBF %s failed since %s", REPO_ID(pTsdb), tReadH.dFile.path, tstrerror(terrno));
    return TSDB_CODE_FAILED;
  }

C
Cary Xu 已提交
1359 1360
  char    smaKey[SMA_KEY_LEN] = {0};
  void   *pSmaKey = &smaKey;
C
Cary Xu 已提交
1361 1362
  int64_t queryGroupId = 1;
  tsdbEncodeTSmaKey(queryGroupId, querySKey, (void **)&pSmaKey);
C
Cary Xu 已提交
1363

C
Cary Xu 已提交
1364 1365
  tsdbDebug("vgId:%d get sma data from %s: smaKey %" PRIx64 "-%" PRIx64 ", keyLen %d", REPO_ID(pTsdb),
            tReadH.dFile.path, *(int64_t *)smaKey, *(int64_t *)POINTER_SHIFT(smaKey, 8), SMA_KEY_LEN);
C
Cary Xu 已提交
1366

C
Cary Xu 已提交
1367
  void    *result = NULL;
C
Cary Xu 已提交
1368 1369
  uint32_t valueSize = 0;
  if ((result = tsdbGetSmaDataByKey(&tReadH.dFile, smaKey, SMA_KEY_LEN, &valueSize)) == NULL) {
C
Cary Xu 已提交
1370 1371
    tsdbWarn("vgId:%d get sma data failed from smaIndex %" PRIi64 ", smaKey %" PRIx64 "-%" PRIx64 " since %s",
             REPO_ID(pTsdb), indexUid, *(int64_t *)smaKey, *(int64_t *)POINTER_SHIFT(smaKey, 8), tstrerror(terrno));
C
Cary Xu 已提交
1372 1373 1374
    tsdbCloseDBF(&tReadH.dFile);
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
1375 1376

#ifdef _TEST_SMA_PRINT_DEBUG_LOG_
C
Cary Xu 已提交
1377
  for (uint32_t v = 0; v < valueSize; v += 8) {
C
Cary Xu 已提交
1378
    tsdbWarn("vgId:%d get sma data v[%d]=%" PRIi64, REPO_ID(pTsdb), v, *(int64_t *)POINTER_SHIFT(result, v));
C
Cary Xu 已提交
1379 1380
  }
#endif
wafwerar's avatar
wafwerar 已提交
1381
  taosMemoryFreeClear(result);  // TODO: fill the result to output
C
Cary Xu 已提交
1382

C
Cary Xu 已提交
1383
#if 0
C
Cary Xu 已提交
1384 1385 1386 1387 1388 1389 1390 1391 1392
  int32_t nResult = 0;
  int64_t lastKey = 0;

  while (true) {
    if (nResult >= nMaxResult) {
      break;
    }

    // set and open the file according to the STSma param
C
Cary Xu 已提交
1393
    if (tsdbSetAndOpenTSmaFile(&tReadH, queryWin)) {
C
Cary Xu 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
      char bTree[100] = "\0";
      while (strncmp(bTree, "has more nodes", 100) == 0) {
        if (nResult >= nMaxResult) {
          break;
        }
        // tsdbGetDataFromBTree(bTree, queryWin, lastKey)
        // fill the pData
        ++nResult;
      }
    }
  }
C
Cary Xu 已提交
1405
#endif
C
Cary Xu 已提交
1406
  // read data from file and fill the result
C
Cary Xu 已提交
1407
  tsdbCloseDBF(&tReadH.dFile);
C
Cary Xu 已提交
1408 1409 1410
  return TSDB_CODE_SUCCESS;
}

C
Cary Xu 已提交
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
int32_t tsdbCreateTSma(STsdb *pTsdb, char *pMsg) {
  SSmaCfg vCreateSmaReq = {0};
  if (tDeserializeSVCreateTSmaReq(pMsg, &vCreateSmaReq) == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    tsdbWarn("vgId:%d TDMT_VND_CREATE_SMA received but deserialize failed since %s", REPO_ID(pTsdb), terrstr(terrno));
    return -1;
  }
  tsdbDebug("vgId:%d TDMT_VND_CREATE_SMA msg received for %s:%" PRIi64, REPO_ID(pTsdb), vCreateSmaReq.tSma.indexName,
         vCreateSmaReq.tSma.indexUid);

  // record current timezone of server side
  vCreateSmaReq.tSma.timezoneInt = tsTimezone;

  if (metaCreateTSma(pTsdb->pMeta, &vCreateSmaReq) < 0) {
    // TODO: handle error
    tdDestroyTSma(&vCreateSmaReq.tSma);
    return -1;
  }

  tsdbTSmaAdd(pTsdb, 1);

  tdDestroyTSma(&vCreateSmaReq.tSma);
  // TODO: return directly or go on follow steps?
}

int32_t tsdbDropTSma(STsdb *pTsdb, char *pMsg) {
  SVDropTSmaReq vDropSmaReq = {0};
  if (tDeserializeSVDropTSmaReq(pMsg, &vDropSmaReq) == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return -1;
  }

  // TODO: send msg to stream computing to drop tSma
  // if ((send msg to stream computing) < 0) {
  //   tdDestroyTSma(&vCreateSmaReq);
  //   return -1;
  // }
  //

  if (metaDropTSma(pTsdb->pMeta, vDropSmaReq.indexUid) < 0) {
    // TODO: handle error
    return -1;
  }

  if (tsdbDropTSmaData(pTsdb, vDropSmaReq.indexUid) < 0) {
    // TODO: handle error
    return -1;
  }

  tsdbTSmaSub(pTsdb, 1);  

  // TODO: return directly or go on follow steps?
}

C
Cary Xu 已提交
1465
#if 0
C
Cary Xu 已提交
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
/**
 * @brief Get the start TS key of the last data block of one interval/sliding.
 *
 * @param pTsdb
 * @param param
 * @param result
 * @return int32_t
 *         1) Return 0 and fill the result if the check procedure is normal;
 *         2) Return -1 if error occurs during the check procedure.
 */
C
Cary Xu 已提交
1476
int32_t tsdbGetTSmaStatus(STsdb *pTsdb, void *smaIndex, void *result) {
C
Cary Xu 已提交
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  const char *procedure = "";
  if (strncmp(procedure, "get the start TS key of the last data block", 100) != 0) {
    return -1;
  }
  // fill the result
  return TSDB_CODE_SUCCESS;
}

/**
 * @brief Remove the tSma data files related to param between pWin.
 *
 * @param pTsdb
 * @param param
 * @param pWin
 * @return int32_t
 */
C
Cary Xu 已提交
1493
int32_t tsdbRemoveTSmaData(STsdb *pTsdb, void *smaIndex, STimeWindow *pWin) {
C
Cary Xu 已提交
1494 1495 1496 1497
  // for ("tSmaFiles of param-interval-sliding between pWin") {
  //   // remove the tSmaFile
  // }
  return TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
1498
}
C
Cary Xu 已提交
1499 1500
#endif

C
Cary Xu 已提交
1501
// TODO: Who is responsible for resource allocate and release?
C
Cary Xu 已提交
1502
int32_t tsdbInsertTSmaData(STsdb *pTsdb, int64_t indexUid, const char *msg) {
C
Cary Xu 已提交
1503
  int32_t code = TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
1504
  if ((code = tsdbInsertTSmaDataImpl(pTsdb, indexUid, msg)) < 0) {
C
Cary Xu 已提交
1505 1506 1507 1508 1509
    tsdbWarn("vgId:%d insert tSma data failed since %s", REPO_ID(pTsdb), tstrerror(terrno));
  }
  return code;
}

C
Cary Xu 已提交
1510
int32_t tsdbUpdateSmaWindow(STsdb *pTsdb, SSubmitReq *pMsg) {
C
Cary Xu 已提交
1511
  int32_t code = TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
1512
  if ((code = tsdbUpdateExpiredWindowImpl(pTsdb, pMsg)) < 0) {
C
Cary Xu 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
    tsdbWarn("vgId:%d update expired sma window failed since %s", REPO_ID(pTsdb), tstrerror(terrno));
  }
  return code;
}

int32_t tsdbInsertRSmaData(STsdb *pTsdb, char *msg) {
  int32_t code = TSDB_CODE_SUCCESS;
  if ((code = tsdbInsertRSmaDataImpl(pTsdb, msg)) < 0) {
    tsdbWarn("vgId:%d insert rSma data failed since %s", REPO_ID(pTsdb), tstrerror(terrno));
  }
  return code;
}

C
Cary Xu 已提交
1526
int32_t tsdbGetTSmaData(STsdb *pTsdb, char *pData, int64_t indexUid, TSKEY querySKey, int32_t nMaxResult) {
C
Cary Xu 已提交
1527
  int32_t code = TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
1528
  if ((code = tsdbGetTSmaDataImpl(pTsdb, pData, indexUid, querySKey, nMaxResult)) < 0) {
C
Cary Xu 已提交
1529 1530 1531
    tsdbWarn("vgId:%d get tSma data failed since %s", REPO_ID(pTsdb), tstrerror(terrno));
  }
  return code;
C
Cary Xu 已提交
1532 1533 1534 1535 1536 1537 1538 1539
}

int32_t tsdbDropTSmaData(STsdb *pTsdb, int64_t indexUid) {
  int32_t code = TSDB_CODE_SUCCESS;
  if ((code = tsdbDropTSmaDataImpl(pTsdb, indexUid)) < 0) {
    tsdbWarn("vgId:%d drop tSma data failed since %s", REPO_ID(pTsdb), tstrerror(terrno));
  }
  return code;
C
Cary Xu 已提交
1540
}