tsdbCommit.c 52.6 KB
Newer Older
H
Hongze Cheng 已提交
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"

H
more  
Hongze Cheng 已提交
18 19
#define TSDB_MAX_SUBBLOCKS 8

H
more  
Hongze Cheng 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
typedef struct {
  STable *           pTable;
  SSkipListIterator *pIter;
} SCommitIter;

typedef struct {
  SRtn         rtn;     // retention snapshot
  SFSIter      fsIter;  // tsdb file iterator
  int          niters;  // memory iterators
  SCommitIter *iters;
  bool         isRFileSet;  // read and commit FSET
  SReadH       readh;
  SDFileSet    wSet;
  bool         isDFileSame;
  bool         isLFileSame;
  TSKEY        minKey;
  TSKEY        maxKey;
  SArray *     aBlkIdx;  // SBlockIdx array
  STable *     pTable;
  SArray *     aSupBlk;  // Table super-block array
  SArray *     aSubBlk;  // table sub-block array
  SDataCols *  pDataCols;
} SCommitH;

H
more  
Hongze Cheng 已提交
44 45
#define TSDB_DEFAULT_BLOCK_ROWS(maxRows) ((maxRows)*4 / 5)

H
refact  
Hongze Cheng 已提交
46 47 48 49 50 51 52 53 54 55 56 57
#define TSDB_COMMIT_REPO(ch) TSDB_READ_REPO(&(ch->readh))
#define TSDB_COMMIT_REPO_ID(ch) REPO_ID(TSDB_READ_REPO(&(ch->readh)))
#define TSDB_COMMIT_WRITE_FSET(ch) (&((ch)->wSet))
#define TSDB_COMMIT_TABLE(ch) ((ch)->pTable)
#define TSDB_COMMIT_HEAD_FILE(ch) TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_HEAD)
#define TSDB_COMMIT_DATA_FILE(ch) TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_DATA)
#define TSDB_COMMIT_LAST_FILE(ch) TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_LAST)
#define TSDB_COMMIT_BUF(ch) TSDB_READ_BUF(&((ch)->readh))
#define TSDB_COMMIT_COMP_BUF(ch) TSDB_READ_COMP_BUF(&((ch)->readh))
#define TSDB_COMMIT_DEFAULT_ROWS(ch) TSDB_DEFAULT_BLOCK_ROWS(TSDB_COMMIT_REPO(ch)->config.maxRowsPerFileBlock)
#define TSDB_COMMIT_TXN_VERSION(ch) FS_TXN_VERSION(REPO_FS(TSDB_COMMIT_REPO(ch)))

H
more  
Hongze Cheng 已提交
58 59
static void tsdbStartCommit(STsdb *pRepo);
static void tsdbEndCommit(STsdb *pTsdb, int eno);
H
refact  
Hongze Cheng 已提交
60 61 62 63 64
static int  tsdbInitCommitH(SCommitH *pCommith, STsdb *pRepo);
static void tsdbSeekCommitIter(SCommitH *pCommith, TSKEY key);
static int  tsdbNextCommitFid(SCommitH *pCommith);
static void tsdbDestroyCommitH(SCommitH *pCommith);
static int  tsdbCreateCommitIters(SCommitH *pCommith);
H
Hongze Cheng 已提交
65
static void tsdbDestroyCommitIters(SCommitH *pCommith);
H
refact  
Hongze Cheng 已提交
66
static int  tsdbCommitToFile(SCommitH *pCommith, SDFileSet *pSet, int fid);
H
more  
Hongze Cheng 已提交
67 68 69 70 71 72
static void tsdbResetCommitFile(SCommitH *pCommith);
static int  tsdbSetAndOpenCommitFile(SCommitH *pCommith, SDFileSet *pSet, int fid);
// static int  tsdbCommitMeta(STsdbRepo *pRepo);
// static int  tsdbUpdateMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid, void *cont, int contLen, bool compact);
// static int  tsdbDropMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid);
// static int  tsdbCompactMetaFile(STsdbRepo *pRepo, STsdbFS *pfs, SMFile *pMFile);
H
more  
Hongze Cheng 已提交
73 74 75 76 77
static int  tsdbCommitToTable(SCommitH *pCommith, int tid);
static int  tsdbSetCommitTable(SCommitH *pCommith, STable *pTable);
static int  tsdbComparKeyBlock(const void *arg1, const void *arg2);
static int  tsdbWriteBlockInfo(SCommitH *pCommih);
static int  tsdbCommitMemData(SCommitH *pCommith, SCommitIter *pIter, TSKEY keyLimit, bool toData);
H
more  
Hongze Cheng 已提交
78
static int  tsdbMergeMemData(SCommitH *pCommith, SCommitIter *pIter, int bidx);
H
more  
Hongze Cheng 已提交
79 80 81 82 83 84
static int  tsdbMoveBlock(SCommitH *pCommith, int bidx);
static int  tsdbCommitAddBlock(SCommitH *pCommith, const SBlock *pSupBlock, const SBlock *pSubBlocks, int nSubBlocks);
static int  tsdbMergeBlockData(SCommitH *pCommith, SCommitIter *pIter, SDataCols *pDataCols, TSKEY keyLimit,
                               bool isLastOneBlock);
static void tsdbResetCommitTable(SCommitH *pCommith);
static void tsdbCloseCommitFile(SCommitH *pCommith, bool hasError);
H
more  
Hongze Cheng 已提交
85 86 87
static bool tsdbCanAddSubBlock(SCommitH *pCommith, SBlock *pBlock, SMergeInfo *pInfo);
static void tsdbLoadAndMergeFromCache(SDataCols *pDataCols, int *iter, SCommitIter *pCommitIter, SDataCols *pTarget,
                                      TSKEY maxKey, int maxRows, int8_t update);
H
more  
Hongze Cheng 已提交
88
int         tsdbWriteBlockIdx(SDFile *pHeadf, SArray *pIdxA, void **ppBuf);
H
refact  
Hongze Cheng 已提交
89 90 91

int tsdbApplyRtnOnFSet(STsdb *pRepo, SDFileSet *pSet, SRtn *pRtn) {
  SDiskID   did;
C
update  
Cary Xu 已提交
92
  SDFileSet nSet = {0};
H
refact  
Hongze Cheng 已提交
93 94 95 96 97 98 99
  STsdbFS * pfs = REPO_FS(pRepo);
  int       level;

  ASSERT(pSet->fid >= pRtn->minFid);

  level = tsdbGetFidLevel(pSet->fid, pRtn);

S
Shengliang Guan 已提交
100
  if (tfsAllocDisk(pRepo->pTfs, level, &did) < 0) {
H
refact  
Hongze Cheng 已提交
101 102 103 104 105 106
    terrno = TSDB_CODE_TDB_NO_AVAIL_DISK;
    return -1;
  }

  if (did.level > TSDB_FSET_LEVEL(pSet)) {
    // Need to move the FSET to higher level
S
Shengliang Guan 已提交
107
    tsdbInitDFileSet(pRepo, &nSet, did, pSet->fid, FS_TXN_VERSION(pfs));
H
refact  
Hongze Cheng 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

    if (tsdbCopyDFileSet(pSet, &nSet) < 0) {
      tsdbError("vgId:%d failed to copy FSET %d from level %d to level %d since %s", REPO_ID(pRepo), pSet->fid,
                TSDB_FSET_LEVEL(pSet), did.level, tstrerror(terrno));
      return -1;
    }

    if (tsdbUpdateDFileSet(pfs, &nSet) < 0) {
      return -1;
    }

    tsdbInfo("vgId:%d FSET %d is copied from level %d disk id %d to level %d disk id %d", REPO_ID(pRepo), pSet->fid,
             TSDB_FSET_LEVEL(pSet), TSDB_FSET_ID(pSet), did.level, did.id);
  } else {
    // On a correct level
    if (tsdbUpdateDFileSet(pfs, pSet) < 0) {
      return -1;
    }
  }

  return 0;
}
H
more  
Hongze Cheng 已提交
130

H
more  
Hongze Cheng 已提交
131 132 133 134 135 136 137 138 139
int tsdbPrepareCommit(STsdb *pTsdb) {
  if (pTsdb->mem == NULL) return 0;

  ASSERT(pTsdb->imem == NULL);

  pTsdb->imem = pTsdb->mem;
  pTsdb->mem = NULL;
}

H
refact  
Hongze Cheng 已提交
140 141 142 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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
int tsdbCommit(STsdb *pRepo) {
  STsdbMemTable *pMem = pRepo->imem;
  SCommitH       commith = {0};
  SDFileSet *    pSet = NULL;
  int            fid;

  if (pRepo->imem == NULL) return 0;

  tsdbStartCommit(pRepo);
  // Resource initialization
  if (tsdbInitCommitH(&commith, pRepo) < 0) {
    return -1;
  }

  // Skip expired memory data and expired FSET
  tsdbSeekCommitIter(&commith, commith.rtn.minKey);
  while ((pSet = tsdbFSIterNext(&(commith.fsIter)))) {
    if (pSet->fid < commith.rtn.minFid) {
      tsdbInfo("vgId:%d FSET %d on level %d disk id %d expires, remove it", REPO_ID(pRepo), pSet->fid,
               TSDB_FSET_LEVEL(pSet), TSDB_FSET_ID(pSet));
    } else {
      break;
    }
  }

  // Loop to commit to each file
  fid = tsdbNextCommitFid(&(commith));
  while (true) {
    // Loop over both on disk and memory
    if (pSet == NULL && fid == TSDB_IVLD_FID) break;

    if (pSet && (fid == TSDB_IVLD_FID || pSet->fid < fid)) {
      // Only has existing FSET but no memory data to commit in this
      // existing FSET, only check if file in correct retention
      if (tsdbApplyRtnOnFSet(pRepo, pSet, &(commith.rtn)) < 0) {
        tsdbDestroyCommitH(&commith);
        return -1;
      }

      pSet = tsdbFSIterNext(&(commith.fsIter));
    } else {
      // Has memory data to commit
      SDFileSet *pCSet;
      int        cfid;

      if (pSet == NULL || pSet->fid > fid) {
        // Commit to a new FSET with fid: fid
        pCSet = NULL;
        cfid = fid;
      } else {
        // Commit to an existing FSET
        pCSet = pSet;
        cfid = pSet->fid;
        pSet = tsdbFSIterNext(&(commith.fsIter));
      }

      if (tsdbCommitToFile(&commith, pCSet, cfid) < 0) {
        tsdbDestroyCommitH(&commith);
        return -1;
      }

      fid = tsdbNextCommitFid(&commith);
    }
  }
H
more  
Hongze Cheng 已提交
204

H
refact  
Hongze Cheng 已提交
205 206
  tsdbDestroyCommitH(&commith);
  tsdbEndCommit(pRepo, TSDB_CODE_SUCCESS);
H
more  
Hongze Cheng 已提交
207

H
Hongze Cheng 已提交
208
  return 0;
H
Hongze Cheng 已提交
209 210
}

