tsdbMain.c 30.1 KB
Newer Older
H
Hongze Cheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * 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/>.
 */

// no test file errors here
#include "taosdef.h"
#include "tsdbint.h"
#include "tthread.h"
H
refact  
Hongze Cheng 已提交
20
#include "ttimer.h"
H
Hongze Cheng 已提交
21 22 23 24 25 26

#define IS_VALID_PRECISION(precision) \
  (((precision) >= TSDB_TIME_PRECISION_MILLI) && ((precision) <= TSDB_TIME_PRECISION_NANO))
#define TSDB_DEFAULT_COMPRESSION TWO_STAGE_COMP
#define IS_VALID_COMPRESSION(compression) (((compression) >= NO_COMPRESSION) && ((compression) <= TWO_STAGE_COMP))

H
refact  
Hongze Cheng 已提交
27 28 29 30 31 32 33
static int32_t tsdbCheckAndSetDefaultCfg(STsdbCfg *pCfg);
static STsdb * tsdbNewRepo(STsdbCfg *pCfg, STsdbAppH *pAppH);
static void    tsdbFreeRepo(STsdb *pRepo);
static void    tsdbStartStream(STsdb *pRepo);
static void    tsdbStopStream(STsdb *pRepo);
static int     tsdbRestoreLastColumns(STsdb *pRepo, STable *pTable, SReadH *pReadh);
static int     tsdbRestoreLastRow(STsdb *pRepo, STable *pTable, SReadH *pReadh, SBlockIdx *pIdx);
H
Hongze Cheng 已提交
34

H
refact  
Hongze Cheng 已提交
35 36 37
STsdb *tsdbOpen(const char *path, STsdbCfg *pCfg) {
  STsdb *  pTsdb;
  STsdbCfg config = *pCfg;
H
Hongze Cheng 已提交
38 39 40 41 42 43 44 45 46 47

  terrno = TSDB_CODE_SUCCESS;

  // Check and set default configurations
  if (tsdbCheckAndSetDefaultCfg(&config) < 0) {
    tsdbError("vgId:%d failed to open TSDB repository since %s", config.tsdbId, tstrerror(terrno));
    return NULL;
  }

  // Create new TSDB object
H
refact  
Hongze Cheng 已提交
48
  if ((pTsdb = tsdbNewRepo(&config, pAppH)) == NULL) {
H
Hongze Cheng 已提交
49 50 51 52 53 54
    tsdbError("vgId:%d failed to open TSDB repository while creating TSDB object since %s", config.tsdbId,
              tstrerror(terrno));
    return NULL;
  }

  // Open meta
H
refact  
Hongze Cheng 已提交
55
  if (tsdbOpenMeta(pTsdb) < 0) {
H
Hongze Cheng 已提交
56
    tsdbError("vgId:%d failed to open TSDB repository while opening Meta since %s", config.tsdbId, tstrerror(terrno));
H
refact  
Hongze Cheng 已提交
57
    tsdbClose(pTsdb, false);
H
Hongze Cheng 已提交
58 59 60
    return NULL;
  }

H
refact  
Hongze Cheng 已提交
61
  if (tsdbOpenFS(pTsdb) < 0) {
H
Hongze Cheng 已提交
62
    tsdbError("vgId:%d failed to open TSDB repository while opening FS since %s", config.tsdbId, tstrerror(terrno));
H
refact  
Hongze Cheng 已提交
63
    tsdbClose(pTsdb, false);
H
Hongze Cheng 已提交
64 65 66 67
    return NULL;
  }

  // TODO: Restore information from data
H
refact  
Hongze Cheng 已提交
68
  if ((!(pTsdb->state & TSDB_STATE_BAD_DATA)) && tsdbRestoreInfo(pTsdb) < 0) {
H
Hongze Cheng 已提交
69
    tsdbError("vgId:%d failed to open TSDB repository while restore info since %s", config.tsdbId, tstrerror(terrno));
H
refact  
Hongze Cheng 已提交
70
    tsdbClose(pTsdb, false);
H
Hongze Cheng 已提交
71 72 73
    return NULL;
  }

H
refact  
Hongze Cheng 已提交
74
  pTsdb->mergeBuf = NULL;
H
Hongze Cheng 已提交
75

H
refact  
Hongze Cheng 已提交
76
  tsdbStartStream(pTsdb);
H
Hongze Cheng 已提交
77

H
refact  
Hongze Cheng 已提交
78
  tsdbDebug("vgId:%d, TSDB repository opened", REPO_ID(pTsdb));
H
Hongze Cheng 已提交
79

H
refact  
Hongze Cheng 已提交
80
  return pTsdb;
H
Hongze Cheng 已提交
81 82 83
}

// Note: all working thread and query thread must stopped when calling this function
H
more  
Hongze Cheng 已提交
84
int tsdbClose(STsdb *repo, int toCommit) {
H
Hongze Cheng 已提交
85 86
  if (repo == NULL) return 0;

H
Hongze Cheng 已提交
87
  STsdb *pRepo = repo;
H
refact  
Hongze Cheng 已提交
88
  int    vgId = REPO_ID(pRepo);
H
Hongze Cheng 已提交
89 90 91 92

  terrno = TSDB_CODE_SUCCESS;

  tsdbStopStream(pRepo);
H
refact  
Hongze Cheng 已提交
93
  if (pRepo->pthread) {
H
Hongze Cheng 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    taosDestoryThread(pRepo->pthread);
    pRepo->pthread = NULL;
  }

  if (toCommit) {
    tsdbSyncCommit(repo);
  }

  tsem_wait(&(pRepo->readyToCommit));

  tsdbUnRefMemTable(pRepo, pRepo->mem);
  tsdbUnRefMemTable(pRepo, pRepo->imem);
  pRepo->mem = NULL;
  pRepo->imem = NULL;

  tsdbCloseFS(pRepo);
  tsdbCloseMeta(pRepo);
  tsdbFreeRepo(pRepo);
  tsdbDebug("vgId:%d repository is closed", vgId);

  if (terrno != TSDB_CODE_SUCCESS) {
    return -1;
  } else {
    return 0;
  }
}

