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

S
TD-1207  
Shengliang Guan 已提交
16
#include "os.h"
H
Hongze Cheng 已提交
17
#include "tsdbint.h"
S
TD-1207  
Shengliang Guan 已提交
18
#include <regex.h>
H
Hongze Cheng 已提交
19

H
Hongze Cheng 已提交
20 21
typedef enum { TSDB_TXN_TEMP_FILE = 0, TSDB_TXN_CURR_FILE } TSDB_TXN_FILE_T;
static const char *tsdbTxnFname[] = {"current.t", "current"};
H
Hongze Cheng 已提交
22
#define TSDB_MAX_FSETS(keep, days) ((keep) / (days) + 3)
H
Hongze Cheng 已提交
23

H
Hongze Cheng 已提交
24 25
static int  tsdbComparFidFSet(const void *arg1, const void *arg2);
static void tsdbResetFSStatus(SFSStatus *pStatus);
H
Hongze Cheng 已提交
26
static int  tsdbSaveFSStatus(SFSStatus *pStatus, int vid);
H
Hongze Cheng 已提交
27
static void tsdbApplyFSTxnOnDisk(SFSStatus *pFrom, SFSStatus *pTo);
H
Hongze Cheng 已提交
28 29 30
static void tsdbGetTxnFname(int repoid, TSDB_TXN_FILE_T ftype, char fname[]);
static int  tsdbOpenFSFromCurrent(STsdbRepo *pRepo);
static int  tsdbScanAndTryFixFS(STsdbRepo *pRepo);
31 32 33
static int  tsdbScanRootDir(STsdbRepo *pRepo);
static int  tsdbScanDataDir(STsdbRepo *pRepo);
static bool tsdbIsTFileInFS(STsdbFS *pfs, const TFILE *pf);
H
Hongze Cheng 已提交
34
static int  tsdbRestoreCurrent(STsdbRepo *pRepo);
H
Hongze Cheng 已提交
35
static int  tsdbComparTFILE(const void *arg1, const void *arg2);
36 37 38
static void tsdbScanAndTryFixDFilesHeader(STsdbRepo *pRepo, int32_t *nExpired);
static int  tsdbProcessExpiredFS(STsdbRepo *pRepo);
static int  tsdbCreateMeta(STsdbRepo *pRepo);
H
Hongze Cheng 已提交
39

40
// For backward compatibility
H
Hongze Cheng 已提交
41 42 43 44 45 46 47 48 49 50
// ================== CURRENT file header info
static int tsdbEncodeFSHeader(void **buf, SFSHeader *pHeader) {
  int tlen = 0;

  tlen += taosEncodeFixedU32(buf, pHeader->version);
  tlen += taosEncodeFixedU32(buf, pHeader->len);

  return tlen;
}

H
Hongze Cheng 已提交
51
static void *tsdbDecodeFSHeader(void *buf, SFSHeader *pHeader) {
H
Hongze Cheng 已提交
52 53
  buf = taosDecodeFixedU32(buf, &(pHeader->version));
  buf = taosDecodeFixedU32(buf, &(pHeader->len));
H
Hongze Cheng 已提交
54 55 56 57 58 59 60 61

  return buf;
}

// ================== STsdbFSMeta
static int tsdbEncodeFSMeta(void **buf, STsdbFSMeta *pMeta) {
  int tlen = 0;

H
Hongze Cheng 已提交
62
  tlen += taosEncodeFixedU32(buf, pMeta->version);
H
Hongze Cheng 已提交
63 64 65 66 67 68
  tlen += taosEncodeFixedI64(buf, pMeta->totalPoints);
  tlen += taosEncodeFixedI64(buf, pMeta->totalStorage);

  return tlen;
}

H
Hongze Cheng 已提交
69
static void *tsdbDecodeFSMeta(void *buf, STsdbFSMeta *pMeta) {
H
Hongze Cheng 已提交
70
  buf = taosDecodeFixedU32(buf, &(pMeta->version));
H
Hongze Cheng 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  buf = taosDecodeFixedI64(buf, &(pMeta->totalPoints));
  buf = taosDecodeFixedI64(buf, &(pMeta->totalStorage));

  return buf;
}

// ================== SFSStatus
static int tsdbEncodeDFileSetArray(void **buf, SArray *pArray) {
  int      tlen = 0;
  uint64_t nset = taosArrayGetSize(pArray);

  tlen += taosEncodeFixedU64(buf, nset);
  for (size_t i = 0; i < nset; i++) {
    SDFileSet *pSet = taosArrayGet(pArray, i);

    tlen += tsdbEncodeDFileSet(buf, pSet);
  }

  return tlen;
}

H
Hongze Cheng 已提交
92
static void *tsdbDecodeDFileSetArray(void *buf, SArray *pArray) {
H
Hongze Cheng 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106
  uint64_t  nset;
  SDFileSet dset;

  taosArrayClear(pArray);

  buf = taosDecodeFixedU64(buf, &nset);
  for (size_t i = 0; i < nset; i++) {
    buf = tsdbDecodeDFileSet(buf, &dset);
    taosArrayPush(pArray, (void *)(&dset));
  }
  return buf;
}

static int tsdbEncodeFSStatus(void **buf, SFSStatus *pStatus) {
H
Hongze Cheng 已提交
107 108
  ASSERT(pStatus->pmf);

H
Hongze Cheng 已提交
109 110
  int tlen = 0;

H
Hongze Cheng 已提交
111
  tlen += tsdbEncodeSMFile(buf, pStatus->pmf);
H
Hongze Cheng 已提交
112 113 114 115 116
  tlen += tsdbEncodeDFileSetArray(buf, pStatus->df);

  return tlen;
}

H
Hongze Cheng 已提交
117
static void *tsdbDecodeFSStatus(void *buf, SFSStatus *pStatus) {
H
Hongze Cheng 已提交
118 119 120 121 122
  tsdbResetFSStatus(pStatus);

  pStatus->pmf = &(pStatus->mf);

  buf = tsdbDecodeSMFile(buf, pStatus->pmf);
H
Hongze Cheng 已提交
123 124 125 126 127 128 129 130 131 132 133 134
  buf = tsdbDecodeDFileSetArray(buf, pStatus->df);

  return buf;
}

static SFSStatus *tsdbNewFSStatus(int maxFSet) {
  SFSStatus *pStatus = (SFSStatus *)calloc(1, sizeof(*pStatus));
  if (pStatus == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }

H
Hongze Cheng 已提交
135
  TSDB_FILE_SET_CLOSED(&(pStatus->mf));
H
Hongze Cheng 已提交
136

H
Hongze Cheng 已提交
137
  pStatus->df = taosArrayInit(maxFSet, sizeof(SDFileSet));
H
Hongze Cheng 已提交
138
  if (pStatus->df == NULL) {
H
Hongze Cheng 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    free(pStatus);
    return NULL;
  }

  return pStatus;
}

static SFSStatus *tsdbFreeFSStatus(SFSStatus *pStatus) {
  if (pStatus) {
    pStatus->df = taosArrayDestroy(pStatus->df);
    free(pStatus);
  }

  return NULL;
}

static void tsdbResetFSStatus(SFSStatus *pStatus) {
  if (pStatus == NULL) {
    return;
  }

H
Hongze Cheng 已提交
161
  TSDB_FILE_SET_CLOSED(&(pStatus->mf));
H
Hongze Cheng 已提交
162

H
Hongze Cheng 已提交
163
  pStatus->pmf = NULL;
H
Hongze Cheng 已提交
164 165 166
  taosArrayClear(pStatus->df);
}

H
Hongze Cheng 已提交
167
static void tsdbSetStatusMFile(SFSStatus *pStatus, const SMFile *pMFile) {
H
refact  
Hongze Cheng 已提交
168
  ASSERT(pStatus->pmf == NULL);
H
Hongze Cheng 已提交
169 170

  pStatus->pmf = &(pStatus->mf);
S
TD-1207  
Shengliang Guan 已提交
171
  tsdbInitMFileEx(pStatus->pmf, (SMFile *)pMFile);
H
Hongze Cheng 已提交
172 173 174
}