H
Hongze Cheng 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
void tsdbGetRtnSnap(STsdb *pRepo, SRtn *pRtn) {
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  TSKEY     minKey, midKey, maxKey, now;

  now = taosGetTimestamp(pCfg->precision);
  minKey = now - pCfg->keep * tsTickPerDay[pCfg->precision];
  midKey = now - pCfg->keep2 * tsTickPerDay[pCfg->precision];
  maxKey = now - pCfg->keep1 * tsTickPerDay[pCfg->precision];

  pRtn->minKey = minKey;
  pRtn->minFid = (int)(TSDB_KEY_FID(minKey, pCfg->daysPerFile, pCfg->precision));
  pRtn->midFid = (int)(TSDB_KEY_FID(midKey, pCfg->daysPerFile, pCfg->precision));
  pRtn->maxFid = (int)(TSDB_KEY_FID(maxKey, pCfg->daysPerFile, pCfg->precision));
  tsdbDebug("vgId:%d now:%" PRId64 " minKey:%" PRId64 " minFid:%d, midFid:%d, maxFid:%d", REPO_ID(pRepo), now, minKey,
            pRtn->minFid, pRtn->midFid, pRtn->maxFid);
}

H
more  
Hongze Cheng 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
static void tsdbStartCommit(STsdb *pRepo) {
  STsdbMemTable *pMem = pRepo->imem;

  tsdbInfo("vgId:%d start to commit", REPO_ID(pRepo));

  tsdbStartFSTxn(pRepo, 0, 0);
}

static void tsdbEndCommit(STsdb *pTsdb, int eno) {
  tsdbEndFSTxn(pTsdb);
  tsdbFreeMemTable(pTsdb, pTsdb->imem);
  pTsdb->imem = NULL;
  tsdbInfo("vgId:%d commit over, %s", REPO_ID(pTsdb), (eno == TSDB_CODE_SUCCESS) ? "succeed" : "failed");
}

H
refact  
Hongze Cheng 已提交
243 244 245 246 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
static int tsdbInitCommitH(SCommitH *pCommith, STsdb *pRepo) {
  STsdbCfg *pCfg = REPO_CFG(pRepo);

  memset(pCommith, 0, sizeof(*pCommith));
  tsdbGetRtnSnap(pRepo, &(pCommith->rtn));

  TSDB_FSET_SET_CLOSED(TSDB_COMMIT_WRITE_FSET(pCommith));

  // Init read handle
  if (tsdbInitReadH(&(pCommith->readh), pRepo) < 0) {
    return -1;
  }

  // Init file iterator
  tsdbFSIterInit(&(pCommith->fsIter), REPO_FS(pRepo), TSDB_FS_ITER_FORWARD);

  if (tsdbCreateCommitIters(pCommith) < 0) {
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->aBlkIdx = taosArrayInit(1024, sizeof(SBlockIdx));
  if (pCommith->aBlkIdx == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->aSupBlk = taosArrayInit(1024, sizeof(SBlock));
  if (pCommith->aSupBlk == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->aSubBlk = taosArrayInit(1024, sizeof(SBlock));
  if (pCommith->aSubBlk == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->pDataCols = tdNewDataCols(0, pCfg->maxRowsPerFileBlock);
  if (pCommith->pDataCols == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  return 0;
}

// Skip all keys until key (not included)
static void tsdbSeekCommitIter(SCommitH *pCommith, TSKEY key) {
  for (int i = 0; i < pCommith->niters; i++) {
    SCommitIter *pIter = pCommith->iters + i;
    if (pIter->pTable == NULL || pIter->pIter == NULL) continue;

    tsdbLoadDataFromCache(pIter->pTable, pIter->pIter, key - 1, INT32_MAX, NULL, NULL, 0, true, NULL);
  }
}

H
more  
Hongze Cheng 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
static int tsdbNextCommitFid(SCommitH *pCommith) {
  STsdb *   pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  int       fid = TSDB_IVLD_FID;

  for (int i = 0; i < pCommith->niters; i++) {
    SCommitIter *pIter = pCommith->iters + i;
    // if (pIter->pTable == NULL || pIter->pIter == NULL) continue;

    TSKEY nextKey = tsdbNextIterKey(pIter->pIter);
    if (nextKey == TSDB_DATA_TIMESTAMP_NULL) {
      continue;
    } else {
      int tfid = (int)(TSDB_KEY_FID(nextKey, pCfg->daysPerFile, pCfg->precision));
      if (fid == TSDB_IVLD_FID || fid > tfid) {
        fid = tfid;
      }
    }
  }

  return fid;
}
H
refact  
Hongze Cheng 已提交
327 328 329 330 331 332 333 334 335 336 337

static void tsdbDestroyCommitH(SCommitH *pCommith) {
  pCommith->pDataCols = tdFreeDataCols(pCommith->pDataCols);
  pCommith->aSubBlk = taosArrayDestroy(pCommith->aSubBlk);
  pCommith->aSupBlk = taosArrayDestroy(pCommith->aSupBlk);
  pCommith->aBlkIdx = taosArrayDestroy(pCommith->aBlkIdx);
  tsdbDestroyCommitIters(pCommith);
  tsdbDestroyReadH(&(pCommith->readh));
  tsdbCloseDFileSet(TSDB_COMMIT_WRITE_FSET(pCommith));
}

H
more  
Hongze Cheng 已提交
338 339 340
static int tsdbCommitToFile(SCommitH *pCommith, SDFileSet *pSet, int fid) {
  STsdb *   pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg *pCfg = REPO_CFG(pRepo);
H
Hongze Cheng 已提交
341

H
more  
Hongze Cheng 已提交
342
  ASSERT(pSet == NULL || pSet->fid == fid);
H
Hongze Cheng 已提交
343

H
more  
Hongze Cheng 已提交
344 345
  tsdbResetCommitFile(pCommith);
  tsdbGetFidKeyRange(pCfg->daysPerFile, pCfg->precision, fid, &(pCommith->minKey), &(pCommith->maxKey));
H
Hongze Cheng 已提交
346

H
more  
Hongze Cheng 已提交
347 348 349 350
  // Set and open files
  if (tsdbSetAndOpenCommitFile(pCommith, pSet, fid) < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
351

H
more  
Hongze Cheng 已提交
352
  // Loop to commit each table data
H
more  
Hongze Cheng 已提交
353
  for (int tid = 0; tid < pCommith->niters; tid++) {
H
more  
Hongze Cheng 已提交
354
    SCommitIter *pIter = pCommith->iters + tid;
H
Hongze Cheng 已提交
355

H
more  
Hongze Cheng 已提交
356
    if (pIter->pTable == NULL) continue;
H
Hongze Cheng 已提交
357

H
more  
Hongze Cheng 已提交
358 359 360 361 362 363 364
    if (tsdbCommitToTable(pCommith, tid) < 0) {
      tsdbCloseCommitFile(pCommith, true);
      // revert the file change
      tsdbApplyDFileSetChange(TSDB_COMMIT_WRITE_FSET(pCommith), pSet);
      return -1;
    }
  }
H
Hongze Cheng 已提交
365

H
more  
Hongze Cheng 已提交
366 367 368 369 370 371 372 373
  if (tsdbWriteBlockIdx(TSDB_COMMIT_HEAD_FILE(pCommith), pCommith->aBlkIdx, (void **)(&(TSDB_COMMIT_BUF(pCommith)))) <
      0) {
    tsdbError("vgId:%d failed to write SBlockIdx part to FSET %d since %s", REPO_ID(pRepo), fid, tstrerror(terrno));
    tsdbCloseCommitFile(pCommith, true);
    // revert the file change
    tsdbApplyDFileSetChange(TSDB_COMMIT_WRITE_FSET(pCommith), pSet);
    return -1;
  }
H
Hongze Cheng 已提交
374

H
more  
Hongze Cheng 已提交
375 376 377 378 379 380 381
  if (tsdbUpdateDFileSetHeader(&(pCommith->wSet)) < 0) {
    tsdbError("vgId:%d failed to update FSET %d header since %s", REPO_ID(pRepo), fid, tstrerror(terrno));
    tsdbCloseCommitFile(pCommith, true);
    // revert the file change
    tsdbApplyDFileSetChange(TSDB_COMMIT_WRITE_FSET(pCommith), pSet);
    return -1;
  }
H
Hongze Cheng 已提交
382

H
more  
Hongze Cheng 已提交
383 384
  // Close commit file
  tsdbCloseCommitFile(pCommith, false);
H
Hongze Cheng 已提交
385

H
more  
Hongze Cheng 已提交
386 387 388
  if (tsdbUpdateDFileSet(REPO_FS(pRepo), &(pCommith->wSet)) < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
389

H
more  
Hongze Cheng 已提交
390 391
  return 0;
}
H
refact  
Hongze Cheng 已提交
392

H
Hongze Cheng 已提交
393 394 395 396 397 398 399 400 401 402 403 404
static int tsdbCreateCommitIters(SCommitH *pCommith) {
  STsdb *            pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbMemTable *    pMem = pRepo->imem;
  SSkipListIterator *pSlIter;
  SCommitIter *      pCommitIter;
  SSkipListNode *    pNode;
  STbData *          pTbData;

  pCommith->niters = SL_SIZE(pMem->pSlIdx);
  pCommith->iters = (SCommitIter *)calloc(pCommith->niters, sizeof(SCommitIter));
  if (pCommith->iters == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
H
refact  
Hongze Cheng 已提交
405 406 407
    return -1;
  }

H
Hongze Cheng 已提交
408 409 410 411
  // Loop to create iters for each skiplist
  pSlIter = tSkipListCreateIter(pMem->pSlIdx);
  if (pSlIter == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
H
refact  
Hongze Cheng 已提交
412 413
    return -1;
  }
H
Hongze Cheng 已提交
414 415 416 417
  for (int i = 0; i < pCommith->niters; i++) {
    tSkipListIterNext(pSlIter);
    pNode = tSkipListIterGet(pSlIter);
    pTbData = (STbData *)pNode->pData;
H
refact  
Hongze Cheng 已提交
418

H
Hongze Cheng 已提交
419 420 421
    pCommitIter = pCommith->iters + i;
    pCommitIter->pIter = tSkipListCreateIter(pTbData->pData);
    tSkipListIterNext(pCommitIter->pIter);
H
more  
Hongze Cheng 已提交
422 423 424

    pCommitIter->pTable = (STable *)malloc(sizeof(STable));
    pCommitIter->pTable->uid = pTbData->uid;
H
more  
Hongze Cheng 已提交
425 426
    pCommitIter->pTable->tid = pTbData->uid;
    pCommitIter->pTable->pSchema = metaGetTbTSchema(pRepo->pMeta, pTbData->uid, 0);
H
refact  
Hongze Cheng 已提交
427 428 429 430 431
  }

  return 0;
}

H
Hongze Cheng 已提交
432 433
static void tsdbDestroyCommitIters(SCommitH *pCommith) {
  if (pCommith->iters == NULL) return;
H
refact  
Hongze Cheng 已提交
434

H
Hongze Cheng 已提交
435 436
  for (int i = 1; i < pCommith->niters; i++) {
    tSkipListDestroyIter(pCommith->iters[i].pIter);
H
more  
Hongze Cheng 已提交
437 438
    tdFreeSchema(pCommith->iters[i].pTable->pSchema);
    free(pCommith->iters[i].pTable);
H
refact  
Hongze Cheng 已提交
439 440
  }

H
Hongze Cheng 已提交
441 442 443
  free(pCommith->iters);
  pCommith->iters = NULL;
  pCommith->niters = 0;
H
refact  
Hongze Cheng 已提交
444 445
}

H
more  
Hongze Cheng 已提交
446 447 448 449 450 451
static void tsdbResetCommitFile(SCommitH *pCommith) {
  pCommith->isRFileSet = false;
  pCommith->isDFileSame = false;
  pCommith->isLFileSame = false;
  taosArrayClear(pCommith->aBlkIdx);
}
H
Hongze Cheng 已提交
452

H
more  
Hongze Cheng 已提交
453 454 455 456
static int tsdbSetAndOpenCommitFile(SCommitH *pCommith, SDFileSet *pSet, int fid) {
  SDiskID    did;
  STsdb *    pRepo = TSDB_COMMIT_REPO(pCommith);
  SDFileSet *pWSet = TSDB_COMMIT_WRITE_FSET(pCommith);
H
Hongze Cheng 已提交
457

S
Shengliang Guan 已提交
458
  if (tfsAllocDisk(pRepo->pTfs, tsdbGetFidLevel(fid, &(pCommith->rtn)), &did) < 0) {
H
more  
Hongze Cheng 已提交
459 460 461
    terrno = TSDB_CODE_TDB_NO_AVAIL_DISK;
    return -1;
  }
H
Hongze Cheng 已提交
462

H
more  
Hongze Cheng 已提交
463 464 465 466 467
  // Open read FSET
  if (pSet) {
    if (tsdbSetAndOpenReadFSet(&(pCommith->readh), pSet) < 0) {
      return -1;
    }
H
Hongze Cheng 已提交
468

H
more  
Hongze Cheng 已提交
469
    pCommith->isRFileSet = true;
H
Hongze Cheng 已提交
470

H
more  
Hongze Cheng 已提交
471 472 473 474
    if (tsdbLoadBlockIdx(&(pCommith->readh)) < 0) {
      tsdbCloseAndUnsetFSet(&(pCommith->readh));
      return -1;
    }
H
Hongze Cheng 已提交
475

H
more  
Hongze Cheng 已提交
476 477 478 479 480
    tsdbDebug("vgId:%d FSET %d at level %d disk id %d is opened to read to commit", REPO_ID(pRepo), TSDB_FSET_FID(pSet),
              TSDB_FSET_LEVEL(pSet), TSDB_FSET_ID(pSet));
  } else {
    pCommith->isRFileSet = false;
  }
H
Hongze Cheng 已提交
481

H
more  
Hongze Cheng 已提交
482 483 484
  // Set and open commit FSET
  if (pSet == NULL || did.level > TSDB_FSET_LEVEL(pSet)) {
    // Create a new FSET to write data
S
Shengliang Guan 已提交
485
    tsdbInitDFileSet(pRepo, pWSet, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)));
H
Hongze Cheng 已提交
486

S
Shengliang Guan 已提交
487
    if (tsdbCreateDFileSet(pRepo, pWSet, true) < 0) {
H
more  
Hongze Cheng 已提交
488 489 490 491 492 493 494
      tsdbError("vgId:%d failed to create FSET %d at level %d disk id %d since %s", REPO_ID(pRepo),
                TSDB_FSET_FID(pWSet), TSDB_FSET_LEVEL(pWSet), TSDB_FSET_ID(pWSet), tstrerror(terrno));
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
      }
      return -1;
    }
H
Hongze Cheng 已提交
495

H
more  
Hongze Cheng 已提交
496 497
    pCommith->isDFileSame = false;
    pCommith->isLFileSame = false;
H
Hongze Cheng 已提交
498

H
more  
Hongze Cheng 已提交
499 500 501 502 503
    tsdbDebug("vgId:%d FSET %d at level %d disk id %d is created to commit", REPO_ID(pRepo), TSDB_FSET_FID(pWSet),
              TSDB_FSET_LEVEL(pWSet), TSDB_FSET_ID(pWSet));
  } else {
    did.level = TSDB_FSET_LEVEL(pSet);
    did.id = TSDB_FSET_ID(pSet);
H
Hongze Cheng 已提交
504

H
more  
Hongze Cheng 已提交
505 506
    pCommith->wSet.fid = fid;
    pCommith->wSet.state = 0;
H
Hongze Cheng 已提交
507

H
more  
Hongze Cheng 已提交
508 509
    // TSDB_FILE_HEAD
    SDFile *pWHeadf = TSDB_COMMIT_HEAD_FILE(pCommith);
S
Shengliang Guan 已提交
510
    tsdbInitDFile(pRepo, pWHeadf, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)), TSDB_FILE_HEAD);
S
Shengliang Guan 已提交
511
    if (tsdbCreateDFile(pRepo, pWHeadf, true) < 0) {
H
more  
Hongze Cheng 已提交
512 513
      tsdbError("vgId:%d failed to create file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWHeadf),
                tstrerror(terrno));
H
Hongze Cheng 已提交
514

H
more  
Hongze Cheng 已提交
515 516 517
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
        return -1;
H
Hongze Cheng 已提交
518 519 520
      }
    }

H
more  
Hongze Cheng 已提交
521 522 523 524 525 526 527
    // TSDB_FILE_DATA
    SDFile *pRDataf = TSDB_READ_DATA_FILE(&(pCommith->readh));
    SDFile *pWDataf = TSDB_COMMIT_DATA_FILE(pCommith);
    tsdbInitDFileEx(pWDataf, pRDataf);
    if (tsdbOpenDFile(pWDataf, O_WRONLY) < 0) {
      tsdbError("vgId:%d failed to open file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWDataf),
                tstrerror(terrno));
H
Hongze Cheng 已提交
528

H
more  
Hongze Cheng 已提交
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
      tsdbCloseDFileSet(pWSet);
      tsdbRemoveDFile(pWHeadf);
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
        return -1;
      }
    }
    pCommith->isDFileSame = true;

    // TSDB_FILE_LAST
    SDFile *pRLastf = TSDB_READ_LAST_FILE(&(pCommith->readh));
    SDFile *pWLastf = TSDB_COMMIT_LAST_FILE(pCommith);
    if (pRLastf->info.size < 32 * 1024) {
      tsdbInitDFileEx(pWLastf, pRLastf);
      pCommith->isLFileSame = true;

      if (tsdbOpenDFile(pWLastf, O_WRONLY) < 0) {
        tsdbError("vgId:%d failed to open file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWLastf),
                  tstrerror(terrno));
H
Hongze Cheng 已提交
548

H
more  
Hongze Cheng 已提交
549 550 551 552 553 554 555 556
        tsdbCloseDFileSet(pWSet);
        tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    } else {
S
Shengliang Guan 已提交
557
      tsdbInitDFile(pRepo, pWLastf, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)), TSDB_FILE_LAST);
H
more  
Hongze Cheng 已提交
558
      pCommith->isLFileSame = false;
H
Hongze Cheng 已提交
559

S
Shengliang Guan 已提交
560
      if (tsdbCreateDFile(pRepo, pWLastf, true) < 0) {
H
more  
Hongze Cheng 已提交
561 562
        tsdbError("vgId:%d failed to create file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWLastf),
                  tstrerror(terrno));
H
Hongze Cheng 已提交
563

H
more  
Hongze Cheng 已提交
564 565 566 567 568 569 570 571 572
        tsdbCloseDFileSet(pWSet);
        (void)tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    }
  }
H
Hongze Cheng 已提交
573 574 575 576

  return 0;
}

