tsdbCommit.c 46.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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/>.
 */
H
Hongze Cheng 已提交
15
#include "tsdbint.h"
16

H
Hongze Cheng 已提交
17
#define TSDB_MAX_SUBBLOCKS 8
H
Hongze Cheng 已提交
18
#define TSDB_KEY_FID(key, days, precision) ((key) / tsMsPerDay[(precision)] / (days))
H
Hongze Cheng 已提交
19

H
Hongze Cheng 已提交
20
typedef struct {
H
Hongze Cheng 已提交
21 22 23 24 25 26 27
  int   minFid;
  int   midFid;
  int   maxFid;
  TSKEY minKey;
} SRtn;

typedef struct {
H
Hongze Cheng 已提交
28 29
  uint32_t     version;
  SRtn         rtn;     // retention snapshot
H
Hongze Cheng 已提交
30 31 32
  SFSIter      fsIter;  // tsdb file iterator
  int          niters;  // memory iterators
  SCommitIter *iters;
H
Hongze Cheng 已提交
33 34 35 36 37
  bool         isRFileSet; // read and commit FSET
  SReadH       readh;
  SDFileSet    wSet;
  bool         isDFileSame;
  bool         isLFileSame;
H
Hongze Cheng 已提交
38 39
  TSKEY        minKey;
  TSKEY        maxKey;
H
Hongze Cheng 已提交
40 41 42
  SArray *     aBlkIdx;  // SBlockIdx array
  SArray *     aSupBlk;  // Table super-block array
  SArray *     aSubBlk;  // table sub-block array
H
Hongze Cheng 已提交
43 44 45
  SDataCols *  pDataCols;
} SCommitH;

H
Hongze Cheng 已提交
46
#define TSDB_COMMIT_REPO(ch) TSDB_READ_REPO(&(ch->readh))
H
Hongze Cheng 已提交
47
#define TSDB_COMMIT_REPO_ID(ch) REPO_ID(TSDB_READ_REPO(&(ch->readh)))
H
Hongze Cheng 已提交
48
#define TSDB_COMMIT_WRITE_FSET(ch) (&((ch)->wSet))
H
Hongze Cheng 已提交
49
#define TSDB_COMMIT_TABLE(ch) TSDB_READ_TABLE(&(ch->readh))
H
Hongze Cheng 已提交
50 51 52
#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)
H
Hongze Cheng 已提交
53 54
#define TSDB_COMMIT_BUF(ch) TSDB_READ_BUF(&((ch)->readh))
#define TSDB_COMMIT_COMP_BUF(ch) TSDB_READ_COMP_BUF(&((ch)->readh))
H
Hongze Cheng 已提交
55
#define TSDB_COMMIT_DEFAULT_ROWS(ch) (TSDB_COMMIT_REPO(ch)->config.maxRowsPerFileBlock * 4 / 5)
H
Hongze Cheng 已提交
56

H
Hongze Cheng 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
static int  tsdbCommitMeta(STsdbRepo *pRepo);
static int  tsdbUpdateMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid, void *cont, int contLen);
static int  tsdbDropMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid);
static int  tsdbCommitTSData(STsdbRepo *pRepo);
static int  tsdbStartCommit(STsdbRepo *pRepo);
static void tsdbEndCommit(STsdbRepo *pRepo, int eno);
static int  tsdbCommitToFile(SCommitH *pCommith, SDFileSet *pSet, int fid);
static int  tsdbCreateCommitIters(SCommitH *pCommith);
static void tsdbDestroyCommitIters(SCommitH *pCommith);
static void tsdbSeekCommitIter(SCommitH *pCommith, TSKEY key);
static int  tsdbInitCommitH(SCommitH *pCommith, STsdbRepo *pRepo);
static void tsdbDestroyCommitH(SCommitH *pCommith);
static void tsdbGetRtnSnap(STsdbRepo *pRepo, SRtn *pRtn);
static int  tsdbGetFidLevel(int fid, SRtn *pRtn);
static int  tsdbNextCommitFid(SCommitH *pCommith);
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  tsdbWriteBlockIdx(SCommitH *pCommih);
static int  tsdbCommitMemData(SCommitH *pCommith, SCommitIter *pIter, TSKEY keyLimit, bool toData);
static int  tsdbMergeMemData(SCommitH *pCommith, SCommitIter *pIter, int bidx);
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 tsdbResetCommitFile(SCommitH *pCommith);
static void tsdbResetCommitTable(SCommitH *pCommith);
static int  tsdbSetAndOpenCommitFile(SCommitH *pCommith, SDFileSet *pSet, int fid);
static void tsdbCloseCommitFile(SCommitH *pCommith, bool hasError);
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);

91
void *tsdbCommitData(STsdbRepo *pRepo) {
H
refact  
Hongze Cheng 已提交
92 93 94 95
  if (tsdbStartCommit(pRepo) < 0) {
    tsdbError("vgId:%d failed to commit data while startting to commit since %s", REPO_ID(pRepo), tstrerror(terrno));
    goto _err;
  }
H
Hongze Cheng 已提交
96

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  // Commit to update meta file
  if (tsdbCommitMeta(pRepo) < 0) {
    tsdbError("vgId:%d error occurs while committing META data since %s", REPO_ID(pRepo), tstrerror(terrno));
    goto _err;
  }

  // Create the iterator to read from cache
  if (tsdbCommitTSData(pRepo) < 0) {
    tsdbError("vgId:%d error occurs while committing TS data since %s", REPO_ID(pRepo), tstrerror(terrno));
    goto _err;
  }

  tsdbEndCommit(pRepo, TSDB_CODE_SUCCESS);
  return NULL;

_err:
  ASSERT(terrno != TSDB_CODE_SUCCESS);
H
Hongze Cheng 已提交
114
  pRepo->code = terrno;
115

H
refact  
Hongze Cheng 已提交
116
  tsdbEndCommit(pRepo, terrno);
117 118 119
  return NULL;
}

H
Hongze Cheng 已提交
120
// =================== Commit Meta Data
121
static int tsdbCommitMeta(STsdbRepo *pRepo) {
H
Hongze Cheng 已提交
122
  STsdbFS *  pfs = REPO_FS(pRepo);
123
  SMemTable *pMem = pRepo->imem;
H
Hongze Cheng 已提交
124 125
  SMFile *   pOMFile = pfs->cstatus->pmf;
  SMFile     mf;
126 127
  SActObj *  pAct = NULL;
  SActCont * pCont = NULL;
H
Hongze Cheng 已提交
128
  SListNode *pNode = NULL;
H
Hongze Cheng 已提交
129
  SDiskID    did;
130

H
Hongze Cheng 已提交
131
  ASSERT(pOMFile != NULL || listNEles(pMem->actList) > 0);
132

H
Hongze Cheng 已提交
133 134 135 136 137 138 139 140
  if (listNEles(pMem->actList) <= 0) {
    // no 
    tsdbUpdateMFile(pfs, pOMFile);
    return 0;
  } else {
    // Create/Open a meta file or open the existing file
    if (pOMFile == NULL) {
      // Create a new meta file
H
Hongze Cheng 已提交
141 142 143
      did.level = TFS_PRIMARY_LEVEL;
      did.id = TFS_PRIMARY_ID;
      tsdbInitMFile(&mf, did, REPO_ID(pRepo), pfs->nstatus->meta.version);
144

H
Hongze Cheng 已提交
145 146 147 148
      if (tsdbCreateMFile(&mf) < 0) {
        return -1;
      }
    } else {
H
Hongze Cheng 已提交
149
      tsdbInitMFileEx(&mf, pOMFile);
H
Hongze Cheng 已提交
150 151 152 153 154
      if (tsdbOpenMFile(&mf, O_WRONLY) < 0) {
        return -1;
      }
    }
  }
155

H
Hongze Cheng 已提交
156
  // Loop to write
157 158 159 160
  while ((pNode = tdListPopHead(pMem->actList)) != NULL) {
    pAct = (SActObj *)pNode->data;
    if (pAct->act == TSDB_UPDATE_META) {
      pCont = (SActCont *)POINTER_SHIFT(pAct, sizeof(SActObj));
H
Hongze Cheng 已提交
161 162 163
      if (tsdbUpdateMetaRecord(pfs, &mf, pAct->uid, (void *)(pCont->cont), pCont->len) < 0) {
        tsdbCloseMFile(&mf);
        return -1;
164 165
      }
    } else if (pAct->act == TSDB_DROP_META) {
H
Hongze Cheng 已提交
166 167 168
      if (tsdbDropMetaRecord(pfs, &mf, pAct->uid) < 0) {
        tsdbCloseMFile(&mf);
        return -1;
169 170 171 172 173 174
      }
    } else {
      ASSERT(false);
    }
  }

H
Hongze Cheng 已提交
175 176
  if (tsdbUpdateMFileHeader(&mf) < 0) {
    return -1;
177 178
  }

H
Hongze Cheng 已提交
179 180
  tsdbCloseMFile(&mf);
  tsdbUpdateMFile(pfs, &mf);
H
refact  
Hongze Cheng 已提交
181

182
  return 0;
H
Hongze Cheng 已提交
183
}
184