H
Hongze Cheng 已提交
121
STsdbCfg *tsdbGetCfg(const STsdb *repo) {
H
Hongze Cheng 已提交
122
  ASSERT(repo != NULL);
H
Hongze Cheng 已提交
123
  return &((STsdb *)repo)->config;
H
Hongze Cheng 已提交
124 125
}

H
Hongze Cheng 已提交
126
int tsdbLockRepo(STsdb *pRepo) {
H
Hongze Cheng 已提交
127 128 129 130 131 132 133 134 135 136
  int code = pthread_mutex_lock(&pRepo->mutex);
  if (code != 0) {
    tsdbError("vgId:%d failed to lock tsdb since %s", REPO_ID(pRepo), strerror(errno));
    terrno = TAOS_SYSTEM_ERROR(code);
    return -1;
  }
  pRepo->repoLocked = true;
  return 0;
}

H
Hongze Cheng 已提交
137
int tsdbUnlockRepo(STsdb *pRepo) {
H
Hongze Cheng 已提交
138 139 140 141 142 143 144 145 146 147 148
  ASSERT(IS_REPO_LOCKED(pRepo));
  pRepo->repoLocked = false;
  int code = pthread_mutex_unlock(&pRepo->mutex);
  if (code != 0) {
    tsdbError("vgId:%d failed to unlock tsdb since %s", REPO_ID(pRepo), strerror(errno));
    terrno = TAOS_SYSTEM_ERROR(code);
    return -1;
  }
  return 0;
}

H
Hongze Cheng 已提交
149 150 151 152 153 154 155
// int tsdbCheckWal(STsdbRepo *pRepo, uint32_t walSize) {  // MB
//   STsdbCfg *pCfg = &(pRepo->config);
//   if ((walSize > tsdbWalFlushSize) && (walSize > (pCfg->totalBlocks / 2 * pCfg->cacheBlockSize))) {
//     if (tsdbAsyncCommit(pRepo) < 0) return -1;
//   }
//   return 0;
// }
H
Hongze Cheng 已提交
156

H
Hongze Cheng 已提交
157 158 159
// int tsdbCheckCommit(STsdb *pRepo) {
//   ASSERT(pRepo->mem != NULL);
//   STsdbCfg *pCfg = &(pRepo->config);
H
Hongze Cheng 已提交
160

H
Hongze Cheng 已提交
161 162 163
//   STsdbBufBlock *pBufBlock = tsdbGetCurrBufBlock(pRepo);
//   ASSERT(pBufBlock != NULL);
//   if ((pRepo->mem->extraBuffList != NULL) ||
H
refact  
Hongze Cheng 已提交
164 165
//       ((listNEles(pRepo->mem->bufBlockList) >= pCfg->totalBlocks / 3) && (pBufBlock->remain < TSDB_BUFFER_RESERVE)))
//       {
H
Hongze Cheng 已提交
166 167 168 169 170
//     // trigger commit
//     if (tsdbAsyncCommit(pRepo) < 0) return -1;
//   }
//   return 0;
// }
H
Hongze Cheng 已提交
171

H
Hongze Cheng 已提交
172
STsdbMeta *tsdbGetMeta(STsdb *pRepo) { return pRepo->tsdbMeta; }
H
Hongze Cheng 已提交
173

H
Hongze Cheng 已提交
174
STsdbRepoInfo *tsdbGetStatus(STsdb *pRepo) { return NULL; }
H
Hongze Cheng 已提交
175

H
Hongze Cheng 已提交
176
int tsdbGetState(STsdb *repo) { return repo->state; }
H
Hongze Cheng 已提交
177

H
Hongze Cheng 已提交
178
int8_t tsdbGetCompactState(STsdb *repo) { return (int8_t)(repo->compactState); }
H
Hongze Cheng 已提交
179 180 181

void tsdbReportStat(void *repo, int64_t *totalPoints, int64_t *totalStorage, int64_t *compStorage) {
  ASSERT(repo != NULL);
H
Hongze Cheng 已提交
182
  STsdb *pRepo = repo;
H
Hongze Cheng 已提交
183 184 185 186 187
  *totalPoints = pRepo->stat.pointsWritten;
  *totalStorage = pRepo->stat.totalStorage;
  *compStorage = pRepo->stat.compStorage;
}