H
more  
Hongze Cheng 已提交
577
// extern int32_t tsTsdbMetaCompactRatio;
H
Hongze Cheng 已提交
578

H
more  
Hongze Cheng 已提交
579 580 581 582 583 584 585 586
int tsdbWriteBlockInfoImpl(SDFile *pHeadf, STable *pTable, SArray *pSupA, SArray *pSubA, void **ppBuf,
                           SBlockIdx *pIdx) {
  size_t      nSupBlocks;
  size_t      nSubBlocks;
  uint32_t    tlen;
  SBlockInfo *pBlkInfo;
  int64_t     offset;
  SBlock *    pBlock;
H
Hongze Cheng 已提交
587

H
more  
Hongze Cheng 已提交
588
  memset(pIdx, 0, sizeof(*pIdx));
H
Hongze Cheng 已提交
589

H
more  
Hongze Cheng 已提交
590 591
  nSupBlocks = taosArrayGetSize(pSupA);
  nSubBlocks = (pSubA == NULL) ? 0 : taosArrayGetSize(pSubA);
H
Hongze Cheng 已提交
592

H
more  
Hongze Cheng 已提交
593 594 595 596
  if (nSupBlocks <= 0) {
    // No data (data all deleted)
    return 0;
  }
H
Hongze Cheng 已提交
597

H
more  
Hongze Cheng 已提交
598 599 600
  tlen = (uint32_t)(sizeof(SBlockInfo) + sizeof(SBlock) * (nSupBlocks + nSubBlocks) + sizeof(TSCKSUM));
  if (tsdbMakeRoom(ppBuf, tlen) < 0) return -1;
  pBlkInfo = *ppBuf;
H
Hongze Cheng 已提交
601

H
more  
Hongze Cheng 已提交
602 603 604
  pBlkInfo->delimiter = TSDB_FILE_DELIMITER;
  pBlkInfo->tid = TABLE_TID(pTable);
  pBlkInfo->uid = TABLE_UID(pTable);
H
Hongze Cheng 已提交
605

H
more  
Hongze Cheng 已提交
606 607 608
  memcpy((void *)(pBlkInfo->blocks), taosArrayGet(pSupA, 0), nSupBlocks * sizeof(SBlock));
  if (nSubBlocks > 0) {
    memcpy((void *)(pBlkInfo->blocks + nSupBlocks), taosArrayGet(pSubA, 0), nSubBlocks * sizeof(SBlock));
H
Hongze Cheng 已提交
609

H
more  
Hongze Cheng 已提交
610 611
    for (int i = 0; i < nSupBlocks; i++) {
      pBlock = pBlkInfo->blocks + i;
H
Hongze Cheng 已提交
612

H
more  
Hongze Cheng 已提交
613 614 615 616 617
      if (pBlock->numOfSubBlocks > 1) {
        pBlock->offset += (sizeof(SBlockInfo) + sizeof(SBlock) * nSupBlocks);
      }
    }
  }
H
Hongze Cheng 已提交
618

H
more  
Hongze Cheng 已提交
619
  taosCalcChecksumAppend(0, (uint8_t *)pBlkInfo, tlen);
H
Hongze Cheng 已提交
620

H
more  
Hongze Cheng 已提交
621 622 623
  if (tsdbAppendDFile(pHeadf, (void *)pBlkInfo, tlen, &offset) < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
624

H
more  
Hongze Cheng 已提交
625
  tsdbUpdateDFileMagic(pHeadf, POINTER_SHIFT(pBlkInfo, tlen - sizeof(TSCKSUM)));
H
Hongze Cheng 已提交
626

H
more  
Hongze Cheng 已提交
627 628
  // Set pIdx
  pBlock = taosArrayGetLast(pSupA);
H
Hongze Cheng 已提交
629

H
more  
Hongze Cheng 已提交
630 631 632 633 634 635 636
  pIdx->tid = TABLE_TID(pTable);
  pIdx->uid = TABLE_UID(pTable);
  pIdx->hasLast = pBlock->last ? 1 : 0;
  pIdx->maxKey = pBlock->keyLast;
  pIdx->numOfBlocks = (uint32_t)nSupBlocks;
  pIdx->len = tlen;
  pIdx->offset = (uint32_t)offset;
H
Hongze Cheng 已提交
637

H
more  
Hongze Cheng 已提交
638 639
  return 0;
}
H
Hongze Cheng 已提交
640

H
more  
Hongze Cheng 已提交
641 642 643 644 645
int tsdbWriteBlockIdx(SDFile *pHeadf, SArray *pIdxA, void **ppBuf) {
  SBlockIdx *pBlkIdx;
  size_t     nidx = taosArrayGetSize(pIdxA);
  int        tlen = 0, size;
  int64_t    offset;
H
more  
Hongze Cheng 已提交
646

H
more  
Hongze Cheng 已提交
647 648 649 650 651 652
  if (nidx <= 0) {
    // All data are deleted
    pHeadf->info.offset = 0;
    pHeadf->info.len = 0;
    return 0;
  }
H
Hongze Cheng 已提交
653

H
more  
Hongze Cheng 已提交
654 655
  for (size_t i = 0; i < nidx; i++) {
    pBlkIdx = (SBlockIdx *)taosArrayGet(pIdxA, i);
H
Hongze Cheng 已提交
656

H
more  
Hongze Cheng 已提交
657 658
    size = tsdbEncodeSBlockIdx(NULL, pBlkIdx);
    if (tsdbMakeRoom(ppBuf, tlen + size) < 0) return -1;
H
Hongze Cheng 已提交
659

H
more  
Hongze Cheng 已提交
660 661
    void *ptr = POINTER_SHIFT(*ppBuf, tlen);
    tsdbEncodeSBlockIdx(&ptr, pBlkIdx);
H
Hongze Cheng 已提交
662

H
more  
Hongze Cheng 已提交
663 664
    tlen += size;
  }
H
Hongze Cheng 已提交
665

H
more  
Hongze Cheng 已提交
666 667 668
  tlen += sizeof(TSCKSUM);
  if (tsdbMakeRoom(ppBuf, tlen) < 0) return -1;
  taosCalcChecksumAppend(0, (uint8_t *)(*ppBuf), tlen);
H
Hongze Cheng 已提交
669

H
more  
Hongze Cheng 已提交
670 671 672
  if (tsdbAppendDFile(pHeadf, *ppBuf, tlen, &offset) < tlen) {
    return -1;
  }
H
Hongze Cheng 已提交
673

H
more  
Hongze Cheng 已提交
674 675 676
  tsdbUpdateDFileMagic(pHeadf, POINTER_SHIFT(*ppBuf, tlen - sizeof(TSCKSUM)));
  pHeadf->info.offset = (uint32_t)offset;
  pHeadf->info.len = tlen;
H
Hongze Cheng 已提交
677

H
more  
Hongze Cheng 已提交
678 679
  return 0;
}
H
Hongze Cheng 已提交
680

H
more  
Hongze Cheng 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
// // =================== Commit Meta Data
// static int tsdbInitCommitMetaFile(STsdbRepo *pRepo, SMFile* pMf, bool open) {
//   STsdbFS *  pfs = REPO_FS(pRepo);
//   SMFile *   pOMFile = pfs->cstatus->pmf;
//   SDiskID    did;

//   // Create/Open a meta file or open the existing file
//   if (pOMFile == NULL) {
//     // Create a new meta file
//     did.level = TFS_PRIMARY_LEVEL;
//     did.id = TFS_PRIMARY_ID;
//     tsdbInitMFile(pMf, did, REPO_ID(pRepo), FS_TXN_VERSION(REPO_FS(pRepo)));

//     if (open && tsdbCreateMFile(pMf, true) < 0) {
//       tsdbError("vgId:%d failed to create META file since %s", REPO_ID(pRepo), tstrerror(terrno));
//       return -1;
//     }
H
Hongze Cheng 已提交
698

H
more  
Hongze Cheng 已提交
699 700 701 702 703 704 705 706
//     tsdbInfo("vgId:%d meta file %s is created to commit", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pMf));
//   } else {
//     tsdbInitMFileEx(pMf, pOMFile);
//     if (open && tsdbOpenMFile(pMf, O_WRONLY) < 0) {
//       tsdbError("vgId:%d failed to open META file since %s", REPO_ID(pRepo), tstrerror(terrno));
//       return -1;
//     }
//   }
H
Hongze Cheng 已提交
707

H
more  
Hongze Cheng 已提交
708 709
//   return 0;
// }
H
Hongze Cheng 已提交
710

H
more  
Hongze Cheng 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
// static int tsdbCommitMeta(STsdbRepo *pRepo) {
//   STsdbFS *  pfs = REPO_FS(pRepo);
//   SMemTable *pMem = pRepo->imem;
//   SMFile *   pOMFile = pfs->cstatus->pmf;
//   SMFile     mf;
//   SActObj *  pAct = NULL;
//   SActCont * pCont = NULL;
//   SListNode *pNode = NULL;

//   ASSERT(pOMFile != NULL || listNEles(pMem->actList) > 0);

//   if (listNEles(pMem->actList) <= 0) {
//     // no meta data to commit, just keep the old meta file
//     tsdbUpdateMFile(pfs, pOMFile);
//     if (tsTsdbMetaCompactRatio > 0) {
//       if (tsdbInitCommitMetaFile(pRepo, &mf, false) < 0) {
//         return -1;
//       }
//       int ret = tsdbCompactMetaFile(pRepo, pfs, &mf);
//       if (ret < 0) tsdbError("compact meta file error");

//       return ret;
//     }
//     return 0;
//   } else {
//     if (tsdbInitCommitMetaFile(pRepo, &mf, true) < 0) {
//       return -1;
//     }
//   }
H
Hongze Cheng 已提交
740

H
more  
Hongze Cheng 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
//   // Loop to write
//   while ((pNode = tdListPopHead(pMem->actList)) != NULL) {
//     pAct = (SActObj *)pNode->data;
//     if (pAct->act == TSDB_UPDATE_META) {
//       pCont = (SActCont *)POINTER_SHIFT(pAct, sizeof(SActObj));
//       if (tsdbUpdateMetaRecord(pfs, &mf, pAct->uid, (void *)(pCont->cont), pCont->len, false) < 0) {
//         tsdbError("vgId:%d failed to update META record, uid %" PRIu64 " since %s", REPO_ID(pRepo), pAct->uid,
//                   tstrerror(terrno));
//         tsdbCloseMFile(&mf);
//         (void)tsdbApplyMFileChange(&mf, pOMFile);
//         // TODO: need to reload metaCache
//         return -1;
//       }
//     } else if (pAct->act == TSDB_DROP_META) {
//       if (tsdbDropMetaRecord(pfs, &mf, pAct->uid) < 0) {
//         tsdbError("vgId:%d failed to drop META record, uid %" PRIu64 " since %s", REPO_ID(pRepo), pAct->uid,
//                   tstrerror(terrno));
//         tsdbCloseMFile(&mf);
//         tsdbApplyMFileChange(&mf, pOMFile);
//         // TODO: need to reload metaCache
//         return -1;
//       }
//     } else {
//       ASSERT(false);
//     }
//   }
H
Hongze Cheng 已提交
767

H
more  
Hongze Cheng 已提交
768 769 770 771 772 773
//   if (tsdbUpdateMFileHeader(&mf) < 0) {
//     tsdbError("vgId:%d failed to update META file header since %s, revert it", REPO_ID(pRepo), tstrerror(terrno));
//     tsdbApplyMFileChange(&mf, pOMFile);
//     // TODO: need to reload metaCache
//     return -1;
//   }
H
Hongze Cheng 已提交
774

H
more  
Hongze Cheng 已提交
775 776 777
//   TSDB_FILE_FSYNC(&mf);
//   tsdbCloseMFile(&mf);
//   tsdbUpdateMFile(pfs, &mf);
H
Hongze Cheng 已提交
778

H
more  
Hongze Cheng 已提交
779 780 781
//   if (tsTsdbMetaCompactRatio > 0 && tsdbCompactMetaFile(pRepo, pfs, &mf) < 0) {
//     tsdbError("compact meta file error");
//   }
H
Hongze Cheng 已提交
782

H
more  
Hongze Cheng 已提交
783 784
//   return 0;
// }
H
Hongze Cheng 已提交
785

H
more  
Hongze Cheng 已提交
786 787 788 789 790
// int tsdbEncodeKVRecord(void **buf, SKVRecord *pRecord) {
//   int tlen = 0;
//   tlen += taosEncodeFixedU64(buf, pRecord->uid);
//   tlen += taosEncodeFixedI64(buf, pRecord->offset);
//   tlen += taosEncodeFixedI64(buf, pRecord->size);
H
Hongze Cheng 已提交
791

H
more  
Hongze Cheng 已提交
792 793
//   return tlen;
// }
H
Hongze Cheng 已提交
794

H
more  
Hongze Cheng 已提交
795 796 797 798
// void *tsdbDecodeKVRecord(void *buf, SKVRecord *pRecord) {
//   buf = taosDecodeFixedU64(buf, &(pRecord->uid));
//   buf = taosDecodeFixedI64(buf, &(pRecord->offset));
//   buf = taosDecodeFixedI64(buf, &(pRecord->size));
H
Hongze Cheng 已提交
799

H
more  
Hongze Cheng 已提交
800 801
//   return buf;
// }
H
Hongze Cheng 已提交
802

H
more  
Hongze Cheng 已提交
803 804 805 806 807
// static int tsdbUpdateMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid, void *cont, int contLen, bool compact) {
//   char      buf[64] = "\0";
//   void *    pBuf = buf;
//   SKVRecord rInfo;
//   int64_t   offset;
H
Hongze Cheng 已提交
808

H
more  
Hongze Cheng 已提交
809 810 811 812 813
//   // Seek to end of meta file
//   offset = tsdbSeekMFile(pMFile, 0, SEEK_END);
//   if (offset < 0) {
//     return -1;
//   }
H
Hongze Cheng 已提交
814

H
more  
Hongze Cheng 已提交
815 816 817
//   rInfo.offset = offset;
//   rInfo.uid = uid;
//   rInfo.size = contLen;
H
Hongze Cheng 已提交
818

H
more  
Hongze Cheng 已提交
819 820 821 822
//   int tlen = tsdbEncodeKVRecord((void **)(&pBuf), &rInfo);
//   if (tsdbAppendMFile(pMFile, buf, tlen, NULL) < tlen) {
//     return -1;
//   }
H
Hongze Cheng 已提交
823

H
more  
Hongze Cheng 已提交
824 825 826
//   if (tsdbAppendMFile(pMFile, cont, contLen, NULL) < contLen) {
//     return -1;
//   }
H
Hongze Cheng 已提交
827

H
more  
Hongze Cheng 已提交
828
//   tsdbUpdateMFileMagic(pMFile, POINTER_SHIFT(cont, contLen - sizeof(TSCKSUM)));
H
Hongze Cheng 已提交
829

H
more  
Hongze Cheng 已提交
830
//   SHashObj* cache = compact ? pfs->metaCacheComp : pfs->metaCache;
H
Hongze Cheng 已提交
831

H
more  
Hongze Cheng 已提交
832
//   pMFile->info.nRecords++;
H
Hongze Cheng 已提交
833

H
more  
Hongze Cheng 已提交
834 835 836 837 838 839 840
//   SKVRecord *pRecord = taosHashGet(cache, (void *)&uid, sizeof(uid));
//   if (pRecord != NULL) {
//     pMFile->info.tombSize += (pRecord->size + sizeof(SKVRecord));
//   } else {
//     pMFile->info.nRecords++;
//   }
//   taosHashPut(cache, (void *)(&uid), sizeof(uid), (void *)(&rInfo), sizeof(rInfo));
H
Hongze Cheng 已提交
841

H
more  
Hongze Cheng 已提交
842 843
//   return 0;
// }
H
Hongze Cheng 已提交
844

H
more  
Hongze Cheng 已提交
845 846 847
// static int tsdbDropMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid) {
//   SKVRecord rInfo = {0};
//   char      buf[128] = "\0";
H
Hongze Cheng 已提交
848

H
more  
Hongze Cheng 已提交
849 850 851 852 853
//   SKVRecord *pRecord = taosHashGet(pfs->metaCache, (void *)(&uid), sizeof(uid));
//   if (pRecord == NULL) {
//     tsdbError("failed to drop META record with key %" PRIu64 " since not find", uid);
//     return -1;
//   }
H
Hongze Cheng 已提交
854

H
more  
Hongze Cheng 已提交
855 856 857
//   rInfo.offset = -pRecord->offset;
//   rInfo.uid = pRecord->uid;
//   rInfo.size = pRecord->size;
H
Hongze Cheng 已提交
858

H
more  
Hongze Cheng 已提交
859 860
//   void *pBuf = buf;
//   tsdbEncodeKVRecord(&pBuf, &rInfo);
H
Hongze Cheng 已提交
861

H
more  
Hongze Cheng 已提交
862 863 864
//   if (tsdbAppendMFile(pMFile, buf, sizeof(SKVRecord), NULL) < 0) {
//     return -1;
//   }
H
Hongze Cheng 已提交
865

H
more  
Hongze Cheng 已提交
866 867 868 869
//   pMFile->info.magic = taosCalcChecksum(pMFile->info.magic, (uint8_t *)buf, sizeof(SKVRecord));
//   pMFile->info.nDels++;
//   pMFile->info.nRecords--;
//   pMFile->info.tombSize += (rInfo.size + sizeof(SKVRecord) * 2);
H
Hongze Cheng 已提交
870

H
more  
Hongze Cheng 已提交
871 872 873
//   taosHashRemove(pfs->metaCache, (void *)(&uid), sizeof(uid));
//   return 0;
// }
H
Hongze Cheng 已提交
874

H
more  
Hongze Cheng 已提交
875 876 877 878
// static int tsdbCompactMetaFile(STsdbRepo *pRepo, STsdbFS *pfs, SMFile *pMFile) {
//   float delPercent = (float)(pMFile->info.nDels) / (float)(pMFile->info.nRecords);
//   float tombPercent = (float)(pMFile->info.tombSize) / (float)(pMFile->info.size);
//   float compactRatio = (float)(tsTsdbMetaCompactRatio)/100;
H
Hongze Cheng 已提交
879

H
more  
Hongze Cheng 已提交
880 881 882
//   if (delPercent < compactRatio && tombPercent < compactRatio) {
//     return 0;
//   }
H
Hongze Cheng 已提交
883

H
more  
Hongze Cheng 已提交
884 885 886 887
//   if (tsdbOpenMFile(pMFile, O_RDONLY) < 0) {
//     tsdbError("open meta file %s compact fail", pMFile->f.rname);
//     return -1;
//   }
H
Hongze Cheng 已提交
888

H
more  
Hongze Cheng 已提交
889 890 891
//   tsdbInfo("begin compact tsdb meta file, ratio:%d, nDels:%" PRId64 ",nRecords:%" PRId64 ",tombSize:%" PRId64
//   ",size:%" PRId64,
//     tsTsdbMetaCompactRatio, pMFile->info.nDels,pMFile->info.nRecords,pMFile->info.tombSize,pMFile->info.size);
H
Hongze Cheng 已提交
892

H
more  
Hongze Cheng 已提交
893 894
//   SMFile mf;
//   SDiskID did;
H
Hongze Cheng 已提交
895

H
more  
Hongze Cheng 已提交
896 897 898 899
//   // first create tmp meta file
//   did.level = TFS_PRIMARY_LEVEL;
//   did.id = TFS_PRIMARY_ID;
//   tsdbInitMFile(&mf, did, REPO_ID(pRepo), FS_TXN_VERSION(REPO_FS(pRepo)) + 1);
H
Hongze Cheng 已提交
900

H
more  
Hongze Cheng 已提交
901 902 903 904
//   if (tsdbCreateMFile(&mf, true) < 0) {
//     tsdbError("vgId:%d failed to create META file since %s", REPO_ID(pRepo), tstrerror(terrno));
//     return -1;
//   }
H
Hongze Cheng 已提交
905

H
more  
Hongze Cheng 已提交
906
//   tsdbInfo("vgId:%d meta file %s is created to compact meta data", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(&mf));
H
Hongze Cheng 已提交
907

H
more  
Hongze Cheng 已提交
908 909 910 911 912
//   // second iterator metaCache
//   int code = -1;
//   int64_t maxBufSize = 1024;
//   SKVRecord *pRecord;
//   void *pBuf = NULL;
H
Hongze Cheng 已提交
913

H
more  
Hongze Cheng 已提交
914 915 916 917
//   pBuf = malloc((size_t)maxBufSize);
//   if (pBuf == NULL) {
//     goto _err;
//   }
H
Hongze Cheng 已提交
918

H
more  
Hongze Cheng 已提交
919 920 921 922 923 924
//   // init Comp
//   assert(pfs->metaCacheComp == NULL);
//   pfs->metaCacheComp = taosHashInit(4096, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
//   if (pfs->metaCacheComp == NULL) {
//     goto _err;
//   }
H
Hongze Cheng 已提交
925

H
more  
Hongze Cheng 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 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 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
//   pRecord = taosHashIterate(pfs->metaCache, NULL);
//   while (pRecord) {
//     if (tsdbSeekMFile(pMFile, pRecord->offset + sizeof(SKVRecord), SEEK_SET) < 0) {
//       tsdbError("vgId:%d failed to seek file %s since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pMFile),
//                 tstrerror(terrno));
//       goto _err;
//     }
//     if (pRecord->size > maxBufSize) {
//       maxBufSize = pRecord->size;
//       void* tmp = realloc(pBuf, (size_t)maxBufSize);
//       if (tmp == NULL) {
//         goto _err;
//       }
//       pBuf = tmp;
//     }
//     int nread = (int)tsdbReadMFile(pMFile, pBuf, pRecord->size);
//     if (nread < 0) {
//       tsdbError("vgId:%d failed to read file %s since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pMFile),
//         tstrerror(terrno));
//       goto _err;
//     }

//     if (nread < pRecord->size) {
//       tsdbError("vgId:%d failed to read file %s since file corrupted, expected read:%" PRId64 " actual read:%d",
//                 REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pMFile), pRecord->size, nread);
//       goto _err;
//     }

//     if (tsdbUpdateMetaRecord(pfs, &mf, pRecord->uid, pBuf, (int)pRecord->size, true) < 0) {
//       tsdbError("vgId:%d failed to update META record, uid %" PRIu64 " since %s", REPO_ID(pRepo), pRecord->uid,
//                 tstrerror(terrno));
//       goto _err;
//     }

//     pRecord = taosHashIterate(pfs->metaCache, pRecord);
//   }
//   code = 0;

// _err:
//   if (code == 0) TSDB_FILE_FSYNC(&mf);
//   tsdbCloseMFile(&mf);
//   tsdbCloseMFile(pMFile);

//   if (code == 0) {
//     // rename meta.tmp -> meta
//     tsdbInfo("vgId:%d meta file rename %s -> %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(&mf),
//     TSDB_FILE_FULL_NAME(pMFile)); taosRename(mf.f.aname,pMFile->f.aname); tstrncpy(mf.f.aname, pMFile->f.aname,
//     TSDB_FILENAME_LEN); tstrncpy(mf.f.rname, pMFile->f.rname, TSDB_FILENAME_LEN);
//     // update current meta file info
//     pfs->nstatus->pmf = NULL;
//     tsdbUpdateMFile(pfs, &mf);

//     taosHashCleanup(pfs->metaCache);
//     pfs->metaCache = pfs->metaCacheComp;
//     pfs->metaCacheComp = NULL;
//   } else {
//     // remove meta.tmp file
//     remove(mf.f.aname);
//     taosHashCleanup(pfs->metaCacheComp);
//     pfs->metaCacheComp = NULL;
//   }

//   tfree(pBuf);

//   ASSERT(mf.info.nDels == 0);
//   ASSERT(mf.info.tombSize == 0);

//   tsdbInfo("end compact tsdb meta file,code:%d,nRecords:%" PRId64 ",size:%" PRId64,
//     code,mf.info.nRecords,mf.info.size);
//   return code;
// }

// // =================== Commit Time-Series Data
// #if 0
// static bool tsdbHasDataToCommit(SCommitIter *iters, int nIters, TSKEY minKey, TSKEY maxKey) {
//   for (int i = 0; i < nIters; i++) {
//     TSKEY nextKey = tsdbNextIterKey((iters + i)->pIter);
//     if (nextKey != TSDB_DATA_TIMESTAMP_NULL && (nextKey >= minKey && nextKey <= maxKey)) return true;
//   }
//   return false;
// }
// #endif
H
Hongze Cheng 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061

static int tsdbCommitToTable(SCommitH *pCommith, int tid) {
  SCommitIter *pIter = pCommith->iters + tid;
  TSKEY        nextKey = tsdbNextIterKey(pIter->pIter);

  tsdbResetCommitTable(pCommith);

  // Set commit table
  if (tsdbSetCommitTable(pCommith, pIter->pTable) < 0) {
    return -1;
  }

  // No disk data and no memory data, just return
  if (pCommith->readh.pBlkIdx == NULL && (nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey)) {
    return 0;
  }

  // Must has disk data or has memory data
  int     nBlocks;
  int     bidx = 0;
  SBlock *pBlock;

  if (pCommith->readh.pBlkIdx) {
    if (tsdbLoadBlockInfo(&(pCommith->readh), NULL) < 0) {
      return -1;
    }

    nBlocks = pCommith->readh.pBlkIdx->numOfBlocks;
  } else {
    nBlocks = 0;
  }

  if (bidx < nBlocks) {
    pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
  } else {
    pBlock = NULL;
  }

  while (true) {
    if (pBlock == NULL && (nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey)) break;

    if ((nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey) ||
        (pBlock && (!pBlock->last) && tsdbComparKeyBlock((void *)(&nextKey), pBlock) > 0)) {
      if (tsdbMoveBlock(pCommith, bidx) < 0) {
        return -1;
      }

      bidx++;
      if (bidx < nBlocks) {
        pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
      } else {
        pBlock = NULL;
      }
    } else if (pBlock && (pBlock->last || tsdbComparKeyBlock((void *)(&nextKey), pBlock) == 0)) {
H
more  
Hongze Cheng 已提交
1062 1063 1064 1065
      // merge pBlock data and memory data
      if (tsdbMergeMemData(pCommith, pIter, bidx) < 0) {
        return -1;
      }
H
more  
Hongze Cheng 已提交
1066

H
more  
Hongze Cheng 已提交
1067 1068 1069 1070 1071 1072 1073
      bidx++;
      if (bidx < nBlocks) {
        pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
      } else {
        pBlock = NULL;
      }
      nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
1074
    } else {
H
more  
Hongze Cheng 已提交
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
      // Only commit memory data
      if (pBlock == NULL) {
        if (tsdbCommitMemData(pCommith, pIter, pCommith->maxKey, false) < 0) {
          return -1;
        }
      } else {
        if (tsdbCommitMemData(pCommith, pIter, pBlock->keyFirst - 1, true) < 0) {
          return -1;
        }
      }
      nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
1086 1087 1088
    }
  }

H
more  
Hongze Cheng 已提交
1089 1090 1091 1092 1093
  if (tsdbWriteBlockInfo(pCommith) < 0) {
    tsdbError("vgId:%d failed to write SBlockInfo part into file %s since %s", TSDB_COMMIT_REPO_ID(pCommith),
              TSDB_FILE_FULL_NAME(TSDB_COMMIT_HEAD_FILE(pCommith)), tstrerror(terrno));
    return -1;
  }
H
Hongze Cheng 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130

  return 0;
}

static int tsdbSetCommitTable(SCommitH *pCommith, STable *pTable) {
  STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1);

  pCommith->pTable = pTable;

  if (tdInitDataCols(pCommith->pDataCols, pSchema) < 0) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  if (pCommith->isRFileSet) {
    if (tsdbSetReadTable(&(pCommith->readh), pTable) < 0) {
      return -1;
    }
  } else {
    pCommith->readh.pBlkIdx = NULL;
  }
  return 0;
}

