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

wafwerar's avatar
wafwerar 已提交
19
#ifdef WINDOWS
20
#include <io.h>
wafwerar's avatar
wafwerar 已提交
21 22 23
#define F_OK 0
#define W_OK 2
#define R_OK 4
24

wafwerar's avatar
wafwerar 已提交
25 26
#define _SEND_FILE_STEP_ 1000

27
#else
28 29
#include <fcntl.h>
#include <sys/file.h>
30 31

#if !defined(_TD_DARWIN_64)
L
Liu Jicong 已提交
32
#include <sys/sendfile.h>
33
#endif
34 35 36 37
#include <sys/stat.h>
#include <unistd.h>
#define LINUX_FILE_NO_TEXT_OPTION 0
#define O_TEXT                    LINUX_FILE_NO_TEXT_OPTION
wafwerar's avatar
wafwerar 已提交
38 39

#define _SEND_FILE_STEP_ 1000
40 41
#endif

wafwerar's avatar
wafwerar 已提交
42 43 44
typedef int32_t FileFd;

typedef struct TdFile {
wafwerar's avatar
wafwerar 已提交
45
  TdThreadRwlock rwlock;
L
Liu Jicong 已提交
46 47 48
  int            refId;
  FileFd         fd;
  FILE          *fp;
49
} TdFile;
wafwerar's avatar
wafwerar 已提交
50

51 52
#define FILE_WITH_LOCK 1

53
void taosGetTmpfilePath(const char *inputTmpDir, const char *fileNamePrefix, char *dstPath) {
wafwerar's avatar
wafwerar 已提交
54
#ifdef WINDOWS
S
Shengliang Guan 已提交
55
  const char *tdengineTmpFileNamePrefix = "tdengine-";
S
TD-4088  
Shengliang Guan 已提交
56
  char        tmpPath[PATH_MAX];
S
Shengliang Guan 已提交
57

S
Shengliang Guan 已提交
58 59
  int32_t len = (int32_t)strlen(inputTmpDir);
  memcpy(tmpPath, inputTmpDir, len);
S
TD-4088  
Shengliang Guan 已提交
60 61 62

  if (tmpPath[len - 1] != '/' && tmpPath[len - 1] != '\\') {
    tmpPath[len++] = '\\';
63
  }
S
Shengliang Guan 已提交
64

65
  strcpy(tmpPath + len, tdengineTmpFileNamePrefix);
S
Shengliang Guan 已提交
66 67 68
  if (strlen(tmpPath) + strlen(fileNamePrefix) + strlen("-%d-%s") < PATH_MAX) {
    strcat(tmpPath, fileNamePrefix);
    strcat(tmpPath, "-%d-%s");
S
Shengliang Guan 已提交
69
  }
S
Shengliang Guan 已提交
70

S
TD-4088  
Shengliang Guan 已提交
71 72
  char rand[8] = {0};
  taosRandStr(rand, tListLen(rand) - 1);
S
Shengliang Guan 已提交
73
  snprintf(dstPath, PATH_MAX, tmpPath, getpid(), rand);
S
TD-1912  
Shengliang Guan 已提交
74

S
TD-4088  
Shengliang Guan 已提交
75
#else
S
Shengliang Guan 已提交
76

S
TD-4088  
Shengliang Guan 已提交
77
  const char *tdengineTmpFileNamePrefix = "tdengine-";
S
Shengliang Guan 已提交
78

79
  char    tmpPath[PATH_MAX];
S
Shengliang Guan 已提交
80 81
  int32_t len = strlen(inputTmpDir);
  memcpy(tmpPath, inputTmpDir, len);
S
TD-4088  
Shengliang Guan 已提交
82
  static uint64_t seqId = 0;
S
Shengliang Guan 已提交
83

S
TD-4088  
Shengliang Guan 已提交
84 85
  if (tmpPath[len - 1] != '/') {
    tmpPath[len++] = '/';
S
TD-1912  
Shengliang Guan 已提交
86
  }
S
Shengliang Guan 已提交
87

S
TD-4088  
Shengliang Guan 已提交
88 89 90 91
  strcpy(tmpPath + len, tdengineTmpFileNamePrefix);
  if (strlen(tmpPath) + strlen(fileNamePrefix) + strlen("-%d-%s") < PATH_MAX) {
    strcat(tmpPath, fileNamePrefix);
    strcat(tmpPath, "-%d-%s");
S
Shengliang Guan 已提交
92 93
  }

S
TD-4088  
Shengliang Guan 已提交
94 95 96
  char rand[32] = {0};

  sprintf(rand, "%" PRIu64, atomic_add_fetch_64(&seqId, 1));
S
Shengliang Guan 已提交
97

S
TD-4088  
Shengliang Guan 已提交
98
  snprintf(dstPath, PATH_MAX, tmpPath, getpid(), rand);
S
Shengliang Guan 已提交
99

S
TD-4088  
Shengliang Guan 已提交
100
#endif
S
Shengliang Guan 已提交
101
}
S
TD-4088  
Shengliang Guan 已提交
102