H
Hongze Cheng 已提交
188
int32_t tsdbConfigRepo(STsdb *repo, STsdbCfg *pCfg) {
H
Hongze Cheng 已提交
189 190
  // TODO: think about multithread cases
  if (tsdbCheckAndSetDefaultCfg(pCfg) < 0) return -1;
H
refact  
Hongze Cheng 已提交
191 192 193

  STsdbCfg *pRCfg = &repo->config;

H
Hongze Cheng 已提交
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 226 227 228 229 230 231
  ASSERT(pRCfg->tsdbId == pCfg->tsdbId);
  ASSERT(pRCfg->cacheBlockSize == pCfg->cacheBlockSize);
  ASSERT(pRCfg->daysPerFile == pCfg->daysPerFile);
  ASSERT(pRCfg->minRowsPerFileBlock == pCfg->minRowsPerFileBlock);
  ASSERT(pRCfg->maxRowsPerFileBlock == pCfg->maxRowsPerFileBlock);
  ASSERT(pRCfg->precision == pCfg->precision);

  bool configChanged = false;
  if (pRCfg->compression != pCfg->compression) {
    configChanged = true;
  }
  if (pRCfg->keep != pCfg->keep) {
    configChanged = true;
  }
  if (pRCfg->keep1 != pCfg->keep1) {
    configChanged = true;
  }
  if (pRCfg->keep2 != pCfg->keep2) {
    configChanged = true;
  }
  if (pRCfg->cacheLastRow != pCfg->cacheLastRow) {
    configChanged = true;
  }
  if (pRCfg->totalBlocks != pCfg->totalBlocks) {
    configChanged = true;
  }

  if (!configChanged) {
    tsdbError("vgId:%d no config changed", REPO_ID(repo));
  }

  int code = pthread_mutex_lock(&repo->save_mutex);
  if (code != 0) {
    tsdbError("vgId:%d failed to lock tsdb save config mutex since %s", REPO_ID(repo), strerror(errno));
    terrno = TAOS_SYSTEM_ERROR(code);
    return -1;
  }

H
refact  
Hongze Cheng 已提交
232
  STsdbCfg *pSaveCfg = &repo->save_config;
H
Hongze Cheng 已提交
233 234 235 236 237 238 239 240 241
  *pSaveCfg = repo->config;

  pSaveCfg->compression = pCfg->compression;
  pSaveCfg->keep = pCfg->keep;
  pSaveCfg->keep1 = pCfg->keep1;
  pSaveCfg->keep2 = pCfg->keep2;
  pSaveCfg->cacheLastRow = pCfg->cacheLastRow;
  pSaveCfg->totalBlocks = pCfg->totalBlocks;

H
refact  
Hongze Cheng 已提交
242 243 244 245 246
  tsdbInfo("vgId:%d old config: compression(%d), keep(%d,%d,%d), cacheLastRow(%d),totalBlocks(%d)", REPO_ID(repo),
           pRCfg->compression, pRCfg->keep, pRCfg->keep1, pRCfg->keep2, pRCfg->cacheLastRow, pRCfg->totalBlocks);
  tsdbInfo("vgId:%d new config: compression(%d), keep(%d,%d,%d), cacheLastRow(%d),totalBlocks(%d)", REPO_ID(repo),
           pSaveCfg->compression, pSaveCfg->keep, pSaveCfg->keep1, pSaveCfg->keep2, pSaveCfg->cacheLastRow,
           pSaveCfg->totalBlocks);
H
Hongze Cheng 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

  repo->config_changed = true;

  pthread_mutex_unlock(&repo->save_mutex);

  // schedule a commit msg and wait for the new config applied
  tsdbSyncCommitConfig(repo);

  return 0;
#if 0
  STsdbRepo *pRepo = (STsdbRepo *)repo;
  STsdbCfg   config = pRepo->config;
  STsdbCfg * pRCfg = &pRepo->config;

  if (tsdbCheckAndSetDefaultCfg(pCfg) < 0) return -1;

  ASSERT(pRCfg->tsdbId == pCfg->tsdbId);
  ASSERT(pRCfg->cacheBlockSize == pCfg->cacheBlockSize);
  ASSERT(pRCfg->daysPerFile == pCfg->daysPerFile);
  ASSERT(pRCfg->minRowsPerFileBlock == pCfg->minRowsPerFileBlock);
  ASSERT(pRCfg->maxRowsPerFileBlock == pCfg->maxRowsPerFileBlock);
  ASSERT(pRCfg->precision == pCfg->precision);

  bool configChanged = false;
  if (pRCfg->compression != pCfg->compression) {
    tsdbAlterCompression(pRepo, pCfg->compression);
    config.compression = pCfg->compression;
    configChanged = true;
  }
  if (pRCfg->keep != pCfg->keep) {
    if (tsdbAlterKeep(pRepo, pCfg->keep) < 0) {
      tsdbError("vgId:%d failed to configure repo when alter keep since %s", REPO_ID(pRepo), tstrerror(terrno));
      config.keep = pCfg->keep;
      return -1;
    }
    configChanged = true;
  }
  if (pRCfg->totalBlocks != pCfg->totalBlocks) {
    tsdbAlterCacheTotalBlocks(pRepo, pCfg->totalBlocks);
    config.totalBlocks = pCfg->totalBlocks;
    configChanged = true;
  }
  if (pRCfg->cacheLastRow != pCfg->cacheLastRow) {
    config.cacheLastRow = pCfg->cacheLastRow;
    configChanged = true;
  }

  if (configChanged) {
    if (tsdbSaveConfig(pRepo->rootDir, &config) < 0) {
      tsdbError("vgId:%d failed to configure repository while save config since %s", REPO_ID(pRepo), tstrerror(terrno));
      return -1;
    }
  }

  return 0;
#endif
}

H
refact  
Hongze Cheng 已提交
305
void tsdbGetRootDir(int repoid, char dirName[]) { snprintf(dirName, TSDB_FILENAME_LEN, "vnode/vnode%d/tsdb", repoid); }
H
Hongze Cheng 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 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 435

void tsdbGetDataDir(int repoid, char dirName[]) {
  snprintf(dirName, TSDB_FILENAME_LEN, "vnode/vnode%d/tsdb/data", repoid);
}