H
Hongze Cheng 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
int tsdbEncodeKVRecord(void **buf, SKVRecord *pRecord) {
  int tlen = 0;
  tlen += taosEncodeFixedU64(buf, pRecord->uid);
  tlen += taosEncodeFixedI64(buf, pRecord->offset);
  tlen += taosEncodeFixedI64(buf, pRecord->size);

  return tlen;
}

void *tsdbDecodeKVRecord(void *buf, SKVRecord *pRecord) {
  buf = taosDecodeFixedU64(buf, &(pRecord->uid));
  buf = taosDecodeFixedI64(buf, &(pRecord->offset));
  buf = taosDecodeFixedI64(buf, &(pRecord->size));

  return buf;
200 201
}

H
Hongze Cheng 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
static int tsdbUpdateMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid, void *cont, int contLen) {
  char      buf[64] = "\0";
  void *    pBuf = buf;
  SKVRecord rInfo;
  int64_t   offset;

  // Seek to end of meta file
  offset = tsdbSeekMFile(pMFile, 0, SEEK_END);
  if (offset < 0) {
    return -1;
  }

  rInfo.offset = offset;
  rInfo.uid = uid;
  rInfo.size = contLen;

H
Hongze Cheng 已提交
218 219
  int tlen = tsdbEncodeKVRecord((void **)(&pBuf), &rInfo);
  if (tsdbAppendMFile(pMFile, buf, tlen, NULL) < tlen) {
H
Hongze Cheng 已提交
220 221 222
    return -1;
  }

H
Hongze Cheng 已提交
223
  if (tsdbAppendMFile(pMFile, cont, contLen, NULL) < contLen) {
H
Hongze Cheng 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    return -1;
  }

  tsdbUpdateMFileMagic(pMFile, POINTER_SHIFT(cont, contLen - sizeof(TSCKSUM)));
  SKVRecord *pRecord = taosHashGet(pfs->metaCache, (void *)&uid, sizeof(uid));
  if (pRecord != NULL) {
    pMFile->info.tombSize += pRecord->size;
  } else {
    pMFile->info.nRecords++;
  }
  taosHashPut(pfs->metaCache, (void *)(&uid), sizeof(uid), (void *)(&rInfo), sizeof(rInfo));

  return 0;
}

static int tsdbDropMetaRecord(STsdbFS *pfs, SMFile *pMFile, uint64_t uid) {
  SKVRecord rInfo = {0};
  char      buf[128] = "\0";

  SKVRecord *pRecord = taosHashGet(pfs->metaCache, (void *)(&uid), sizeof(uid));
  if (pRecord == NULL) {
    tsdbError("failed to drop KV store record with key %" PRIu64 " since not find", uid);
    return -1;
  }

  rInfo.offset = -pRecord->offset;
  rInfo.uid = pRecord->uid;
  rInfo.size = pRecord->size;

  void *pBuf = buf;
H
Hongze Cheng 已提交
254
  tsdbEncodeKVRecord(&pBuf, &rInfo);
H
Hongze Cheng 已提交
255 256 257 258 259

  if (tsdbAppendMFile(pMFile, buf, POINTER_DISTANCE(pBuf, buf), NULL) < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
260 261 262 263
  pMFile->info.magic = taosCalcChecksum(pMFile->info.magic, (uint8_t *)buf, (uint32_t)POINTER_DISTANCE(pBuf, buf));
  pMFile->info.nDels++;
  pMFile->info.nRecords--;
  pMFile->info.tombSize += (rInfo.size + sizeof(SKVRecord) * 2);
H
Hongze Cheng 已提交
264 265 266 267 268 269

  taosHashRemove(pfs->metaCache, (void *)(&uid), sizeof(uid));
  return 0;
}


H
Hongze Cheng 已提交
270 271 272
// =================== Commit Time-Series Data
static int tsdbCommitTSData(STsdbRepo *pRepo) {
  SMemTable *pMem = pRepo->imem;
H
Hongze Cheng 已提交
273
  SCommitH   commith = {0};
H
Hongze Cheng 已提交
274
  STsdbFS *  pfs = REPO_FS(pRepo);
H
Hongze Cheng 已提交
275 276 277 278 279 280 281
  SDFileSet *pSet = NULL;
  SDFileSet  nSet;
  int        fid;

  if (pMem->numOfRows <= 0) return 0;

  // Resource initialization
H
Hongze Cheng 已提交
282
  if (tsdbInitCommitH(&commith, pRepo) < 0) {
H
Hongze Cheng 已提交
283 284 285 286
    return -1;
  }

  // Skip expired memory data and expired FSET
H
Hongze Cheng 已提交
287
  tsdbSeekCommitIter(&commith, commith.rtn.minKey);
H
Hongze Cheng 已提交
288
  while (true) {
H
Hongze Cheng 已提交
289 290
    pSet = tsdbFSIterNext(&(commith.fsIter));
    if (pSet == NULL || pSet->fid >= commith.rtn.minFid) break;
H
Hongze Cheng 已提交
291 292 293
  }

  // Loop to commit to each file
H
Hongze Cheng 已提交
294
  fid = tsdbNextCommitFid(&(commith));
H
Hongze Cheng 已提交
295 296 297 298 299 300 301 302 303
  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
      int level, id;

H
Hongze Cheng 已提交
304
      tfsAllocDisk(tsdbGetFidLevel(pSet->fid, &(commith.rtn)), &level, &id);
H
Hongze Cheng 已提交
305
      if (level == TFS_UNDECIDED_LEVEL) {
H
Hongze Cheng 已提交
306 307
        terrno = TSDB_CODE_TDB_NO_AVAIL_DISK;
        tsdbDestroyCommitH(&commith);
H
Hongze Cheng 已提交
308 309 310 311
        return -1;
      }

      if (level > TSDB_FSET_LEVEL(pSet)) {
H
Hongze Cheng 已提交
312
        // Need to move the FSET to higher level
H
Hongze Cheng 已提交
313
        if (tsdbCopyDFileSet(pSet, &nSet) < 0) {
H
Hongze Cheng 已提交
314
          tsdbDestroyCommitH(&commith);
H
Hongze Cheng 已提交
315 316 317
          return -1;
        }

H
Hongze Cheng 已提交
318
        if (tsdbUpdateDFileSet(pfs, &nSet) < 0) {
H
Hongze Cheng 已提交
319
          tsdbDestroyCommitH(&commith);
H
Hongze Cheng 已提交
320 321 322
          return -1;
        }
      } else {
H
Hongze Cheng 已提交
323
        if (tsdbUpdateDFileSet(pfs, pSet) < 0) {
H
Hongze Cheng 已提交
324
          tsdbDestroyCommitH(&commith);
H
Hongze Cheng 已提交
325 326 327 328
          return -1;
        }
      }

H
Hongze Cheng 已提交
329
      pSet = tsdbFSIterNext(&(commith.fsIter));
H
Hongze Cheng 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342
    } 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;
H
Hongze Cheng 已提交
343
        pSet = tsdbFSIterNext(&(commith.fsIter));
H
Hongze Cheng 已提交
344
      }
H
Hongze Cheng 已提交
345
      fid = tsdbNextCommitFid(&commith);
H
Hongze Cheng 已提交
346

H
Hongze Cheng 已提交
347
      if (tsdbCommitToFile(&commith, pCSet, cfid) < 0) {
H
Hongze Cheng 已提交
348
        tsdbDestroyCommitH(&commith);
H
Hongze Cheng 已提交
349 350 351 352 353
        return -1;
      }
    }
  }

H
Hongze Cheng 已提交
354
  tsdbDestroyCommitH(&commith);