103
int64_t taosCopyFile(const char *from, const char *to) {
wafwerar's avatar
wafwerar 已提交
104
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
105 106 107 108 109
  if (CopyFile(from, to, 0)) {
    return 1;
  } else {
    return -1;
  }
110 111 112 113 114 115
#else
  char    buffer[4096];
  int64_t size = 0;
  int64_t bytes;

  // fidfrom = open(from, O_RDONLY);
116
  TdFilePtr pFileFrom = taosOpenFile(from, TD_FILE_READ);
117 118 119
  if (pFileFrom == NULL) goto _err;

  // fidto = open(to, O_WRONLY | O_CREAT | O_EXCL, 0755);
120
  TdFilePtr pFileTo = taosOpenFile(to, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_EXCL);
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  if (pFileTo == NULL) goto _err;

  while (true) {
    bytes = taosReadFile(pFileFrom, buffer, sizeof(buffer));
    if (bytes < 0) goto _err;
    if (bytes == 0) break;

    size += bytes;

    if (taosWriteFile(pFileTo, (void *)buffer, bytes) < bytes) goto _err;
    if (bytes < sizeof(buffer)) break;
  }

  taosFsyncFile(pFileTo);

  taosCloseFile(&pFileFrom);
  taosCloseFile(&pFileTo);
  return size;

_err:
  if (pFileFrom != NULL) taosCloseFile(&pFileFrom);
  if (pFileTo != NULL) taosCloseFile(&pFileTo);
143
  taosRemoveFile(to);
144 145 146 147
  return -1;
#endif
}

C
Cary Xu 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
TdFilePtr taosCreateFile(const char *path, int32_t tdFileOptions) {
  TdFilePtr fp = taosOpenFile(path, tdFileOptions);
  if (!fp) {
    if (errno == ENOENT) {
      // Try to create directory recursively
      char *s = strdup(path);
      if (taosMulMkDir(taosDirName(s)) != 0) {
        taosMemoryFree(s);
        return NULL;
      }
      taosMemoryFree(s);
      fp = taosOpenFile(path, tdFileOptions);
      if (!fp) {
        return NULL;
      }
    }
  }
  return fp;
}

168 169
int32_t taosRemoveFile(const char *path) { return remove(path); }

170
int32_t taosRenameFile(const char *oldName, const char *newName) {
wafwerar's avatar
wafwerar 已提交
171
#ifdef WINDOWS
172 173
  bool code = MoveFileEx(oldName, newName, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);
  if (!code) {
C
Cary Xu 已提交
174
    printf("failed to rename file %s to %s, reason:%s\n", oldName, newName, strerror(errno));
175 176
  }

A
Alex Duan 已提交
177
  return code ? 0 : -1;
178 179 180
#else
  int32_t code = rename(oldName, newName);
  if (code < 0) {
C
Cary Xu 已提交
181
    printf("failed to rename file %s to %s, reason:%s\n", oldName, newName, strerror(errno));
182 183 184 185 186 187 188
  }

  return code;
#endif
}

int32_t taosStatFile(const char *path, int64_t *size, int32_t *mtime) {
wafwerar's avatar
wafwerar 已提交
189
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
190
  struct _stati64 fileStat;
H
Hongze Cheng 已提交
191
  int32_t         code = _stati64(path, &fileStat);
192
#else
wafwerar's avatar
wafwerar 已提交
193
  struct stat fileStat;
H
Hongze Cheng 已提交
194
  int32_t     code = stat(path, &fileStat);
195
#endif
196 197 198 199 200 201 202 203 204 205 206 207 208 209
  if (code < 0) {
    return code;
  }

  if (size != NULL) {
    *size = fileStat.st_size;
  }

  if (mtime != NULL) {
    *mtime = fileStat.st_mtime;
  }

  return 0;
}
wafwerar's avatar
wafwerar 已提交
210 211 212 213 214
int32_t taosDevInoFile(TdFilePtr pFile, int64_t *stDev, int64_t *stIno) {
  if (pFile == NULL) {
    return 0;
  }
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
215

wafwerar's avatar
wafwerar 已提交
216
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
217 218

  BY_HANDLE_FILE_INFORMATION bhfi;
219
  HANDLE                     handle = (HANDLE)_get_osfhandle(pFile->fd);
wafwerar's avatar
wafwerar 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232
  if (GetFileInformationByHandle(handle, &bhfi) == FALSE) {
    printf("taosFStatFile get file info fail.");
    return -1;
  }

  if (stDev != NULL) {
    *stDev = (int64_t)(bhfi.dwVolumeSerialNumber);
  }

  if (stIno != NULL) {
    *stIno = (int64_t)((((uint64_t)bhfi.nFileIndexHigh) << 32) + bhfi.nFileIndexLow);
  }

233
#else
234

wafwerar's avatar
wafwerar 已提交
235 236
  struct stat fileStat;
  int32_t     code = fstat(pFile->fd, &fileStat);
237
  if (code < 0) {
wafwerar's avatar
wafwerar 已提交
238
    printf("taosFStatFile run fstat fail.");
239 240 241 242 243 244 245 246 247 248
    return code;
  }

  if (stDev != NULL) {
    *stDev = fileStat.st_dev;
  }

  if (stIno != NULL) {
    *stIno = fileStat.st_ino;
  }
wafwerar's avatar
wafwerar 已提交
249
#endif
250 251 252

  return 0;
}
253

