sdbEngine.c 32.8 KB
Newer Older
H
hzcheng 已提交
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/>.
 */

16
#include "os.h"
H
hzcheng 已提交
17 18 19 20 21 22 23 24 25

#include "sdb.h"
#include "sdbint.h"
#include "tutil.h"

#define abs(x) (((x) < 0) ? -(x) : (x))

extern char   version[];
const int16_t sdbFileVersion = 0;
S
slguan 已提交
26
int           sdbExtConns = 0;
S
slguan 已提交
27 28 29
SRpcIpSet    *pSdbIpList = NULL;
SRpcIpSet    *pSdbPublicIpList = NULL;
SSdbPeer *    sdbPeer[SDB_MAX_PEERS];  // first slot for self
S
slguan 已提交
30 31 32 33

#ifdef CLUSTER
int           sdbMaster = 0;
#else
S
slguan 已提交
34
int           sdbMaster = 1;
S
slguan 已提交
35
#endif
H
hzcheng 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

void *(*sdbInitIndexFp[])(int maxRows, int dataSize) = {sdbOpenStrHash, sdbOpenIntHash, sdbOpenIntHash};

void *(*sdbAddIndexFp[])(void *handle, void *key, void *data) = {sdbAddStrHash, sdbAddIntHash, sdbAddIntHash};

void (*sdbDeleteIndexFp[])(void *handle, void *key) = {sdbDeleteStrHash, sdbDeleteIntHash, sdbDeleteIntHash};

void *(*sdbGetIndexFp[])(void *handle, void *key) = {sdbGetStrHashData, sdbGetIntHashData, sdbGetIntHashData};

void (*sdbCleanUpIndexFp[])(void *handle) = {
    sdbCloseStrHash, sdbCloseIntHash, sdbCloseIntHash,
};

void *(*sdbFetchRowFp[])(void *handle, void *ptr, void **ppRow) = {
    sdbFetchStrHashData, sdbFetchIntHashData, sdbFetchIntHashData,
};

SSdbTable *tableList[20];
int        sdbNumOfTables;
int64_t    sdbVersion;

S
slguan 已提交
57 58 59 60
int64_t sdbGetVersion() {
  return sdbVersion;
};

S
slguan 已提交
61
int32_t sdbGetRunStatus() {
S
slguan 已提交
62 63 64 65
  if (!tsIsCluster) {
    return SDB_STATUS_SERVING;
  }

S
slguan 已提交
66 67 68 69 70 71
  if (sdbInited == NULL) {
    return SDB_STATUS_OFFLINE;
  }
  return sdbStatus;
}

H
hzcheng 已提交
72 73 74 75 76 77
void sdbFinishCommit(void *handle) {
  SSdbTable *pTable = (SSdbTable *)handle;
  uint32_t   sdbEcommit = SDB_ENDCOMMIT;

  off_t offset = lseek(pTable->fd, 0, SEEK_END);
  assert(offset == pTable->size);
S
slguan 已提交
78
  twrite(pTable->fd, &sdbEcommit, sizeof(sdbEcommit));
H
hzcheng 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  pTable->size += sizeof(sdbEcommit);
}

