walWrite.c 20.7 KB
Newer Older
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "os.h"
S
Shengliang Guan 已提交
17
#include "taoserror.h"
18
#include "tchecksum.h"
19
#include "tglobal.h"
S
Shengliang Guan 已提交
20
#include "walInt.h"
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
21

22 23 24
int32_t walRestoreFromSnapshot(SWal *pWal, int64_t ver) {
  taosThreadMutexLock(&pWal->mutex);

L
Liu Jicong 已提交
25 26
  wInfo("vgId:%d, restore from snapshot, version %" PRId64, pWal->cfg.vgId, ver);

27 28
  void *pIter = NULL;
  while (1) {
L
Liu Jicong 已提交
29
    pIter = taosHashIterate(pWal->pRefHash, pIter);
30
    if (pIter == NULL) break;
L
Liu Jicong 已提交
31
    SWalRef *pRef = *(SWalRef **)pIter;
L
Liu Jicong 已提交
32
    if (pRef->refVer != -1 && pRef->refVer <= ver) {
33
      taosHashCancelIterate(pWal->pRefHash, pIter);
L
Liu Jicong 已提交
34
      taosThreadMutexUnlock(&pWal->mutex);
35 36 37 38
      return -1;
    }
  }

L
Liu Jicong 已提交
39 40
  taosCloseFile(&pWal->pLogFile);
  taosCloseFile(&pWal->pIdxFile);
41 42 43 44 45 46 47

  if (pWal->vers.firstVer != -1) {
    int32_t fileSetSize = taosArrayGetSize(pWal->fileInfoSet);
    for (int32_t i = 0; i < fileSetSize; i++) {
      SWalFileInfo *pFileInfo = taosArrayGet(pWal->fileInfoSet, i);
      char          fnameStr[WAL_FILE_LEN];
      walBuildLogName(pWal, pFileInfo->firstVer, fnameStr);
L
Liu Jicong 已提交
48 49
      if (taosRemoveFile(fnameStr) < 0) {
        terrno = TAOS_SYSTEM_ERROR(errno);
S
Shengliang Guan 已提交
50
        wError("vgId:%d, restore from snapshot, cannot remove file %s since %s", pWal->cfg.vgId, fnameStr, terrstr());
L
Liu Jicong 已提交
51
        taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
52 53
        return -1;
      }
S
Shengliang Guan 已提交
54
      wInfo("vgId:%d, restore from snapshot, remove file %s", pWal->cfg.vgId, fnameStr);
55 56

      walBuildIdxName(pWal, pFileInfo->firstVer, fnameStr);
L
Liu Jicong 已提交
57 58
      if (taosRemoveFile(fnameStr) < 0) {
        terrno = TAOS_SYSTEM_ERROR(errno);
S
Shengliang Guan 已提交
59
        wError("vgId:%d, cannot remove file %s since %s", pWal->cfg.vgId, fnameStr, terrstr());
L
Liu Jicong 已提交
60
        taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
61 62
        return -1;
      }
S
Shengliang Guan 已提交
63
      wInfo("vgId:%d, restore from snapshot, remove file %s", pWal->cfg.vgId, fnameStr);
64 65 66 67 68 69 70 71 72
    }
  }
  walRemoveMeta(pWal);

  pWal->writeCur = -1;
  pWal->totSize = 0;
  pWal->lastRollSeq = -1;

  taosArrayClear(pWal->fileInfoSet);
73
  pWal->vers.firstVer = ver + 1;
74
  pWal->vers.lastVer = ver;
75 76
  pWal->vers.commitVer = ver;
  pWal->vers.snapshotVer = ver;
77
  pWal->vers.verInSnapshotting = -1;
78 79 80

  taosThreadMutexUnlock(&pWal->mutex);
  return 0;
81 82
}

L
Liu Jicong 已提交
83 84 85 86 87 88
int32_t walApplyVer(SWal *pWal, int64_t ver) {
  // TODO: error check
  pWal->vers.appliedVer = ver;
  return 0;
}

L
Liu Jicong 已提交
89
int32_t walCommit(SWal *pWal, int64_t ver) {
90 91
  ASSERT(pWal->vers.commitVer >= pWal->vers.snapshotVer);
  ASSERT(pWal->vers.commitVer <= pWal->vers.lastVer);
L
Liu Jicong 已提交
92 93 94 95
  if (ver < pWal->vers.commitVer) {
    return 0;
  }
  if (ver > pWal->vers.lastVer) {
L
Liu Jicong 已提交
96
    terrno = TSDB_CODE_WAL_INVALID_VER;
L
Liu Jicong 已提交
97 98
    return -1;
  }
L
Liu Jicong 已提交
99
  pWal->vers.commitVer = ver;
L
Liu Jicong 已提交
100 101 102 103
  return 0;
}