254
TdFilePtr taosOpenFile(const char *path, int32_t tdFileOptions) {
L
Liu Jicong 已提交
255
  int   fd = -1;
256 257 258 259 260
  FILE *fp = NULL;
  if (tdFileOptions & TD_FILE_STREAM) {
    char *mode = NULL;
    if (tdFileOptions & TD_FILE_APPEND) {
      mode = (tdFileOptions & TD_FILE_TEXT) ? "at+" : "ab+";
L
Liu Jicong 已提交
261
    } else if (tdFileOptions & TD_FILE_TRUNC) {
262
      mode = (tdFileOptions & TD_FILE_TEXT) ? "wt+" : "wb+";
L
Liu Jicong 已提交
263
    } else if ((tdFileOptions & TD_FILE_READ) && !(tdFileOptions & TD_FILE_WRITE)) {
264
      mode = (tdFileOptions & TD_FILE_TEXT) ? "rt" : "rb";
L
Liu Jicong 已提交
265
    } else {
266 267 268 269 270 271 272 273 274
      mode = (tdFileOptions & TD_FILE_TEXT) ? "rt+" : "rb+";
    }
    assert(!(tdFileOptions & TD_FILE_EXCL));
    fp = fopen(path, mode);
    if (fp == NULL) {
      return NULL;
    }
  } else {
    int access = O_BINARY;
275
    access |= (tdFileOptions & TD_FILE_CREATE) ? O_CREAT : 0;
276 277 278 279 280 281 282 283 284 285 286
    if ((tdFileOptions & TD_FILE_WRITE) && (tdFileOptions & TD_FILE_READ)) {
      access |= O_RDWR;
    } else if (tdFileOptions & TD_FILE_WRITE) {
      access |= O_WRONLY;
    } else if (tdFileOptions & TD_FILE_READ) {
      access |= O_RDONLY;
    }
    access |= (tdFileOptions & TD_FILE_TRUNC) ? O_TRUNC : 0;
    access |= (tdFileOptions & TD_FILE_APPEND) ? O_APPEND : 0;
    access |= (tdFileOptions & TD_FILE_TEXT) ? O_TEXT : 0;
    access |= (tdFileOptions & TD_FILE_EXCL) ? O_EXCL : 0;
L
Liu Jicong 已提交
287
#ifdef WINDOWS
288 289 290 291 292
    int32_t pmode = _S_IREAD | _S_IWRITE;
    if (tdFileOptions & TD_FILE_AUTO_DEL) {
      pmode |= _O_TEMPORARY;
    }
    fd = _open(path, access, pmode);
L
Liu Jicong 已提交
293
#else
294
    fd = open(path, access, S_IRWXU | S_IRWXG | S_IRWXO);
L
Liu Jicong 已提交
295
#endif
296 297 298 299 300
    if (fd == -1) {
      return NULL;
    }
  }

wafwerar's avatar
wafwerar 已提交
301
  TdFilePtr pFile = (TdFilePtr)taosMemoryMalloc(sizeof(TdFile));
302
  if (pFile == NULL) {
303 304
    if (fd >= 0) close(fd);
    if (fp != NULL) fclose(fp);
305 306
    return NULL;
  }
307

308
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
309
  taosThreadRwlockInit(&(pFile->rwlock), NULL);
310
#endif
311 312 313
  pFile->fd = fd;
  pFile->fp = fp;
  pFile->refId = 0;
314

wafwerar's avatar
wafwerar 已提交
315
  if (tdFileOptions & TD_FILE_AUTO_DEL) {
316 317 318 319 320 321 322 323
#ifdef WINDOWS
    // do nothing, since the property of pmode is set with _O_TEMPORARY; the OS will recycle
    // the file handle, as well as the space on disk.
#else
    // Remove it instantly, so when the program exits normally/abnormally, the file
    // will be automatically remove by OS.
    unlink(path);
#endif
wafwerar's avatar
wafwerar 已提交
324
  }
325

326 327 328
  return pFile;
}