int sdbOpenSdbFile(SSdbTable *pTable) {
  struct stat fstat, ofstat;
  uint64_t    size;
  char *      dirc = NULL;
  char *      basec = NULL;
  union {
    char     cversion[64];
    uint64_t iversion;
  } swVersion;

  memcpy(swVersion.cversion, version, sizeof(uint64_t));

  // check sdb.db and .sdb.db status
  char fn[128] = "\0";
  dirc = strdup(pTable->fn);
  basec = strdup(pTable->fn);
  sprintf(fn, "%s/.%s", dirname(dirc), basename(basec));
  tfree(dirc);
  tfree(basec);
  if (stat(fn, &ofstat) == 0) {  // .sdb.db file exists
    if (stat(pTable->fn, &fstat) == 0) {
      remove(fn);
    } else {
      remove(pTable->fn);
      rename(fn, pTable->fn);
    }
  }

  pTable->fd = open(pTable->fn, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
  if (pTable->fd < 0) {
    sdbError("failed to open file:%s", pTable->fn);
    return -1;
  }

  pTable->size = 0;
  stat(pTable->fn, &fstat);
  size = sizeof(pTable->header);

  if (fstat.st_size == 0) {
    pTable->header.swVersion = swVersion.iversion;
    pTable->header.sdbFileVersion = sdbFileVersion;
    if (taosCalcChecksumAppend(0, (uint8_t *)(&pTable->header), size) < 0) {
S
slguan 已提交
124
      sdbError("failed to get file header checksum, file:%s", pTable->fn);
H
hzcheng 已提交
125 126 127
      tclose(pTable->fd);
      return -1;
    }
S
slguan 已提交
128
    twrite(pTable->fd, &(pTable->header), size);
H
hzcheng 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    pTable->size += size;
    sdbFinishCommit(pTable);
  } else {
    uint32_t sdbEcommit = 0;
    off_t    offset = lseek(pTable->fd, -(sizeof(sdbEcommit)), SEEK_END);
    while (offset > 0) {
      read(pTable->fd, &sdbEcommit, sizeof(sdbEcommit));
      if (sdbEcommit == SDB_ENDCOMMIT) {
        ftruncate(pTable->fd, offset + sizeof(sdbEcommit));
        break;
      }
      offset = lseek(pTable->fd, -(sizeof(sdbEcommit) + 1), SEEK_CUR);
    }
    lseek(pTable->fd, 0, SEEK_SET);

    ssize_t tsize = read(pTable->fd, &(pTable->header), size);
    if (tsize < size) {
S
slguan 已提交
146
      sdbError("failed to read sdb file header, file:%s", pTable->fn);
H
hzcheng 已提交
147 148 149 150 151
      tclose(pTable->fd);
      return -1;
    }

    if (pTable->header.swVersion != swVersion.iversion) {
S
slguan 已提交
152
      sdbWarn("sdb file:%s version not match software version", pTable->fn);
H
hzcheng 已提交
153 154 155
    }

    if (!taosCheckChecksumWhole((uint8_t *)(&pTable->header), size)) {
S
slguan 已提交
156
      sdbError("sdb file header is broken since checksum mismatch, file:%s", pTable->fn);
H
hzcheng 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
      tclose(pTable->fd);
      return -1;
    }

    pTable->size += size;
    // skip end commit symbol
    lseek(pTable->fd, sizeof(sdbEcommit), SEEK_CUR);
    pTable->size += sizeof(sdbEcommit);
  }

  pTable->numOfRows = 0;

  return pTable->fd;
}

// TODO: Change here
void sdbAddIntoUpdateList(SSdbTable *pTable, char type, char *row) {
  pTable->numOfUpdates++;
  pTable->updatePos = pTable->numOfUpdates % pTable->maxRows;

  if (pTable->update[pTable->updatePos].type == SDB_TYPE_DELETE)
    (*(pTable->appTool))(SDB_TYPE_DESTROY, pTable->update[pTable->updatePos].row, NULL, 0, NULL);

  pTable->update[pTable->updatePos].type = type;
  pTable->update[pTable->updatePos].row = row;
}

int sdbInitTableByFile(SSdbTable *pTable) {
  SRowMeta rowMeta;
  int      numOfDels = 0;
  int      bytes = 0;
  int64_t  oldId = 0;
  void *   pMetaRow = NULL;
  int      total_size = 0;
  int      real_size = 0;
S
slguan 已提交
192
  int      maxAutoIndex = 0;
H
hzcheng 已提交
193 194 195 196 197 198 199

  oldId = pTable->id;
  if (sdbOpenSdbFile(pTable) < 0) return -1;

  total_size = sizeof(SRowHead) + pTable->maxRowSize + sizeof(TSCKSUM);
  SRowHead *rowHead = (SRowHead *)malloc(total_size);
  if (rowHead == NULL) {
S
slguan 已提交
200
    sdbError("failed to allocate row head memory, sdb:%s", pTable->name);
H
hzcheng 已提交
201 202 203
    return -1;
  }

S
slguan 已提交
204 205
  sdbTrace("open sdb file:%s for read", pTable->fn);

H
hzcheng 已提交
206 207 208 209 210 211
  // Loop to read sdb file row by row
  while (1) {
    memset(rowHead, 0, total_size);

    bytes = read(pTable->fd, rowHead, sizeof(SRowHead));
    if (bytes < 0) {
S
slguan 已提交
212
      sdbError("failed to read sdb file:%s", pTable->fn);
H
hzcheng 已提交
213 214 215 216 217 218 219 220 221 222 223 224
      goto sdb_exit1;
    }

    if (bytes == 0) break;

    if (bytes < sizeof(SRowHead) || rowHead->delimiter != SDB_DELIMITER) {
      pTable->size++;
      lseek(pTable->fd, -(bytes - 1), SEEK_CUR);
      continue;
    }

    if (rowHead->rowSize < 0 || rowHead->rowSize > pTable->maxRowSize) {
S
slguan 已提交
225 226
      sdbError("error row size in sdb file:%s, id:%d rowSize:%d maxRowSize:%d",
              pTable->fn, rowHead->id, rowHead->rowSize, pTable->maxRowSize);
H
hzcheng 已提交
227 228 229 230 231 232 233 234 235 236
      pTable->size += sizeof(SRowHead);
      continue;
    }

    // sdbTrace("%s id:%ld rowSize:%d", pTable->name, rowHead->id,
    // rowHead->rowSize);

    bytes = read(pTable->fd, rowHead->data, rowHead->rowSize + sizeof(TSCKSUM));
    if (bytes < rowHead->rowSize + sizeof(TSCKSUM)) {
      // TODO: Here may cause pTable->size not end of the file
S
slguan 已提交
237
      sdbError("failed to read sdb file:%s id:%d rowSize:%d", pTable->fn, rowHead->id, rowHead->rowSize);
H
hzcheng 已提交
238 239 240 241 242
      break;
    }

    real_size = sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM);
    if (!taosCheckChecksumWhole((uint8_t *)rowHead, real_size)) {
S
slguan 已提交
243
      sdbError("error sdb checksum, sdb:%s  id:%d, skip", pTable->name, rowHead->id);
H
hzcheng 已提交
244 245 246 247 248 249 250 251 252 253
      pTable->size += real_size;
      continue;
    }

    // Check if the the object exists already

    pMetaRow = sdbGetRow(pTable, rowHead->data);
    if (pMetaRow == NULL) {  // New object
      if (rowHead->id < 0) {
        /* assert(0); */
S
slguan 已提交
254
        sdbError("error sdb negative id:%d, sdb:%s, skip", rowHead->id, pTable->name);
H
hzcheng 已提交
255 256 257 258 259 260 261
      } else {
        rowMeta.id = rowHead->id;
        // TODO: Get rid of the rowMeta.offset and rowSize
        rowMeta.offset = pTable->size;
        rowMeta.rowSize = rowHead->rowSize;
        rowMeta.row = (*(pTable->appTool))(SDB_TYPE_DECODE, NULL, rowHead->data, rowHead->rowSize, NULL);
        (*sdbAddIndexFp[pTable->keyType])(pTable->iHandle, rowMeta.row, &rowMeta);
S
slguan 已提交
262 263
        if (pTable->keyType == SDB_KEYTYPE_AUTO) {
          pTable->autoIndex++;
S
slguan 已提交
264
          maxAutoIndex = MAX(maxAutoIndex, *(int32_t*)rowHead->data);
S
slguan 已提交
265
        }
H
hzcheng 已提交
266 267 268
        pTable->numOfRows++;
      }
    } else {                  // already exists
S
slguan 已提交
269 270
      if (pTable->keyType == SDB_KEYTYPE_AUTO) {
        pTable->autoIndex++;
S
slguan 已提交
271
        maxAutoIndex = MAX(maxAutoIndex, *(int32_t *) rowHead->data);
S
slguan 已提交
272 273
      }

H
hzcheng 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
      if (rowHead->id < 0) {  // Delete the object
        (*sdbDeleteIndexFp[pTable->keyType])(pTable->iHandle, rowHead->data);
        (*(pTable->appTool))(SDB_TYPE_DESTROY, pMetaRow, NULL, 0, NULL);
        pTable->numOfRows--;
        numOfDels++;
      } else {  // Reset the object TODO: is it possible to merge reset and
                // update ??
        (*(pTable->appTool))(SDB_TYPE_RESET, pMetaRow, rowHead->data, rowHead->rowSize, NULL);
      }
      numOfDels++;
    }

    pTable->size += real_size;
    if (pTable->id < abs(rowHead->id)) pTable->id = abs(rowHead->id);
  }

S
slguan 已提交
290 291 292
  if (pTable->keyType == SDB_KEYTYPE_AUTO) {
    pTable->autoIndex = maxAutoIndex;
  }
S
slguan 已提交
293

H
hzcheng 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307
  sdbVersion += (pTable->id - oldId);
  if (numOfDels > pTable->maxRows / 4) sdbSaveSnapShot(pTable);

  pTable->numOfUpdates = 0;
  pTable->updatePos = 0;

  tfree(rowHead);
  return 0;

sdb_exit1:
  tfree(rowHead);
  return -1;
}