H
Hongze Cheng 已提交
355 356 357
  return 0;
}

H
refact  
Hongze Cheng 已提交
358 359 360 361 362 363
static int tsdbStartCommit(STsdbRepo *pRepo) {
  SMemTable *pMem = pRepo->imem;

  tsdbInfo("vgId:%d start to commit! keyFirst %" PRId64 " keyLast %" PRId64 " numOfRows %" PRId64 " meta rows: %d",
           REPO_ID(pRepo), pMem->keyFirst, pMem->keyLast, pMem->numOfRows, listNEles(pMem->actList));

H
Hongze Cheng 已提交
364
  if (tsdbStartTxn(REPO_FS(pRepo)) < 0) return -1;
H
refact  
Hongze Cheng 已提交
365 366 367 368 369

  pRepo->code = TSDB_CODE_SUCCESS;
  return 0;
}

370
static void tsdbEndCommit(STsdbRepo *pRepo, int eno) {
H
Hongze Cheng 已提交
371 372 373 374
  if (eno != TSDB_CODE_SUCCESS) {
    tsdbEndTxnWithError(REPO_FS(pRepo));
  } else {
    tsdbEndTxn(REPO_FS(pRepo));
H
Hongze Cheng 已提交
375 376
  }

H
refact  
Hongze Cheng 已提交
377 378
  tsdbInfo("vgId:%d commit over, %s", REPO_ID(pRepo), (eno == TSDB_CODE_SUCCESS) ? "succeed" : "failed");

379
  if (pRepo->appH.notifyStatus) pRepo->appH.notifyStatus(pRepo->appH.appH, TSDB_STATUS_COMMIT_OVER, eno);
H
refact  
Hongze Cheng 已提交
380

381 382 383 384 385
  SMemTable *pIMem = pRepo->imem;
  tsdbLockRepo(pRepo);
  pRepo->imem = NULL;
  tsdbUnlockRepo(pRepo);
  tsdbUnRefMemTable(pRepo, pIMem);
H
refact  
Hongze Cheng 已提交
386

387 388 389
  sem_post(&(pRepo->readyToCommit));
}

H
Hongze Cheng 已提交
390
#if 0
H
Hongze Cheng 已提交
391
static bool tsdbHasDataToCommit(SCommitIter *iters, int nIters, TSKEY minKey, TSKEY maxKey) {
392 393
  for (int i = 0; i < nIters; i++) {
    TSKEY nextKey = tsdbNextIterKey((iters + i)->pIter);
H
Hongze Cheng 已提交
394
    if (nextKey != TSDB_DATA_TIMESTAMP_NULL && (nextKey >= minKey && nextKey <= maxKey)) return true;
395
  }
H
Hongze Cheng 已提交
396
  return false;
397
}
H
Hongze Cheng 已提交
398
#endif
399

H
Hongze Cheng 已提交
400 401 402 403 404
static int tsdbCommitToFile(SCommitH *pCommith, SDFileSet *pSet, int fid) {
  STsdbRepo *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg * pCfg = REPO_CFG(pRepo);

  ASSERT(pSet == NULL || pSet->fid == fid);
405

H
Hongze Cheng 已提交
406 407
  tsdbResetCommitFile(pCommith);
  tsdbGetFidKeyRange(pCfg->daysPerFile, pCfg->precision, fid, &(pCommith->minKey), &(pCommith->maxKey));
H
Hongze Cheng 已提交
408

H
Hongze Cheng 已提交
409 410
  // Set and open files
  if (tsdbSetAndOpenCommitFile(pCommith, pSet, fid) < 0) {
H
Hongze Cheng 已提交
411 412
    return -1;
  }
H
Hongze Cheng 已提交
413

H
Hongze Cheng 已提交
414
  // Loop to commit each table data
H
Hongze Cheng 已提交
415
  for (int tid = 1; tid < pCommith->niters; tid++) {
H
Hongze Cheng 已提交
416
    SCommitIter *pIter = pCommith->iters + tid;
H
Hongze Cheng 已提交
417

H
Hongze Cheng 已提交
418 419
    if (pIter->pTable == NULL) continue;

H
Hongze Cheng 已提交
420 421 422
    if (tsdbCommitToTable(pCommith, tid) < 0) {
      // TODO: revert the file change
      tsdbCloseCommitFile(pCommith, true);
H
Hongze Cheng 已提交
423
      return -1;
H
Hongze Cheng 已提交
424
    }
425 426
  }

H
Hongze Cheng 已提交
427 428 429 430 431
  if (tsdbWriteBlockIdx(pCommith) < 0) {
    tsdbCloseCommitFile(pCommith, true);
    return -1;
  }

H
Hongze Cheng 已提交
432 433
  tsdbCloseCommitFile(pCommith, false);

H
Hongze Cheng 已提交
434
  if (tsdbUpdateDFileSet(REPO_FS(pRepo), &(pCommith->wSet)) < 0) {
H
Hongze Cheng 已提交
435 436 437 438 439
    // TODO
    return -1;
  }

  return 0;
440 441
}

H
Hongze Cheng 已提交
442
static int tsdbCreateCommitIters(SCommitH *pCommith) {
H
Hongze Cheng 已提交
443
  STsdbRepo *pRepo = TSDB_COMMIT_REPO(pCommith);
444 445 446
  SMemTable *pMem = pRepo->imem;
  STsdbMeta *pMeta = pRepo->tsdbMeta;

H
Hongze Cheng 已提交
447 448 449
  pCommith->niters = pMem->maxTables;
  pCommith->iters = (SCommitIter *)calloc(pMem->maxTables, sizeof(SCommitIter));
  if (pCommith->iters == NULL) {
450
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
H
Hongze Cheng 已提交
451
    return -1;
452 453
  }

H
Hongze Cheng 已提交
454
  if (tsdbRLockRepoMeta(pRepo) < 0) return -1;
455 456 457 458 459

  // reference all tables
  for (int i = 0; i < pMem->maxTables; i++) {
    if (pMeta->tables[i] != NULL) {
      tsdbRefTable(pMeta->tables[i]);
H
Hongze Cheng 已提交
460
      pCommith->iters[i].pTable = pMeta->tables[i];
461 462 463
    }
  }

H
Hongze Cheng 已提交
464
  if (tsdbUnlockRepoMeta(pRepo) < 0) return -1;
465 466

  for (int i = 0; i < pMem->maxTables; i++) {
H
Hongze Cheng 已提交
467 468
    if ((pCommith->iters[i].pTable != NULL) && (pMem->tData[i] != NULL) &&
        (TABLE_UID(pCommith->iters[i].pTable) == pMem->tData[i]->uid)) {
H
Hongze Cheng 已提交
469
      if ((pCommith->iters[i].pIter = tSkipListCreateIter(pMem->tData[i]->pData)) == NULL) {
470
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
H
Hongze Cheng 已提交
471
        return -1;
472 473
      }

H
Hongze Cheng 已提交
474
      tSkipListIterNext(pCommith->iters[i].pIter);
475 476 477
    }
  }

H
Hongze Cheng 已提交
478
  return 0;
479 480
}

H
Hongze Cheng 已提交
481 482
static void tsdbDestroyCommitIters(SCommitH *pCommith) {
  if (pCommith->iters == NULL) return;
483

H
Hongze Cheng 已提交
484 485 486
  for (int i = 1; i < pCommith->niters; i++) {
    if (pCommith->iters[i].pTable != NULL) {
      tsdbUnRefTable(pCommith->iters[i].pTable);
H
Hongze Cheng 已提交
487
      tSkipListDestroyIter(pCommith->iters[i].pIter);
488 489 490
    }
  }

H
Hongze Cheng 已提交
491 492
  free(pCommith->iters);
  pCommith->iters = NULL;
H
Hongze Cheng 已提交
493
  pCommith->niters = 0;
494
}
H
Hongze Cheng 已提交
495

H
Hongze Cheng 已提交
496 497 498 499
// 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;
H
Hongze Cheng 已提交
500
    if (pIter->pTable == NULL || pIter->pIter == NULL) continue;
H
Hongze Cheng 已提交
501

H
Hongze Cheng 已提交
502
    tsdbLoadDataFromCache(pIter->pTable, pIter->pIter, key - 1, INT32_MAX, NULL, NULL, 0, true, NULL);
H
Hongze Cheng 已提交
503
  }