L
Liu Jicong 已提交
329 330
int32_t taosCloseFile(TdFilePtr *ppFile) {
  int32_t code = 0;
331 332 333 334
  if (ppFile == NULL || *ppFile == NULL) {
    return 0;
  }
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
335
  taosThreadRwlockWrlock(&((*ppFile)->rwlock));
336
#endif
337 338 339 340 341 342
  if ((*ppFile)->fp != NULL) {
    fflush((*ppFile)->fp);
    fclose((*ppFile)->fp);
    (*ppFile)->fp = NULL;
  }
  if ((*ppFile)->fd >= 0) {
343
#ifdef WINDOWS
344 345
    HANDLE h = (HANDLE)_get_osfhandle((*ppFile)->fd);
    !FlushFileBuffers(h);
346
#else
L
Liu Jicong 已提交
347 348
    // warning: never fsync silently in base lib
    /*fsync((*ppFile)->fd);*/
349
#endif
L
Liu Jicong 已提交
350
    code = close((*ppFile)->fd);
351 352
    (*ppFile)->fd = -1;
  }
353
  (*ppFile)->refId = 0;
354
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
355 356
  taosThreadRwlockUnlock(&((*ppFile)->rwlock));
  taosThreadRwlockDestroy(&((*ppFile)->rwlock));
357
#endif
wafwerar's avatar
wafwerar 已提交
358
  taosMemoryFree(*ppFile);
359
  *ppFile = NULL;
L
Liu Jicong 已提交
360
  return code;
361 362 363
}

int64_t taosReadFile(TdFilePtr pFile, void *buf, int64_t count) {
364
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
365
  taosThreadRwlockRdlock(&(pFile->rwlock));
366
#endif
L
Liu Jicong 已提交
367
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
S
TD-1912  
Shengliang Guan 已提交
368 369
  int64_t leftbytes = count;
  int64_t readbytes;
370
  char   *tbuf = (char *)buf;
S
Shengliang Guan 已提交
371 372

  while (leftbytes > 0) {
373
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
374
    readbytes = _read(pFile->fd, (void *)tbuf, (uint32_t)leftbytes);
375
#else
376
    readbytes = read(pFile->fd, (void *)tbuf, (uint32_t)leftbytes);
377
#endif
S
Shengliang Guan 已提交
378 379 380 381
    if (readbytes < 0) {
      if (errno == EINTR) {
        continue;
      } else {
382
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
383
        taosThreadRwlockUnlock(&(pFile->rwlock));
384
#endif
S
Shengliang Guan 已提交
385 386 387
        return -1;
      }
    } else if (readbytes == 0) {
388
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
389
      taosThreadRwlockUnlock(&(pFile->rwlock));
390
#endif
S
TD-1912  
Shengliang Guan 已提交
391
      return (int64_t)(count - leftbytes);
S
Shengliang Guan 已提交
392 393 394 395 396 397
    }

    leftbytes -= readbytes;
    tbuf += readbytes;
  }

398
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
399
  taosThreadRwlockUnlock(&(pFile->rwlock));
400
#endif
S
TD-1912  
Shengliang Guan 已提交
401
  return count;
S
Shengliang Guan 已提交
402 403
}

404
int64_t taosPReadFile(TdFilePtr pFile, void *buf, int64_t count, int64_t offset) {
405
  if (pFile == NULL) {
406 407
    return 0;
  }
408
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
409
  taosThreadRwlockRdlock(&(pFile->rwlock));
410
#endif
L
Liu Jicong 已提交
411
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
wafwerar's avatar
wafwerar 已提交
412
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
413 414
  size_t pos = _lseeki64(pFile->fd, 0, SEEK_CUR);
  _lseeki64(pFile->fd, offset, SEEK_SET);
wafwerar's avatar
wafwerar 已提交
415
  int64_t ret = _read(pFile->fd, buf, count);
wafwerar's avatar
wafwerar 已提交
416
  _lseeki64(pFile->fd, pos, SEEK_SET);
wafwerar's avatar
wafwerar 已提交
417
#else
418
  int64_t ret = pread(pFile->fd, buf, count, offset);
wafwerar's avatar
wafwerar 已提交
419
#endif
420
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
421
  taosThreadRwlockUnlock(&(pFile->rwlock));
422 423
#endif
  return ret;
424 425 426
}