static int32_t tsdbCheckAndSetDefaultCfg(STsdbCfg *pCfg) {
  // Check tsdbId
  if (pCfg->tsdbId < 0) {
    tsdbError("vgId:%d invalid vgroup ID", pCfg->tsdbId);
    terrno = TSDB_CODE_TDB_INVALID_CONFIG;
    return -1;
  }

  // Check precision
  if (pCfg->precision == -1) {
    pCfg->precision = TSDB_DEFAULT_PRECISION;
  } else {
    if (!IS_VALID_PRECISION(pCfg->precision)) {
      tsdbError("vgId:%d invalid precision configuration %d", pCfg->tsdbId, pCfg->precision);
      terrno = TSDB_CODE_TDB_INVALID_CONFIG;
      return -1;
    }
  }

  // Check compression
  if (pCfg->compression == -1) {
    pCfg->compression = TSDB_DEFAULT_COMPRESSION;
  } else {
    if (!IS_VALID_COMPRESSION(pCfg->compression)) {
      tsdbError("vgId:%d invalid compression configuration %d", pCfg->tsdbId, pCfg->precision);
      terrno = TSDB_CODE_TDB_INVALID_CONFIG;
      return -1;
    }
  }

  // Check daysPerFile
  if (pCfg->daysPerFile == -1) {
    pCfg->daysPerFile = TSDB_DEFAULT_DAYS_PER_FILE;
  } else {
    if (pCfg->daysPerFile < TSDB_MIN_DAYS_PER_FILE || pCfg->daysPerFile > TSDB_MAX_DAYS_PER_FILE) {
      tsdbError(
          "vgId:%d invalid daysPerFile configuration! daysPerFile %d TSDB_MIN_DAYS_PER_FILE %d TSDB_MAX_DAYS_PER_FILE "
          "%d",
          pCfg->tsdbId, pCfg->daysPerFile, TSDB_MIN_DAYS_PER_FILE, TSDB_MAX_DAYS_PER_FILE);
      terrno = TSDB_CODE_TDB_INVALID_CONFIG;
      return -1;
    }
  }

  // Check minRowsPerFileBlock and maxRowsPerFileBlock
  if (pCfg->minRowsPerFileBlock == -1) {
    pCfg->minRowsPerFileBlock = TSDB_DEFAULT_MIN_ROW_FBLOCK;
  } else {
    if (pCfg->minRowsPerFileBlock < TSDB_MIN_MIN_ROW_FBLOCK || pCfg->minRowsPerFileBlock > TSDB_MAX_MIN_ROW_FBLOCK) {
      tsdbError(
          "vgId:%d invalid minRowsPerFileBlock configuration! minRowsPerFileBlock %d TSDB_MIN_MIN_ROW_FBLOCK %d "
          "TSDB_MAX_MIN_ROW_FBLOCK %d",
          pCfg->tsdbId, pCfg->minRowsPerFileBlock, TSDB_MIN_MIN_ROW_FBLOCK, TSDB_MAX_MIN_ROW_FBLOCK);
      terrno = TSDB_CODE_TDB_INVALID_CONFIG;
      return -1;
    }
  }

  if (pCfg->maxRowsPerFileBlock == -1) {
    pCfg->maxRowsPerFileBlock = TSDB_DEFAULT_MAX_ROW_FBLOCK;
  } else {
    if (pCfg->maxRowsPerFileBlock < TSDB_MIN_MAX_ROW_FBLOCK || pCfg->maxRowsPerFileBlock > TSDB_MAX_MAX_ROW_FBLOCK) {
      tsdbError(
          "vgId:%d invalid maxRowsPerFileBlock configuration! maxRowsPerFileBlock %d TSDB_MIN_MAX_ROW_FBLOCK %d "
          "TSDB_MAX_MAX_ROW_FBLOCK %d",
          pCfg->tsdbId, pCfg->maxRowsPerFileBlock, TSDB_MIN_MIN_ROW_FBLOCK, TSDB_MAX_MIN_ROW_FBLOCK);
      terrno = TSDB_CODE_TDB_INVALID_CONFIG;
      return -1;
    }
  }

  if (pCfg->minRowsPerFileBlock > pCfg->maxRowsPerFileBlock) {
    tsdbError("vgId:%d invalid configuration! minRowsPerFileBlock %d maxRowsPerFileBlock %d", pCfg->tsdbId,
              pCfg->minRowsPerFileBlock, pCfg->maxRowsPerFileBlock);
    terrno = TSDB_CODE_TDB_INVALID_CONFIG;
    return -1;
  }

  // Check keep
#if 0  // already checked and set in mnodeSetDefaultDbCfg
  if (pCfg->keep == -1) {
    pCfg->keep = TSDB_DEFAULT_KEEP;
  } else {
    if (pCfg->keep < TSDB_MIN_KEEP || pCfg->keep > TSDB_MAX_KEEP) {
      tsdbError(
          "vgId:%d invalid keep configuration! keep %d TSDB_MIN_KEEP %d "
          "TSDB_MAX_KEEP %d",
          pCfg->tsdbId, pCfg->keep, TSDB_MIN_KEEP, TSDB_MAX_KEEP);
      terrno = TSDB_CODE_TDB_INVALID_CONFIG;
      return -1;
    }
  }

  if (pCfg->keep1 == 0) {
    pCfg->keep1 = pCfg->keep;
  }

  if (pCfg->keep2 == 0) {
    pCfg->keep2 = pCfg->keep;
  }
#endif

  int32_t keepMin = pCfg->keep1;
  int32_t keepMid = pCfg->keep2;
  int32_t keepMax = pCfg->keep;

  if (keepMin > keepMid) {
    SWAP(keepMin, keepMid, int32_t);
  }
  if (keepMin > keepMax) {
    SWAP(keepMin, keepMax, int32_t);
  }
  if (keepMid > keepMax) {
    SWAP(keepMid, keepMax, int32_t);
  }

  pCfg->keep = keepMax;
  pCfg->keep1 = keepMin;
  pCfg->keep2 = keepMid;
  // update check
  if (pCfg->update < TD_ROW_DISCARD_UPDATE || pCfg->update > TD_ROW_PARTIAL_UPDATE)
    pCfg->update = TD_ROW_DISCARD_UPDATE;

  // update cacheLastRow
  if (pCfg->cacheLastRow != 0) {
H
refact  
Hongze Cheng 已提交
436
    if (pCfg->cacheLastRow > 3) pCfg->cacheLastRow = 1;
H
Hongze Cheng 已提交
437 438 439 440
  }
  return 0;
}

H
Hongze Cheng 已提交
441 442
static STsdb *tsdbNewRepo(STsdbCfg *pCfg, STsdbAppH *pAppH) {
  STsdb *pRepo = (STsdb *)calloc(1, sizeof(*pRepo));
H
Hongze Cheng 已提交
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 497 498
  if (pRepo == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }

  pRepo->state = TSDB_STATE_OK;
  pRepo->code = TSDB_CODE_SUCCESS;
  pRepo->compactState = 0;
  pRepo->config = *pCfg;
  if (pAppH) {
    pRepo->appH = *pAppH;
  }
  pRepo->repoLocked = false;
  pRepo->pthread = NULL;

  int code = pthread_mutex_init(&(pRepo->mutex), NULL);
  if (code != 0) {
    terrno = TAOS_SYSTEM_ERROR(code);
    tsdbFreeRepo(pRepo);
    return NULL;
  }

  code = pthread_mutex_init(&(pRepo->save_mutex), NULL);
  if (code != 0) {
    terrno = TAOS_SYSTEM_ERROR(code);
    tsdbFreeRepo(pRepo);
    return NULL;
  }
  pRepo->config_changed = false;
  pRepo->cacheLastConfigVersion = 0;

  code = tsem_init(&(pRepo->readyToCommit), 0, 1);
  if (code != 0) {
    code = errno;
    terrno = TAOS_SYSTEM_ERROR(code);
    tsdbFreeRepo(pRepo);
    return NULL;
  }

  pRepo->tsdbMeta = tsdbNewMeta(pCfg);
  if (pRepo->tsdbMeta == NULL) {
    tsdbError("vgId:%d failed to create meta since %s", REPO_ID(pRepo), tstrerror(terrno));
    tsdbFreeRepo(pRepo);
    return NULL;
  }

  pRepo->fs = tsdbNewFS(pCfg);
  if (pRepo->fs == NULL) {
    tsdbError("vgId:%d failed to TSDB file system since %s", REPO_ID(pRepo), tstrerror(terrno));
    tsdbFreeRepo(pRepo);
    return NULL;
  }

  return pRepo;
}