static int tsdbComparKeyBlock(const void *arg1, const void *arg2) {
  TSKEY   key = *(TSKEY *)arg1;
  SBlock *pBlock = (SBlock *)arg2;

  if (key < pBlock->keyFirst) {
    return -1;
  } else if (key > pBlock->keyLast) {
    return 1;
  } else {
    return 0;
  }
}

H
more  
Hongze Cheng 已提交
1131 1132
int tsdbWriteBlockImpl(STsdb *pRepo, STable *pTable, SDFile *pDFile, SDataCols *pDataCols, SBlock *pBlock, bool isLast,
                       bool isSuper, void **ppBuf, void **ppCBuf) {
H
Hongze Cheng 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
  STsdbCfg *  pCfg = REPO_CFG(pRepo);
  SBlockData *pBlockData;
  int64_t     offset = 0;
  int         rowsToWrite = pDataCols->numOfRows;

  ASSERT(rowsToWrite > 0 && rowsToWrite <= pCfg->maxRowsPerFileBlock);
  ASSERT((!isLast) || rowsToWrite < pCfg->minRowsPerFileBlock);

  // Make buffer space
  if (tsdbMakeRoom(ppBuf, TSDB_BLOCK_STATIS_SIZE(pDataCols->numOfCols)) < 0) {
    return -1;
  }
  pBlockData = (SBlockData *)(*ppBuf);

  // Get # of cols not all NULL(not including key column)
  int nColsNotAllNull = 0;
  for (int ncol = 1; ncol < pDataCols->numOfCols; ncol++) {  // ncol from 1, we skip the timestamp column
    SDataCol * pDataCol = pDataCols->cols + ncol;
    SBlockCol *pBlockCol = pBlockData->cols + nColsNotAllNull;

    if (isAllRowsNull(pDataCol)) {  // all data to commit are NULL, just ignore it
      continue;
    }

    memset(pBlockCol, 0, sizeof(*pBlockCol));

    pBlockCol->colId = pDataCol->colId;
    pBlockCol->type = pDataCol->type;
    if (tDataTypes[pDataCol->type].statisFunc) {
      (*tDataTypes[pDataCol->type].statisFunc)(pDataCol->pData, rowsToWrite, &(pBlockCol->min), &(pBlockCol->max),
                                               &(pBlockCol->sum), &(pBlockCol->minIndex), &(pBlockCol->maxIndex),
                                               &(pBlockCol->numOfNull));
C
Cary Xu 已提交
1165
      if (pBlockCol->numOfNull == 0) {
C
Cary Xu 已提交
1166
        TD_SET_COL_ROWS_NORM(pBlockCol);
C
Cary Xu 已提交
1167
      } else {
C
Cary Xu 已提交
1168
        TD_SET_COL_ROWS_MISC(pBlockCol);
C
Cary Xu 已提交
1169 1170
      }
    } else {
C
Cary Xu 已提交
1171
      TD_SET_COL_ROWS_MISC(pBlockCol);
H
Hongze Cheng 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    }
    nColsNotAllNull++;
  }

  ASSERT(nColsNotAllNull >= 0 && nColsNotAllNull <= pDataCols->numOfCols);

  // Compress the data if neccessary
  int      tcol = 0;  // counter of not all NULL and written columns
  uint32_t toffset = 0;
  int32_t  tsize = TSDB_BLOCK_STATIS_SIZE(nColsNotAllNull);
  int32_t  lsize = tsize;
  int32_t  keyLen = 0;
C
Cary Xu 已提交
1184 1185 1186
  int32_t  nBitmaps = (int32_t)TD_BITMAP_BYTES(rowsToWrite);
  int32_t  tBitmaps = 0;

H
Hongze Cheng 已提交
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
  for (int ncol = 0; ncol < pDataCols->numOfCols; ncol++) {
    // All not NULL columns finish
    if (ncol != 0 && tcol >= nColsNotAllNull) break;

    SDataCol * pDataCol = pDataCols->cols + ncol;
    SBlockCol *pBlockCol = pBlockData->cols + tcol;

    if (ncol != 0 && (pDataCol->colId != pBlockCol->colId)) continue;

    int32_t flen;  // final length
    int32_t tlen = dataColGetNEleLen(pDataCol, rowsToWrite);
C
Cary Xu 已提交
1198

C
Cary Xu 已提交
1199
#ifdef TD_SUPPORT_BITMAP
C
Cary Xu 已提交
1200
    int32_t tBitmaps = 0;
C
Cary Xu 已提交
1201
    if ((ncol != 0) && !TD_COL_ROWS_NORM(pBlockCol)) {
C
Cary Xu 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
      if (IS_VAR_DATA_TYPE(pDataCol->type)) {
        tBitmaps = nBitmaps;
        tlen += tBitmaps;
      } else {
        tBitmaps = (int32_t)ceil((double)nBitmaps / TYPE_BYTES[pDataCol->type]);
        tlen += tBitmaps * TYPE_BYTES[pDataCol->type];
      }
      // move bitmap parts ahead
      // TODO: put bitmap part to the 1st location(pBitmap points to pData) to avoid the memmove
      memcpy(POINTER_SHIFT(pDataCol->pData, pDataCol->len), pDataCol->pBitmap, nBitmaps);
    }
C
Cary Xu 已提交
1213
#endif
C
Cary Xu 已提交
1214

H
Hongze Cheng 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    void *  tptr;

    // Make room
    if (tsdbMakeRoom(ppBuf, lsize + tlen + COMP_OVERFLOW_BYTES + sizeof(TSCKSUM)) < 0) {
      return -1;
    }
    pBlockData = (SBlockData *)(*ppBuf);
    pBlockCol = pBlockData->cols + tcol;
    tptr = POINTER_SHIFT(pBlockData, lsize);

H
more  
Hongze Cheng 已提交
1225
    if (pCfg->compression == TWO_STAGE_COMP && tsdbMakeRoom(ppCBuf, tlen + COMP_OVERFLOW_BYTES) < 0) {
H
Hongze Cheng 已提交
1226 1227 1228 1229 1230
      return -1;
    }

    // Compress or just copy
    if (pCfg->compression) {
C
Cary Xu 已提交
1231
      flen = (*(tDataTypes[pDataCol->type].compFunc))((char *)pDataCol->pData, tlen, rowsToWrite + tBitmaps, tptr,
H
Hongze Cheng 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
                                                      tlen + COMP_OVERFLOW_BYTES, pCfg->compression, *ppCBuf,
                                                      tlen + COMP_OVERFLOW_BYTES);
    } else {
      flen = tlen;
      memcpy(tptr, pDataCol->pData, flen);
    }

    // Add checksum
    ASSERT(flen > 0);
    flen += sizeof(TSCKSUM);
    taosCalcChecksumAppend(0, (uint8_t *)tptr, flen);
    tsdbUpdateDFileMagic(pDFile, POINTER_SHIFT(tptr, flen - sizeof(TSCKSUM)));

    if (ncol != 0) {
      tsdbSetBlockColOffset(pBlockCol, toffset);
      pBlockCol->len = flen;
      tcol++;
    } else {
      keyLen = flen;
    }

    toffset += flen;
    lsize += flen;
  }

  pBlockData->delimiter = TSDB_FILE_DELIMITER;
  pBlockData->uid = TABLE_UID(pTable);
  pBlockData->numOfCols = nColsNotAllNull;

  taosCalcChecksumAppend(0, (uint8_t *)pBlockData, tsize);
  tsdbUpdateDFileMagic(pDFile, POINTER_SHIFT(pBlockData, tsize - sizeof(TSCKSUM)));

  // Write the whole block to file
  if (tsdbAppendDFile(pDFile, (void *)pBlockData, lsize, &offset) < lsize) {
    return -1;
  }

  // Update pBlock membership vairables
  pBlock->last = isLast;
  pBlock->offset = offset;
  pBlock->algorithm = pCfg->compression;
  pBlock->numOfRows = rowsToWrite;
  pBlock->len = lsize;
  pBlock->keyLen = keyLen;
  pBlock->numOfSubBlocks = isSuper ? 1 : 0;
  pBlock->numOfCols = nColsNotAllNull;
  pBlock->keyFirst = dataColsKeyFirst(pDataCols);
  pBlock->keyLast = dataColsKeyLast(pDataCols);

1281
  tsdbDebug("vgId:%d uid:%"PRId64" a block of data is written to file %s, offset %" PRId64
H
Hongze Cheng 已提交
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
            " numOfRows %d len %d numOfCols %" PRId16 " keyFirst %" PRId64 " keyLast %" PRId64,
            REPO_ID(pRepo), TABLE_TID(pTable), TSDB_FILE_FULL_NAME(pDFile), offset, rowsToWrite, pBlock->len,
            pBlock->numOfCols, pBlock->keyFirst, pBlock->keyLast);

  return 0;
}