S
slguan 已提交
308
void *sdbOpenTable(int maxRows, int32_t maxRowSize, char *name, uint8_t keyType, char *directory,
H
hzcheng 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
                   void *(*appTool)(char, void *, char *, int, int *)) {
  SSdbTable *pTable = (SSdbTable *)malloc(sizeof(SSdbTable));
  if (pTable == NULL) return NULL;
  memset(pTable, 0, sizeof(SSdbTable));

  int size = sizeof(SSdbUpdate) * maxRows;
  pTable->update = (SSdbUpdate *)malloc(size);
  if (pTable->update == NULL) {
    free(pTable);
    return NULL;
  };
  memset(pTable->update, 0, size);

  strcpy(pTable->name, name);
  pTable->keyType = keyType;
  pTable->maxRows = maxRows;
  pTable->maxRowSize = maxRowSize;
  pTable->appTool = appTool;
  sprintf(pTable->fn, "%s/%s.db", directory, pTable->name);

  if (sdbInitIndexFp[keyType] != NULL) pTable->iHandle = (*sdbInitIndexFp[keyType])(maxRows, sizeof(SRowMeta));

  pthread_mutex_init(&pTable->mutex, NULL);

  if (sdbInitTableByFile(pTable) < 0) return NULL;

  pTable->dbId = sdbNumOfTables++;
  tableList[pTable->dbId] = pTable;

  sdbTrace("table:%s is initialized, numOfRows:%d, numOfTables:%d", pTable->name, pTable->numOfRows, sdbNumOfTables);

  return pTable;
}

SRowMeta *sdbGetRowMeta(void *handle, void *key) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta * pMeta;

  if (handle == NULL) return NULL;

  pMeta = (*sdbGetIndexFp[pTable->keyType])(pTable->iHandle, key);

  return pMeta;
}

void *sdbGetRow(void *handle, void *key) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta * pMeta;

  if (handle == NULL) return NULL;

  pthread_mutex_lock(&pTable->mutex);
  pMeta = (*sdbGetIndexFp[pTable->keyType])(pTable->iHandle, key);
  pthread_mutex_unlock(&pTable->mutex);

  if (pMeta == NULL) return NULL;

  return pMeta->row;
}

// row here must be encoded string (rowSize > 0) or the object it self (rowSize
// = 0)
int64_t sdbInsertRow(void *handle, void *row, int rowSize) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta   rowMeta;
  int64_t    id = -1;
  void *     pObj = NULL;
  int        total_size = 0;
  int        real_size = 0;
  /* char       action = SDB_TYPE_INSERT; */

S
slguan 已提交
380 381 382 383
  if (pTable == NULL) {
    sdbError("sdb tables is null");
    return -1;
  }
H
hzcheng 已提交
384

S
slguan 已提交
385
  if ((pTable->keyType != SDB_KEYTYPE_AUTO) || *((int64_t *)row))
S
slguan 已提交
386
    if (sdbGetRow(handle, row)) {
S
slguan 已提交
387 388 389 390 391 392 393
      if (strcmp(pTable->name, "mnode") == 0) {
        /*
         * The first mnode created when the system just start, so the insert action may failed
         * see sdbPeer.c : sdbInitPeers
         */
        pTable->id++;
        sdbVersion++;
L
lihui 已提交
394
        sdbPrint("table:%s, record:%s already exist, think it successed, sdbVersion:%" PRId64 " id:%" PRId64,
S
slguan 已提交
395 396 397 398 399
                pTable->name, taosIpStr(*(int32_t *)row), sdbVersion, pTable->id);
        return 0;
      } else {
        switch (pTable->keyType) {
          case SDB_KEYTYPE_STRING:
L
lihui 已提交
400
            sdbError("table:%s, failed to insert record:%s sdbVersion:%" PRId64 " id:%" PRId64 , pTable->name, (char *)row, sdbVersion, pTable->id);
S
slguan 已提交
401 402
            break;
          case SDB_KEYTYPE_UINT32: //dnodes or mnodes
L
lihui 已提交
403
            sdbError("table:%s, failed to insert record:%s sdbVersion:%" PRId64 " id:%" PRId64, pTable->name, taosIpStr(*(int32_t *)row), sdbVersion, pTable->id);
S
slguan 已提交
404 405
            break;
          case SDB_KEYTYPE_AUTO:
L
lihui 已提交
406
            sdbError("table:%s, failed to insert record:%d sdbVersion:%" PRId64 " id:%" PRId64, pTable->name, *(int32_t *)row, sdbVersion, pTable->id);
S
slguan 已提交
407 408
            break;
          default:
L
lihui 已提交
409
            sdbError("table:%s, failed to insert record sdbVersion:%" PRId64 " id:%" PRId64, pTable->name, sdbVersion, pTable->id);
S
slguan 已提交
410 411 412 413
            break;
        }
        return -1;
      }
S
slguan 已提交
414
    }