int64_t taosWriteFile(TdFilePtr pFile, const void *buf, int64_t count) {
wafwerar's avatar
wafwerar 已提交
427 428 429
  if (pFile == NULL) {
    return 0;
  }
430
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
431
  taosThreadRwlockWrlock(&(pFile->rwlock));
432
#endif
433 434 435
  if (pFile->fd < 0) {
    return 0;
  }
436

437
  int64_t nleft = count;
S
TD-1912  
Shengliang Guan 已提交
438
  int64_t nwritten = 0;
439
  char   *tbuf = (char *)buf;
S
Shengliang Guan 已提交
440 441

  while (nleft > 0) {
442
    nwritten = write(pFile->fd, (void *)tbuf, (uint32_t)nleft);
S
Shengliang Guan 已提交
443 444 445 446
    if (nwritten < 0) {
      if (errno == EINTR) {
        continue;
      }
447
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
448
      taosThreadRwlockUnlock(&(pFile->rwlock));
449
#endif
S
Shengliang Guan 已提交
450 451 452 453 454
      return -1;
    }
    nleft -= nwritten;
    tbuf += nwritten;
  }
455

456
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
457
  taosThreadRwlockUnlock(&(pFile->rwlock));
458
#endif
459
  return count;
S
Shengliang Guan 已提交
460 461
}

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
int64_t taosPWriteFile(TdFilePtr pFile, const void *buf, int64_t count, int64_t offset) {
  if (pFile == NULL) {
    return 0;
  }
#if FILE_WITH_LOCK
  taosThreadRwlockWrlock(&(pFile->rwlock));
#endif
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
#ifdef WINDOWS
  size_t pos = _lseeki64(pFile->fd, 0, SEEK_CUR);
  _lseeki64(pFile->fd, offset, SEEK_SET);
  int64_t ret = _write(pFile->fd, buf, count);
  _lseeki64(pFile->fd, pos, SEEK_SET);
#else
  int64_t ret = pwrite(pFile->fd, buf, count, offset);
#endif
#if FILE_WITH_LOCK
  taosThreadRwlockUnlock(&(pFile->rwlock));
#endif
  return ret;
}

484
int64_t taosLSeekFile(TdFilePtr pFile, int64_t offset, int32_t whence) {
485
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
486
  taosThreadRwlockRdlock(&(pFile->rwlock));
487
#endif
L
Liu Jicong 已提交
488
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
wafwerar's avatar
wafwerar 已提交
489
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
490
  int64_t ret = _lseeki64(pFile->fd, offset, whence);
wafwerar's avatar
wafwerar 已提交
491
#else
L
Liu Jicong 已提交
492
  int64_t ret = lseek(pFile->fd, offset, whence);
wafwerar's avatar
wafwerar 已提交
493
#endif
494
#if FILE_WITH_LOCK
wafwerar's avatar
wafwerar 已提交
495
  taosThreadRwlockUnlock(&(pFile->rwlock));
496 497
#endif
  return ret;
498
}
S
Shengliang Guan 已提交
499

500
int32_t taosFStatFile(TdFilePtr pFile, int64_t *size, int32_t *mtime) {
501 502 503
  if (pFile == NULL) {
    return 0;
  }
L
Liu Jicong 已提交
504
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
505

506
  struct stat fileStat;
507
#ifdef WINDOWS
508
  int32_t code = _fstat(pFile->fd, &fileStat);
509
#else
510
  int32_t code = fstat(pFile->fd, &fileStat);
511
#endif
512 513 514
  if (code < 0) {
    return code;
  }
H
Hongze Cheng 已提交
515

516 517 518
  if (size != NULL) {
    *size = fileStat.st_size;
  }
H
Hongze Cheng 已提交
519

520 521 522
  if (mtime != NULL) {
    *mtime = fileStat.st_mtime;
  }
H
Hongze Cheng 已提交
523

524 525
  return 0;
}
H
Hongze Cheng 已提交
526

527
int32_t taosLockFile(TdFilePtr pFile) {
wafwerar's avatar
wafwerar 已提交
528
#ifdef WINDOWS
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  BOOL          fSuccess = FALSE;
  LARGE_INTEGER fileSize;
  OVERLAPPED    overlapped = {0};

  HANDLE hFile = (HANDLE)_get_osfhandle(pFile->fd);

  fSuccess = LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
                        0,           // reserved
                        ~0,          // number of bytes to lock low
                        ~0,          // number of bytes to lock high
                        &overlapped  // overlapped structure
  );
  if (!fSuccess) {
    return GetLastError();
  }