int32_t walRollback(SWal *pWal, int64_t ver) {
104
  taosThreadMutexLock(&pWal->mutex);
L
Liu Jicong 已提交
105
  wInfo("vgId:%d, wal rollback for version %" PRId64, pWal->cfg.vgId, ver);
L
Liu Jicong 已提交
106 107
  int64_t code;
  char    fnameStr[WAL_FILE_LEN];
108
  if (ver > pWal->vers.lastVer || ver <= pWal->vers.commitVer || ver <= pWal->vers.snapshotVer) {
L
Liu Jicong 已提交
109
    terrno = TSDB_CODE_WAL_INVALID_VER;
L
Liu Jicong 已提交
110
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
111 112 113
    return -1;
  }

L
Liu Jicong 已提交
114 115
  // find correct file
  if (ver < walGetLastFileFirstVer(pWal)) {
L
Liu Jicong 已提交
116 117 118
    // change current files
    code = walChangeWrite(pWal, ver);
    if (code < 0) {
L
Liu Jicong 已提交
119
      taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
120 121 122
      return -1;
    }

123
    // delete files in descending order
L
Liu Jicong 已提交
124
    int fileSetSize = taosArrayGetSize(pWal->fileInfoSet);
125
    for (int i = fileSetSize - 1; i >= pWal->writeCur + 1; i--) {
L
Liu Jicong 已提交
126
      walBuildLogName(pWal, ((SWalFileInfo *)taosArrayGet(pWal->fileInfoSet, i))->firstVer, fnameStr);
L
Liu Jicong 已提交
127
      wDebug("vgId:%d, wal remove file %s for rollback", pWal->cfg.vgId, fnameStr);
128
      taosRemoveFile(fnameStr);
L
Liu Jicong 已提交
129
      walBuildIdxName(pWal, ((SWalFileInfo *)taosArrayGet(pWal->fileInfoSet, i))->firstVer, fnameStr);
L
Liu Jicong 已提交
130
      wDebug("vgId:%d, wal remove file %s for rollback", pWal->cfg.vgId, fnameStr);
131
      taosRemoveFile(fnameStr);
L
Liu Jicong 已提交
132
    }
L
Liu Jicong 已提交
133
    // pop from fileInfoSet
L
Liu Jicong 已提交
134 135 136 137
    taosArraySetSize(pWal->fileInfoSet, pWal->writeCur + 1);
  }

  walBuildIdxName(pWal, walGetCurFileFirstVer(pWal), fnameStr);
L
Liu Jicong 已提交
138
  TdFilePtr pIdxFile = taosOpenFile(fnameStr, TD_FILE_WRITE | TD_FILE_READ | TD_FILE_APPEND);
L
Liu Jicong 已提交
139

L
Liu Jicong 已提交
140
  if (pIdxFile == NULL) {
141
    ASSERT(0);
wafwerar's avatar
wafwerar 已提交
142
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
143 144
    return -1;
  }
L
Liu Jicong 已提交
145
  int64_t idxOff = walGetVerIdxOffset(pWal, ver);
L
Liu Jicong 已提交
146
  code = taosLSeekFile(pIdxFile, idxOff, SEEK_SET);
L
Liu Jicong 已提交
147
  if (code < 0) {
148
    ASSERT(0);
wafwerar's avatar
wafwerar 已提交
149
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
150 151
    return -1;
  }
L
Liu Jicong 已提交
152
  // read idx file and get log file pos
L
Liu Jicong 已提交
153
  SWalIdxEntry entry;
L
Liu Jicong 已提交
154
  if (taosReadFile(pIdxFile, &entry, sizeof(SWalIdxEntry)) != sizeof(SWalIdxEntry)) {
155
    ASSERT(0);
wafwerar's avatar
wafwerar 已提交
156
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
157 158
    return -1;
  }
159
  ASSERT(entry.ver == ver);
L
Liu Jicong 已提交
160 161

  walBuildLogName(pWal, walGetCurFileFirstVer(pWal), fnameStr);
L
Liu Jicong 已提交
162
  TdFilePtr pLogFile = taosOpenFile(fnameStr, TD_FILE_WRITE | TD_FILE_READ | TD_FILE_APPEND);
L
Liu Jicong 已提交
163
  wDebug("vgId:%d, wal truncate file %s", pWal->cfg.vgId, fnameStr);
L
Liu Jicong 已提交
164
  if (pLogFile == NULL) {
L
Liu Jicong 已提交
165
    // TODO
L
Liu Jicong 已提交
166
    terrno = TAOS_SYSTEM_ERROR(errno);
wafwerar's avatar
wafwerar 已提交
167
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
168 169
    return -1;
  }
L
Liu Jicong 已提交
170
  code = taosLSeekFile(pLogFile, entry.offset, SEEK_SET);
L
Liu Jicong 已提交
171 172
  if (code < 0) {
    // TODO
L
Liu Jicong 已提交
173
    terrno = TAOS_SYSTEM_ERROR(errno);
wafwerar's avatar
wafwerar 已提交
174
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
175 176
    return -1;
  }
L
Liu Jicong 已提交
177
  // validate offset
L
Liu Jicong 已提交
178
  SWalCkHead head;
179
  ASSERT(taosValidFile(pLogFile));
L
Liu Jicong 已提交
180
  int64_t size = taosReadFile(pLogFile, &head, sizeof(SWalCkHead));
L
Liu Jicong 已提交
181
  if (size != sizeof(SWalCkHead)) {
182
    ASSERT(0);
L
Liu Jicong 已提交
183
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
184 185 186 187
    return -1;
  }
  code = walValidHeadCksum(&head);

188
  ASSERT(code == 0);
L
Liu Jicong 已提交
189
  if (code != 0) {
L
Liu Jicong 已提交
190
    terrno = TSDB_CODE_WAL_FILE_CORRUPTED;
191
    ASSERT(0);
L
Liu Jicong 已提交
192
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
193 194
    return -1;
  }
L
Liu Jicong 已提交
195
  if (head.head.version != ver) {
196
    ASSERT(0);
L
Liu Jicong 已提交
197
    terrno = TSDB_CODE_WAL_FILE_CORRUPTED;
L
Liu Jicong 已提交
198
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
199 200
    return -1;
  }
L
Liu Jicong 已提交
201

L
Liu Jicong 已提交
202
  // truncate old files
L
Liu Jicong 已提交
203
  code = taosFtruncateFile(pLogFile, entry.offset);
L
Liu Jicong 已提交
204
  if (code < 0) {
205
    ASSERT(0);
L
Liu Jicong 已提交
206
    terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
207
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
208 209
    return -1;
  }
L
Liu Jicong 已提交
210
  code = taosFtruncateFile(pIdxFile, idxOff);
L
Liu Jicong 已提交
211
  if (code < 0) {
212
    ASSERT(0);
L
Liu Jicong 已提交
213
    terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
214
    taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
215 216
    return -1;
  }
L
Liu Jicong 已提交
217
  pWal->vers.lastVer = ver - 1;
L
Liu Jicong 已提交
218
  if (pWal->vers.lastVer < pWal->vers.firstVer) {
219
    ASSERT(pWal->vers.lastVer == pWal->vers.firstVer - 1);
L
Liu Jicong 已提交
220
  }
L
Liu Jicong 已提交
221 222
  ((SWalFileInfo *)taosArrayGetLast(pWal->fileInfoSet))->lastVer = ver - 1;
  ((SWalFileInfo *)taosArrayGetLast(pWal->fileInfoSet))->fileSize = entry.offset;
L
Liu Jicong 已提交
223 224 225
  taosCloseFile(&pIdxFile);
  taosCloseFile(&pLogFile);

226 227 228 229 230 231
  code = walSaveMeta(pWal);
  if (code < 0) {
    wError("vgId:%d, failed to save meta since %s", pWal->cfg.vgId, terrstr());
    taosThreadMutexUnlock(&pWal->mutex);
    return -1;
  }
L
Liu Jicong 已提交
232

L
Liu Jicong 已提交
233
  // unlock
wafwerar's avatar
wafwerar 已提交
234
  taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
235 236
  return 0;
}
L
Liu Jicong 已提交
237