H
hzcheng 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433

  total_size = sizeof(SRowHead) + pTable->maxRowSize + sizeof(TSCKSUM);
  SRowHead *rowHead = (SRowHead *)malloc(total_size);
  if (rowHead == NULL) {
    sdbError("failed to allocate row head memory, sdb: %s", pTable->name);
    return -1;
  }
  memset(rowHead, 0, total_size);

  if (rowSize == 0) {  // object is created already
    pObj = row;
  } else {  // encoded string, to create object
    pObj = (*(pTable->appTool))(SDB_TYPE_DECODE, NULL, row, rowSize, NULL);
  }
  (*(pTable->appTool))(SDB_TYPE_ENCODE, pObj, rowHead->data, pTable->maxRowSize, &(rowHead->rowSize));
  assert(rowHead->rowSize > 0 && rowHead->rowSize <= pTable->maxRowSize);

  pthread_mutex_lock(&pTable->mutex);

S
slguan 已提交
434 435 436 437
  if (sdbForwardDbReqToPeer(pTable, SDB_TYPE_INSERT, rowHead->data, rowHead->rowSize) == 0) {
    pTable->id++;
    sdbVersion++;
    if (pTable->keyType == SDB_KEYTYPE_AUTO) {
S
slguan 已提交
438
      // TODO:here need to change
S
slguan 已提交
439 440 441
      *((uint32_t *)pObj) = ++pTable->autoIndex;
      (*(pTable->appTool))(SDB_TYPE_ENCODE, pObj, rowHead->data, pTable->maxRowSize, &(rowHead->rowSize));
    }
H
hzcheng 已提交
442

S
slguan 已提交
443
    real_size = sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM);
H
hzcheng 已提交
444

S
slguan 已提交
445 446 447
    rowHead->delimiter = SDB_DELIMITER;
    rowHead->id = pTable->id;
    if (taosCalcChecksumAppend(0, (uint8_t *)rowHead, real_size) < 0) {
S
slguan 已提交
448
      sdbError("failed to get checksum while inserting, sdb:%s", pTable->name);
S
slguan 已提交
449 450 451 452
      pthread_mutex_unlock(&pTable->mutex);
      tfree(rowHead);
      return -1;
    }
H
hzcheng 已提交
453

S
slguan 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466
    // update in SDB layer
    rowMeta.id = pTable->id;
    rowMeta.offset = pTable->size;
    rowMeta.rowSize = rowHead->rowSize;
    rowMeta.row = pObj;
    (*sdbAddIndexFp[pTable->keyType])(pTable->iHandle, pObj, &rowMeta);

    /* Update the disk content */
    /* write(pTable->fd, &action, sizeof(action)); */
    /* pTable->size += sizeof(action); */
    twrite(pTable->fd, rowHead, real_size);
    pTable->size += real_size;
    sdbFinishCommit(pTable);
H
hzcheng 已提交
467

S
slguan 已提交
468
    sdbAddIntoUpdateList(pTable, SDB_TYPE_INSERT, rowMeta.row);
H
hzcheng 已提交
469

S
slguan 已提交
470 471 472
    pTable->numOfRows++;
    switch (pTable->keyType) {
      case SDB_KEYTYPE_STRING:
L
lihui 已提交
473
        sdbTrace("table:%s, a record is inserted:%s, sdbVersion:%" PRId64 " id:%" PRId64 " rowSize:%d numOfRows:%d fileSize:%" PRId64,
S
slguan 已提交
474 475 476
                pTable->name, (char *)row, sdbVersion, rowHead->id, rowHead->rowSize, pTable->numOfRows, pTable->size);
        break;
      case SDB_KEYTYPE_UINT32: //dnodes or mnodes
L
lihui 已提交
477
        sdbTrace("table:%s, a record is inserted:%s, sdbVersion:%" PRId64 " id:%" PRId64 " rowSize:%d numOfRows:%d fileSize:%" PRId64,
S
slguan 已提交
478
                 pTable->name, taosIpStr(*(int32_t *)row), sdbVersion, rowHead->id, rowHead->rowSize, pTable->numOfRows, pTable->size);
S
slguan 已提交
479 480
        break;
      case SDB_KEYTYPE_AUTO:
L
lihui 已提交
481
        sdbTrace("table:%s, a record is inserted:%d, sdbVersion:%" PRId64 " id:%" PRId64 " rowSize:%d numOfRows:%d fileSize:%" PRId64,
S
slguan 已提交
482
                pTable->name, *(int32_t *)row, sdbVersion, rowHead->id, rowHead->rowSize, pTable->numOfRows, pTable->size);
S
slguan 已提交
483 484
        break;
      default:
L
lihui 已提交
485
        sdbTrace("table:%s, a record is inserted, sdbVersion:%" PRId64 " id:%" PRId64 " rowSize:%d numOfRows:%d fileSize:%" PRId64,
S
slguan 已提交
486
                pTable->name, sdbVersion, rowHead->id, rowHead->rowSize, pTable->numOfRows, pTable->size);
S
slguan 已提交
487 488
        break;
    }
H
hzcheng 已提交
489

S
slguan 已提交
490
    id = rowMeta.id;
S
slguan 已提交
491 492
  } else {
    sdbError("table:%s, failed to insert record", pTable->name);
H
hzcheng 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  }

  tfree(rowHead);

  pthread_mutex_unlock(&pTable->mutex);

  /* callback function to update the MGMT layer */
  if (id >= 0 && pTable->appTool) (*pTable->appTool)(SDB_TYPE_INSERT, pObj, NULL, 0, NULL);

  return id;
}