544 545
  return 0;
#else
L
Liu Jicong 已提交
546
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
547

548 549 550
  return (int32_t)flock(pFile->fd, LOCK_EX | LOCK_NB);
#endif
}
H
Hongze Cheng 已提交
551

552
int32_t taosUnLockFile(TdFilePtr pFile) {
wafwerar's avatar
wafwerar 已提交
553
#ifdef WINDOWS
554 555 556 557 558 559 560 561
  BOOL          fSuccess = FALSE;
  OVERLAPPED    overlapped = {0};
  HANDLE        hFile = (HANDLE)_get_osfhandle(pFile->fd);

  fSuccess = UnlockFileEx(hFile, 0, ~0, ~0, &overlapped);
  if (!fSuccess) {
    return GetLastError();
  }
562 563
  return 0;
#else
L
Liu Jicong 已提交
564
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
565

566 567 568 569 570
  return (int32_t)flock(pFile->fd, LOCK_UN | LOCK_NB);
#endif
}

int32_t taosFtruncateFile(TdFilePtr pFile, int64_t l_size) {
wafwerar's avatar
wafwerar 已提交
571
#ifdef WINDOWS
572 573
  if (pFile->fd < 0) {
    errno = EBADF;
574
    printf("Ftruncate file error, fd arg was negative\n");
575
    return -1;
H
Hongze Cheng 已提交
576 577
  }

578
  HANDLE h = (HANDLE)_get_osfhandle(pFile->fd);
H
Hongze Cheng 已提交
579

580 581 582 583
  LARGE_INTEGER li_0;
  li_0.QuadPart = (int64_t)0;
  BOOL cur = SetFilePointerEx(h, li_0, NULL, FILE_CURRENT);
  if (!cur) {
wafwerar's avatar
wafwerar 已提交
584
    printf("SetFilePointerEx Error getting current position in file.\n");
585 586
    return -1;
  }
H
Hongze Cheng 已提交
587

588 589 590 591 592
  LARGE_INTEGER li_size;
  li_size.QuadPart = l_size;
  BOOL cur2 = SetFilePointerEx(h, li_size, NULL, FILE_BEGIN);
  if (cur2 == 0) {
    int error = GetLastError();
wafwerar's avatar
wafwerar 已提交
593
    printf("SetFilePointerEx GetLastError is: %d\n", error);
594 595 596 597 598 599 600 601 602 603 604 605 606
    switch (error) {
      case ERROR_INVALID_HANDLE:
        errno = EBADF;
        break;
      default:
        errno = EIO;
        break;
    }
    return -1;
  }

  if (!SetEndOfFile(h)) {
    int error = GetLastError();
wafwerar's avatar
wafwerar 已提交
607
    printf("SetEndOfFile GetLastError is:%d", error);
608 609 610 611 612 613 614 615 616 617 618 619 620
    switch (error) {
      case ERROR_INVALID_HANDLE:
        errno = EBADF;
        break;
      default:
        errno = EIO;
        break;
    }
    return -1;
  }

  return 0;
#else
621 622 623
  if (pFile == NULL) {
    return 0;
  }
L
Liu Jicong 已提交
624
  assert(pFile->fd >= 0);  // Please check if you have closed the file.
625

626 627 628 629 630
  return ftruncate(pFile->fd, l_size);
#endif
}

int32_t taosFsyncFile(TdFilePtr pFile) {
631 632 633 634
  if (pFile == NULL) {
    return 0;
  }

L
Liu Jicong 已提交
635 636
  // this implementation is WRONG
  // fflush is not a replacement of fsync
637
  if (pFile->fp != NULL) return fflush(pFile->fp);
638
  if (pFile->fd >= 0) {
639
#ifdef WINDOWS
640 641
    HANDLE h = (HANDLE)_get_osfhandle(pFile->fd);
    return !FlushFileBuffers(h);
642
#else
643
    return fsync(pFile->fd);
644
#endif
645
  }
646
  return 0;
H
Hongze Cheng 已提交
647 648
}