static int tsdbAddDFileSetToStatus(SFSStatus *pStatus, const SDFileSet *pSet) {
H
Hongze Cheng 已提交
175
  if (taosArrayPush(pStatus->df, (void *)pSet) == NULL) {
H
Hongze Cheng 已提交
176 177 178 179
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

H
refact  
Hongze Cheng 已提交
180 181
  TSDB_FSET_SET_CLOSED(((SDFileSet *)taosArrayGetLast(pStatus->df)));

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

H
Hongze Cheng 已提交
185
// ================== STsdbFS
H
Hongze Cheng 已提交
186 187 188
STsdbFS *tsdbNewFS(STsdbCfg *pCfg) {
  int      keep = pCfg->keep;
  int      days = pCfg->daysPerFile;
H
Hongze Cheng 已提交
189 190 191 192 193
  int      maxFSet = TSDB_MAX_FSETS(keep, days);
  STsdbFS *pfs;

  pfs = (STsdbFS *)calloc(1, sizeof(*pfs));
  if (pfs == NULL) {
H
Hongze Cheng 已提交
194 195 196 197
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }

H
Hongze Cheng 已提交
198
  int code = pthread_rwlock_init(&(pfs->lock), NULL);
H
Hongze Cheng 已提交
199 200
  if (code) {
    terrno = TAOS_SYSTEM_ERROR(code);
H
Hongze Cheng 已提交
201
    free(pfs);
H
Hongze Cheng 已提交
202 203 204
    return NULL;
  }

H
Hongze Cheng 已提交
205 206 207
  pfs->cstatus = tsdbNewFSStatus(maxFSet);
  if (pfs->cstatus == NULL) {
    tsdbFreeFS(pfs);
H
Hongze Cheng 已提交
208 209 210
    return NULL;
  }

H
Hongze Cheng 已提交
211 212
  pfs->metaCache = taosHashInit(4096, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
  if (pfs->metaCache == NULL) {
H
Hongze Cheng 已提交
213
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
H
Hongze Cheng 已提交
214
    tsdbFreeFS(pfs);
H
Hongze Cheng 已提交
215 216 217
    return NULL;
  }

218
  pfs->intxn = false;
219
  pfs->metaCacheComp = NULL;
220

H
Hongze Cheng 已提交
221 222 223
  pfs->nstatus = tsdbNewFSStatus(maxFSet);
  if (pfs->nstatus == NULL) {
    tsdbFreeFS(pfs);
H
Hongze Cheng 已提交
224 225 226
    return NULL;
  }

H
Hongze Cheng 已提交
227
  return pfs;
H
Hongze Cheng 已提交
228 229
}

H
Hongze Cheng 已提交
230 231 232 233 234 235 236
void *tsdbFreeFS(STsdbFS *pfs) {
  if (pfs) {
    pfs->nstatus = tsdbFreeFSStatus(pfs->nstatus);
    taosHashCleanup(pfs->metaCache);
    pfs->metaCache = NULL;
    pfs->cstatus = tsdbFreeFSStatus(pfs->cstatus);
    pthread_rwlock_destroy(&(pfs->lock));
H
Hongze Cheng 已提交
237
    free(pfs);
H
Hongze Cheng 已提交
238
  }
H
Hongze Cheng 已提交
239

H
Hongze Cheng 已提交
240 241 242
  return NULL;
}

243 244 245
static int tsdbProcessExpiredFS(STsdbRepo *pRepo) {
  tsdbStartFSTxn(pRepo, 0, 0);
  if (tsdbCreateMeta(pRepo) < 0) {
K
Kaili Xu 已提交
246
    tsdbError("vgId:%d failed to create meta since %s", REPO_ID(pRepo), tstrerror(terrno));
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
    return -1;
  }

  if (tsdbApplyRtn(pRepo) < 0) {
    tsdbEndFSTxnWithError(REPO_FS(pRepo));
    tsdbError("vgId:%d failed to apply rtn since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
  }
  if (tsdbEndFSTxn(pRepo) < 0) {
    tsdbError("vgId:%d failed to end fs txn since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
  }
  return 0;
}

static int tsdbCreateMeta(STsdbRepo *pRepo) {
  STsdbFS *pfs = REPO_FS(pRepo);
  SMFile * pOMFile = pfs->cstatus->pmf;
  SMFile   mf;
  SDiskID  did;

  if (pOMFile != NULL) {
    // keep the old meta file
    tsdbUpdateMFile(pfs, pOMFile);
    return 0;
  }

  // Create a new meta file
  did.level = TFS_PRIMARY_LEVEL;
  did.id = TFS_PRIMARY_ID;
  tsdbInitMFile(&mf, did, REPO_ID(pRepo), FS_TXN_VERSION(REPO_FS(pRepo)));

  if (tsdbCreateMFile(&mf, true) < 0) {
    tsdbError("vgId:%d failed to create META file since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
  }

  tsdbInfo("vgId:%d meta file %s is created", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(&mf));

  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);
    return -1;
  }

  TSDB_FILE_FSYNC(&mf);
  tsdbCloseMFile(&mf);
  tsdbUpdateMFile(pfs, &mf);

  return 0;
}

H
Hongze Cheng 已提交
299
int tsdbOpenFS(STsdbRepo *pRepo) {
H
refact  
Hongze Cheng 已提交
300 301
  STsdbFS *pfs = REPO_FS(pRepo);
  char     current[TSDB_FILENAME_LEN] = "\0";
302
  int      nExpired = 0;
H
Hongze Cheng 已提交
303 304 305 306 307

  ASSERT(pfs != NULL);

  tsdbGetTxnFname(REPO_ID(pRepo), TSDB_TXN_CURR_FILE, current);

308
  tsdbGetRtnSnap(pRepo, &pRepo->rtn);
H
Hongze Cheng 已提交
309 310 311 312 313
  if (access(current, F_OK) == 0) {
    if (tsdbOpenFSFromCurrent(pRepo) < 0) {
      tsdbError("vgId:%d failed to open FS since %s", REPO_ID(pRepo), tstrerror(terrno));
      return -1;
    }
H
Hongze Cheng 已提交
314

315 316 317 318
    tsdbScanAndTryFixDFilesHeader(pRepo, &nExpired);
    if (nExpired > 0) {
      tsdbProcessExpiredFS(pRepo);
    }
H
refact  
Hongze Cheng 已提交
319
  } else {
320
    // should skip expired fileset inside of the function
H
refact  
Hongze Cheng 已提交
321 322 323 324 325 326 327 328 329
    if (tsdbRestoreCurrent(pRepo) < 0) {
      tsdbError("vgId:%d failed to restore current file since %s", REPO_ID(pRepo), tstrerror(terrno));
      return -1;
    }
  }

  if (tsdbScanAndTryFixFS(pRepo) < 0) {
    tsdbError("vgId:%d failed to scan and fix FS since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
H
Hongze Cheng 已提交
330
  }
H
Hongze Cheng 已提交
331

H
Hongze Cheng 已提交
332
  // Load meta cache if has meta file
H
Hongze Cheng 已提交
333
  if ((!(pRepo->state & TSDB_STATE_BAD_META)) && tsdbLoadMetaCache(pRepo, true) < 0) {
H
Hongze Cheng 已提交
334 335
    tsdbError("vgId:%d failed to open FS while loading meta cache since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
H
Hongze Cheng 已提交
336 337
  }

H
Hongze Cheng 已提交
338 339 340
  return 0;
}

H
Hongze Cheng 已提交
341
void tsdbCloseFS(STsdbRepo *pRepo) {
H
refact  
Hongze Cheng 已提交
342
  // Do nothing
H
Hongze Cheng 已提交
343 344
}

H
Hongze Cheng 已提交
345
// Start a new transaction to modify the file system
H
Hongze Cheng 已提交
346 347
void tsdbStartFSTxn(STsdbRepo *pRepo, int64_t pointsAdd, int64_t storageAdd) {
  STsdbFS *pfs = REPO_FS(pRepo);
H
Hongze Cheng 已提交
348
  ASSERT(pfs->intxn == false);
H
Hongze Cheng 已提交
349

H
Hongze Cheng 已提交
350 351
  pfs->intxn = true;
  tsdbResetFSStatus(pfs->nstatus);
H
Hongze Cheng 已提交
352
  pfs->nstatus->meta = pfs->cstatus->meta;
H
Hongze Cheng 已提交
353 354 355 356 357
  if (pfs->cstatus->pmf == NULL) {
    pfs->nstatus->meta.version = 0;
  } else {
    pfs->nstatus->meta.version = pfs->cstatus->meta.version + 1;
  }
H
Hongze Cheng 已提交
358
  pfs->nstatus->meta.totalPoints = pfs->cstatus->meta.totalPoints + pointsAdd;
H
Hongze Cheng 已提交
359
  pfs->nstatus->meta.totalStorage = pfs->cstatus->meta.totalStorage += storageAdd;
H
Hongze Cheng 已提交
360
}
H
Hongze Cheng 已提交
361

H
Hongze Cheng 已提交
362 363
void tsdbUpdateFSTxnMeta(STsdbFS *pfs, STsdbFSMeta *pMeta) { pfs->nstatus->meta = *pMeta; }

H
Hongze Cheng 已提交
364 365
int tsdbEndFSTxn(STsdbRepo *pRepo) {
  STsdbFS *pfs = REPO_FS(pRepo);
H
Hongze Cheng 已提交
366 367
  ASSERT(FS_IN_TXN(pfs));
  SFSStatus *pStatus;
H
Hongze Cheng 已提交
368

H
Hongze Cheng 已提交
369
  // Write current file system snapshot
H
Hongze Cheng 已提交
370
  if (tsdbSaveFSStatus(pfs->nstatus, REPO_ID(pRepo)) < 0) {
H
Hongze Cheng 已提交
371
    tsdbEndFSTxnWithError(pfs);
H
Hongze Cheng 已提交
372 373
    return -1;
  }
H
Hongze Cheng 已提交
374

H
Hongze Cheng 已提交
375 376 377 378 379 380
  // Make new 
  tsdbWLockFS(pfs);
  pStatus = pfs->cstatus;
  pfs->cstatus = pfs->nstatus;
  pfs->nstatus = pStatus;
  tsdbUnLockFS(pfs);
H
Hongze Cheng 已提交
381

H
Hongze Cheng 已提交
382
  // Apply actual change to each file and SDFileSet
H
Hongze Cheng 已提交
383
  tsdbApplyFSTxnOnDisk(pfs->nstatus, pfs->cstatus);
H
Hongze Cheng 已提交
384

H
Hongze Cheng 已提交
385
  pfs->intxn = false;
H
Hongze Cheng 已提交
386 387 388
  return 0;
}

H
Hongze Cheng 已提交
389
int tsdbEndFSTxnWithError(STsdbFS *pfs) {
H
Hongze Cheng 已提交
390 391
  tsdbApplyFSTxnOnDisk(pfs->nstatus, pfs->cstatus);
  // TODO: if mf change, reload pfs->metaCache
H
Hongze Cheng 已提交
392 393
  pfs->intxn = false;
  return 0;
H
Hongze Cheng 已提交
394 395
}

H
Hongze Cheng 已提交
396
void tsdbUpdateMFile(STsdbFS *pfs, const SMFile *pMFile) { tsdbSetStatusMFile(pfs->nstatus, pMFile); }
H
Hongze Cheng 已提交
397

H
Hongze Cheng 已提交
398
int tsdbUpdateDFileSet(STsdbFS *pfs, const SDFileSet *pSet) { return tsdbAddDFileSetToStatus(pfs->nstatus, pSet); }
H
Hongze Cheng 已提交
399

H
Hongze Cheng 已提交
400
static int tsdbSaveFSStatus(SFSStatus *pStatus, int vid) {
H
Hongze Cheng 已提交
401 402 403 404
  SFSHeader fsheader;
  void *    pBuf = NULL;
  void *    ptr;
  char      hbuf[TSDB_FILE_HEAD_SIZE] = "\0";
H
Hongze Cheng 已提交
405 406
  char      tfname[TSDB_FILENAME_LEN] = "\0";
  char      cfname[TSDB_FILENAME_LEN] = "\0";
H
Hongze Cheng 已提交
407

H
Hongze Cheng 已提交
408 409
  tsdbGetTxnFname(vid, TSDB_TXN_TEMP_FILE, tfname);
  tsdbGetTxnFname(vid, TSDB_TXN_CURR_FILE, cfname);
H
Hongze Cheng 已提交
410

S
Shengliang Guan 已提交
411
  int fd = open(tfname, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0755);
H
Hongze Cheng 已提交
412 413
  if (fd < 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
H
Hongze Cheng 已提交
414 415 416
    return -1;
  }

H
Hongze Cheng 已提交
417
  fsheader.version = TSDB_FS_VERSION;
H
Hongze Cheng 已提交
418 419
  if (pStatus->pmf == NULL) {
    ASSERT(taosArrayGetSize(pStatus->df) == 0);
H
Hongze Cheng 已提交
420 421
    fsheader.len = 0;
  } else {
H
Hongze Cheng 已提交
422
    fsheader.len = tsdbEncodeFSStatus(NULL, pStatus) + sizeof(TSCKSUM);
H
Hongze Cheng 已提交
423 424
  }

H
Hongze Cheng 已提交
425 426 427
  // Encode header part and write
  ptr = hbuf;
  tsdbEncodeFSHeader(&ptr, &fsheader);
H
Hongze Cheng 已提交
428
  tsdbEncodeFSMeta(&ptr, &(pStatus->meta));
H
Hongze Cheng 已提交
429

H
Hongze Cheng 已提交
430
  taosCalcChecksumAppend(0, (uint8_t *)hbuf, TSDB_FILE_HEAD_SIZE);
H
Hongze Cheng 已提交
431

H
Hongze Cheng 已提交
432 433 434
  if (taosWrite(fd, hbuf, TSDB_FILE_HEAD_SIZE) < TSDB_FILE_HEAD_SIZE) {
    terrno = TAOS_SYSTEM_ERROR(errno);
    close(fd);
H
Hongze Cheng 已提交
435
    remove(tfname);
H
Hongze Cheng 已提交
436 437 438
    return -1;
  }

H
Hongze Cheng 已提交
439 440 441 442
  // Encode file status and write to file
  if (fsheader.len > 0) {
    if (tsdbMakeRoom(&(pBuf), fsheader.len) < 0) {
      close(fd);
H
Hongze Cheng 已提交
443
      remove(tfname);
H
Hongze Cheng 已提交
444
      return -1;
H
Hongze Cheng 已提交
445 446
    }

H
Hongze Cheng 已提交
447
    ptr = pBuf;
H
Hongze Cheng 已提交
448
    tsdbEncodeFSStatus(&ptr, pStatus);
H
Hongze Cheng 已提交
449
    taosCalcChecksumAppend(0, (uint8_t *)pBuf, fsheader.len);
H
Hongze Cheng 已提交
450

H
Hongze Cheng 已提交
451 452 453
    if (taosWrite(fd, pBuf, fsheader.len) < fsheader.len) {
      terrno = TAOS_SYSTEM_ERROR(errno);
      close(fd);
454
      (void)remove(tfname);
H
Hongze Cheng 已提交
455
      taosTZfree(pBuf);
H
Hongze Cheng 已提交
456 457 458 459
      return -1;
    }
  }

H
Hongze Cheng 已提交
460
  // fsync, close and rename
S
TD-4088  
Shengliang Guan 已提交
461
  if (taosFsync(fd) < 0) {
H
Hongze Cheng 已提交
462 463
    terrno = TAOS_SYSTEM_ERROR(errno);
    close(fd);
H
Hongze Cheng 已提交
464
    remove(tfname);
H
Hongze Cheng 已提交
465 466
    taosTZfree(pBuf);
    return -1;
H
Hongze Cheng 已提交
467
  }
H
Hongze Cheng 已提交
468

H
Hongze Cheng 已提交
469
  (void)close(fd);
S
Shengliang Guan 已提交
470
  (void)taosRename(tfname, cfname);
H
Hongze Cheng 已提交
471
  taosTZfree(pBuf);
H
Hongze Cheng 已提交
472

H
Hongze Cheng 已提交
473 474
  return 0;
}
H
Hongze Cheng 已提交
475

H
Hongze Cheng 已提交
476
static void tsdbApplyFSTxnOnDisk(SFSStatus *pFrom, SFSStatus *pTo) {
H
Hongze Cheng 已提交
477 478 479 480 481
  int        ifrom = 0;
  int        ito = 0;
  size_t     sizeFrom, sizeTo;
  SDFileSet *pSetFrom;
  SDFileSet *pSetTo;
H
Hongze Cheng 已提交
482

H
Hongze Cheng 已提交
483 484
  sizeFrom = taosArrayGetSize(pFrom->df);
  sizeTo = taosArrayGetSize(pTo->df);
H
Hongze Cheng 已提交
485

H
Hongze Cheng 已提交
486
  // Apply meta file change
487
  (void)tsdbApplyMFileChange(pFrom->pmf, pTo->pmf);
H
Hongze Cheng 已提交
488

H
Hongze Cheng 已提交
489 490 491
  // Apply SDFileSet change
  if (ifrom >= sizeFrom) {
    pSetFrom = NULL;
H
Hongze Cheng 已提交
492
  } else {
H
Hongze Cheng 已提交
493
    pSetFrom = taosArrayGet(pFrom->df, ifrom);
H
Hongze Cheng 已提交
494 495
  }

H
Hongze Cheng 已提交
496 497 498 499 500
  if (ito >= sizeTo) {
    pSetTo = NULL;
  } else {
    pSetTo = taosArrayGet(pTo->df, ito);
  }
H
Hongze Cheng 已提交
501

H
Hongze Cheng 已提交
502 503
  while (true) {
    if ((pSetTo == NULL) && (pSetFrom == NULL)) break;
H
Hongze Cheng 已提交
504

H
Hongze Cheng 已提交
505 506
    if (pSetTo == NULL || (pSetFrom && pSetFrom->fid < pSetTo->fid)) {
      tsdbApplyDFileSetChange(pSetFrom, NULL);
H
Hongze Cheng 已提交
507

H
Hongze Cheng 已提交
508 509 510 511 512 513 514 515
      ifrom++;
      if (ifrom >= sizeFrom) {
        pSetFrom = NULL;
      } else {
        pSetFrom = taosArrayGet(pFrom->df, ifrom);
      }
    } else if (pSetFrom == NULL || pSetFrom->fid > pSetTo->fid) {
      // Do nothing
H
Hongze Cheng 已提交
516 517 518 519 520
      ito++;
      if (ito >= sizeTo) {
        pSetTo = NULL;
      } else {
        pSetTo = taosArrayGet(pTo->df, ito);
H
Hongze Cheng 已提交
521 522 523
      }
    } else {
      tsdbApplyDFileSetChange(pSetFrom, pSetTo);
H
Hongze Cheng 已提交
524

H
Hongze Cheng 已提交
525 526 527 528 529 530
      ifrom++;
      if (ifrom >= sizeFrom) {
        pSetFrom = NULL;
      } else {
        pSetFrom = taosArrayGet(pFrom->df, ifrom);
      }
H
Hongze Cheng 已提交
531

H
Hongze Cheng 已提交
532 533 534 535 536 537 538 539
      ito++;
      if (ito >= sizeTo) {
        pSetTo = NULL;
      } else {
        pSetTo = taosArrayGet(pTo->df, ito);
      }
    }
  }
H
Hongze Cheng 已提交
540 541
}

H
Hongze Cheng 已提交
542 543 544 545 546
// ================== SFSIter
// ASSUMPTIONS: the FS Should be read locked when calling these functions
void tsdbFSIterInit(SFSIter *pIter, STsdbFS *pfs, int direction) {
  pIter->pfs = pfs;
  pIter->direction = direction;
H
Hongze Cheng 已提交
547

H
Hongze Cheng 已提交
548
  size_t size = taosArrayGetSize(pfs->cstatus->df);
H
Hongze Cheng 已提交
549

H
Hongze Cheng 已提交
550
  pIter->version = pfs->cstatus->meta.version;
H
Hongze Cheng 已提交
551

H
Hongze Cheng 已提交
552 553 554 555 556 557 558
  if (size == 0) {
    pIter->index = -1;
    pIter->fid = TSDB_IVLD_FID;
  } else {
    if (direction == TSDB_FS_ITER_FORWARD) {
      pIter->index = 0;
    } else {
S
TD-1207  
Shengliang Guan 已提交
559
      pIter->index = (int)(size - 1);
H
Hongze Cheng 已提交
560
    }
H
Hongze Cheng 已提交
561

H
Hongze Cheng 已提交
562
    pIter->fid = ((SDFileSet *)taosArrayGet(pfs->cstatus->df, pIter->index))->fid;
H
Hongze Cheng 已提交
563 564 565
  }
}

H
Hongze Cheng 已提交
566 567 568
void tsdbFSIterSeek(SFSIter *pIter, int fid) {
  STsdbFS *pfs = pIter->pfs;
  size_t   size = taosArrayGetSize(pfs->cstatus->df);
H
Hongze Cheng 已提交
569

H
Hongze Cheng 已提交
570 571 572 573 574
  int flags;
  if (pIter->direction == TSDB_FS_ITER_FORWARD) {
    flags = TD_GE;
  } else {
    flags = TD_LE;
H
Hongze Cheng 已提交
575 576
  }

H
Hongze Cheng 已提交
577
  void *ptr = taosbsearch(&fid, pfs->cstatus->df->pData, size, sizeof(SDFileSet), tsdbComparFidFSet, flags);
H
Hongze Cheng 已提交
578 579 580 581
  if (ptr == NULL) {
    pIter->index = -1;
    pIter->fid = TSDB_IVLD_FID;
  } else {
S
TD-1207  
Shengliang Guan 已提交
582
    pIter->index = (int)(TARRAY_ELEM_IDX(pfs->cstatus->df, ptr));
H
Hongze Cheng 已提交
583
    pIter->fid = ((SDFileSet *)ptr)->fid;
H
Hongze Cheng 已提交
584 585 586
  }
}

H
Hongze Cheng 已提交
587 588 589
SDFileSet *tsdbFSIterNext(SFSIter *pIter) {
  STsdbFS *  pfs = pIter->pfs;
  SDFileSet *pSet;
H
Hongze Cheng 已提交
590

H
Hongze Cheng 已提交
591 592
  if (pIter->index < 0) {
    ASSERT(pIter->fid == TSDB_IVLD_FID);
H
Hongze Cheng 已提交
593 594 595
    return NULL;
  }

H
Hongze Cheng 已提交
596
  ASSERT(pIter->fid != TSDB_IVLD_FID);
H
Hongze Cheng 已提交
597

H
Hongze Cheng 已提交
598
  if (pIter->version != pfs->cstatus->meta.version) {
599
    pIter->version = pfs->cstatus->meta.version;
H
Hongze Cheng 已提交
600
    tsdbFSIterSeek(pIter, pIter->fid);
H
Hongze Cheng 已提交
601 602
  }

H
Hongze Cheng 已提交
603 604
  if (pIter->index < 0) {
    return NULL;
H
Hongze Cheng 已提交
605 606
  }

H
Hongze Cheng 已提交
607 608
  pSet = (SDFileSet *)taosArrayGet(pfs->cstatus->df, pIter->index);
  ASSERT(pSet->fid == pIter->fid);
H
Hongze Cheng 已提交
609

H
Hongze Cheng 已提交
610 611 612 613
  if (pIter->direction == TSDB_FS_ITER_FORWARD) {
    pIter->index++;
    if (pIter->index >= taosArrayGetSize(pfs->cstatus->df)) {
      pIter->index = -1;
H
Hongze Cheng 已提交
614 615
    }
  } else {
H
Hongze Cheng 已提交
616
    pIter->index--;
H
Hongze Cheng 已提交
617 618
  }

H
Hongze Cheng 已提交
619
  if (pIter->index >= 0) {
H
Hongze Cheng 已提交
620
    pIter->fid = ((SDFileSet *)taosArrayGet(pfs->cstatus->df, pIter->index))->fid;
H
Hongze Cheng 已提交
621
  } else {
H
Hongze Cheng 已提交
622
    pIter->fid = TSDB_IVLD_FID;
H
Hongze Cheng 已提交
623 624
  }

H
Hongze Cheng 已提交
625
  return pSet;
H
Hongze Cheng 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638
}

static int tsdbComparFidFSet(const void *arg1, const void *arg2) {
  int        fid = *(int *)arg1;
  SDFileSet *pSet = (SDFileSet *)arg2;

  if (fid < pSet->fid) {
    return -1;
  } else if (fid == pSet->fid) {
    return 0;
  } else {
    return 1;
  }
H
Hongze Cheng 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
}

static void tsdbGetTxnFname(int repoid, TSDB_TXN_FILE_T ftype, char fname[]) {
  snprintf(fname, TSDB_FILENAME_LEN, "%s/vnode/vnode%d/tsdb/%s", TFS_PRIMARY_PATH(), repoid, tsdbTxnFname[ftype]);
}

static int tsdbOpenFSFromCurrent(STsdbRepo *pRepo) {
  STsdbFS * pfs = REPO_FS(pRepo);
  int       fd = -1;
  void *    buffer = NULL;
  SFSHeader fsheader;
  char      current[TSDB_FILENAME_LEN] = "\0";
  void *    ptr;

  tsdbGetTxnFname(REPO_ID(pRepo), TSDB_TXN_CURR_FILE, current);

  // current file exists, try to recover
S
Shengliang Guan 已提交
656
  fd = open(current, O_RDONLY | O_BINARY);
H
Hongze Cheng 已提交
657 658 659 660 661 662 663 664 665 666
  if (fd < 0) {
    tsdbError("vgId:%d failed to open file %s since %s", REPO_ID(pRepo), current, strerror(errno));
    terrno = TAOS_SYSTEM_ERROR(errno);
    goto _err;
  }

  if (tsdbMakeRoom(&buffer, TSDB_FILE_HEAD_SIZE) < 0) {
    goto _err;
  }

S
TD-1207  
Shengliang Guan 已提交
667
  int nread = (int)taosRead(fd, buffer, TSDB_FILE_HEAD_SIZE);
H
Hongze Cheng 已提交
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
  if (nread < 0) {
    tsdbError("vgId:%d failed to read %d bytes from file %s since %s", REPO_ID(pRepo), TSDB_FILENAME_LEN, current,
              strerror(errno));
    terrno = TAOS_SYSTEM_ERROR(errno);
    goto _err;
  }

  if (nread < TSDB_FILE_HEAD_SIZE) {
    tsdbError("vgId:%d failed to read header of file %s, read bytes:%d", REPO_ID(pRepo), current, nread);
    terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
    goto _err;
  }

  if (!taosCheckChecksumWhole((uint8_t *)buffer, TSDB_FILE_HEAD_SIZE)) {
    tsdbError("vgId:%d header of file %s failed checksum check", REPO_ID(pRepo), current);
    terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
    goto _err;
  }

H
Hongze Cheng 已提交
687
  SFSStatus *pStatus = pfs->cstatus;
H
Hongze Cheng 已提交
688 689
  ptr = buffer;
  ptr = tsdbDecodeFSHeader(ptr, &fsheader);
H
Hongze Cheng 已提交
690
  ptr = tsdbDecodeFSMeta(ptr, &(pStatus->meta));
H
Hongze Cheng 已提交
691 692 693 694 695 696 697 698 699 700

  if (fsheader.version != TSDB_FS_VERSION) {
    // TODO: handle file version change
  }

  if (fsheader.len > 0) {
    if (tsdbMakeRoom(&buffer, fsheader.len) < 0) {
      goto _err;
    }

S
TD-1207  
Shengliang Guan 已提交
701
    nread = (int)taosRead(fd, buffer, fsheader.len);
H
Hongze Cheng 已提交
702 703 704 705 706 707 708 709 710 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 740 741 742 743
    if (nread < 0) {
      tsdbError("vgId:%d failed to read file %s since %s", REPO_ID(pRepo), current, strerror(errno));
      terrno = TAOS_SYSTEM_ERROR(errno);
      goto _err;
    }

    if (nread < fsheader.len) {
      tsdbError("vgId:%d failed to read %d bytes from file %s", REPO_ID(pRepo), fsheader.len, current);
      terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
      goto _err;
    }

    if (!taosCheckChecksumWhole((uint8_t *)buffer, fsheader.len)) {
      tsdbError("vgId:%d file %s is corrupted since wrong checksum", REPO_ID(pRepo), current);
      terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
      goto _err;
    }

    ptr = buffer;
    ptr = tsdbDecodeFSStatus(ptr, pStatus);
  } else {
    tsdbResetFSStatus(pStatus);
  }

  taosTZfree(buffer);
  close(fd);

  return 0;

_err:
  if (fd >= 0) {
    close(fd);
  }
  taosTZfree(buffer);
  return -1;
}

// Scan and try to fix incorrect files
static int tsdbScanAndTryFixFS(STsdbRepo *pRepo) {
  STsdbFS *  pfs = REPO_FS(pRepo);
  SFSStatus *pStatus = pfs->cstatus;

H
Hongze Cheng 已提交
744 745 746
  if (tsdbScanAndTryFixMFile(pRepo) < 0) {
    tsdbError("vgId:%d failed to fix MFile since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
H
Hongze Cheng 已提交
747 748 749 750 751 752 753
  }

  size_t size = taosArrayGetSize(pStatus->df);

  for (size_t i = 0; i < size; i++) {
    SDFileSet *pSet = (SDFileSet *)taosArrayGet(pStatus->df, i);

H
Hongze Cheng 已提交
754
    if (tsdbScanAndTryFixDFileSet(pRepo, pSet) < 0) {
H
Hongze Cheng 已提交
755 756 757 758 759
      tsdbError("vgId:%d failed to fix MFile since %s", REPO_ID(pRepo), tstrerror(terrno));
      return -1;
    }
  }

H
Hongze Cheng 已提交
760
  // remove those unused files
761 762
  tsdbScanRootDir(pRepo);
  tsdbScanDataDir(pRepo);
H
Hongze Cheng 已提交
763 764 765
  return 0;
}

H
Hongze Cheng 已提交
766
int tsdbLoadMetaCache(STsdbRepo *pRepo, bool recoverMeta) {
H
Hongze Cheng 已提交
767 768 769 770 771 772 773 774 775
  char      tbuf[128];
  STsdbFS * pfs = REPO_FS(pRepo);
  SMFile    mf;
  SMFile *  pMFile = &mf;
  void *    pBuf = NULL;
  SKVRecord rInfo;
  int64_t   maxBufSize = 0;
  SMFInfo   minfo;

776
  taosHashClear(pfs->metaCache);
H
refact  
Hongze Cheng 已提交
777

H
Hongze Cheng 已提交
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  // No meta file, just return
  if (pfs->cstatus->pmf == NULL) return 0;

  mf = pfs->cstatus->mf;
  // Load cache first
  if (tsdbOpenMFile(pMFile, O_RDONLY) < 0) {
    return -1;
  }

  if (tsdbLoadMFileHeader(pMFile, &minfo) < 0) {
    tsdbCloseMFile(pMFile);
    return -1;
  }

  while (true) {
    int64_t tsize = tsdbReadMFile(pMFile, tbuf, sizeof(SKVRecord));
    if (tsize == 0) break;
H
refact  
Hongze Cheng 已提交
795 796 797 798 799 800

    if (tsize < 0) {
      tsdbError("vgId:%d failed to read META file since %s", REPO_ID(pRepo), tstrerror(terrno));
      return -1;
    }

H
Hongze Cheng 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    if (tsize < sizeof(SKVRecord)) {
      tsdbError("vgId:%d failed to read %" PRIzu " bytes from file %s", REPO_ID(pRepo), sizeof(SKVRecord),
                TSDB_FILE_FULL_NAME(pMFile));
      terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
      tsdbCloseMFile(pMFile);
      return -1;
    }

    void *ptr = tsdbDecodeKVRecord(tbuf, &rInfo);
    ASSERT(POINTER_DISTANCE(ptr, tbuf) == sizeof(SKVRecord));
    // ASSERT((rInfo.offset > 0) ? (pStore->info.size == rInfo.offset) : true);

    if (rInfo.offset < 0) {
      taosHashRemove(pfs->metaCache, (void *)(&rInfo.uid), sizeof(rInfo.uid));
#if 0
      pStore->info.size += sizeof(SKVRecord);
      pStore->info.nRecords--;
      pStore->info.nDels++;
      pStore->info.tombSize += (rInfo.size + sizeof(SKVRecord) * 2);
#endif
    } else {
      ASSERT(rInfo.offset > 0 && rInfo.size > 0);
      if (taosHashPut(pfs->metaCache, (void *)(&rInfo.uid), sizeof(rInfo.uid), &rInfo, sizeof(rInfo)) < 0) {
        tsdbError("vgId:%d failed to load meta cache from file %s since OOM", REPO_ID(pRepo),
                  TSDB_FILE_FULL_NAME(pMFile));
        terrno = TSDB_CODE_COM_OUT_OF_MEMORY;
        tsdbCloseMFile(pMFile);
        return -1;
      }

      maxBufSize = MAX(maxBufSize, rInfo.size);

      if (tsdbSeekMFile(pMFile, rInfo.size, SEEK_CUR) < 0) {
        tsdbError("vgId:%d failed to lseek file %s since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pMFile),
                  tstrerror(terrno));
        tsdbCloseMFile(pMFile);
        return -1;
      }

#if 0
      pStore->info.size += (sizeof(SKVRecord) + rInfo.size);
      pStore->info.nRecords++;
#endif
    }
  }

  if (recoverMeta) {
S
TD-1207  
Shengliang Guan 已提交
848
    pBuf = malloc((size_t)maxBufSize);
H
Hongze Cheng 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    if (pBuf == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      tsdbCloseMFile(pMFile);
      return -1;
    }

    SKVRecord *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));
        tfree(pBuf);
        tsdbCloseMFile(pMFile);
        return -1;
      }

S
TD-1207  
Shengliang Guan 已提交
865
      int nread = (int)tsdbReadMFile(pMFile, pBuf, pRecord->size);
H
Hongze Cheng 已提交
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
      if (nread < 0) {
        tsdbError("vgId:%d failed to read file %s since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pMFile),
                  tstrerror(terrno));
        tfree(pBuf);
        tsdbCloseMFile(pMFile);
        return -1;
      }

      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);
        terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
        tfree(pBuf);
        tsdbCloseMFile(pMFile);
        return -1;
      }

S
TD-1207  
Shengliang Guan 已提交
883
      if (tsdbRestoreTable(pRepo, pBuf, (int)pRecord->size) < 0) {
H
Hongze Cheng 已提交
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
        tsdbError("vgId:%d failed to restore table, uid %" PRId64 ", since %s" PRIu64, REPO_ID(pRepo), pRecord->uid,
                  tstrerror(terrno));
        tfree(pBuf);
        tsdbCloseMFile(pMFile);
        return -1;
      }

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

    tsdbOrgMeta(pRepo);
  }

  tsdbCloseMFile(pMFile);
  tfree(pBuf);
H
Hongze Cheng 已提交
899
  return 0;
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
}

static int tsdbScanRootDir(STsdbRepo *pRepo) {
  char         rootDir[TSDB_FILENAME_LEN];
  char         bname[TSDB_FILENAME_LEN];
  STsdbFS *    pfs = REPO_FS(pRepo);
  const TFILE *pf;

  tsdbGetRootDir(REPO_ID(pRepo), rootDir);
  TDIR *tdir = tfsOpendir(rootDir);
  if (tdir == NULL) {
    tsdbError("vgId:%d failed to open directory %s since %s", REPO_ID(pRepo), rootDir, tstrerror(terrno));
    return -1;
  }

  while ((pf = tfsReaddir(tdir))) {
    tfsbasename(pf, bname);

    if (strcmp(bname, tsdbTxnFname[TSDB_TXN_CURR_FILE]) == 0 || strcmp(bname, "data") == 0) {
      // Skip current file and data directory
      continue;
    }

H
Hongze Cheng 已提交
923
    if (pfs->cstatus->pmf && tfsIsSameFile(pf, &(pfs->cstatus->pmf->f))) {
924 925 926
      continue;
    }

927
    (void)tfsremove(pf);
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
    tsdbDebug("vgId:%d invalid file %s is removed", REPO_ID(pRepo), TFILE_NAME(pf));
  }

  tfsClosedir(tdir);

  return 0;
}

static int tsdbScanDataDir(STsdbRepo *pRepo) {
  char         dataDir[TSDB_FILENAME_LEN];
  char         bname[TSDB_FILENAME_LEN];
  STsdbFS *    pfs = REPO_FS(pRepo);
  const TFILE *pf;

  tsdbGetDataDir(REPO_ID(pRepo), dataDir);
  TDIR *tdir = tfsOpendir(dataDir);
  if (tdir == NULL) {
    tsdbError("vgId:%d failed to open directory %s since %s", REPO_ID(pRepo), dataDir, tstrerror(terrno));
    return -1;
  }

  while ((pf = tfsReaddir(tdir))) {
    tfsbasename(pf, bname);

    if (!tsdbIsTFileInFS(pfs, pf)) {
953
      (void)tfsremove(pf);
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
      tsdbDebug("vgId:%d invalid file %s is removed", REPO_ID(pRepo), TFILE_NAME(pf));
    }
  }

  tfsClosedir(tdir);

  return 0;
}

static bool tsdbIsTFileInFS(STsdbFS *pfs, const TFILE *pf) {
  SFSIter fsiter;
  tsdbFSIterInit(&fsiter, pfs, TSDB_FS_ITER_FORWARD);
  SDFileSet *pSet;

  while ((pSet = tsdbFSIterNext(&fsiter))) {
    for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
      SDFile *pDFile = TSDB_DFILE_IN_SET(pSet, ftype);
      if (tfsIsSameFile(pf, TSDB_FILE_F(pDFile))) {
        return true;
      }
    }
  }

  return false;
H
Hongze Cheng 已提交
978 979
}

H
Hongze Cheng 已提交
980
static int tsdbRestoreMeta(STsdbRepo *pRepo) {
H
Hongze Cheng 已提交
981
  char         rootDir[TSDB_FILENAME_LEN];
H
Hongze Cheng 已提交
982
  char         bname[TSDB_FILENAME_LEN];
H
Hongze Cheng 已提交
983 984
  TDIR *       tdir = NULL;
  const TFILE *pf = NULL;
H
Hongze Cheng 已提交
985 986 987 988 989 990 991
  const char * pattern = "^meta(-ver[0-9]+)?$";
  regex_t      regex;
  STsdbFS *    pfs = REPO_FS(pRepo);

  regcomp(&regex, pattern, REG_EXTENDED);

  tsdbInfo("vgId:%d try to restore meta", REPO_ID(pRepo));
H
Hongze Cheng 已提交
992 993

  tsdbGetRootDir(REPO_ID(pRepo), rootDir);
H
Hongze Cheng 已提交
994

H
Hongze Cheng 已提交
995 996 997
  tdir = tfsOpendir(rootDir);
  if (tdir == NULL) {
    tsdbError("vgId:%d failed to open dir %s since %s", REPO_ID(pRepo), rootDir, tstrerror(terrno));
H
Hongze Cheng 已提交
998
    regfree(&regex);
H
Hongze Cheng 已提交
999 1000 1001 1002 1003
    return -1;
  }

  while ((pf = tfsReaddir(tdir))) {
    tfsbasename(pf, bname);
H
Hongze Cheng 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012

    if (strcmp(bname, "data") == 0) {
      // Skip the data/ directory
      continue;
    }

    if (strcmp(bname, tsdbTxnFname[TSDB_TXN_TEMP_FILE]) == 0) {
      // Skip current.t file
      tsdbInfo("vgId:%d file %s exists, remove it", REPO_ID(pRepo), TFILE_NAME(pf));
1013
      (void)tfsremove(pf);
H
Hongze Cheng 已提交
1014
      continue;
H
Hongze Cheng 已提交
1015
    }
H
Hongze Cheng 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

    int code = regexec(&regex, bname, 0, NULL, 0);
    if (code == 0) {
      // Match
      if (pfs->cstatus->pmf != NULL) {
        tsdbError("vgId:%d failed to restore meta since two file exists, file1 %s and file2 %s", REPO_ID(pRepo),
                  TSDB_FILE_FULL_NAME(pfs->cstatus->pmf), TFILE_NAME(pf));
        terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
        tfsClosedir(tdir);
        regfree(&regex);
        return -1;
      } else {
1028
        uint32_t _version = 0;
H
Hongze Cheng 已提交
1029
        if (strcmp(bname, "meta") != 0) {
1030 1031
          sscanf(bname, "meta-ver%" PRIu32, &_version);
          pfs->cstatus->meta.version = _version;
H
Hongze Cheng 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
        }

        pfs->cstatus->pmf = &(pfs->cstatus->mf);
        pfs->cstatus->pmf->f = *pf;
        TSDB_FILE_SET_CLOSED(pfs->cstatus->pmf);

        if (tsdbOpenMFile(pfs->cstatus->pmf, O_RDONLY) < 0) {
          tsdbError("vgId:%d failed to restore meta since %s", REPO_ID(pRepo), tstrerror(terrno));
          tfsClosedir(tdir);
          regfree(&regex);
          return -1;
        }

        if (tsdbLoadMFileHeader(pfs->cstatus->pmf, &(pfs->cstatus->pmf->info)) < 0) {
          tsdbError("vgId:%d failed to restore meta since %s", REPO_ID(pRepo), tstrerror(terrno));
H
refact  
Hongze Cheng 已提交
1047
          tsdbCloseMFile(pfs->cstatus->pmf);
H
Hongze Cheng 已提交
1048 1049 1050 1051 1052
          tfsClosedir(tdir);
          regfree(&regex);
          return -1;
        }

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
        if (tsdbForceKeepFile) {
          struct stat tfstat;

          // Get real file size
          if (fstat(pfs->cstatus->pmf->fd, &tfstat) < 0) {
            terrno = TAOS_SYSTEM_ERROR(errno);
            tsdbCloseMFile(pfs->cstatus->pmf);
            tfsClosedir(tdir);
            regfree(&regex);
            return -1;
          }

          if (pfs->cstatus->pmf->info.size != tfstat.st_size) {
            int64_t tfsize = pfs->cstatus->pmf->info.size;
            pfs->cstatus->pmf->info.size = tfstat.st_size;
            tsdbInfo("vgId:%d file %s header size is changed from %" PRId64 " to %" PRId64, REPO_ID(pRepo),
                     TSDB_FILE_FULL_NAME(pfs->cstatus->pmf), tfsize, pfs->cstatus->pmf->info.size);
          }
        }

H
Hongze Cheng 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        tsdbCloseMFile(pfs->cstatus->pmf);
      }
    } else if (code == REG_NOMATCH) {
      // Not match
      tsdbInfo("vgId:%d invalid file %s exists, remove it", REPO_ID(pRepo), TFILE_NAME(pf));
      tfsremove(pf);
      continue;
    } else {
      // Has other error
      tsdbError("vgId:%d failed to restore meta file while run regexec since %s", REPO_ID(pRepo), strerror(code));
      terrno = TAOS_SYSTEM_ERROR(code);
      tfsClosedir(tdir);
      regfree(&regex);
      return -1;
    }
  }

  if (pfs->cstatus->pmf) {
    tsdbInfo("vgId:%d meta file %s is restored", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pfs->cstatus->pmf));
  } else {
    tsdbInfo("vgId:%d no meta file is restored", REPO_ID(pRepo));
H
Hongze Cheng 已提交
1094 1095 1096
  }

  tfsClosedir(tdir);
H
Hongze Cheng 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
  regfree(&regex);
  return 0;
}