static int tsdbWriteBlock(SCommitH *pCommith, SDFile *pDFile, SDataCols *pDataCols, SBlock *pBlock, bool isLast,
                          bool isSuper) {
  return tsdbWriteBlockImpl(TSDB_COMMIT_REPO(pCommith), TSDB_COMMIT_TABLE(pCommith), pDFile, pDataCols, pBlock, isLast,
                            isSuper, (void **)(&(TSDB_COMMIT_BUF(pCommith))),
                            (void **)(&(TSDB_COMMIT_COMP_BUF(pCommith))));
}

H
more  
Hongze Cheng 已提交
1296 1297 1298 1299
static int tsdbWriteBlockInfo(SCommitH *pCommih) {
  SDFile *  pHeadf = TSDB_COMMIT_HEAD_FILE(pCommih);
  SBlockIdx blkIdx;
  STable *  pTable = TSDB_COMMIT_TABLE(pCommih);
H
Hongze Cheng 已提交
1300

H
more  
Hongze Cheng 已提交
1301 1302 1303 1304
  if (tsdbWriteBlockInfoImpl(pHeadf, pTable, pCommih->aSupBlk, pCommih->aSubBlk, (void **)(&(TSDB_COMMIT_BUF(pCommih))),
                             &blkIdx) < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
1305

H
more  
Hongze Cheng 已提交
1306 1307 1308
  if (blkIdx.numOfBlocks == 0) {
    return 0;
  }
H
Hongze Cheng 已提交
1309

H
more  
Hongze Cheng 已提交
1310 1311 1312 1313
  if (taosArrayPush(pCommih->aBlkIdx, (void *)(&blkIdx)) == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }
H
Hongze Cheng 已提交
1314

H
more  
Hongze Cheng 已提交
1315 1316
  return 0;
}
H
Hongze Cheng 已提交
1317

H
more  
Hongze Cheng 已提交
1318 1319 1320 1321 1322 1323 1324 1325
static int tsdbCommitMemData(SCommitH *pCommith, SCommitIter *pIter, TSKEY keyLimit, bool toData) {
  STsdb *    pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg * pCfg = REPO_CFG(pRepo);
  SMergeInfo mInfo;
  int32_t    defaultRows = TSDB_COMMIT_DEFAULT_ROWS(pCommith);
  SDFile *   pDFile;
  bool       isLast;
  SBlock     block;
H
more  
Hongze Cheng 已提交
1326

H
more  
Hongze Cheng 已提交
1327 1328 1329
  while (true) {
    tsdbLoadDataFromCache(pIter->pTable, pIter->pIter, keyLimit, defaultRows, pCommith->pDataCols, NULL, 0,
                          pCfg->update, &mInfo);
H
more  
Hongze Cheng 已提交
1330

H
more  
Hongze Cheng 已提交
1331
    if (pCommith->pDataCols->numOfRows <= 0) break;
H
more  
Hongze Cheng 已提交
1332

H
more  
Hongze Cheng 已提交
1333 1334 1335 1336 1337 1338 1339
    if (toData || pCommith->pDataCols->numOfRows >= pCfg->minRowsPerFileBlock) {
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
      isLast = false;
    } else {
      pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
      isLast = true;
    }
H
Hongze Cheng 已提交
1340

H
more  
Hongze Cheng 已提交
1341
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, isLast, true) < 0) return -1;
H
Hongze Cheng 已提交
1342

H
more  
Hongze Cheng 已提交
1343 1344 1345 1346
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) {
      return -1;
    }
  }