L
Liu Jicong 已提交
238 239 240 241 242
static FORCE_INLINE int32_t walCheckAndRoll(SWal *pWal) {
  if (taosArrayGetSize(pWal->fileInfoSet) == 0) {
    if (walRollImpl(pWal) < 0) {
      return -1;
    }
243 244 245 246 247 248 249 250 251 252 253
    return 0;
  }

  int64_t passed = walGetSeq() - pWal->lastRollSeq;
  if (pWal->cfg.rollPeriod != -1 && pWal->cfg.rollPeriod != 0 && passed > pWal->cfg.rollPeriod) {
    if (walRollImpl(pWal) < 0) {
      return -1;
    }
  } else if (pWal->cfg.segSize != -1 && pWal->cfg.segSize != 0 && walGetLastFileSize(pWal) > pWal->cfg.segSize) {
    if (walRollImpl(pWal) < 0) {
      return -1;
L
Liu Jicong 已提交
254 255
    }
  }
256

257
  if (walGetLastFileCachedSize(pWal) > tsWalFsyncDataSizeLimit) {
258 259 260 261 262
    if (walSaveMeta(pWal) < 0) {
      return -1;
    }
  }

L
Liu Jicong 已提交
263 264 265
  return 0;
}

L
Liu Jicong 已提交
266
int32_t walBeginSnapshot(SWal *pWal, int64_t ver) {
267 268
  taosThreadMutexLock(&pWal->mutex);

L
Liu Jicong 已提交
269
  pWal->vers.verInSnapshotting = ver;
L
Liu Jicong 已提交
270 271
  wDebug("vgId:%d, wal begin snapshot for version %" PRId64 ", first ver %" PRId64 ", last ver %" PRId64,
         pWal->cfg.vgId, ver, pWal->vers.firstVer, pWal->vers.lastVer);
L
Liu Jicong 已提交
272 273
  // check file rolling
  if (pWal->cfg.retentionPeriod == 0) {
L
Liu Jicong 已提交
274
    if (walGetLastFileSize(pWal) != 0) {
275 276 277 278
      if (walRollImpl(pWal) < 0) {
        wError("vgId:%d, failed to roll wal files since %s", pWal->cfg.vgId, terrstr());
        goto _err;
      }
L
Liu Jicong 已提交
279
    }
L
Liu Jicong 已提交
280
  }
281
  taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
282
  return 0;
283 284 285 286

_err:
  taosThreadMutexUnlock(&pWal->mutex);
  return -1;
L
Liu Jicong 已提交
287 288
}