// row here can be object or null-terminated string
int sdbDeleteRow(void *handle, void *row) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta * pMeta = NULL;
  int        code = -1;
  void *     pMetaRow = NULL;
  SRowHead * rowHead = NULL;
  int        rowSize = 0;
  int        total_size = 0;
  /* char       action     = SDB_TYPE_DELETE; */

  if (pTable == NULL) return -1;

  pMeta = sdbGetRowMeta(handle, row);
  if (pMeta == NULL) {
    sdbTrace("table:%s, record is not there, delete failed", pTable->name);
    return -1;
  }

  pMetaRow = pMeta->row;
  assert(pMetaRow != NULL);

  switch (pTable->keyType) {
    case SDB_KEYTYPE_STRING:
      rowSize = strlen((char *)row) + 1;
      break;
    case SDB_KEYTYPE_UINT32:
      rowSize = sizeof(uint32_t);
      break;
    case SDB_KEYTYPE_AUTO:
      rowSize = sizeof(uint64_t);
      break;
    default:
      return -1;
  }

  total_size = sizeof(SRowHead) + rowSize + sizeof(TSCKSUM);
  rowHead = (SRowHead *)malloc(total_size);
  if (rowHead == NULL) {
S
slguan 已提交
544
    sdbError("failed to allocate row head memory, sdb:%s", pTable->name);
H
hzcheng 已提交
545 546 547 548 549 550
    return -1;
  }
  memset(rowHead, 0, total_size);

  pthread_mutex_lock(&pTable->mutex);

S
slguan 已提交
551 552 553 554 555 556 557 558 559
  if (sdbForwardDbReqToPeer(pTable, SDB_TYPE_DELETE, (char *)row, rowSize) == 0) {
    pTable->id++;
    sdbVersion++;

    rowHead->delimiter = SDB_DELIMITER;
    rowHead->rowSize = rowSize;
    rowHead->id = -(pTable->id);
    memcpy(rowHead->data, row, rowSize);
    if (taosCalcChecksumAppend(0, (uint8_t *)rowHead, total_size) < 0) {
S
slguan 已提交
560
      sdbError("failed to get checksum while inserting, sdb:%s", pTable->name);
S
slguan 已提交
561 562 563 564 565 566 567 568 569 570 571
      pthread_mutex_unlock(&pTable->mutex);
      tfree(rowHead);
      return -1;
    }
    /* write(pTable->fd, &action, sizeof(action)); */
    /* pTable->size += sizeof(action); */
    twrite(pTable->fd, rowHead, total_size);
    pTable->size += total_size;
    sdbFinishCommit(pTable);

    pTable->numOfRows--;
S
slguan 已提交
572
    // TODO:Change the update list here
S
slguan 已提交
573 574 575
    sdbAddIntoUpdateList(pTable, SDB_TYPE_DELETE, pMetaRow);
    switch (pTable->keyType) {
      case SDB_KEYTYPE_STRING:
L
lihui 已提交
576
        sdbTrace("table:%s, a record is deleted:%s, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%d",
S
slguan 已提交
577 578 579
                pTable->name, (char *)row, sdbVersion, pTable->id, pTable->numOfRows);
        break;
      case SDB_KEYTYPE_UINT32:  //dnodes or mnodes
L
lihui 已提交
580
        sdbTrace("table:%s, a record is deleted:%s, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%d",
S
slguan 已提交
581
                 pTable->name, taosIpStr(*(int32_t *)row), sdbVersion, pTable->id, pTable->numOfRows);
S
slguan 已提交
582 583
        break;
      case SDB_KEYTYPE_AUTO:
L
lihui 已提交
584
        sdbTrace("table:%s, a record is deleted:%d, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%d",
S
slguan 已提交
585
                pTable->name, *(int32_t *)row, sdbVersion, pTable->id, pTable->numOfRows);
S
slguan 已提交
586 587
        break;
      default:
L
lihui 已提交
588
        sdbTrace("table:%s, a record is deleted, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%d",
S
slguan 已提交
589 590 591
                pTable->name, sdbVersion, pTable->id, pTable->numOfRows);
        break;
    }
H
hzcheng 已提交
592

S
slguan 已提交
593 594
    // Delete from current layer
    (*sdbDeleteIndexFp[pTable->keyType])(pTable->iHandle, row);
H
hzcheng 已提交
595

S
slguan 已提交
596 597
    code = 0;
  }
H
hzcheng 已提交
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620

  pthread_mutex_unlock(&pTable->mutex);

  tfree(rowHead);

  // callback function of the delete
  if (code == 0 && pTable->appTool) (*pTable->appTool)(SDB_TYPE_DELETE, pMetaRow, NULL, 0, NULL);

  return code;
}

// row here can be the object or the string info (encoded string)
int sdbUpdateRow(void *handle, void *row, int updateSize, char isUpdated) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta * pMeta = NULL;
  int        code = -1;
  int        total_size = 0;
  int        real_size = 0;
  /* char       action     = SDB_TYPE_UPDATE; */

  if (pTable == NULL || row == NULL) return -1;
  pMeta = sdbGetRowMeta(handle, row);
  if (pMeta == NULL) {
S
slguan 已提交
621 622
    switch (pTable->keyType) {
      case SDB_KEYTYPE_STRING:
L
lihui 已提交
623
        sdbError("table:%s, failed to update record:%s, record is not there, sdbVersion:%" PRId64 " id:%" PRId64,
S
slguan 已提交
624 625 626
                pTable->name, (char *) row, sdbVersion, pTable->id);
        break;
      case SDB_KEYTYPE_UINT32: //dnodes or mnodes
L
lihui 已提交
627
        sdbError("table:%s, failed to update record:%s, record is not there, sdbVersion:%" PRId64 " id:%" PRId64,
S
slguan 已提交
628 629 630
                pTable->name, taosIpStr(*(int32_t *) row), sdbVersion, pTable->id);
        break;
      case SDB_KEYTYPE_AUTO:
L
lihui 已提交
631
        sdbError("table:%s, failed to update record:%d, record is not there, sdbVersion:%" PRId64 " id:%" PRId64,
S
slguan 已提交
632 633 634
                pTable->name, *(int32_t *) row, sdbVersion, pTable->id);
        break;
      default:
L
lihui 已提交
635
        sdbError("table:%s, failed to update record, record is not there, sdbVersion:%" PRId64 " id:%" PRId64,
S
slguan 已提交
636 637 638
                pTable->name, sdbVersion, pTable->id);
        break;
    }
H
hzcheng 已提交
639 640 641 642 643 644 645 646 647
    return -1;
  }

  void *pMetaRow = pMeta->row;
  assert(pMetaRow != NULL);

  total_size = sizeof(SRowHead) + pTable->maxRowSize + sizeof(TSCKSUM);
  SRowHead *rowHead = (SRowHead *)malloc(total_size);
  if (rowHead == NULL) {
S
slguan 已提交
648
    sdbError("failed to allocate row head memory, sdb:%s", pTable->name);
H
hzcheng 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    return -1;
  }
  memset(rowHead, 0, total_size);

  if (!isUpdated) {
    (*(pTable->appTool))(SDB_TYPE_UPDATE, pMetaRow, row, updateSize, NULL);  // update in upper layer
  }

  if (pMetaRow != row) {
    memcpy(rowHead->data, row, updateSize);
    rowHead->rowSize = updateSize;
  } else {
    (*(pTable->appTool))(SDB_TYPE_ENCODE, pMetaRow, rowHead->data, pTable->maxRowSize, &(rowHead->rowSize));
  }

  real_size = sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM);
  ;

  pthread_mutex_lock(&pTable->mutex);