H
Hongze Cheng 已提交
499
static void tsdbFreeRepo(STsdb *pRepo) {
H
Hongze Cheng 已提交
500 501 502 503 504 505 506 507 508 509 510 511
  if (pRepo) {
    tsdbFreeFS(pRepo->fs);
    tsdbFreeMeta(pRepo->tsdbMeta);
    tsdbFreeMergeBuf(pRepo->mergeBuf);
    // tsdbFreeMemTable(pRepo->mem);
    // tsdbFreeMemTable(pRepo->imem);
    tsem_destroy(&(pRepo->readyToCommit));
    pthread_mutex_destroy(&pRepo->mutex);
    free(pRepo);
  }
}

H
Hongze Cheng 已提交
512
static void tsdbStartStream(STsdb *pRepo) {
H
Hongze Cheng 已提交
513 514 515 516 517
  STsdbMeta *pMeta = pRepo->tsdbMeta;

  for (int i = 0; i < pMeta->maxTables; i++) {
    STable *pTable = pMeta->tables[i];
    if (pTable && pTable->type == TSDB_STREAM_TABLE) {
H
refact  
Hongze Cheng 已提交
518 519 520
      pTable->cqhandle =
          (*pRepo->appH.cqCreateFunc)(pRepo->appH.cqH, TABLE_UID(pTable), TABLE_TID(pTable), TABLE_NAME(pTable)->data,
                                      pTable->sql, tsdbGetTableSchemaImpl(pTable, false, false, -1, -1), 0);
H
Hongze Cheng 已提交
521 522 523 524
    }
  }
}

H
Hongze Cheng 已提交
525
static void tsdbStopStream(STsdb *pRepo) {
H
Hongze Cheng 已提交
526 527 528 529 530 531 532 533 534 535
  STsdbMeta *pMeta = pRepo->tsdbMeta;

  for (int i = 0; i < pMeta->maxTables; i++) {
    STable *pTable = pMeta->tables[i];
    if (pTable && pTable->type == TSDB_STREAM_TABLE) {
      (*pRepo->appH.cqDropFunc)(pTable->cqhandle);
    }
  }
}

H
refact  
Hongze Cheng 已提交
536 537
static int tsdbRestoreLastColumns(STsdb *pRepo, STable *pTable, SReadH *pReadh) {
  // tsdbInfo("tsdbRestoreLastColumns of table %s", pTable->name->data);
H
Hongze Cheng 已提交
538 539 540 541 542 543 544

  STSchema *pSchema = tsdbGetTableLatestSchema(pTable);
  if (pSchema == NULL) {
    tsdbError("tsdbGetTableLatestSchema of table %s fail", pTable->name->data);
    return 0;
  }

H
refact  
Hongze Cheng 已提交
545 546 547 548
  SBlock *     pBlock;
  int          numColumns;
  int32_t      blockIdx;
  SDataStatis *pBlockStatis = NULL;
H
Hongze Cheng 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
  // SMemRow      row = NULL;
  // restore last column data with last schema

  int err = 0;

  numColumns = schemaNCols(pSchema);
  if (numColumns <= pTable->restoreColumnNum) {
    pTable->hasRestoreLastColumn = true;
    return 0;
  }
  if (pTable->lastColSVersion != schemaVersion(pSchema)) {
    if (tsdbInitColIdCacheWithSchema(pTable, pSchema) < 0) {
      return -1;
    }
  }

  // row = taosTMalloc(memRowMaxBytesFromSchema(pSchema));
  // if (row == NULL) {
  //   terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
  //   err = -1;
  //   goto out;
  // }

  // memRowSetType(row, SMEM_ROW_DATA);
  // tdInitDataRow(memRowDataBody(row), pSchema);

  // first load block index info
  if (tsdbLoadBlockInfo(pReadh, NULL, NULL) < 0) {
    err = -1;
    goto out;
  }

  pBlockStatis = calloc(numColumns, sizeof(SDataStatis));
  if (pBlockStatis == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    err = -1;
    goto out;
  }
  memset(pBlockStatis, 0, numColumns * sizeof(SDataStatis));
H
refact  
Hongze Cheng 已提交
588
  for (int32_t i = 0; i < numColumns; ++i) {
H
Hongze Cheng 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
    STColumn *pCol = schemaColAt(pSchema, i);
    pBlockStatis[i].colId = pCol->colId;
  }

  // load block from backward
  SBlockIdx *pIdx = pReadh->pBlkIdx;
  blockIdx = (int32_t)(pIdx->numOfBlocks - 1);

  while (numColumns > pTable->restoreColumnNum && blockIdx >= 0) {
    bool loadStatisData = false;
    pBlock = pReadh->pBlkInfo->blocks + blockIdx;
    blockIdx -= 1;

    // load block data
    if (tsdbLoadBlockData(pReadh, pBlock, NULL) < 0) {
      err = -1;
      goto out;
    }

    // file block with sub-blocks has no statistics data
    if (pBlock->numOfSubBlocks <= 1) {
H
Hongze Cheng 已提交
610
      if (tsdbLoadBlockStatis(pReadh, pBlock) == 0) {
H
Hongze Cheng 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        tsdbGetBlockStatis(pReadh, pBlockStatis, (int)numColumns, pBlock);
        loadStatisData = true;
      }
    }
    TSDB_WLOCK_TABLE(pTable);  // lock when update pTable->lastCols[]
    for (int16_t i = 0; i < numColumns && numColumns > pTable->restoreColumnNum; ++i) {
      STColumn *pCol = schemaColAt(pSchema, i);
      // ignore loaded columns
      if (pTable->lastCols[i].bytes != 0) {
        continue;
      }

      // ignore block which has no not-null colId column
      if (loadStatisData && pBlockStatis[i].numOfNull == pBlock->numOfRows) {
        continue;
      }

      // OK,let's load row from backward to get not-null column
      for (int32_t rowId = pBlock->numOfRows - 1; rowId >= 0; rowId--) {
H
refact  
Hongze Cheng 已提交
630 631
        SDataCol *  pDataCol = pReadh->pDCols[0]->cols + i;
        const void *pColData = tdGetColDataOfRow(pDataCol, rowId);
H
Hongze Cheng 已提交
632 633 634 635 636 637 638 639 640 641 642
        // tdAppendColVal(memRowDataBody(row), pColData, pCol->type, pCol->offset);
        //  SDataCol *pDataCol = readh.pDCols[0]->cols + j;
        // void *value = tdGetRowDataOfCol(memRowDataBody(row), (int8_t)pCol->type, TD_DATA_ROW_HEAD_SIZE +
        //
        // pCol->offset);
        if (isNull(pColData, pCol->type)) {
          continue;
        }

        int16_t idx = tsdbGetLastColumnsIndexByColId(pTable, pCol->colId);
        if (idx == -1) {
H
refact  
Hongze Cheng 已提交
643 644
          tsdbError("tsdbRestoreLastColumns restore vgId:%d,table:%s cache column %d fail", REPO_ID(pRepo),
                    pTable->name->data, pCol->colId);
H
Hongze Cheng 已提交
645 646 647
          continue;
        }
        // save not-null column
H
refact  
Hongze Cheng 已提交
648
        uint16_t  bytes = IS_VAR_DATA_TYPE(pCol->type) ? varDataTLen(pColData) : pCol->bytes;
H
Hongze Cheng 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
        SDataCol *pLastCol = &(pTable->lastCols[idx]);
        pLastCol->pData = malloc(bytes);
        pLastCol->bytes = bytes;
        pLastCol->colId = pCol->colId;
        memcpy(pLastCol->pData, pColData, bytes);

        // save row ts(in column 0)
        pDataCol = pReadh->pDCols[0]->cols + 0;
        // pCol = schemaColAt(pSchema, 0);
        // tdAppendColVal(memRowDataBody(row), tdGetColDataOfRow(pDataCol, rowId), pCol->type, pCol->offset);
        // pLastCol->ts = memRowKey(row);
        pLastCol->ts = tdGetKey(*(TKEY *)(tdGetColDataOfRow(pDataCol, rowId)));

        pTable->restoreColumnNum += 1;

H
refact  
Hongze Cheng 已提交
664 665
        tsdbDebug("tsdbRestoreLastColumns restore vgId:%d,table:%s cache column %d, %" PRId64, REPO_ID(pRepo),
                  pTable->name->data, pLastCol->colId, pLastCol->ts);
H
Hongze Cheng 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
        break;
      }
    }
    TSDB_WUNLOCK_TABLE(pTable);
  }

out:
  // taosTZfree(row);
  tfree(pBlockStatis);

  if (err == 0 && numColumns <= pTable->restoreColumnNum) {
    pTable->hasRestoreLastColumn = true;
  }

  return err;
}