L
Liu Jicong 已提交
289
int32_t walEndSnapshot(SWal *pWal) {
L
Liu Jicong 已提交
290 291
  int32_t code = 0;
  taosThreadMutexLock(&pWal->mutex);
L
Liu Jicong 已提交
292
  int64_t ver = pWal->vers.verInSnapshotting;
L
Liu Jicong 已提交
293 294 295 296

  wDebug("vgId:%d, wal end snapshot for version %" PRId64 ", first ver %" PRId64 ", last ver %" PRId64, pWal->cfg.vgId,
         ver, pWal->vers.firstVer, pWal->vers.lastVer);

L
Liu Jicong 已提交
297 298 299 300
  if (ver == -1) {
    code = -1;
    goto END;
  };
L
Liu Jicong 已提交
301

L
Liu Jicong 已提交
302
  pWal->vers.snapshotVer = ver;
L
Liu Jicong 已提交
303 304
  int ts = taosGetTimestampSec();

305
  void *pIter = NULL;
306 307 308 309 310
  while (1) {
    pIter = taosHashIterate(pWal->pRefHash, pIter);
    if (pIter == NULL) break;
    SWalRef *pRef = *(SWalRef **)pIter;
    if (pRef->refVer == -1) continue;
L
Liu Jicong 已提交
311 312
    ver = TMIN(ver, pRef->refVer - 1);
    wDebug("vgId:%d, wal found ref %" PRId64 ", refId %" PRId64, pWal->cfg.vgId, pRef->refVer, pRef->refId);
313 314
  }

L
Liu Jicong 已提交
315 316 317
  int          deleteCnt = 0;
  int64_t      newTotSize = pWal->totSize;
  SWalFileInfo tmp;
L
Liu Jicong 已提交
318
  tmp.firstVer = ver;
L
Liu Jicong 已提交
319
  // find files safe to delete
L
Liu Jicong 已提交
320
  SWalFileInfo *pInfo = taosArraySearch(pWal->fileInfoSet, &tmp, compareWalFileInfo, TD_LE);
321
  if (pInfo) {
L
Liu Jicong 已提交
322
    SWalFileInfo *pLastFileInfo = taosArrayGetLast(pWal->fileInfoSet);
L
Liu Jicong 已提交
323
    wDebug("vgId:%d, wal search found file info: first:%" PRId64 " last:%" PRId64, pWal->cfg.vgId, pInfo->firstVer,
L
Liu Jicong 已提交
324
           pInfo->lastVer);
325
    if (ver >= pInfo->lastVer) {
326
      pInfo++;
L
Liu Jicong 已提交
327
      wDebug("vgId:%d, wal remove advance one file: first:%" PRId64 " last:%" PRId64, pWal->cfg.vgId, pInfo->firstVer,
L
Liu Jicong 已提交
328
             pInfo->lastVer);
329
    }
L
Liu Jicong 已提交
330
    if (pInfo <= pLastFileInfo) {
L
Liu Jicong 已提交
331
      wDebug("vgId:%d, wal end remove for first:%" PRId64 " last:%" PRId64, pWal->cfg.vgId, pInfo->firstVer,
L
Liu Jicong 已提交
332
             pInfo->lastVer);
L
Liu Jicong 已提交
333
    } else {
L
Liu Jicong 已提交
334
      wDebug("vgId:%d, wal no remove", pWal->cfg.vgId);
335
    }
336

337 338
    // iterate files, until the searched result
    for (SWalFileInfo *iter = pWal->fileInfoSet->pData; iter < pInfo; iter++) {
L
Liu Jicong 已提交
339 340 341 342 343 344
      wDebug("vgId:%d, wal check remove file %" PRId64 "(file size %" PRId64 " close ts %" PRId64
             "), new tot size %" PRId64,
             pWal->cfg.vgId, iter->firstVer, iter->fileSize, iter->closeTs, newTotSize);
      if (((pWal->cfg.retentionSize == 0) || (pWal->cfg.retentionSize != -1 && newTotSize > pWal->cfg.retentionSize)) ||
          ((pWal->cfg.retentionPeriod == 0) ||
           (pWal->cfg.retentionPeriod != -1 && iter->closeTs + pWal->cfg.retentionPeriod > ts))) {
345
        // delete according to file size or close time
L
Liu Jicong 已提交
346
        wDebug("vgId:%d, check pass", pWal->cfg.vgId);
347 348
        deleteCnt++;
        newTotSize -= iter->fileSize;
349
        taosArrayPush(pWal->toDeleteFiles, iter);
350
      }
L
Liu Jicong 已提交
351
      wDebug("vgId:%d, check not pass", pWal->cfg.vgId);
352
    }
L
Liu Jicong 已提交
353

354
  UPDATE_META:
355
    // make new array, remove files
356
    taosArrayPopFrontBatch(pWal->fileInfoSet, deleteCnt);
357 358
    if (taosArrayGetSize(pWal->fileInfoSet) == 0) {
      pWal->writeCur = -1;
359
      pWal->vers.firstVer = pWal->vers.lastVer + 1;
360 361 362
    } else {
      pWal->vers.firstVer = ((SWalFileInfo *)taosArrayGet(pWal->fileInfoSet, 0))->firstVer;
    }
L
Liu Jicong 已提交
363
  }
L
Liu Jicong 已提交
364
  pWal->writeCur = taosArrayGetSize(pWal->fileInfoSet) - 1;
L
Liu Jicong 已提交
365
  pWal->totSize = newTotSize;
L
Liu Jicong 已提交
366
  pWal->vers.verInSnapshotting = -1;
L
Liu Jicong 已提交
367

L
Liu Jicong 已提交
368
  // save snapshot ver, commit ver
L
Liu Jicong 已提交
369
  code = walSaveMeta(pWal);
L
Liu Jicong 已提交
370
  if (code < 0) {
L
Liu Jicong 已提交
371
    goto END;
L
Liu Jicong 已提交
372 373
  }

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  // delete files
  deleteCnt = taosArrayGetSize(pWal->toDeleteFiles);
  wDebug("vgId:%d, wal should delete %d files", pWal->cfg.vgId, deleteCnt);
  char fnameStr[WAL_FILE_LEN];
  for (int i = 0; i < deleteCnt; i++) {
    pInfo = taosArrayGet(pWal->toDeleteFiles, i);
    walBuildLogName(pWal, pInfo->firstVer, fnameStr);
    wDebug("vgId:%d, wal remove file %s", pWal->cfg.vgId, fnameStr);
    if (taosRemoveFile(fnameStr) < 0 && errno != ENOENT) {
      wError("vgId:%d, failed to remove log file %s due to %s", pWal->cfg.vgId, fnameStr, strerror(errno));
      goto END;
    }
    walBuildIdxName(pWal, pInfo->firstVer, fnameStr);
    wDebug("vgId:%d, wal remove file %s", pWal->cfg.vgId, fnameStr);
    if (taosRemoveFile(fnameStr) < 0 && errno != ENOENT) {
389
      ASSERT(0);
390 391 392 393
    }
  }
  taosArrayClear(pWal->toDeleteFiles);

L
Liu Jicong 已提交
394 395 396
END:
  taosThreadMutexUnlock(&pWal->mutex);
  return code;
L
Liu Jicong 已提交
397 398
}