S
slguan 已提交
669 670 671
  if (sdbForwardDbReqToPeer(pTable, SDB_TYPE_UPDATE, rowHead->data, rowHead->rowSize) == 0) {
    pTable->id++;
    sdbVersion++;
H
hzcheng 已提交
672

S
slguan 已提交
673 674 675 676
    // write to the new position
    rowHead->delimiter = SDB_DELIMITER;
    rowHead->id = pTable->id;
    if (taosCalcChecksumAppend(0, (uint8_t *)rowHead, real_size) < 0) {
S
slguan 已提交
677
      sdbError("failed to get checksum, sdb:%s id:%d", pTable->name, rowHead->id);
S
slguan 已提交
678 679 680 681 682 683 684
      pthread_mutex_unlock(&pTable->mutex);
      tfree(rowHead);
      return -1;
    }
    /* write(pTable->fd, &action, sizeof(action)); */
    /* pTable->size += sizeof(action); */
    twrite(pTable->fd, rowHead, real_size);
H
hzcheng 已提交
685

S
slguan 已提交
686 687 688 689
    pMeta->id = pTable->id;
    pMeta->offset = pTable->size;
    pMeta->rowSize = rowHead->rowSize;
    pTable->size += real_size;
H
hzcheng 已提交
690

S
slguan 已提交
691
    sdbFinishCommit(pTable);
H
hzcheng 已提交
692

S
slguan 已提交
693 694
    switch (pTable->keyType) {
      case SDB_KEYTYPE_STRING:
L
lihui 已提交
695
        sdbTrace("table:%s, a record is updated:%s, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%" PRId64,
S
slguan 已提交
696 697 698
                pTable->name, (char *)row, sdbVersion, pTable->id, pTable->numOfRows);
        break;
      case SDB_KEYTYPE_UINT32: //dnodes or mnodes
L
lihui 已提交
699
        sdbTrace("table:%s, a record is updated:%s, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%" PRId64,
S
slguan 已提交
700
                 pTable->name, taosIpStr(*(int32_t *)row), sdbVersion, pTable->id, pTable->numOfRows);
S
slguan 已提交
701 702
        break;
      case SDB_KEYTYPE_AUTO:
L
lihui 已提交
703
        sdbTrace("table:%s, a record is updated:%d, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%" PRId64,
S
slguan 已提交
704
                pTable->name, *(int32_t *)row, sdbVersion, pTable->id, pTable->numOfRows);
S
slguan 已提交
705 706
        break;
      default:
L
lihui 已提交
707
        sdbTrace("table:%s, a record is updated, sdbVersion:%" PRId64 " id:%" PRId64 " numOfRows:%" PRId64, pTable->name, sdbVersion,
S
slguan 已提交
708 709 710
                 pTable->id, pTable->numOfRows);
        break;
    }
H
hzcheng 已提交
711

S
slguan 已提交
712 713 714
    sdbAddIntoUpdateList(pTable, SDB_TYPE_UPDATE, pMetaRow);
    code = 0;
  }
H
hzcheng 已提交
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

  pthread_mutex_unlock(&pTable->mutex);

  tfree(rowHead);

  return code;
}

// row here must be the instruction string
int sdbBatchUpdateRow(void *handle, void *row, int rowSize) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta * pMeta = NULL;
  int        total_size = 0;
  /* char        action = SDB_TYPE_BATCH_UPDATE; */

  if (pTable == NULL || row == NULL || rowSize <= 0) return -1;
  pMeta = sdbGetRowMeta(handle, row);
  if (pMeta == NULL) {
S
slguan 已提交
733
    sdbTrace("table:%s, record is not there, batch update failed", pTable->name);
H
hzcheng 已提交
734 735 736 737 738 739 740 741 742
    return -1;
  }

  void *pMetaRow = pMeta->row;
  assert(pMetaRow != NULL);

  total_size = sizeof(SRowHead) + pTable->maxRowSize + sizeof(TSCKSUM);
  SRowHead *rowHead = (SRowHead *)malloc(total_size);
  if (rowHead == NULL) {
S
slguan 已提交
743
    sdbError("failed to allocate row head memory, sdb:%s", pTable->name);
H
hzcheng 已提交
744 745 746 747
    return -1;
  }

  pthread_mutex_lock(&pTable->mutex);