H
Hongze Cheng 已提交
504 505
}

H
Hongze Cheng 已提交
506
static int tsdbInitCommitH(SCommitH *pCommith, STsdbRepo *pRepo) {
H
Hongze Cheng 已提交
507 508 509 510 511 512
  STsdbCfg *pCfg = REPO_CFG(pRepo);

  memset(pCommith, 0, sizeof(*pCommith));
  for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
    TSDB_FILE_SET_CLOSED(TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(pCommith), ftype));
  }
H
Hongze Cheng 已提交
513

H
Hongze Cheng 已提交
514 515 516 517
  pCommith->version = REPO_FS_VERSION(pRepo) + 1;

  tsdbGetRtnSnap(pRepo, &(pCommith->rtn));

H
Hongze Cheng 已提交
518 519 520 521 522
  for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
    SDFile *pDFile = TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(pCommith), ftype);
    TSDB_FILE_SET_CLOSED(pDFile);
  }

H
Hongze Cheng 已提交
523 524
  // Init read handle
  if (tsdbInitReadH(&(pCommith->readh), pRepo) < 0) {
H
Hongze Cheng 已提交
525 526 527
    return -1;
  }

H
Hongze Cheng 已提交
528
  // Init file iterator
H
Hongze Cheng 已提交
529
  tsdbFSIterInit(&(pCommith->fsIter), REPO_FS(pRepo), TSDB_FS_ITER_FORWARD);
H
Hongze Cheng 已提交
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

  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);
H
Hongze Cheng 已提交
547 548 549
    return -1;
  }

H
Hongze Cheng 已提交
550 551
  pCommith->aSubBlk = taosArrayInit(1024, sizeof(SBlock));
  if (pCommith->aSubBlk == NULL) {
H
Hongze Cheng 已提交
552
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
H
Hongze Cheng 已提交
553 554 555 556 557 558 559 560
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->pDataCols = tdNewDataCols(0, 0, pCfg->maxRowsPerFileBlock);
  if (pCommith->pDataCols == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
H
Hongze Cheng 已提交
561 562 563 564 565 566
    return -1;
  }

  return 0;
}

H
Hongze Cheng 已提交
567 568 569 570 571 572 573 574
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
Hongze Cheng 已提交
575 576 577
}

static void tsdbGetRtnSnap(STsdbRepo *pRepo, SRtn *pRtn) {
H
Hongze Cheng 已提交
578
  STsdbCfg *pCfg = REPO_CFG(pRepo);
H
Hongze Cheng 已提交
579 580 581 582 583 584 585 586
  TSKEY     minKey, midKey, maxKey, now;

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

  pRtn->minKey = minKey;
H
Hongze Cheng 已提交
587 588 589
  pRtn->minFid = TSDB_KEY_FID(minKey, pCfg->daysPerFile, pCfg->precision);
  pRtn->midFid = TSDB_KEY_FID(midKey, pCfg->daysPerFile, pCfg->precision);
  pRtn->maxFid = TSDB_KEY_FID(maxKey, pCfg->daysPerFile, pCfg->precision);
H
Hongze Cheng 已提交
590 591 592 593 594 595 596 597 598 599 600 601
}

static int tsdbGetFidLevel(int fid, SRtn *pRtn) {
  if (fid >= pRtn->maxFid) {
    return 0;
  } else if (fid >= pRtn->midFid) {
    return 1;
  } else if (fid >= pRtn->minFid) {
    return 2;
  } else {
    return -1;
  }
H
Hongze Cheng 已提交
602 603
}

H
Hongze Cheng 已提交
604
static int tsdbNextCommitFid(SCommitH *pCommith) {
H
Hongze Cheng 已提交
605 606 607
  STsdbRepo *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg * pCfg = REPO_CFG(pRepo);
  int        fid = TSDB_IVLD_FID;
H
Hongze Cheng 已提交
608

H
Hongze Cheng 已提交
609
  for (int i = 0; i < pCommith->niters; i++) {
H
Hongze Cheng 已提交
610
    SCommitIter *pIter = pCommith->iters + i;
H
Hongze Cheng 已提交
611 612 613 614 615 616 617 618 619 620 621 622
    if (pIter->pTable == NULL || pIter->pIter == NULL) continue;

    TSKEY nextKey = tsdbNextIterKey(pIter->pIter);
    if (nextKey == TSDB_DATA_TIMESTAMP_NULL) {
      continue;
    } else {
      int tfid = TSDB_KEY_FID(nextKey, pCfg->daysPerFile, pCfg->precision);
      if (fid == TSDB_IVLD_FID || fid > tfid) {
        fid = tfid;
      }
    }
  }
H
Hongze Cheng 已提交
623 624

  return fid;
H
Hongze Cheng 已提交
625 626
}

H
Hongze Cheng 已提交
627 628
static int tsdbCommitToTable(SCommitH *pCommith, int tid) {
  SCommitIter *pIter = pCommith->iters + tid;
H
Hongze Cheng 已提交
629
  TSKEY        nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
630

H
Hongze Cheng 已提交
631
  TSDB_RLOCK_TABLE(pIter->pTable);
H
Hongze Cheng 已提交
632

H
Hongze Cheng 已提交
633 634 635 636
  // Set commit table
  tsdbResetCommitTable(pCommith);
  if (tsdbSetCommitTable(pCommith, pIter->pTable) < 0) {
    TSDB_RUNLOCK_TABLE(pIter->pTable);
H
Hongze Cheng 已提交
637 638 639
    return -1;
  }

H
Hongze Cheng 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
  if (pCommith->readh.pBlkIdx == NULL && (nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey)) {
    // No disk data and no memory data
    TSDB_RUNLOCK_TABLE(pIter->pTable);
    return 0;
  } else {
    // Must has disk data, maybe has memory data
    int     nBlocks;
    int     bidx = 0;
    SBlock *pBlock;

    if (pCommith->readh.pBlkIdx) {
      if (tsdbLoadBlockInfo(&(pCommith->readh), NULL) < 0) {
        TSDB_RUNLOCK_TABLE(pIter->pTable);
        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) {
          TSDB_RUNLOCK_TABLE(pIter->pTable);
          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)) {
        // merge pBlock data and memory data
        if (tsdbMergeMemData(pCommith, pIter, bidx) < 0) {
          TSDB_RUNLOCK_TABLE(pIter->pTable);
          return -1;
        }

        bidx++;
        if (bidx < nBlocks) {
          pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
        } else {
          pBlock = NULL;
        }
        nextKey = tsdbNextIterKey(pIter->pIter);
      } else {
        // Only commit memory data
        if (pBlock == NULL) {
          if (tsdbCommitMemData(pCommith, pIter, pCommith->maxKey, false) < 0) {
            TSDB_RUNLOCK_TABLE(pIter->pTable);
            return -1;
          }
        } else {
          if (tsdbCommitMemData(pCommith, pIter, pBlock->keyFirst - 1, true) < 0) {
            TSDB_RUNLOCK_TABLE(pIter->pTable);
            return -1;
          }
        }
        nextKey = tsdbNextIterKey(pIter->pIter);
      }
    }
  }

#if 0
H
Hongze Cheng 已提交
716 717 718 719 720 721 722 723 724 725 726
  if (!pCommith->isRFileSet) {
    if (pIter->pIter == NULL) {
      // No memory data
      TSDB_RUNLOCK_TABLE(pIter->pTable);
      return 0;
    } else {
      // TODO: think about no data committed at all
      if (tsdbCommitMemData(pCommith, pIter, pCommith->maxKey, true) < 0) {
        TSDB_RUNLOCK_TABLE(pIter->pTable);
        return -1;
      }
H
Hongze Cheng 已提交
727

H
Hongze Cheng 已提交
728 729 730 731
      TSDB_RUNLOCK_TABLE(pIter->pTable);
      if (tsdbWriteBlockInfo(pCommith) < 0) {
        return -1;
      }
H
Hongze Cheng 已提交
732

H
Hongze Cheng 已提交
733 734 735
      return 0;
    }
  }
H
Hongze Cheng 已提交
736

H
Hongze Cheng 已提交
737
  // No memory data and no disk data, just return
H
Hongze Cheng 已提交
738
  if (pIter->pIter == NULL && pCommith->readh.pBlkIdx == NULL) {
H
Hongze Cheng 已提交
739 740 741 742
    TSDB_RUNLOCK_TABLE(pIter->pTable);
    return 0;
  }