static int tsdbRestoreDFileSet(STsdbRepo *pRepo) {
  char         dataDir[TSDB_FILENAME_LEN];
  char         bname[TSDB_FILENAME_LEN];
  TDIR *       tdir = NULL;
  const TFILE *pf = NULL;
  const char * pattern = "^v[0-9]+f[0-9]+\\.(head|data|last)(-ver[0-9]+)?$";
  SArray *     fArray = NULL;
  regex_t      regex;
  STsdbFS *    pfs = REPO_FS(pRepo);
H
Hongze Cheng 已提交
1110 1111

  tsdbGetDataDir(REPO_ID(pRepo), dataDir);
H
Hongze Cheng 已提交
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124

  // Resource allocation and init
  regcomp(&regex, pattern, REG_EXTENDED);

  fArray = taosArrayInit(1024, sizeof(TFILE));
  if (fArray == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbError("vgId:%d failed to restore DFileSet while open directory %s since %s", REPO_ID(pRepo), dataDir,
              tstrerror(terrno));
    regfree(&regex);
    return -1;
  }

H
Hongze Cheng 已提交
1125 1126
  tdir = tfsOpendir(dataDir);
  if (tdir == NULL) {
H
Hongze Cheng 已提交
1127 1128 1129 1130
    tsdbError("vgId:%d failed to restore DFileSet while open directory %s since %s", REPO_ID(pRepo), dataDir,
              tstrerror(terrno));
    taosArrayDestroy(fArray);
    regfree(&regex);
H
Hongze Cheng 已提交
1131 1132 1133
    return -1;
  }

H
Hongze Cheng 已提交
1134 1135 1136 1137 1138
  while ((pf = tfsReaddir(tdir))) {
    tfsbasename(pf, bname);

    int code = regexec(&regex, bname, 0, NULL, 0);
    if (code == 0) {
1139
      if (taosArrayPush(fArray, (void *)pf) == NULL) {
H
Hongze Cheng 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        tfsClosedir(tdir);
        taosArrayDestroy(fArray);
        regfree(&regex);
        return -1;
      }
    } else if (code == REG_NOMATCH) {
      // Not match
      tsdbInfo("vgId:%d invalid file %s exists, remove it", REPO_ID(pRepo), TFILE_NAME(pf));
1149
      (void)tfsremove(pf);
H
Hongze Cheng 已提交
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
      continue;
    } else {
      // Has other error
      tsdbError("vgId:%d failed to restore DFileSet Array while run regexec since %s", REPO_ID(pRepo), strerror(code));
      terrno = TAOS_SYSTEM_ERROR(code);
      tfsClosedir(tdir);
      taosArrayDestroy(fArray);
      regfree(&regex);
      return -1;
    }
  }
H
Hongze Cheng 已提交
1161 1162

  tfsClosedir(tdir);
H
Hongze Cheng 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
  regfree(&regex);

  // Sort the array according to file name
  taosArraySort(fArray, tsdbComparTFILE);

  size_t index = 0;
  // Loop to recover each file set
  for (;;) {
    if (index >= taosArrayGetSize(fArray)) {
      break;
    }

    SDFileSet fset = {0};

    TSDB_FSET_SET_CLOSED(&fset);

    // Loop to recover ONE fset
    for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
      SDFile *pDFile = TSDB_DFILE_IN_SET(&fset, ftype);

      if (index >= taosArrayGetSize(fArray)) {
        tsdbError("vgId:%d incomplete DFileSet, fid:%d", REPO_ID(pRepo), fset.fid);
        taosArrayDestroy(fArray);
        return -1;
      }

      pf = taosArrayGet(fArray, index);

      int         tvid, tfid;
      TSDB_FILE_T ttype;
      uint32_t    tversion;
1194
      char        _bname[TSDB_FILENAME_LEN];
H
Hongze Cheng 已提交
1195

1196 1197
      tfsbasename(pf, _bname);
      tsdbParseDFilename(_bname, &tvid, &tfid, &ttype, &tversion);
H
Hongze Cheng 已提交
1198 1199 1200

      ASSERT(tvid == REPO_ID(pRepo));

1201 1202 1203 1204 1205
      if (tfid < pRepo->rtn.minFid) {  // skip file expired
        ++index;
        continue;
      }

H
Hongze Cheng 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
      if (ftype == 0) {
        fset.fid = tfid;
      } else {
        if (tfid != fset.fid) {
          tsdbError("vgId:%d incomplete dFileSet, fid:%d", REPO_ID(pRepo), fset.fid);
          taosArrayDestroy(fArray);
          return -1;
        }
      }

      if (ttype != ftype) {
        tsdbError("vgId:%d incomplete dFileSet, fid:%d", REPO_ID(pRepo), fset.fid);
        taosArrayDestroy(fArray);
        return -1;
      }

      pDFile->f = *pf;
      
      if (tsdbOpenDFile(pDFile, O_RDONLY) < 0) {
        tsdbError("vgId:%d failed to open DFile %s since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pDFile), tstrerror(terrno));
        taosArrayDestroy(fArray);
        return -1;
      }

      if (tsdbLoadDFileHeader(pDFile, &(pDFile->info)) < 0) {
        tsdbError("vgId:%d failed to load DFile %s header since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pDFile),
                  tstrerror(terrno));
        taosArrayDestroy(fArray);
        return -1;
      }

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
      if (tsdbForceKeepFile) {
        struct stat tfstat;

        // Get real file size
        if (fstat(pDFile->fd, &tfstat) < 0) {
          terrno = TAOS_SYSTEM_ERROR(errno);
          taosArrayDestroy(fArray);
          return -1;
        }

        if (pDFile->info.size != tfstat.st_size) {
          int64_t tfsize = pDFile->info.size;
          pDFile->info.size = tfstat.st_size;
          tsdbInfo("vgId:%d file %s header size is changed from %" PRId64 " to %" PRId64, REPO_ID(pRepo),
                   TSDB_FILE_FULL_NAME(pDFile), tfsize, pDFile->info.size);
        }
      }

H
Hongze Cheng 已提交
1255
      tsdbCloseDFile(pDFile);
H
Hongze Cheng 已提交
1256
      index++;
H
Hongze Cheng 已提交
1257 1258
    }

H
Hongze Cheng 已提交
1259
    tsdbInfo("vgId:%d FSET %d is restored", REPO_ID(pRepo), fset.fid);
H
Hongze Cheng 已提交
1260 1261 1262 1263 1264
    taosArrayPush(pfs->cstatus->df, &fset);
  }

  // Resource release
  taosArrayDestroy(fArray);
H
Hongze Cheng 已提交
1265 1266

  return 0;
H
Hongze Cheng 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
}