S
slguan 已提交
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
  if (sdbForwardDbReqToPeer(pTable, SDB_TYPE_BATCH_UPDATE, row, rowSize) == 0) {
    /* // write action */
    /* write(pTable->fd, &action, sizeof(action)); */
    /* pTable->size += sizeof(action); */

    (*(pTable->appTool))(SDB_TYPE_BEFORE_BATCH_UPDATE, pMetaRow, NULL, 0, NULL);

    void *next_row = pMetaRow;
    while (next_row != NULL) {
      pTable->id++;
      sdbVersion++;

      void *last_row = next_row;
      next_row = (*(pTable->appTool))(SDB_TYPE_BATCH_UPDATE, last_row, (char *)row, rowSize, 0);
      memset(rowHead, 0, sizeof(SRowHead) + pTable->maxRowSize + sizeof(TSCKSUM));

      // update in current layer
      pMeta->id = pTable->id;
      pMeta->offset = pTable->size;

      // write to disk
      rowHead->delimiter = SDB_DELIMITER;
      rowHead->id = pMeta->id;
      (*(pTable->appTool))(SDB_TYPE_ENCODE, last_row, rowHead->data, pTable->maxRowSize, &(rowHead->rowSize));
      taosCalcChecksumAppend(0, (uint8_t *)rowHead, sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM));
      pMeta->rowSize = rowHead->rowSize;
      lseek(pTable->fd, pTable->size, SEEK_SET);
      twrite(pTable->fd, rowHead, sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM));
      pTable->size += (sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM));

      sdbAddIntoUpdateList(pTable, SDB_TYPE_UPDATE, last_row);

      if (next_row != NULL) {
        pMeta = sdbGetRowMeta(handle, next_row);
      }
H
hzcheng 已提交
783 784
    }

S
slguan 已提交
785
    sdbFinishCommit(pTable);
H
hzcheng 已提交
786

S
slguan 已提交
787 788
    (*(pTable->appTool))(SDB_TYPE_AFTER_BATCH_UPDATE, pMetaRow, NULL, 0, NULL);
  }
H
hzcheng 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
  pthread_mutex_unlock(&pTable->mutex);

  tfree(rowHead);

  return 0;
}

void sdbCloseTable(void *handle) {
  SSdbTable *pTable = (SSdbTable *)handle;
  void *     pNode = NULL;
  void *     row;

  if (pTable == NULL) return;

  while (1) {
    pNode = sdbFetchRow(handle, pNode, &row);
    if (row == NULL) break;
    (*(pTable->appTool))(SDB_TYPE_DESTROY, row, NULL, 0, NULL);
  }

  if (sdbCleanUpIndexFp[pTable->keyType]) (*sdbCleanUpIndexFp[pTable->keyType])(pTable->iHandle);

  if (pTable->fd) tclose(pTable->fd);

  pthread_mutex_destroy(&pTable->mutex);

  sdbNumOfTables--;
L
lihui 已提交
816
  sdbTrace("table:%s is closed, id:%" PRId64 " numOfTables:%d", pTable->name, pTable->id, sdbNumOfTables);
H
hzcheng 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829

  tfree(pTable->update);
  tfree(pTable);
}

void sdbResetTable(SSdbTable *pTable) {
  /* SRowHead rowHead; */
  SRowMeta  rowMeta;
  int       bytes;
  int       total_size = 0;
  int       real_size = 0;
  SRowHead *rowHead = NULL;
  void *    pMetaRow = NULL;
S
#1041  
slguan 已提交
830 831
  int64_t   oldId = pTable->id;
  int       oldNumOfRows = pTable->numOfRows;
H
hzcheng 已提交
832 833

  if (sdbOpenSdbFile(pTable) < 0) return;
S
#1041  
slguan 已提交
834
  pTable->numOfRows = oldNumOfRows;
H
hzcheng 已提交
835 836 837 838

  total_size = sizeof(SRowHead) + pTable->maxRowSize + sizeof(TSCKSUM);
  rowHead = (SRowHead *)malloc(total_size);
  if (rowHead == NULL) {
S
#1041  
slguan 已提交
839
    sdbError("failed to allocate row head memory for reset, sdb:%s", pTable->name);
H
hzcheng 已提交
840 841 842
    return;
  }

S
#1041  
slguan 已提交
843
  sdbPrint("open sdb file:%s for reset table", pTable->fn);
S
slguan 已提交
844

H
hzcheng 已提交
845 846 847 848 849
  while (1) {
    memset(rowHead, 0, total_size);

    bytes = read(pTable->fd, rowHead, sizeof(SRowHead));
    if (bytes < 0) {
S
slguan 已提交
850
      sdbError("failed to read sdb file:%s", pTable->fn);
H
hzcheng 已提交
851 852 853 854 855 856 857 858 859 860 861 862 863
      tfree(rowHead);
      return;
    }

    if (bytes == 0) break;

    if (bytes < sizeof(SRowHead) || rowHead->delimiter != SDB_DELIMITER) {
      pTable->size++;
      lseek(pTable->fd, -(bytes - 1), SEEK_CUR);
      continue;
    }

    if (rowHead->rowSize < 0 || rowHead->rowSize > pTable->maxRowSize) {
S
#1041  
slguan 已提交
864 865
      sdbError("error row size in sdb file:%s for reset, id:%d rowSize:%d maxRowSize:%d",
               pTable->fn, rowHead->id, rowHead->rowSize, pTable->maxRowSize);
H
hzcheng 已提交
866 867 868 869 870 871
      pTable->size += sizeof(SRowHead);
      continue;
    }

    bytes = read(pTable->fd, rowHead->data, rowHead->rowSize + sizeof(TSCKSUM));
    if (bytes < rowHead->rowSize + sizeof(TSCKSUM)) {
S
#1041  
slguan 已提交
872
      sdbError("failed to read sdb file:%s for reset, id:%d  rowSize:%d", pTable->fn, rowHead->id, rowHead->rowSize);
H
hzcheng 已提交
873 874 875 876 877
      break;
    }

    real_size = sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM);
    if (!taosCheckChecksumWhole((uint8_t *)rowHead, real_size)) {
S
slguan 已提交
878
      sdbError("error sdb checksum, sdb:%s  id:%d, skip", pTable->name, rowHead->id);
H
hzcheng 已提交
879 880 881 882 883 884 885 886
      pTable->size += real_size;
      continue;
    }

    if (abs(rowHead->id) > oldId) {  // not operated
      pMetaRow = sdbGetRow(pTable, rowHead->data);
      if (pMetaRow == NULL) {  // New object
        if (rowHead->id < 0) {
S
slguan 已提交
887
          sdbError("error sdb negative id:%d, sdb:%s, skip", rowHead->id, pTable->name);
H
hzcheng 已提交
888 889
        } else {
          rowMeta.id = rowHead->id;
S
slguan 已提交
890
          // TODO:Get rid of the rowMeta.offset and rowSize
H
hzcheng 已提交
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
          rowMeta.offset = pTable->size;
          rowMeta.rowSize = rowHead->rowSize;
          rowMeta.row = (*(pTable->appTool))(SDB_TYPE_DECODE, NULL, rowHead->data, rowHead->rowSize, NULL);
          (*sdbAddIndexFp[pTable->keyType])(pTable->iHandle, rowMeta.row, &rowMeta);
          pTable->numOfRows++;

          (*pTable->appTool)(SDB_TYPE_INSERT, rowMeta.row, NULL, 0, NULL);
        }
      } else {                  // already exists
        if (rowHead->id < 0) {  // Delete the object
          (*sdbDeleteIndexFp[pTable->keyType])(pTable->iHandle, rowHead->data);
          (*(pTable->appTool))(SDB_TYPE_DESTROY, pMetaRow, NULL, 0, NULL);
          pTable->numOfRows--;
        } else {  // update the object
          (*(pTable->appTool))(SDB_TYPE_UPDATE, pMetaRow, rowHead->data, rowHead->rowSize, NULL);
        }
      }
    }

    pTable->size += real_size;
    if (pTable->id < abs(rowHead->id)) pTable->id = abs(rowHead->id);
  }

  sdbVersion += (pTable->id - oldId);
  pTable->numOfUpdates = 0;
  pTable->updatePos = 0;

  tfree(rowHead);