wafwerar's avatar
wafwerar 已提交
649 650 651
int64_t taosFSendFile(TdFilePtr pFileOut, TdFilePtr pFileIn, int64_t *offset, int64_t size) {
  if (pFileOut == NULL || pFileIn == NULL) {
    return 0;
S
TD-4088  
Shengliang Guan 已提交
652
  }
wafwerar's avatar
wafwerar 已提交
653
  assert(pFileIn->fd >= 0 && pFileOut->fd >= 0);
S
TD-4088  
Shengliang Guan 已提交
654

wafwerar's avatar
wafwerar 已提交
655
#ifdef WINDOWS
S
TD-4088  
Shengliang Guan 已提交
656

wafwerar's avatar
wafwerar 已提交
657
  _lseeki64(pFileIn->fd, *offset, 0);
S
TD-4088  
Shengliang Guan 已提交
658 659 660
  int64_t writeLen = 0;
  uint8_t buffer[_SEND_FILE_STEP_] = {0};

wafwerar's avatar
wafwerar 已提交
661
  for (int64_t len = 0; len < (size - _SEND_FILE_STEP_); len += _SEND_FILE_STEP_) {
wafwerar's avatar
wafwerar 已提交
662
    size_t rlen = _read(pFileIn->fd, (void *)buffer, _SEND_FILE_STEP_);
S
TD-4088  
Shengliang Guan 已提交
663 664 665
    if (rlen <= 0) {
      return writeLen;
    } else if (rlen < _SEND_FILE_STEP_) {
wafwerar's avatar
wafwerar 已提交
666
      write(pFileOut->fd, (void *)buffer, (uint32_t)rlen);
S
TD-4088  
Shengliang Guan 已提交
667 668
      return (int64_t)(writeLen + rlen);
    } else {
wafwerar's avatar
wafwerar 已提交
669
      write(pFileOut->fd, (void *)buffer, _SEND_FILE_STEP_);
S
TD-4088  
Shengliang Guan 已提交
670 671 672 673
      writeLen += _SEND_FILE_STEP_;
    }
  }

wafwerar's avatar
wafwerar 已提交
674
  int64_t remain = size - writeLen;
S
TD-4088  
Shengliang Guan 已提交
675
  if (remain > 0) {
wafwerar's avatar
wafwerar 已提交
676
    size_t rlen = _read(pFileIn->fd, (void *)buffer, (size_t)remain);
S
TD-4088  
Shengliang Guan 已提交
677 678 679
    if (rlen <= 0) {
      return writeLen;
    } else {
wafwerar's avatar
wafwerar 已提交
680
      write(pFileOut->fd, (void *)buffer, (uint32_t)remain);
S
TD-4088  
Shengliang Guan 已提交
681 682 683 684 685 686
      writeLen += remain;
    }
  }
  return writeLen;

#elif defined(_TD_DARWIN_64)
S
TD-1912  
Shengliang Guan 已提交
687

wafwerar's avatar
wafwerar 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701
  lseek(pFileIn->fd, (int32_t)(*offset), 0);
  int64_t writeLen = 0;
  uint8_t buffer[_SEND_FILE_STEP_] = {0};

  for (int64_t len = 0; len < (size - _SEND_FILE_STEP_); len += _SEND_FILE_STEP_) {
    size_t rlen = read(pFileIn->fd, (void *)buffer, _SEND_FILE_STEP_);
    if (rlen <= 0) {
      return writeLen;
    } else if (rlen < _SEND_FILE_STEP_) {
      write(pFileOut->fd, (void *)buffer, (uint32_t)rlen);
      return (int64_t)(writeLen + rlen);
    } else {
      write(pFileOut->fd, (void *)buffer, _SEND_FILE_STEP_);
      writeLen += _SEND_FILE_STEP_;
S
TD-4088  
Shengliang Guan 已提交
702
    }
wafwerar's avatar
wafwerar 已提交
703 704 705 706 707 708 709 710 711 712
  }

  int64_t remain = size - writeLen;
  if (remain > 0) {
    size_t rlen = read(pFileIn->fd, (void *)buffer, (size_t)remain);
    if (rlen <= 0) {
      return writeLen;
    } else {
      write(pFileOut->fd, (void *)buffer, (uint32_t)remain);
      writeLen += remain;
S
TD-4088  
Shengliang Guan 已提交
713 714
    }
  }
wafwerar's avatar
wafwerar 已提交
715
  return writeLen;
S
TD-4088  
Shengliang Guan 已提交
716 717 718

#else

S
TD-1912  
Shengliang Guan 已提交
719 720
  int64_t leftbytes = size;
  int64_t sentbytes;
S
Shengliang Guan 已提交
721 722

  while (leftbytes > 0) {
H
Hongze Cheng 已提交
723 724 725
#ifdef _TD_ARM_32
    sentbytes = sendfile(pFileOut->fd, pFileIn->fd, (long int *)offset, leftbytes);
#else
726
    sentbytes = sendfile(pFileOut->fd, pFileIn->fd, offset, leftbytes);
H
Hongze Cheng 已提交
727
#endif
S
Shengliang Guan 已提交
728
    if (sentbytes == -1) {
S
TD-1985  
Shengliang Guan 已提交
729
      if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
S
Shengliang Guan 已提交
730 731 732 733 734
        continue;
      } else {
        return -1;
      }
    } else if (sentbytes == 0) {
S
TD-1912  
Shengliang Guan 已提交
735
      return (int64_t)(size - leftbytes);
S
Shengliang Guan 已提交
736 737 738 739 740 741
    }

    leftbytes -= sentbytes;
  }

  return size;