L
Liu Jicong 已提交
399
int32_t walRollImpl(SWal *pWal) {
L
Liu Jicong 已提交
400
  int32_t code = 0;
L
Liu Jicong 已提交
401 402
  if (pWal->pIdxFile != NULL) {
    code = taosCloseFile(&pWal->pIdxFile);
L
Liu Jicong 已提交
403
    if (code != 0) {
L
Liu Jicong 已提交
404
      terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
405
      goto END;
L
Liu Jicong 已提交
406
    }
L
Liu Jicong 已提交
407
  }
L
Liu Jicong 已提交
408 409
  if (pWal->pLogFile != NULL) {
    code = taosCloseFile(&pWal->pLogFile);
L
Liu Jicong 已提交
410
    if (code != 0) {
L
Liu Jicong 已提交
411
      terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
412
      goto END;
L
Liu Jicong 已提交
413
    }
L
Liu Jicong 已提交
414
  }
L
Liu Jicong 已提交
415
  TdFilePtr pIdxFile, pLogFile;
L
Liu Jicong 已提交
416
  // create new file
L
Liu Jicong 已提交
417
  int64_t newFileFirstVer = pWal->vers.lastVer + 1;
L
Liu Jicong 已提交
418
  char    fnameStr[WAL_FILE_LEN];
L
Liu Jicong 已提交
419 420 421
  walBuildIdxName(pWal, newFileFirstVer, fnameStr);
  pIdxFile = taosOpenFile(fnameStr, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_APPEND);
  if (pIdxFile == NULL) {
L
Liu Jicong 已提交
422
    terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
423 424
    code = -1;
    goto END;
L
Liu Jicong 已提交
425
  }
L
Liu Jicong 已提交
426 427
  walBuildLogName(pWal, newFileFirstVer, fnameStr);
  pLogFile = taosOpenFile(fnameStr, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_APPEND);
428
  wDebug("vgId:%d, wal create new file for write:%s", pWal->cfg.vgId, fnameStr);
L
Liu Jicong 已提交
429
  if (pLogFile == NULL) {
L
Liu Jicong 已提交
430
    terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
431 432
    code = -1;
    goto END;
L
Liu Jicong 已提交
433
  }
L
Liu Jicong 已提交
434
  // error code was set inner
L
Liu Jicong 已提交
435
  code = walRollFileInfo(pWal);
L
Liu Jicong 已提交
436
  if (code != 0) {
L
Liu Jicong 已提交
437
    goto END;
L
Liu Jicong 已提交
438
  }
L
Liu Jicong 已提交
439

L
Liu Jicong 已提交
440
  // switch file
L
Liu Jicong 已提交
441 442
  pWal->pIdxFile = pIdxFile;
  pWal->pLogFile = pLogFile;
L
Liu Jicong 已提交
443
  pWal->writeCur = taosArrayGetSize(pWal->fileInfoSet) - 1;
444
  ASSERT(pWal->writeCur >= 0);
L
Liu Jicong 已提交
445 446

  pWal->lastRollSeq = walGetSeq();
L
Liu Jicong 已提交
447

448 449 450 451 452
  code = walSaveMeta(pWal);
  if (code < 0) {
    wError("vgId:%d, failed to save meta since %s", pWal->cfg.vgId, terrstr());
    goto END;
  }
L
Liu Jicong 已提交
453

L
Liu Jicong 已提交
454 455
END:
  return code;
L
Liu Jicong 已提交
456 457
}