H
Hongze Cheng 已提交
743
  if (tsdbLoadBlockInfo(&(pCommith->readh), NULL) < 0) {
H
Hongze Cheng 已提交
744 745 746
    TSDB_RUNLOCK_TABLE(pIter->pTable);
    return -1;
  }
H
Hongze Cheng 已提交
747

H
Hongze Cheng 已提交
748
  // Process merge commit
H
Hongze Cheng 已提交
749
  int     nBlocks = (pCommith->readh.pBlkIdx == NULL) ? 0 : pCommith->readh.pBlkIdx->numOfBlocks;
H
Hongze Cheng 已提交
750 751 752
  TSKEY   nextKey = tsdbNextIterKey(pIter->pIter);
  int     cidx = 0;
  void *  ptr = NULL;
H
Hongze Cheng 已提交
753 754 755
  SBlock *pBlock;

  if (cidx < nBlocks) {
H
Hongze Cheng 已提交
756
    pBlock = pCommith->readh.pBlkInfo->blocks + cidx;
H
Hongze Cheng 已提交
757 758 759
  } else {
    pBlock = NULL;
  }
H
Hongze Cheng 已提交
760

H
Hongze Cheng 已提交
761
  while (true) {
H
Hongze Cheng 已提交
762
    if ((nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey) && (pBlock == NULL)) break;
H
Hongze Cheng 已提交
763

H
Hongze Cheng 已提交
764
    if ((nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey) ||
H
Hongze Cheng 已提交
765
        (pBlock && (!pBlock->last) && tsdbComparKeyBlock((void *)(&nextKey), pBlock) > 0)) {
H
Hongze Cheng 已提交
766
      if (tsdbMoveBlock(pCommith, cidx) < 0) {
H
more  
Hongze Cheng 已提交
767 768
        TSDB_RUNLOCK_TABLE(pIter->pTable);
        return -1;
H
Hongze Cheng 已提交
769 770
      }

H
Hongze Cheng 已提交
771
      cidx++;
H
Hongze Cheng 已提交
772
      if (cidx < nBlocks) {
H
Hongze Cheng 已提交
773
        pBlock = pCommith->readh.pBlkInfo->blocks + cidx;
H
Hongze Cheng 已提交
774 775 776
      } else {
        pBlock = NULL;
      }
H
Hongze Cheng 已提交
777
    } else if ((cidx < nBlocks) && (pBlock->last || tsdbComparKeyBlock((void *)(&nextKey), pBlock) == 0)) {
H
Hongze Cheng 已提交
778
      if (tsdbMergeMemData(pCommith, pIter, cidx) < 0) {
H
Hongze Cheng 已提交
779 780 781 782
        TSDB_RUNLOCK_TABLE(pIter->pTable);
        return -1;
      }

H
Hongze Cheng 已提交
783
      cidx++;
H
Hongze Cheng 已提交
784
      if (cidx < nBlocks) {
H
Hongze Cheng 已提交
785
        pBlock = pCommith->readh.pBlkInfo->blocks + cidx;
H
Hongze Cheng 已提交
786 787 788 789
      } else {
        pBlock = NULL;
      }
      nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
790 791
    } else {
      if (pBlock == NULL) {
H
Hongze Cheng 已提交
792
        if (tsdbCommitMemData(pCommith, pIter, pCommith->maxKey, false) < 0) {
H
Hongze Cheng 已提交
793 794 795 796
          TSDB_RUNLOCK_TABLE(pIter->pTable);
          return -1;
        }
        nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
797
      } else {
H
Hongze Cheng 已提交
798
        if (tsdbCommitMemData(pCommith, pIter, pBlock->keyFirst - 1, true) < 0) {
H
Hongze Cheng 已提交
799 800 801 802
          TSDB_RUNLOCK_TABLE(pIter->pTable);
          return -1;
        }
        nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
803 804
      }
    }
H
Hongze Cheng 已提交
805
  }
H
Hongze Cheng 已提交
806
#endif
H
Hongze Cheng 已提交
807 808 809

  TSDB_RUNLOCK_TABLE(pIter->pTable);

H
Hongze Cheng 已提交
810
  if (tsdbWriteBlockInfo(pCommith) < 0) return -1;
H
Hongze Cheng 已提交
811 812 813 814

  return 0;
}

H
Hongze Cheng 已提交
815 816 817 818 819 820 821 822 823 824 825 826
static int tsdbSetCommitTable(SCommitH *pCommith, STable *pTable) {
  STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1);

  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;
    }
H
Hongze Cheng 已提交
827 828
  } else {
    pCommith->readh.pBlkIdx = NULL;
H
Hongze Cheng 已提交
829
  }
H
Hongze Cheng 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
  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