H
Hongze Cheng 已提交
1347

H
more  
Hongze Cheng 已提交
1348 1349
  return 0;
}
H
Hongze Cheng 已提交
1350

H
more  
Hongze Cheng 已提交
1351 1352 1353 1354 1355 1356
static int tsdbMergeMemData(SCommitH *pCommith, SCommitIter *pIter, int bidx) {
  STsdb *    pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg * pCfg = REPO_CFG(pRepo);
  int        nBlocks = pCommith->readh.pBlkIdx->numOfBlocks;
  SBlock *   pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
  TSKEY      keyLimit;
1357
  int16_t    colId = PRIMARYKEY_TIMESTAMP_COL_ID;
H
more  
Hongze Cheng 已提交
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
  SMergeInfo mInfo;
  SBlock     subBlocks[TSDB_MAX_SUBBLOCKS];
  SBlock     block, supBlock;
  SDFile *   pDFile;

  if (bidx == nBlocks - 1) {
    keyLimit = pCommith->maxKey;
  } else {
    keyLimit = pBlock[1].keyFirst - 1;
  }
H
Hongze Cheng 已提交
1368

H
more  
Hongze Cheng 已提交
1369 1370
  SSkipListIterator titer = *(pIter->pIter);
  if (tsdbLoadBlockDataCols(&(pCommith->readh), pBlock, NULL, &colId, 1) < 0) return -1;
H
Hongze Cheng 已提交
1371

H
more  
Hongze Cheng 已提交
1372 1373
  tsdbLoadDataFromCache(pIter->pTable, &titer, keyLimit, INT32_MAX, NULL, pCommith->readh.pDCols[0]->cols[0].pData,
                        pCommith->readh.pDCols[0]->numOfRows, pCfg->update, &mInfo);
H
Hongze Cheng 已提交
1374

H
more  
Hongze Cheng 已提交
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
  if (mInfo.nOperations == 0) {
    // no new data to insert (all updates denied)
    if (tsdbMoveBlock(pCommith, bidx) < 0) {
      return -1;
    }
    *(pIter->pIter) = titer;
  } else if (pBlock->numOfRows + mInfo.rowsInserted - mInfo.rowsDeleteSucceed == 0) {
    // Ignore the block
    ASSERT(0);
    *(pIter->pIter) = titer;
  } else if (tsdbCanAddSubBlock(pCommith, pBlock, &mInfo)) {
    // Add a sub-block
    tsdbLoadDataFromCache(pIter->pTable, pIter->pIter, keyLimit, INT32_MAX, pCommith->pDataCols,
                          pCommith->readh.pDCols[0]->cols[0].pData, pCommith->readh.pDCols[0]->numOfRows, pCfg->update,
                          &mInfo);
    if (pBlock->last) {
      pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
    } else {
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
    }
H
Hongze Cheng 已提交
1395

H
more  
Hongze Cheng 已提交
1396
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, pBlock->last, false) < 0) return -1;
H
Hongze Cheng 已提交
1397