S
Shengliang Guan 已提交
742
#endif
wafwerar's avatar
wafwerar 已提交
743
}
S
Shengliang Guan 已提交
744

745
void taosFprintfFile(TdFilePtr pFile, const char *format, ...) {
746 747 748 749 750
  if (pFile == NULL) {
    return;
  }
  assert(pFile->fp != NULL);

751
  va_list ap;
752
  va_start(ap, format);
753
  vfprintf(pFile->fp, format, ap);
754
  va_end(ap);
S
Shengliang Guan 已提交
755 756
}

757
bool taosValidFile(TdFilePtr pFile) { return pFile != NULL && pFile->fd > 0; }
S
Shengliang Guan 已提交
758

759
int32_t taosUmaskFile(int32_t maskVal) {
wafwerar's avatar
wafwerar 已提交
760
#ifdef WINDOWS
S
Shengliang Guan 已提交
761 762
  return 0;
#else
763
  return umask(maskVal);
S
TD-4088  
Shengliang Guan 已提交
764
#endif
765 766
}

767
int32_t taosGetErrorFile(TdFilePtr pFile) { return errno; }
wafwerar's avatar
wafwerar 已提交
768
int64_t taosGetLineFile(TdFilePtr pFile, char **__restrict ptrBuf) {
L
Liu Jicong 已提交
769
  if (pFile == NULL || ptrBuf == NULL) {
770 771
    return -1;
  }
wafwerar's avatar
wafwerar 已提交
772 773 774
  if (*ptrBuf != NULL) {
    taosMemoryFreeClear(*ptrBuf);
  }
775
  assert(pFile->fp != NULL);
wafwerar's avatar
wafwerar 已提交
776 777 778 779 780 781 782 783 784 785
#ifdef WINDOWS
  *ptrBuf = taosMemoryMalloc(1024);
  if (*ptrBuf == NULL) return -1;
  if (fgets(*ptrBuf, 1023, pFile->fp) == NULL) {
    taosMemoryFreeClear(*ptrBuf);
    return -1;
  }
  (*ptrBuf)[1023] = 0;
  return strlen(*ptrBuf);
#else
786 787
  size_t len = 0;
  return getline(ptrBuf, &len, pFile->fp);
wafwerar's avatar
wafwerar 已提交
788
#endif
789
}
H
Haojun Liao 已提交
790

wafwerar's avatar
wafwerar 已提交
791
int64_t taosGetsFile(TdFilePtr pFile, int32_t maxSize, char *__restrict buf) {
L
Liu Jicong 已提交
792
  if (pFile == NULL || buf == NULL) {
wafwerar's avatar
wafwerar 已提交
793 794 795 796 797 798 799 800
    return -1;
  }
  assert(pFile->fp != NULL);
  if (fgets(buf, maxSize, pFile->fp) == NULL) {
    return -1;
  }
  return strlen(buf);
}
H
Haojun Liao 已提交
801

L
Liu Jicong 已提交
802
int32_t taosEOFFile(TdFilePtr pFile) {
803 804 805 806 807
  if (pFile == NULL) {
    return 0;
  }
  assert(pFile->fp != NULL);

L
Liu Jicong 已提交
808
  return feof(pFile->fp);
L
fix  
Liu Jicong 已提交
809
}
810

811 812 813 814 815 816 817 818 819 820 821 822 823 824
bool taosCheckAccessFile(const char *pathname, int32_t tdFileAccessOptions) {
  int flags = 0;

  if (tdFileAccessOptions & TD_FILE_ACCESS_EXIST_OK) {
    flags |= F_OK;
  }

  if (tdFileAccessOptions & TD_FILE_ACCESS_READ_OK) {
    flags |= R_OK;
  }

  if (tdFileAccessOptions & TD_FILE_ACCESS_WRITE_OK) {
    flags |= W_OK;
  }
wafwerar's avatar
wafwerar 已提交
825 826 827
#ifdef WINDOWS
  return _access(pathname, flags) == 0;
#else
828
  return access(pathname, flags) == 0;
wafwerar's avatar
wafwerar 已提交
829
#endif
830
}
831 832

bool taosCheckExistFile(const char *pathname) { return taosCheckAccessFile(pathname, TD_FILE_ACCESS_EXIST_OK); };