Hongze Cheng 已提交
846
static int tsdbWriteBlock(SCommitH *pCommith, SDFile *pDFile, SDataCols *pDataCols, SBlock *pBlock, bool isLast,
H
Hongze Cheng 已提交
847
                          bool isSuper) {
H
Hongze Cheng 已提交
848 849 850
  STsdbRepo * pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg *  pCfg = REPO_CFG(pRepo);
  SBlockData *pBlockData;
H
Hongze Cheng 已提交
851
  int64_t     offset = 0;
H
Hongze Cheng 已提交
852
  STable *    pTable = TSDB_COMMIT_TABLE(pCommith);
H
Hongze Cheng 已提交
853 854 855
  int         rowsToWrite = pDataCols->numOfRows;

  ASSERT(rowsToWrite > 0 && rowsToWrite <= pCfg->maxRowsPerFileBlock);
H
Hongze Cheng 已提交
856
  ASSERT((!isLast) || rowsToWrite < pCfg->minRowsPerFileBlock);
H
Hongze Cheng 已提交
857

H
Hongze Cheng 已提交
858 859
  // Seek file
  offset = tsdbSeekDFile(pDFile, 0, SEEK_END);
H
Hongze Cheng 已提交
860
  if (offset < 0) {
H
Hongze Cheng 已提交
861 862 863 864 865 866
    return -1;
  }

  // Make buffer space
  if (tsdbMakeRoom((void **)(&TSDB_COMMIT_BUF(pCommith)), TSDB_BLOCK_STATIS_SIZE(pDataCols->numOfCols)) < 0) {
    return -1;
H
Hongze Cheng 已提交
867
  }
H
Hongze Cheng 已提交
868
  pBlockData = (SBlockData *)TSDB_COMMIT_BUF(pCommith);
H
Hongze Cheng 已提交
869

H
Hongze Cheng 已提交
870
  // Get # of cols not all NULL(not including key column)
H
Hongze Cheng 已提交
871 872 873
  int nColsNotAllNull = 0;
  for (int ncol = 1; ncol < pDataCols->numOfCols; ncol++) {  // ncol from 1, we skip the timestamp column
    SDataCol * pDataCol = pDataCols->cols + ncol;
H
Hongze Cheng 已提交
874
    SBlockCol *pBlockCol = pBlockData->cols + nColsNotAllNull;
H
Hongze Cheng 已提交
875 876 877 878 879

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

H
Hongze Cheng 已提交
880
    memset(pBlockCol, 0, sizeof(*pBlockCol));
H
Hongze Cheng 已提交
881

H
Hongze Cheng 已提交
882 883
    pBlockCol->colId = pDataCol->colId;
    pBlockCol->type = pDataCol->type;
H
Hongze Cheng 已提交
884
    if (tDataTypeDesc[pDataCol->type].getStatisFunc) {
H
Hongze Cheng 已提交
885 886 887
      (*tDataTypeDesc[pDataCol->type].getStatisFunc)(pDataCol->pData, rowsToWrite, &(pBlockCol->min), &(pBlockCol->max),
                                                     &(pBlockCol->sum), &(pBlockCol->minIndex), &(pBlockCol->maxIndex),
                                                     &(pBlockCol->numOfNull));
H
Hongze Cheng 已提交
888 889 890 891 892 893 894
    }
    nColsNotAllNull++;
  }

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

  // Compress the data if neccessary
H
Hongze Cheng 已提交
895
  int     tcol = 0;  // counter of not all NULL and written columns
H
Hongze Cheng 已提交
896
  int32_t toffset = 0;
H
Hongze Cheng 已提交
897
  int32_t tsize = TSDB_BLOCK_STATIS_SIZE(nColsNotAllNull);
H
Hongze Cheng 已提交
898 899 900
  int32_t lsize = tsize;
  int32_t keyLen = 0;
  for (int ncol = 0; ncol < pDataCols->numOfCols; ncol++) {
H
Hongze Cheng 已提交
901
    // All not NULL columns finish
H
Hongze Cheng 已提交
902 903 904
    if (ncol != 0 && tcol >= nColsNotAllNull) break;

    SDataCol * pDataCol = pDataCols->cols + ncol;
H
Hongze Cheng 已提交
905
    SBlockCol *pBlockCol = pBlockData->cols + tcol;
H
Hongze Cheng 已提交
906

H
Hongze Cheng 已提交
907
    if (ncol != 0 && (pDataCol->colId != pBlockCol->colId)) continue;
H
Hongze Cheng 已提交
908

H
Hongze Cheng 已提交
909
    int32_t flen;  // final length
H
Hongze Cheng 已提交
910
    int32_t tlen = dataColGetNEleLen(pDataCol, rowsToWrite);
H
Hongze Cheng 已提交
911
    void *  tptr;
H
Hongze Cheng 已提交
912

H
Hongze Cheng 已提交
913 914 915 916 917 918
    // Make room
    if (tsdbMakeRoom((void **)TSDB_COMMIT_BUF(pCommith), lsize + tlen + COMP_OVERFLOW_BYTES + sizeof(TSCKSUM)) < 0) {
      return -1;
    }
    pBlockData = (SBlockData *)TSDB_COMMIT_BUF(pCommith);
    tptr = POINTER_SHIFT(pBlockData, lsize);
H
Hongze Cheng 已提交
919

H
Hongze Cheng 已提交
920 921 922 923 924 925 926 927 928 929
    if (pCfg->compression == TWO_STAGE_COMP &&
        tsdbMakeRoom((void **)TSDB_COMMIT_COMP_BUF(pCommith), tlen + COMP_OVERFLOW_BYTES) < 0) {
      return -1;
    }

    // Compress or just copy
    if (pCfg->compression) {
      flen = (*(tDataTypeDesc[pDataCol->type].compFunc))((char *)pDataCol->pData, tlen, rowsToWrite, tptr,
                                                         tlen + COMP_OVERFLOW_BYTES, pCfg->compression,
                                                         TSDB_COMMIT_COMP_BUF(pCommith), tlen + COMP_OVERFLOW_BYTES);
H
Hongze Cheng 已提交
930 931 932 933 934 935 936 937 938
    } else {
      flen = tlen;
      memcpy(tptr, pDataCol->pData, flen);
    }

    // Add checksum
    ASSERT(flen > 0);
    flen += sizeof(TSCKSUM);
    taosCalcChecksumAppend(0, (uint8_t *)tptr, flen);
H
Hongze Cheng 已提交
939
    tsdbUpdateDFileMagic(pDFile, POINTER_SHIFT(tptr, flen - sizeof(TSCKSUM)));
H
Hongze Cheng 已提交
940 941

    if (ncol != 0) {
H
Hongze Cheng 已提交
942 943
      pBlockCol->offset = toffset;
      pBlockCol->len = flen;
H
Hongze Cheng 已提交
944 945 946 947 948 949 950 951 952
      tcol++;
    } else {
      keyLen = flen;
    }

    toffset += flen;
    lsize += flen;
  }

H
Hongze Cheng 已提交
953 954 955
  pBlockData->delimiter = TSDB_FILE_DELIMITER;
  pBlockData->uid = TABLE_UID(pTable);
  pBlockData->numOfCols = nColsNotAllNull;
H
Hongze Cheng 已提交
956

H
Hongze Cheng 已提交
957 958
  taosCalcChecksumAppend(0, (uint8_t *)pBlockData, tsize);
  tsdbUpdateDFileMagic(pDFile, POINTER_SHIFT(pBlockData, tsize - sizeof(TSCKSUM)));
H
Hongze Cheng 已提交
959 960

  // Write the whole block to file
H
Hongze Cheng 已提交
961
  if (tsdbWriteDFile(pDFile, (void *)pBlockData, lsize) < lsize) {
H
Hongze Cheng 已提交
962
    return -1;
H
Hongze Cheng 已提交
963 964 965 966 967 968 969 970 971 972 973 974
  }

  // 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);
H
Hongze Cheng 已提交
975 976 977
  pBlock->keyLast = dataColsKeyLast(pDataCols);

  pDFile->info.size += pBlock->len;
H
Hongze Cheng 已提交
978 979 980

  tsdbDebug("vgId:%d tid:%d a block of data is written to file %s, offset %" PRId64
            " numOfRows %d len %d numOfCols %" PRId16 " keyFirst %" PRId64 " keyLast %" PRId64,
H
Hongze Cheng 已提交
981 982
            REPO_ID(pRepo), TABLE_TID(pTable), TSDB_FILE_FULL_NAME(pDFile), offset, rowsToWrite, pBlock->len,
            pBlock->numOfCols, pBlock->keyFirst, pBlock->keyLast);
H
Hongze Cheng 已提交
983 984 985 986 987 988 989

  return 0;
}

static int tsdbWriteBlockInfo(SCommitH *pCommih) {
  SDFile *pHeadf = TSDB_COMMIT_HEAD_FILE(pCommih);

H
Hongze Cheng 已提交
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 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 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  SBlockIdx   blkIdx;
  STable *    pTable = TSDB_COMMIT_TABLE(pCommih);
  SBlock *    pBlock;
  size_t      nSupBlocks;
  size_t      nSubBlocks;
  uint32_t    tlen;
  SBlockInfo *pBlkInfo;
  int64_t     offset;

  nSupBlocks = taosArrayGetSize(pCommih->aSupBlk);
  nSubBlocks = taosArrayGetSize(pCommih->aSubBlk);
  tlen = sizeof(SBlockInfo) + sizeof(SBlock) * (nSupBlocks + nSubBlocks) + sizeof(TSCKSUM);

  ASSERT(nSupBlocks > 0);

  // Write SBlockInfo part
  if (tsdbMakeRoom((void **)(&(TSDB_COMMIT_BUF(pCommih))), tlen) < 0) return -1;
  pBlkInfo = TSDB_COMMIT_BUF(pCommih);

  pBlkInfo->delimiter = TSDB_FILE_DELIMITER;
  pBlkInfo->tid = TABLE_TID(pTable);
  pBlkInfo->uid = TABLE_UID(pTable);

  memcpy((void *)(pBlkInfo->blocks), taosArrayGet(pCommih->aSupBlk, 0), nSupBlocks * sizeof(SBlock));
  if (nSubBlocks > 0) {
    memcpy((void *)(pBlkInfo->blocks + nSupBlocks), taosArrayGet(pCommih->aSubBlk, 0), nSubBlocks * sizeof(SBlock));

    for (int i = 0; i < nSupBlocks; i++) {
      pBlock = pBlkInfo->blocks + i;

      if (pBlock->numOfSubBlocks > 1) {
        pBlock->offset += (sizeof(SBlockInfo) + sizeof(SBlock) * nSupBlocks);
      }
    }
  }

  taosCalcChecksumAppend(0, (uint8_t *)pBlkInfo, tlen);

  offset = tsdbSeekDFile(pHeadf, 0, SEEK_END);
  if (offset < 0) {
    tsdbError("vgId:%d failed to write block info part to file %s while seek since %s", TSDB_COMMIT_REPO_ID(pCommih),
              TSDB_FILE_FULL_NAME(pHeadf), tstrerror(terrno));
    return -1;
  }

  if (tsdbWriteDFile(pHeadf, TSDB_COMMIT_BUF(pCommih), tlen) < tlen) {
    tsdbError("vgId:%d failed to write block info part to file %s since %s", TSDB_COMMIT_REPO_ID(pCommih),
              TSDB_FILE_FULL_NAME(pHeadf), tstrerror(terrno));
    return -1;
  }

  tsdbUpdateDFileMagic(pHeadf, POINTER_SHIFT(pBlkInfo, tlen - sizeof(TSCKSUM)));

  // Set blkIdx
  pBlock = taosArrayGet(pCommih->aSupBlk, nSupBlocks - 1);

  blkIdx.tid = TABLE_TID(pTable);
  blkIdx.uid = TABLE_UID(pTable);
  blkIdx.hasLast = pBlock->last ? 1 : 0;
  blkIdx.maxKey = pBlock->keyLast;
  blkIdx.numOfBlocks = nSupBlocks;
  blkIdx.len = tlen;
  blkIdx.offset = (uint32_t)offset;

  ASSERT(blkIdx.numOfBlocks > 0);

  if (taosArrayPush(pCommih->aBlkIdx, (void *)(&blkIdx)) == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  return 0;
}

static int tsdbWriteBlockIdx(SCommitH *pCommih) {
  SBlockIdx *pBlkIdx;
  SDFile *   pHeadf = TSDB_COMMIT_HEAD_FILE(pCommih);
  size_t     nidx = taosArrayGetSize(pCommih->aBlkIdx);
  int        tlen = 0, size;
  int64_t    offset;

  ASSERT(nidx > 0);

  for (size_t i = 0; i < nidx; i++) {
    pBlkIdx = (SBlockIdx *)taosArrayGet(pCommih->aBlkIdx, i);

    size = tsdbEncodeSBlockIdx(NULL, pBlkIdx);
    if (tsdbMakeRoom((void **)(&TSDB_COMMIT_BUF(pCommih)), tlen + size) < 0) return -1;

    void *ptr = POINTER_SHIFT(TSDB_COMMIT_BUF(pCommih), tlen);
    tsdbEncodeSBlockIdx(&ptr, pBlkIdx);

    tlen += size;
  }

  tlen += sizeof(TSCKSUM);
  if (tsdbMakeRoom((void **)(&TSDB_COMMIT_BUF(pCommih)), tlen) < 0) return -1;
  taosCalcChecksumAppend(0, (uint8_t *)TSDB_COMMIT_BUF(pCommih), tlen);

  if (tsdbAppendDFile(pHeadf, TSDB_COMMIT_BUF(pCommih), tlen, &offset) < tlen) {
    tsdbError("vgId:%d failed to write block index part to file %s since %s", TSDB_COMMIT_REPO_ID(pCommih),
              TSDB_FILE_FULL_NAME(pHeadf), tstrerror(terrno));
    return -1;
  }

  tsdbUpdateDFileMagic(pHeadf, POINTER_SHIFT(TSDB_COMMIT_BUF(pCommih), tlen - sizeof(TSCKSUM)));
  pHeadf->info.offset = offset;
  pHeadf->info.len = tlen;
H
Hongze Cheng 已提交
1098

H
Hongze Cheng 已提交
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 1131 1132 1133 1134 1135
  return 0;
}

static int tsdbCommitMemData(SCommitH *pCommith, SCommitIter *pIter, TSKEY keyLimit, bool toData) {
  STsdbRepo *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;

  while (true) {
    tsdbLoadDataFromCache(pIter->pTable, pIter->pIter, keyLimit, defaultRows, pCommith->pDataCols, NULL, 0,
                          pCfg->update, &mInfo);

    if (pCommith->pDataCols->numOfRows <= 0) break;

    if (toData || pCommith->pDataCols->numOfRows >= pCfg->minRowsPerFileBlock) {
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
      isLast = false;
    } else {
      pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
      isLast = true;
    }

    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, isLast, true) < 0) return -1;

    if (taosArrayPush(pCommith->aSupBlk, (void *)(&block)) == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
  }

  return 0;
}