H
more  
Hongze Cheng 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    if (pBlock->numOfSubBlocks == 1) {
      subBlocks[0] = *pBlock;
      subBlocks[0].numOfSubBlocks = 0;
    } else {
      memcpy(subBlocks, POINTER_SHIFT(pCommith->readh.pBlkInfo, pBlock->offset),
             sizeof(SBlock) * pBlock->numOfSubBlocks);
    }
    subBlocks[pBlock->numOfSubBlocks] = block;
    supBlock = *pBlock;
    supBlock.keyFirst = mInfo.keyFirst;
    supBlock.keyLast = mInfo.keyLast;
    supBlock.numOfSubBlocks++;
    supBlock.numOfRows = pBlock->numOfRows + mInfo.rowsInserted - mInfo.rowsDeleteSucceed;
    supBlock.offset = taosArrayGetSize(pCommith->aSubBlk) * sizeof(SBlock);

    if (tsdbCommitAddBlock(pCommith, &supBlock, subBlocks, supBlock.numOfSubBlocks) < 0) return -1;
  } else {
    if (tsdbLoadBlockData(&(pCommith->readh), pBlock, NULL) < 0) return -1;
    if (tsdbMergeBlockData(pCommith, pIter, pCommith->readh.pDCols[0], keyLimit, bidx == (nBlocks - 1)) < 0) return -1;
  }
H
Hongze Cheng 已提交
1418

H
more  
Hongze Cheng 已提交
1419 1420
  return 0;
}
H
Hongze Cheng 已提交
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 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474