L
Liu Jicong 已提交
458
static int32_t walWriteIndex(SWal *pWal, int64_t ver, int64_t offset) {
L
Liu Jicong 已提交
459
  SWalIdxEntry  entry = {.ver = ver, .offset = offset};
460
  SWalFileInfo *pFileInfo = walGetCurFileInfo(pWal);
461 462
  ASSERT(pFileInfo != NULL);
  ASSERT(pFileInfo->firstVer >= 0);
463
  int64_t idxOffset = (entry.ver - pFileInfo->firstVer) * sizeof(SWalIdxEntry);
S
Shengliang Guan 已提交
464
  wDebug("vgId:%d, write index, index:%" PRId64 ", offset:%" PRId64 ", at %" PRId64, pWal->cfg.vgId, ver, offset,
S
Shengliang Guan 已提交
465
         idxOffset);
466

L
Liu Jicong 已提交
467
  int64_t size = taosWriteFile(pWal->pIdxFile, &entry, sizeof(SWalIdxEntry));
L
Liu Jicong 已提交
468
  if (size != sizeof(SWalIdxEntry)) {
469
    wError("vgId:%d, failed to write idx entry due to %s. ver:%" PRId64, pWal->cfg.vgId, strerror(errno), ver);
L
Liu Jicong 已提交
470
    terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
471
    return -1;
L
Liu Jicong 已提交
472
  }
473

474 475 476 477 478
  // check alignment of idx entries
  int64_t endOffset = taosLSeekFile(pWal->pIdxFile, 0, SEEK_END);
  if (endOffset < 0) {
    wFatal("vgId:%d, failed to seek end of idxfile due to %s. ver:%" PRId64 "", pWal->cfg.vgId, strerror(errno), ver);
  }
479
  ASSERT(endOffset == idxOffset + sizeof(SWalIdxEntry) && "Offset of idx entries misaligned");
L
Liu Jicong 已提交
480 481 482
  return 0;
}