H
Hongze Cheng 已提交
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 1165 1166 1167 1168 1169
static int tsdbMergeMemData(SCommitH *pCommith, SCommitIter *pIter, int bidx) {
  STsdbRepo *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;
  int16_t    colId = 0;
  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;
  }

  SSkipListIterator titer = *(pIter->pIter);
  if (tsdbLoadBlockDataCols(&(pCommith->readh), pBlock, NULL, &colId, 1) < 0) return -1;

  tsdbLoadDataFromCache(pIter->pTable, &titer, keyLimit, INT32_MAX, NULL, pCommith->readh.pDCols[0]->cols[0].pData,
                        pCommith->readh.pDCols[0]->numOfRows, pCfg->update, &mInfo);

  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;
H
Hongze Cheng 已提交
1170
  } else if (tsdbCanAddSubBlock(pCommith, pBlock, &mInfo)) {
H
Hongze Cheng 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    // 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);
    }

    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, pBlock->last, false) < 0) return -1;

    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, pBlock->numOfSubBlocks + 1) < 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 已提交
1204 1205 1206 1207
  return 0;
}

static int tsdbMoveBlock(SCommitH *pCommith, int bidx) {
H
Hongze Cheng 已提交
1208
  SBlock *pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
H
Hongze Cheng 已提交
1209
  SDFile *pCommitF = (pBlock->last) ? TSDB_COMMIT_LAST_FILE(pCommith) : TSDB_COMMIT_DATA_FILE(pCommith);
H
Hongze Cheng 已提交
1210
  // SDFile *pReadF = (pBlock->last) ? TSDB_READ_LAST_FILE(&(pCommith->readh)) : TSDB_READ_DATA_FILE(&(pCommith->readh));
H
Hongze Cheng 已提交
1211 1212
  SBlock  block;

H
Hongze Cheng 已提交
1213
  if ((pBlock->last && pCommith->isLFileSame) || ((!pBlock->last) && pCommith->isDFileSame)) {
H
Hongze Cheng 已提交
1214
    if (pBlock->numOfSubBlocks == 1) {
H
Hongze Cheng 已提交
1215
      if (tsdbCommitAddBlock(pCommith, pBlock, NULL, 0) < 0) return -1;
H
Hongze Cheng 已提交
1216 1217
    } else {
      block = *pBlock;
H
Hongze Cheng 已提交
1218
      block.offset = sizeof(SBlock) * taosArrayGetSize(pCommith->aSupBlk);
H
Hongze Cheng 已提交
1219

H
Hongze Cheng 已提交
1220 1221
      if (tsdbCommitAddBlock(pCommith, &block, POINTER_SHIFT(pCommith->readh.pBlkInfo, pBlock->offset),
                             pBlock->numOfSubBlocks) < 0) {
H
Hongze Cheng 已提交
1222 1223 1224 1225 1226 1227
        return -1;
      }
    }
  } else {
    if (tsdbLoadBlockData(&(pCommith->readh), pBlock, NULL) < 0) return -1;
    if (tsdbWriteBlock(pCommith, pCommitF, pCommith->readh.pDCols[0], &block, pBlock->last, true) < 0) return -1;
H
Hongze Cheng 已提交
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) return -1;
  }

  return 0;
}

static int tsdbCommitAddBlock(SCommitH *pCommith, const SBlock *pSupBlock, const SBlock *pSubBlocks, int nSubBlocks) {
  ASSERT(pSupBlock != NULL);

  if (taosArrayPush(pCommith->aSupBlk, pSupBlock) < 0) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  if (pSubBlocks && taosArrayPushBatch(pCommith->aSupBlk, pSubBlocks, nSubBlocks) < 0) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
H
Hongze Cheng 已提交
1245 1246
  }

H
Hongze Cheng 已提交
1247
  return 0;
H
Hongze Cheng 已提交
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 1281
}

static int tsdbMergeBlockData(SCommitH *pCommith, SCommitIter *pIter, SDataCols *pDataCols, TSKEY keyLimit, bool isLastOneBlock) {
  STsdbRepo *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg * pCfg = REPO_CFG(pRepo);
  SBlock     block;
  SDFile *   pDFile;
  bool       isLast;
  int32_t    defaultRows = TSDB_COMMIT_DEFAULT_ROWS(pCommith);

  int biter = 0;
  while (true) {
    tsdbLoadAndMergeFromCache(pCommith->readh.pDCols[0], &biter, pIter, pCommith->pDataCols, keyLimit, defaultRows,
                              pCfg->update);

    if (pCommith->pDataCols->numOfRows == 0) break;

    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;
    }

    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, isLast, true) < 0) return -1;
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) return -1;
  }

H
Hongze Cheng 已提交
1282
  return 0;