H
refact  
Hongze Cheng 已提交
683
static int tsdbRestoreLastRow(STsdb *pRepo, STable *pTable, SReadH *pReadh, SBlockIdx *pIdx) {
H
Hongze Cheng 已提交
684 685 686 687 688
  ASSERT(pTable->lastRow == NULL);
  if (tsdbLoadBlockInfo(pReadh, NULL, NULL) < 0) {
    return -1;
  }

H
refact  
Hongze Cheng 已提交
689
  SBlock *pBlock = pReadh->pBlkInfo->blocks + pIdx->numOfBlocks - 1;
H
Hongze Cheng 已提交
690 691 692 693 694 695

  if (tsdbLoadBlockData(pReadh, pBlock, NULL) < 0) {
    return -1;
  }

  // Get the data in row
H
refact  
Hongze Cheng 已提交
696

H
Hongze Cheng 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
  STSchema *pSchema = tsdbGetTableSchema(pTable);
  SMemRow   lastRow = taosTMalloc(memRowMaxBytesFromSchema(pSchema));
  if (lastRow == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }
  memRowSetType(lastRow, SMEM_ROW_DATA);
  tdInitDataRow(memRowDataBody(lastRow), pSchema);
  for (int icol = 0; icol < schemaNCols(pSchema); icol++) {
    STColumn *pCol = schemaColAt(pSchema, icol);
    SDataCol *pDataCol = pReadh->pDCols[0]->cols + icol;
    tdAppendColVal(memRowDataBody(lastRow), tdGetColDataOfRow(pDataCol, pBlock->numOfRows - 1), pCol->type,
                   pCol->offset);
  }

  TSKEY lastKey = memRowKey(lastRow);
H
refact  
Hongze Cheng 已提交
713

H
Hongze Cheng 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727
  // during the load data in file, new data would be inserted and last row has been updated
  TSDB_WLOCK_TABLE(pTable);
  if (pTable->lastRow == NULL) {
    pTable->lastKey = lastKey;
    pTable->lastRow = lastRow;
    TSDB_WUNLOCK_TABLE(pTable);
  } else {
    TSDB_WUNLOCK_TABLE(pTable);
    taosTZfree(lastRow);
  }

  return 0;
}