static int tsdbMoveBlock(SCommitH *pCommith, int bidx) {
  SBlock *pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
  SDFile *pDFile;
  SBlock  block;
  bool    isSameFile;

  ASSERT(pBlock->numOfSubBlocks > 0);

  if (pBlock->last) {
    pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
    isSameFile = pCommith->isLFileSame;
  } else {
    pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
    isSameFile = pCommith->isDFileSame;
  }

  if (isSameFile) {
    if (pBlock->numOfSubBlocks == 1) {
      if (tsdbCommitAddBlock(pCommith, pBlock, NULL, 0) < 0) {
        return -1;
      }
    } else {
      block = *pBlock;
      block.offset = sizeof(SBlock) * taosArrayGetSize(pCommith->aSubBlk);

      if (tsdbCommitAddBlock(pCommith, &block, POINTER_SHIFT(pCommith->readh.pBlkInfo, pBlock->offset),
                             pBlock->numOfSubBlocks) < 0) {
        return -1;
      }
    }
  } else {
    if (tsdbLoadBlockData(&(pCommith->readh), pBlock, NULL) < 0) return -1;
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->readh.pDCols[0], &block, pBlock->last, true) < 0) return -1;
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) return -1;
  }

  return 0;
}

static int tsdbCommitAddBlock(SCommitH *pCommith, const SBlock *pSupBlock, const SBlock *pSubBlocks, int nSubBlocks) {
  if (taosArrayPush(pCommith->aSupBlk, pSupBlock) == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  if (pSubBlocks && taosArrayAddBatch(pCommith->aSubBlk, pSubBlocks, nSubBlocks) == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  return 0;
}

H
more  
Hongze Cheng 已提交
1475 1476 1477 1478 1479 1480 1481 1482
static int tsdbMergeBlockData(SCommitH *pCommith, SCommitIter *pIter, SDataCols *pDataCols, TSKEY keyLimit,
                              bool isLastOneBlock) {
  STsdb *   pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  SBlock    block;
  SDFile *  pDFile;
  bool      isLast;
  int32_t   defaultRows = TSDB_COMMIT_DEFAULT_ROWS(pCommith);
H
more  
Hongze Cheng 已提交
1483

H
more  
Hongze Cheng 已提交
1484 1485 1486 1487
  int biter = 0;
  while (true) {
    tsdbLoadAndMergeFromCache(pCommith->readh.pDCols[0], &biter, pIter, pCommith->pDataCols, keyLimit, defaultRows,
                              pCfg->update);
H
Hongze Cheng 已提交
1488

H
more  
Hongze Cheng 已提交
1489
    if (pCommith->pDataCols->numOfRows == 0) break;
H
Hongze Cheng 已提交
1490

H
more  
Hongze Cheng 已提交
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    if (isLastOneBlock) {
      if (pCommith->pDataCols->numOfRows < pCfg->minRowsPerFileBlock) {
        pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
        isLast = true;
      } else {
        pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
        isLast = false;
      }
    } else {
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
      isLast = false;
    }
H
Hongze Cheng 已提交
1503

H
more  
Hongze Cheng 已提交
1504 1505 1506
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, isLast, true) < 0) return -1;
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) return -1;
  }
H
more  
Hongze Cheng 已提交
1507

H
more  
Hongze Cheng 已提交
1508 1509
  return 0;
}
H
more  
Hongze Cheng 已提交
1510

H
more  
Hongze Cheng 已提交
1511 1512 1513 1514 1515
static void tsdbLoadAndMergeFromCache(SDataCols *pDataCols, int *iter, SCommitIter *pCommitIter, SDataCols *pTarget,
                                      TSKEY maxKey, int maxRows, int8_t update) {
  TSKEY     key1 = INT64_MAX;
  TSKEY     key2 = INT64_MAX;
  STSchema *pSchema = NULL;
H
Hongze Cheng 已提交
1516

H
more  
Hongze Cheng 已提交
1517 1518
  ASSERT(maxRows > 0 && dataColsKeyLast(pDataCols) <= maxKey);
  tdResetDataCols(pTarget);
H
more  
Hongze Cheng 已提交
1519

H
more  
Hongze Cheng 已提交
1520 1521
  while (true) {
    key1 = (*iter >= pDataCols->numOfRows) ? INT64_MAX : dataColsKeyAt(pDataCols, *iter);
C
Cary Xu 已提交
1522 1523
    STSRow *row = tsdbNextIterRow(pCommitIter->pIter);
    if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
more  
Hongze Cheng 已提交
1524 1525
      key2 = INT64_MAX;
    } else {
C
Cary Xu 已提交
1526
      key2 = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
1527
    }
H
more  
Hongze Cheng 已提交
1528

H
more  
Hongze Cheng 已提交
1529
    if (key1 == INT64_MAX && key2 == INT64_MAX) break;
H
more  
Hongze Cheng 已提交
1530

H
more  
Hongze Cheng 已提交
1531 1532 1533
    if (key1 < key2) {
      for (int i = 0; i < pDataCols->numOfCols; i++) {
        // TODO: dataColAppendVal may fail
C
Cary Xu 已提交
1534 1535 1536 1537 1538
        SCellVal sVal = {0};
        if (tdGetColDataOfRow(&sVal, pDataCols->cols + i, *iter) < 0) {
          TASSERT(0);
        }
        tdAppendValToDataCol(pTarget->cols + i, sVal.valType, sVal.val, pTarget->numOfRows, pTarget->maxPoints);
H
more  
Hongze Cheng 已提交
1539
      }
H
more  
Hongze Cheng 已提交
1540

H
more  
Hongze Cheng 已提交
1541 1542 1543
      pTarget->numOfRows++;
      (*iter)++;
    } else if (key1 > key2) {
C
Cary Xu 已提交
1544 1545
      if (pSchema == NULL || schemaVersion(pSchema) != TD_ROW_SVER(row)) {
        pSchema = tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, TD_ROW_SVER(row));
H
more  
Hongze Cheng 已提交
1546 1547
        ASSERT(pSchema != NULL);
      }
H
Hongze Cheng 已提交
1548

C
Cary Xu 已提交
1549
      tdAppendSTSRowToDataCol(row, pSchema, pTarget, true);
H
more  
Hongze Cheng 已提交
1550 1551 1552 1553 1554 1555 1556

      tSkipListIterNext(pCommitIter->pIter);
    } else {
      if (update != TD_ROW_OVERWRITE_UPDATE) {
        // copy disk data
        for (int i = 0; i < pDataCols->numOfCols; i++) {
          // TODO: dataColAppendVal may fail
C
Cary Xu 已提交
1557 1558 1559 1560 1561
          SCellVal sVal = {0};
          if (tdGetColDataOfRow(&sVal, pDataCols->cols + i, *iter) < 0) {
            TASSERT(0);
          }
          tdAppendValToDataCol(pTarget->cols + i, sVal.valType, sVal.val, pTarget->numOfRows, pTarget->maxPoints);
H
more  
Hongze Cheng 已提交
1562 1563 1564 1565 1566 1567
        }

        if (update == TD_ROW_DISCARD_UPDATE) pTarget->numOfRows++;
      }
      if (update != TD_ROW_DISCARD_UPDATE) {
        // copy mem data
C
Cary Xu 已提交
1568 1569
        if (pSchema == NULL || schemaVersion(pSchema) != TD_ROW_SVER(row)) {
          pSchema = tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, TD_ROW_SVER(row));
H
more  
Hongze Cheng 已提交
1570 1571 1572
          ASSERT(pSchema != NULL);
        }

C
Cary Xu 已提交
1573
        tdAppendSTSRowToDataCol(row, pSchema, pTarget, update == TD_ROW_OVERWRITE_UPDATE);
H
more  
Hongze Cheng 已提交
1574 1575 1576 1577 1578 1579 1580 1581
      }
      (*iter)++;
      tSkipListIterNext(pCommitIter->pIter);
    }

    if (pTarget->numOfRows >= maxRows) break;
  }
}
H
Hongze Cheng 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599

static void tsdbResetCommitTable(SCommitH *pCommith) {
  taosArrayClear(pCommith->aSubBlk);
  taosArrayClear(pCommith->aSupBlk);
  pCommith->pTable = NULL;
}

static void tsdbCloseCommitFile(SCommitH *pCommith, bool hasError) {
  if (pCommith->isRFileSet) {
    tsdbCloseAndUnsetFSet(&(pCommith->readh));
  }

  if (!hasError) {
    TSDB_FSET_FSYNC(TSDB_COMMIT_WRITE_FSET(pCommith));
  }
  tsdbCloseDFileSet(TSDB_COMMIT_WRITE_FSET(pCommith));
}

H
more  
Hongze Cheng 已提交
1600 1601 1602 1603
static bool tsdbCanAddSubBlock(SCommitH *pCommith, SBlock *pBlock, SMergeInfo *pInfo) {
  STsdb *   pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  int       mergeRows = pBlock->numOfRows + pInfo->rowsInserted - pInfo->rowsDeleteSucceed;
H
Hongze Cheng 已提交
1604

H
more  
Hongze Cheng 已提交
1605
  ASSERT(mergeRows > 0);
H
Hongze Cheng 已提交
1606

H
more  
Hongze Cheng 已提交
1607 1608 1609 1610 1611 1612 1613
  if (pBlock->numOfSubBlocks < TSDB_MAX_SUBBLOCKS && pInfo->nOperations <= pCfg->maxRowsPerFileBlock) {
    if (pBlock->last) {
      if (pCommith->isLFileSame && mergeRows < pCfg->minRowsPerFileBlock) return true;
    } else {
      if (pCommith->isDFileSame && mergeRows <= pCfg->maxRowsPerFileBlock) return true;
    }
  }
H
Hongze Cheng 已提交
1614

H
more  
Hongze Cheng 已提交
1615 1616
  return false;
}
H
Hongze Cheng 已提交
1617

H
more  
Hongze Cheng 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
// int tsdbApplyRtn(STsdbRepo *pRepo) {
//   SRtn       rtn;
//   SFSIter    fsiter;
//   STsdbFS *  pfs = REPO_FS(pRepo);
//   SDFileSet *pSet;

//   // Get retention snapshot
//   tsdbGetRtnSnap(pRepo, &rtn);

//   tsdbFSIterInit(&fsiter, pfs, TSDB_FS_ITER_FORWARD);
//   while ((pSet = tsdbFSIterNext(&fsiter))) {
//     if (pSet->fid < rtn.minFid) {
//       tsdbInfo("vgId:%d FSET %d at level %d disk id %d expires, remove it", REPO_ID(pRepo), pSet->fid,
//                TSDB_FSET_LEVEL(pSet), TSDB_FSET_ID(pSet));
//       continue;
//     }
H
Hongze Cheng 已提交
1634

H
more  
Hongze Cheng 已提交
1635 1636 1637 1638
//     if (tsdbApplyRtnOnFSet(pRepo, pSet, &rtn) < 0) {
//       return -1;
//     }
//   }
H
Hongze Cheng 已提交
1639

H
more  
Hongze Cheng 已提交
1640
//   return 0;
L
Liu Jicong 已提交
1641
// }