H
Hongze Cheng 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
}

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;

  ASSERT(maxRows > 0 && dataColsKeyLast(pDataCols) <= maxKey);
  tdResetDataCols(pTarget);

  while (true) {
    key1 = (*iter >= pDataCols->numOfRows) ? INT64_MAX : dataColsKeyAt(pDataCols, *iter);
    bool isRowDel = false;
    SDataRow row = tsdbNextIterRow(pCommitIter->pIter);
    if (row == NULL || dataRowKey(row) > maxKey) {
      key2 = INT64_MAX;
    } else {
      key2 = dataRowKey(row);
      isRowDel = dataRowDeleted(row);
    }

    if (key1 == INT64_MAX && key2 == INT64_MAX) break;

    if (key1 < key2) {
      for (int i = 0; i < pDataCols->numOfCols; i++) {
        dataColAppendVal(pTarget->cols + i, tdGetColDataOfRow(pDataCols->cols + i, *iter), pTarget->numOfRows,
                         pTarget->maxPoints);
      }

      pTarget->numOfRows++;
      (*iter)++;
    } else if (key1 > key2) {
      if (!isRowDel) {
        if (pSchema == NULL || schemaVersion(pSchema) != dataRowVersion(row)) {
          pSchema = tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, dataRowVersion(row));
          ASSERT(pSchema != NULL);
        }

        tdAppendDataRowToDataCol(row, pSchema, pTarget);
      }

      tSkipListIterNext(pCommitIter->pIter);
    } else {
      if (update) {
        if (!isRowDel) {
          if (pSchema == NULL || schemaVersion(pSchema) != dataRowVersion(row)) {
            pSchema = tsdbGetTableSchemaImpl(pCommitIter->pTable, false, false, dataRowVersion(row));
            ASSERT(pSchema != NULL);
          }

          tdAppendDataRowToDataCol(row, pSchema, pTarget);
        }
      } else {
        ASSERT(!isRowDel);

        for (int i = 0; i < pDataCols->numOfCols; i++) {
          dataColAppendVal(pTarget->cols + i, tdGetColDataOfRow(pDataCols->cols + i, *iter), pTarget->numOfRows,
                           pTarget->maxPoints);
        }

        pTarget->numOfRows++;
      }
      (*iter)++;
      tSkipListIterNext(pCommitIter->pIter);
    }

    if (pTarget->numOfRows >= maxRows) break;
  }
H
Hongze Cheng 已提交
1352 1353 1354
}

static void tsdbResetCommitFile(SCommitH *pCommith) {
H
Hongze Cheng 已提交
1355 1356 1357
  pCommith->isRFileSet = false;
  pCommith->isDFileSame = false;
  pCommith->isLFileSame = false;
H
Hongze Cheng 已提交
1358 1359 1360 1361 1362 1363 1364 1365 1366
  taosArrayClear(pCommith->aBlkIdx);
}

static void tsdbResetCommitTable(SCommitH *pCommith) {
  tdResetDataCols(pCommith->pDataCols);
  taosArrayClear(pCommith->aSubBlk);
  taosArrayClear(pCommith->aSupBlk);
}

H
Hongze Cheng 已提交
1367 1368
static int tsdbSetAndOpenCommitFile(SCommitH *pCommith, SDFileSet *pSet, int fid) {
  int        level, id;
H
Hongze Cheng 已提交
1369
  SDiskID    did;
H
Hongze Cheng 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
  SDFileSet *pWSet = TSDB_COMMIT_WRITE_FSET(pCommith);

  tfsAllocDisk(tsdbGetFidLevel(fid, &(pCommith->rtn)), &level, &id);
  if (level == TFS_UNDECIDED_LEVEL) {
    terrno = TSDB_CODE_TDB_NO_AVAIL_DISK;
    return -1;
  }

  // Open read FSET
  if (pSet) {
    if (tsdbSetAndOpenReadFSet(&(pCommith->readh), pSet) < 0) {
H
Hongze Cheng 已提交
1381 1382 1383
      return -1;
    }

H
Hongze Cheng 已提交
1384 1385 1386 1387 1388
    pCommith->isRFileSet = true;

    if (tsdbLoadBlockIdx(&(pCommith->readh)) < 0) {
      tsdbCloseAndUnsetFSet(&(pCommith->readh));
    }
H
Hongze Cheng 已提交
1389
    return -1;
H
Hongze Cheng 已提交
1390 1391 1392 1393 1394 1395 1396
  } else {
    pCommith->isRFileSet = false;
  }

  // Set and open commit FSET
  if (pSet == NULL || level > TSDB_FSET_LEVEL(pSet)) {
    // Create new FSET
H
Hongze Cheng 已提交
1397 1398 1399
    did.level = level;
    did.id = id;
    tsdbInitDFileSet(pWSet, did, TSDB_COMMIT_REPO_ID(pCommith), fid, pCommith->version);
H
Hongze Cheng 已提交
1400 1401 1402

    if (tsdbOpenDFileSet(pWSet, O_WRONLY | O_CREAT) < 0) {
      for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
H
Hongze Cheng 已提交
1403
        remove(TSDB_FILE_FULL_NAME(TSDB_DFILE_IN_SET(pWSet, ftype)));
H
Hongze Cheng 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
      }

      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
      }
      return -1;
    }

    if (tsdbUpdateDFileSetHeader(pWSet) < 0) {
      tsdbCloseDFileSet(pWSet);

      for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
H
Hongze Cheng 已提交
1416
        remove(TSDB_FILE_FULL_NAME(TSDB_DFILE_IN_SET(pWSet, ftype)));
H
Hongze Cheng 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
      }

      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
      }

      return -1;
    }

    // TODO: update  file info;
  } else {
    level = TSDB_FSET_LEVEL(pSet);
    id = TSDB_FSET_ID(pSet);

    // TSDB_FILE_HEAD
    SDFile *pWHeadf = TSDB_COMMIT_HEAD_FILE(pCommith);
H
Hongze Cheng 已提交
1433 1434 1435 1436
    did.level = level;
    did.id = id;
    tsdbInitDFile(pWHeadf, did, TSDB_COMMIT_REPO_ID(pCommith), fid, pCommith->version, TSDB_FILE_HEAD);
    if (tsdbCreateDFile(pWHeadf) < 0) {
H
Hongze Cheng 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
        return -1;
      }
    }

    // TSDB_FILE_DATA
    SDFile *pRDataf = TSDB_READ_DATA_FILE(&(pCommith->readh));
    SDFile *pWDataf = TSDB_COMMIT_DATA_FILE(pCommith);
H
Hongze Cheng 已提交
1446
    tsdbInitDFileEx(pWHeadf, pRDataf);
H
Hongze Cheng 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    if (tsdbOpenDFile(pWDataf, O_WRONLY) < 0) {
      tsdbCloseDFile(pWHeadf);
      remove(TSDB_FILE_FULL_NAME(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) {
H
Hongze Cheng 已提交
1461
      tsdbInitDFileEx(pWLastf, pRLastf);
H
Hongze Cheng 已提交
1462 1463
      pCommith->isLFileSame = true;
    } else {
H
Hongze Cheng 已提交
1464
      tsdbInitDFile(pWLastf, did, TSDB_COMMIT_REPO_ID(pCommith), fid, pCommith->version, TSDB_FILE_LAST);
H
Hongze Cheng 已提交
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
      pCommith->isLFileSame = false;
    }
    if (tsdbOpenDFile(pWLastf, O_WRONLY) < 0) {
      tsdbCloseDFile(pWDataf);
      tsdbCloseDFile(pWHeadf);
      remove(TSDB_FILE_FULL_NAME(pWHeadf));
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
        return -1;
      }
    }
H
Hongze Cheng 已提交
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  }

  return 0;
}

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

  if (!hasError) {
    for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
      SDFile *pDFile = TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(pCommith), ftype);
      fsync(TSDB_FILE_FD(pDFile));
    }
  }
  tsdbCloseDFileSet(TSDB_COMMIT_WRITE_FSET(pCommith));
H
Hongze Cheng 已提交
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
}

static bool tsdbCanAddSubBlock(SCommitH *pCommith, SBlock *pBlock, SMergeInfo *pInfo) {
  STsdbRepo *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg * pCfg = REPO_CFG(pRepo);
  int        mergeRows = pBlock->numOfRows + pInfo->rowsInserted - pInfo->rowsDeleteSucceed;

  ASSERT(mergeRows > 0);

  if (pBlock->numOfSubBlocks < TSDB_MAX_SUBBLOCKS && pInfo->nOperations <= pCfg->maxRowsPerFileBlock) {
    if (pBlock->last) {
      if (pCommith->isLFileSame && mergeRows < pCfg->minRowsPerFileBlock) return true;
    } else {
      if (mergeRows < pCfg->maxRowsPerFileBlock) return true;
    }
  }

  return false;
H
Hongze Cheng 已提交
1511
}