H
Hongze Cheng 已提交
728
int tsdbRestoreInfo(STsdb *pRepo) {
H
Hongze Cheng 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  SFSIter    fsiter;
  SReadH     readh;
  SDFileSet *pSet;
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  STsdbCfg * pCfg = REPO_CFG(pRepo);

  if (tsdbInitReadH(&readh, pRepo) < 0) {
    return -1;
  }

  tsdbFSIterInit(&fsiter, REPO_FS(pRepo), TSDB_FS_ITER_BACKWARD);

  if (CACHE_LAST_NULL_COLUMN(pCfg)) {
    for (int i = 1; i < pMeta->maxTables; i++) {
      STable *pTable = pMeta->tables[i];
      if (pTable == NULL) continue;
H
refact  
Hongze Cheng 已提交
745
      pTable->restoreColumnNum = 0;
H
Hongze Cheng 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
      pTable->hasRestoreLastColumn = false;
    }
  }

  while ((pSet = tsdbFSIterNext(&fsiter)) != NULL) {
    if (tsdbSetAndOpenReadFSet(&readh, pSet) < 0) {
      tsdbDestroyReadH(&readh);
      return -1;
    }

    if (tsdbLoadBlockIdx(&readh) < 0) {
      tsdbDestroyReadH(&readh);
      return -1;
    }

    for (int i = 1; i < pMeta->maxTables; i++) {
      STable *pTable = pMeta->tables[i];
      if (pTable == NULL) continue;

H
refact  
Hongze Cheng 已提交
765
      // tsdbInfo("tsdbRestoreInfo restore vgId:%d,table:%s", REPO_ID(pRepo), pTable->name->data);
H
Hongze Cheng 已提交
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781

      if (tsdbSetReadTable(&readh, pTable) < 0) {
        tsdbDestroyReadH(&readh);
        return -1;
      }

      TSKEY      lastKey = tsdbGetTableLastKeyImpl(pTable);
      SBlockIdx *pIdx = readh.pBlkIdx;
      if (pIdx && lastKey < pIdx->maxKey) {
        pTable->lastKey = pIdx->maxKey;

        if (CACHE_LAST_ROW(pCfg) && tsdbRestoreLastRow(pRepo, pTable, &readh, pIdx) != 0) {
          tsdbDestroyReadH(&readh);
          return -1;
        }
      }
H
refact  
Hongze Cheng 已提交
782

H
Hongze Cheng 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
      // restore NULL columns
      if (pIdx && CACHE_LAST_NULL_COLUMN(pCfg) && !pTable->hasRestoreLastColumn) {
        if (tsdbRestoreLastColumns(pRepo, pTable, &readh) != 0) {
          tsdbDestroyReadH(&readh);
          return -1;
        }
      }
    }
  }

  tsdbDestroyReadH(&readh);

  // if (CACHE_LAST_NULL_COLUMN(pCfg)) {
  //   atomic_store_8(&pRepo->hasCachedLastColumn, 1);
  // }

  return 0;
}

H
Hongze Cheng 已提交
802
int32_t tsdbLoadLastCache(STsdb *pRepo, STable *pTable) {
H
Hongze Cheng 已提交
803 804 805
  SFSIter    fsiter;
  SReadH     readh;
  SDFileSet *pSet;
H
refact  
Hongze Cheng 已提交
806 807
  int        cacheLastRowTableNum = 0;
  int        cacheLastColTableNum = 0;
H
Hongze Cheng 已提交
808 809 810 811

  bool cacheLastRow = CACHE_LAST_ROW(&(pRepo->config));
  bool cacheLastCol = CACHE_LAST_NULL_COLUMN(&(pRepo->config));

H
refact  
Hongze Cheng 已提交
812 813
  tsdbDebug("tsdbLoadLastCache for %s, cacheLastRow:%d, cacheLastCol:%d", pTable->name->data, cacheLastRow,
            cacheLastCol);
H
Hongze Cheng 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828

  pTable->cacheLastConfigVersion = pRepo->cacheLastConfigVersion;

  if (!cacheLastRow && pTable->lastRow != NULL) {
    taosTZfree(pTable->lastRow);
    pTable->lastRow = NULL;
  }
  if (!cacheLastCol && pTable->lastCols != NULL) {
    tsdbFreeLastColumns(pTable);
  }

  if (!cacheLastRow && !cacheLastCol) {
    return 0;
  }

H
refact  
Hongze Cheng 已提交
829
  cacheLastRowTableNum = (cacheLastRow && pTable->lastRow == NULL) ? 1 : 0;
H
Hongze Cheng 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
  cacheLastColTableNum = (cacheLastCol && pTable->lastCols == NULL) ? 1 : 0;

  if (cacheLastRowTableNum == 0 && cacheLastColTableNum == 0) {
    return 0;
  }

  if (tsdbInitReadH(&readh, pRepo) < 0) {
    return -1;
  }

  tsdbRLockFS(REPO_FS(pRepo));
  tsdbFSIterInit(&fsiter, REPO_FS(pRepo), TSDB_FS_ITER_BACKWARD);

  while ((cacheLastRowTableNum > 0 || cacheLastColTableNum > 0) && (pSet = tsdbFSIterNext(&fsiter)) != NULL) {
    if (tsdbSetAndOpenReadFSet(&readh, pSet) < 0) {
      tsdbUnLockFS(REPO_FS(pRepo));
      tsdbDestroyReadH(&readh);
      return -1;
    }

    if (tsdbLoadBlockIdx(&readh) < 0) {
      tsdbUnLockFS(REPO_FS(pRepo));
      tsdbDestroyReadH(&readh);
      return -1;
    }

    // tsdbDebug("tsdbRestoreInfo restore vgId:%d,table:%s", REPO_ID(pRepo), pTable->name->data);

    if (tsdbSetReadTable(&readh, pTable) < 0) {
      tsdbUnLockFS(REPO_FS(pRepo));
      tsdbDestroyReadH(&readh);
      return -1;
    }

    SBlockIdx *pIdx = readh.pBlkIdx;

    if (pIdx && (cacheLastRowTableNum > 0) && (pTable->lastRow == NULL)) {
      if (tsdbRestoreLastRow(pRepo, pTable, &readh, pIdx) != 0) {
        tsdbUnLockFS(REPO_FS(pRepo));
        tsdbDestroyReadH(&readh);
        return -1;
      }
      cacheLastRowTableNum -= 1;
    }

    // restore NULL columns
    if (pIdx && (cacheLastColTableNum > 0) && !pTable->hasRestoreLastColumn) {
      if (tsdbRestoreLastColumns(pRepo, pTable, &readh) != 0) {
        tsdbUnLockFS(REPO_FS(pRepo));
        tsdbDestroyReadH(&readh);
        return -1;
      }
      if (pTable->hasRestoreLastColumn) {
        cacheLastColTableNum -= 1;
      }
    }
  }

  tsdbUnLockFS(REPO_FS(pRepo));
  tsdbDestroyReadH(&readh);

  return 0;
}