static int tsdbRestoreCurrent(STsdbRepo *pRepo) {
  // Loop to recover mfile
  if (tsdbRestoreMeta(pRepo) < 0) {
    tsdbError("vgId:%d failed to restore current since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
  }

  // Loop to recover dfile set
  if (tsdbRestoreDFileSet(pRepo) < 0) {
    tsdbError("vgId:%d failed to restore DFileSet since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
  }

  if (tsdbSaveFSStatus(pRepo->fs->cstatus, REPO_ID(pRepo)) < 0) {
    tsdbError("vgId:%d failed to restore corrent since %s", REPO_ID(pRepo), tstrerror(terrno));
    return -1;
  }

  return 0;
}

static int tsdbComparTFILE(const void *arg1, const void *arg2) {
  TFILE *pf1 = (TFILE *)arg1;
  TFILE *pf2 = (TFILE *)arg2;

  int         vid1, fid1, vid2, fid2;
  TSDB_FILE_T ftype1, ftype2;
  uint32_t    version1, version2;
H
Hongze Cheng 已提交
1297 1298
  char        bname1[TSDB_FILENAME_LEN];
  char        bname2[TSDB_FILENAME_LEN];
H
Hongze Cheng 已提交
1299

H
Hongze Cheng 已提交
1300 1301 1302 1303
  tfsbasename(pf1, bname1);
  tfsbasename(pf2, bname2);
  tsdbParseDFilename(bname1, &vid1, &fid1, &ftype1, &version1);
  tsdbParseDFilename(bname2, &vid2, &fid2, &ftype2, &version2);
H
Hongze Cheng 已提交
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

  if (fid1 < fid2) {
    return -1;
  } else if (fid1 > fid2) {
    return 1;
  } else {
    if (ftype1 < ftype2) {
      return -1;
    } else if (ftype1 > ftype2) {
      return 1;
    } else {
      return 0;
    }
  }
H
Hongze Cheng 已提交
1318 1319
}

1320
static void tsdbScanAndTryFixDFilesHeader(STsdbRepo *pRepo, int32_t *nExpired) {
H
Hongze Cheng 已提交
1321 1322 1323 1324 1325 1326 1327
  STsdbFS *  pfs = REPO_FS(pRepo);
  SFSStatus *pStatus = pfs->cstatus;
  SDFInfo    info;

  for (size_t i = 0; i < taosArrayGetSize(pStatus->df); i++) {
    SDFileSet fset;
    tsdbInitDFileSetEx(&fset, (SDFileSet *)taosArrayGet(pStatus->df, i));
1328 1329 1330
    if (fset.fid < pRepo->rtn.minFid) {
      ++*nExpired;
    }
H
Hongze Cheng 已提交
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    tsdbDebug("vgId:%d scan DFileSet %d header", REPO_ID(pRepo), fset.fid);

    if (tsdbOpenDFileSet(&fset, O_RDWR) < 0) {
      tsdbError("vgId:%d failed to open DFileSet %d since %s, continue", REPO_ID(pRepo), fset.fid, tstrerror(terrno));
      continue;
    }

    for (TSDB_FILE_T ftype = 0; ftype < TSDB_FILE_MAX; ftype++) {
      SDFile *pDFile = TSDB_DFILE_IN_SET(&fset, ftype);

H
Hongze Cheng 已提交
1341 1342
      if ((tsdbLoadDFileHeader(pDFile, &info) < 0) || pDFile->info.size != info.size ||
          pDFile->info.magic != info.magic) {
H
Hongze Cheng 已提交
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
        if (tsdbUpdateDFileHeader(pDFile) < 0) {
          tsdbError("vgId:%d failed to update DFile header of %s since %s, continue", REPO_ID(pRepo),
                    TSDB_FILE_FULL_NAME(pDFile), tstrerror(terrno));
        } else {
          tsdbInfo("vgId:%d DFile header of %s is updated", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pDFile));
          TSDB_FILE_FSYNC(pDFile);
        }
      } else {
        tsdbDebug("vgId:%d DFile header of %s is correct", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pDFile));
      }
    }

    tsdbCloseDFileSet(&fset);
  }
L
Liu Jicong 已提交
1357
}