L
Liu Jicong 已提交
483 484 485
static FORCE_INLINE int32_t walWriteImpl(SWal *pWal, int64_t index, tmsg_t msgType, SWalSyncInfo syncMeta,
                                         const void *body, int32_t bodyLen) {
  int64_t code = 0;
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
486

L
Liu Jicong 已提交
487
  int64_t       offset = walGetCurFileOffset(pWal);
488
  SWalFileInfo *pFileInfo = walGetCurFileInfo(pWal);
489
  ASSERT(pFileInfo != NULL);
L
Liu Jicong 已提交
490

491
  ASSERT(pFileInfo->firstVer != -1);
L
Liu Jicong 已提交
492
  pWal->writeHead.head.version = index;
L
Liu Jicong 已提交
493
  pWal->writeHead.head.bodyLen = bodyLen;
L
Liu Jicong 已提交
494
  pWal->writeHead.head.msgType = msgType;
495
  pWal->writeHead.head.ingestTs = 0;
L
Liu Jicong 已提交
496

497
  // sync info for sync module
L
Liu Jicong 已提交
498
  pWal->writeHead.head.syncMeta = syncMeta;
L
Liu Jicong 已提交
499

L
Liu Jicong 已提交
500 501
  pWal->writeHead.cksumHead = walCalcHeadCksum(&pWal->writeHead);
  pWal->writeHead.cksumBody = walCalcBodyCksum(body, bodyLen);
502 503
  wDebug("vgId:%d, wal write log %" PRId64 ", msgType: %s, cksum head %u cksum body %u", pWal->cfg.vgId, index,
         TMSG_INFO(msgType), pWal->writeHead.cksumHead, pWal->writeHead.cksumBody);
L
Liu Jicong 已提交
504

505 506 507 508 509
  code = walWriteIndex(pWal, index, offset);
  if (code < 0) {
    goto END;
  }

L
Liu Jicong 已提交
510
  if (taosWriteFile(pWal->pLogFile, &pWal->writeHead, sizeof(SWalCkHead)) != sizeof(SWalCkHead)) {
L
fix  
Liu Jicong 已提交
511
    terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
512 513
    wError("vgId:%d, file:%" PRId64 ".log, failed to write since %s", pWal->cfg.vgId, walGetLastFileFirstVer(pWal),
           strerror(errno));
L
Liu Jicong 已提交
514 515
    code = -1;
    goto END;
J
Jeff Tao 已提交
516
  }
S
TD-1846  
Shengliang Guan 已提交
517

L
Liu Jicong 已提交
518
  if (taosWriteFile(pWal->pLogFile, (char *)body, bodyLen) != bodyLen) {
L
fix  
Liu Jicong 已提交
519
    terrno = TAOS_SYSTEM_ERROR(errno);
L
Liu Jicong 已提交
520 521
    wError("vgId:%d, file:%" PRId64 ".log, failed to write since %s", pWal->cfg.vgId, walGetLastFileFirstVer(pWal),
           strerror(errno));
L
Liu Jicong 已提交
522 523
    code = -1;
    goto END;
L
Liu Jicong 已提交
524
  }
L
Liu Jicong 已提交
525

L
Liu Jicong 已提交
526
  // set status
527
  if (pWal->vers.firstVer == -1) {
528
    ASSERT(index == 0);
529 530
    pWal->vers.firstVer = 0;
  }
L
Liu Jicong 已提交
531
  pWal->vers.lastVer = index;
L
Liu Jicong 已提交
532
  pWal->totSize += sizeof(SWalCkHead) + bodyLen;
533 534
  pFileInfo->lastVer = index;
  pFileInfo->fileSize += sizeof(SWalCkHead) + bodyLen;
L
Liu Jicong 已提交
535

L
Liu Jicong 已提交
536
  return 0;
537

L
Liu Jicong 已提交
538
END:
539 540
  // recover in a reverse order
  if (taosFtruncateFile(pWal->pLogFile, offset) < 0) {
541 542
    wFatal("vgId:%d, failed to ftruncate logfile to offset:%" PRId64 " during recovery due to %s", pWal->cfg.vgId,
           offset, strerror(errno));
543
    terrno = TAOS_SYSTEM_ERROR(errno);
544
    ASSERT(0 && "failed to recover from error");
545 546 547 548
  }

  int64_t idxOffset = (index - pFileInfo->firstVer) * sizeof(SWalIdxEntry);
  if (taosFtruncateFile(pWal->pIdxFile, idxOffset) < 0) {
549 550
    wFatal("vgId:%d, failed to ftruncate idxfile to offset:%" PRId64 "during recovery due to %s", pWal->cfg.vgId,
           idxOffset, strerror(errno));
551
    terrno = TAOS_SYSTEM_ERROR(errno);
552
    ASSERT(0 && "failed to recover from error");
553
  }
L
Liu Jicong 已提交
554 555 556
  return -1;
}