H
refact  
Hongze Cheng 已提交
894 895
UNUSED_FUNC int tsdbCacheLastData(STsdb *pRepo, STsdbCfg *oldCfg) {
  bool       cacheLastRow = false, cacheLastCol = false;
H
Hongze Cheng 已提交
896 897 898 899
  SFSIter    fsiter;
  SReadH     readh;
  SDFileSet *pSet;
  STsdbMeta *pMeta = pRepo->tsdbMeta;
H
refact  
Hongze Cheng 已提交
900 901 902 903
  int        tableNum = 0;
  int        maxTableIdx = 0;
  int        cacheLastRowTableNum = 0;
  int        cacheLastColTableNum = 0;
H
Hongze Cheng 已提交
904 905 906 907

  bool need_free_last_row = CACHE_LAST_ROW(oldCfg) && !CACHE_LAST_ROW(&(pRepo->config));
  bool need_free_last_col = CACHE_LAST_NULL_COLUMN(oldCfg) && !CACHE_LAST_NULL_COLUMN(&(pRepo->config));

H
refact  
Hongze Cheng 已提交
908
  if (CACHE_LAST_ROW(&(pRepo->config)) || CACHE_LAST_NULL_COLUMN(&(pRepo->config))) {
H
Hongze Cheng 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922
    tsdbInfo("tsdbCacheLastData cache last data since cacheLast option changed");
    cacheLastRow = !CACHE_LAST_ROW(oldCfg) && CACHE_LAST_ROW(&(pRepo->config));
    cacheLastCol = !CACHE_LAST_NULL_COLUMN(oldCfg) && CACHE_LAST_NULL_COLUMN(&(pRepo->config));
  }

  // calc max table idx and table num
  for (int i = 1; i < pMeta->maxTables; i++) {
    STable *pTable = pMeta->tables[i];
    if (pTable == NULL) continue;
    tableNum += 1;
    maxTableIdx = i;
    if (cacheLastCol) {
      pTable->restoreColumnNum = 0;
      pTable->hasRestoreLastColumn = false;
H
refact  
Hongze Cheng 已提交
923
    }
H
Hongze Cheng 已提交
924 925 926 927 928 929 930
  }

  // if close last option,need to free data
  if (need_free_last_row || need_free_last_col) {
    // if (need_free_last_col) {
    //   atomic_store_8(&pRepo->hasCachedLastColumn, 0);
    // }
H
refact  
Hongze Cheng 已提交
931
    tsdbInfo("free cache last data since cacheLast option changed");
H
Hongze Cheng 已提交
932 933
    for (int i = 1; i <= maxTableIdx; i++) {
      STable *pTable = pMeta->tables[i];
H
refact  
Hongze Cheng 已提交
934
      if (pTable == NULL) continue;
H
Hongze Cheng 已提交
935 936 937 938 939 940 941 942
      if (need_free_last_row) {
        taosTZfree(pTable->lastRow);
        pTable->lastRow = NULL;
      }
      if (need_free_last_col) {
        tsdbFreeLastColumns(pTable);
        pTable->hasRestoreLastColumn = false;
      }
H
refact  
Hongze Cheng 已提交
943
    }
H
Hongze Cheng 已提交
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
  }

  if (!cacheLastRow && !cacheLastCol) {
    return 0;
  }

  cacheLastRowTableNum = cacheLastRow ? tableNum : 0;
  cacheLastColTableNum = cacheLastCol ? tableNum : 0;

  if (tsdbInitReadH(&readh, pRepo) < 0) {
    return -1;
  }

  tsdbFSIterInit(&fsiter, REPO_FS(pRepo), TSDB_FS_ITER_BACKWARD);

  while ((pSet = tsdbFSIterNext(&fsiter)) != NULL && (cacheLastRowTableNum > 0 || cacheLastColTableNum > 0)) {
    if (tsdbSetAndOpenReadFSet(&readh, pSet) < 0) {
      tsdbDestroyReadH(&readh);
      return -1;
    }

    if (tsdbLoadBlockIdx(&readh) < 0) {
      tsdbDestroyReadH(&readh);
      return -1;
    }

    for (int i = 1; i <= maxTableIdx; i++) {
      STable *pTable = pMeta->tables[i];
      if (pTable == NULL) continue;

H
refact  
Hongze Cheng 已提交
974
      // tsdbInfo("tsdbRestoreInfo restore vgId:%d,table:%s", REPO_ID(pRepo), pTable->name->data);
H
Hongze Cheng 已提交
975 976 977 978 979 980 981 982

      if (tsdbSetReadTable(&readh, pTable) < 0) {
        tsdbDestroyReadH(&readh);
        return -1;
      }

      SBlockIdx *pIdx = readh.pBlkIdx;

H
refact  
Hongze Cheng 已提交
983
      if (pIdx && cacheLastRowTableNum > 0 && pTable->lastRow == NULL) {
H
Hongze Cheng 已提交
984 985 986 987 988 989 990 991
        pTable->lastKey = pIdx->maxKey;

        if (tsdbRestoreLastRow(pRepo, pTable, &readh, pIdx) != 0) {
          tsdbDestroyReadH(&readh);
          return -1;
        }
        cacheLastRowTableNum -= 1;
      }
H
refact  
Hongze Cheng 已提交
992

H
Hongze Cheng 已提交
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
      // restore NULL columns
      if (pIdx && cacheLastColTableNum > 0 && !pTable->hasRestoreLastColumn) {
        if (tsdbRestoreLastColumns(pRepo, pTable, &readh) != 0) {
          tsdbDestroyReadH(&readh);
          return -1;
        }
        if (pTable->hasRestoreLastColumn) {
          cacheLastColTableNum -= 1;
        }
      }
    }
  }

  tsdbDestroyReadH(&readh);

  // if (cacheLastCol) {
  //   atomic_store_8(&pRepo->hasCachedLastColumn, 1);
  // }
H
refact  
Hongze Cheng 已提交
1011

H
Hongze Cheng 已提交
1012 1013
  return 0;
}