L
lihui 已提交
920
  sdbPrint("table:%s is updated, sdbVerion:%" PRId64 " id:%" PRId64, pTable->name, sdbVersion, pTable->id);
H
hzcheng 已提交
921 922
}

S
slguan 已提交
923
// TODO:A problem here :use snapshot file to sync another node will cause
H
hzcheng 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
// problem
void sdbSaveSnapShot(void *handle) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta * pMeta;
  void *     pNode = NULL;
  int        total_size = 0;
  int        real_size = 0;
  int        size = 0;
  int        numOfRows = 0;
  uint32_t   sdbEcommit = SDB_ENDCOMMIT;
  char *     dirc = NULL;
  char *     basec = NULL;
  /* char       action = SDB_TYPE_INSERT; */

  if (pTable == NULL) return;

  sdbTrace("Table:%s, save the snapshop", pTable->name);

  char fn[128] = "\0";
  dirc = strdup(pTable->fn);
  basec = strdup(pTable->fn);
  sprintf(fn, "%s/.%s", dirname(dirc), basename(basec));
  int fd = open(fn, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
  tfree(dirc);
  tfree(basec);

  total_size = sizeof(SRowHead) + pTable->maxRowSize + sizeof(TSCKSUM);
  SRowHead *rowHead = (SRowHead *)malloc(total_size);
  if (rowHead == NULL) {
S
slguan 已提交
953
    sdbError("failed to allocate memory while saving SDB snapshot, sdb:%s", pTable->name);
H
hzcheng 已提交
954 955 956 957 958
    return;
  }
  memset(rowHead, 0, size);

  // Write the header
S
slguan 已提交
959
  twrite(fd, &(pTable->header), sizeof(SSdbHeader));
H
hzcheng 已提交
960
  size += sizeof(SSdbHeader);
S
slguan 已提交
961
  twrite(fd, &sdbEcommit, sizeof(sdbEcommit));
H
hzcheng 已提交
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
  size += sizeof(sdbEcommit);

  while (1) {
    pNode = (*sdbFetchRowFp[pTable->keyType])(pTable->iHandle, pNode, (void **)&pMeta);
    if (pMeta == NULL) break;

    rowHead->delimiter = SDB_DELIMITER;
    rowHead->id = pMeta->id;
    (*(pTable->appTool))(SDB_TYPE_ENCODE, pMeta->row, rowHead->data, pTable->maxRowSize, &(rowHead->rowSize));
    real_size = sizeof(SRowHead) + rowHead->rowSize + sizeof(TSCKSUM);
    if (taosCalcChecksumAppend(0, (uint8_t *)rowHead, real_size) < 0) {
      sdbError("failed to get checksum while save sdb %s snapshot", pTable->name);
      tfree(rowHead);
      return;
    }

    /* write(fd, &action, sizeof(action)); */
    /* size += sizeof(action); */
S
slguan 已提交
980
    twrite(fd, rowHead, real_size);
H
hzcheng 已提交
981
    size += real_size;
S
slguan 已提交
982
    twrite(fd, &sdbEcommit, sizeof(sdbEcommit));
H
hzcheng 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    size += sizeof(sdbEcommit);
    numOfRows++;
  }

  tfree(rowHead);

  // Remove the old file
  tclose(pTable->fd);
  remove(pTable->fn);
  // Rename the .sdb.db file to sdb.db file
  rename(fn, pTable->fn);
  pTable->fd = fd;
  pTable->size = size;
  pTable->numOfRows = numOfRows;

  fdatasync(pTable->fd);
}

void *sdbFetchRow(void *handle, void *pNode, void **ppRow) {
  SSdbTable *pTable = (SSdbTable *)handle;
  SRowMeta * pMeta;

  *ppRow = NULL;
  if (pTable == NULL) return NULL;

  pNode = (*sdbFetchRowFp[pTable->keyType])(pTable->iHandle, pNode, (void **)&pMeta);
  if (pMeta == NULL) return NULL;

  *ppRow = pMeta->row;

  return pNode;
}

int64_t sdbGetId(void *handle) { return ((SSdbTable *)handle)->id; }

int64_t sdbGetNumOfRows(void *handle) { return ((SSdbTable *)handle)->numOfRows; }