B
Benguang Zhao 已提交
557 558
int64_t walAppendLog(SWal *pWal, int64_t index, tmsg_t msgType, SWalSyncInfo syncMeta, const void *body,
                     int32_t bodyLen) {
L
Liu Jicong 已提交
559 560
  taosThreadMutexLock(&pWal->mutex);

B
Benguang Zhao 已提交
561 562 563 564 565
  if (index != pWal->vers.lastVer + 1) {
    terrno = TSDB_CODE_WAL_INVALID_VER;
    taosThreadMutexUnlock(&pWal->mutex);
    return -1;
  }
L
Liu Jicong 已提交
566 567 568 569 570 571

  if (walCheckAndRoll(pWal) < 0) {
    taosThreadMutexUnlock(&pWal->mutex);
    return -1;
  }

L
Liu Jicong 已提交
572
  if (pWal->pLogFile == NULL || pWal->pIdxFile == NULL || pWal->writeCur < 0) {
L
Liu Jicong 已提交
573 574 575 576 577 578
    if (walInitWriteFile(pWal) < 0) {
      taosThreadMutexUnlock(&pWal->mutex);
      return -1;
    }
  }

579
  ASSERT(pWal->pLogFile != NULL && pWal->pIdxFile != NULL && pWal->writeCur >= 0);
L
Liu Jicong 已提交
580 581 582 583 584 585

  if (walWriteImpl(pWal, index, msgType, syncMeta, body, bodyLen) < 0) {
    taosThreadMutexUnlock(&pWal->mutex);
    return -1;
  }

wafwerar's avatar
wafwerar 已提交
586
  taosThreadMutexUnlock(&pWal->mutex);
L
Liu Jicong 已提交
587 588
  return index;
}
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
589

L
Liu Jicong 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
int32_t walWriteWithSyncInfo(SWal *pWal, int64_t index, tmsg_t msgType, SWalSyncInfo syncMeta, const void *body,
                             int32_t bodyLen) {
  int32_t code = 0;

  taosThreadMutexLock(&pWal->mutex);

  // concurrency control:
  // if logs are write with assigned index,
  // smaller index must be write before larger one
  if (index != pWal->vers.lastVer + 1) {
    terrno = TSDB_CODE_WAL_INVALID_VER;
    taosThreadMutexUnlock(&pWal->mutex);
    return -1;
  }

  if (walCheckAndRoll(pWal) < 0) {
    taosThreadMutexUnlock(&pWal->mutex);
    return -1;
  }

L
Liu Jicong 已提交
610
  if (pWal->pIdxFile == NULL || pWal->pIdxFile == NULL || pWal->writeCur < 0) {
L
Liu Jicong 已提交
611 612 613 614 615 616
    if (walInitWriteFile(pWal) < 0) {
      taosThreadMutexUnlock(&pWal->mutex);
      return -1;
    }
  }

617
  ASSERT(pWal->pIdxFile != NULL && pWal->pLogFile != NULL && pWal->writeCur >= 0);
L
Liu Jicong 已提交
618 619 620 621 622 623 624 625

  if (walWriteImpl(pWal, index, msgType, syncMeta, body, bodyLen) < 0) {
    taosThreadMutexUnlock(&pWal->mutex);
    return -1;
  }

  taosThreadMutexUnlock(&pWal->mutex);
  return code;
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
626 627
}

L
Liu Jicong 已提交
628
int32_t walWrite(SWal *pWal, int64_t index, tmsg_t msgType, const void *body, int32_t bodyLen) {
L
Liu Jicong 已提交
629
  SWalSyncInfo syncMeta = {
L
Liu Jicong 已提交
630 631 632 633
      .isWeek = -1,
      .seqNum = UINT64_MAX,
      .term = UINT64_MAX,
  };
L
Liu Jicong 已提交
634
  return walWriteWithSyncInfo(pWal, index, msgType, syncMeta, body, bodyLen);
L
Liu Jicong 已提交
635 636
}

L
Liu Jicong 已提交
637
void walFsync(SWal *pWal, bool forceFsync) {
L
Liu Jicong 已提交
638
  if (forceFsync || (pWal->cfg.level == TAOS_WAL_FSYNC && pWal->cfg.fsyncPeriod == 0)) {
639 640 641 642 643
    wTrace("vgId:%d, fileId:%" PRId64 ".idx, do fsync", pWal->cfg.vgId, walGetCurFileFirstVer(pWal));
    if (taosFsyncFile(pWal->pIdxFile) < 0) {
      wError("vgId:%d, file:%" PRId64 ".idx, fsync failed since %s", pWal->cfg.vgId, walGetCurFileFirstVer(pWal),
             strerror(errno));
    }
L
Liu Jicong 已提交
644
    wTrace("vgId:%d, fileId:%" PRId64 ".log, do fsync", pWal->cfg.vgId, walGetCurFileFirstVer(pWal));
L
Liu Jicong 已提交
645
    if (taosFsyncFile(pWal->pLogFile) < 0) {
L
Liu Jicong 已提交
646 647
      wError("vgId:%d, file:%" PRId64 ".log, fsync failed since %s", pWal->cfg.vgId, walGetCurFileFirstVer(pWal),
             strerror(errno));
648 649
    }
  }
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
650
}