osSysinfo.c 28.7 KB
Newer Older
S
Shengliang Guan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 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
/*
 * 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/>.
 */

#define _DEFAULT_SOURCE
#include "os.h"

int32_t tsTotalMemoryMB = 0;
int64_t tsPageSize = 0;
int64_t tsOpenMax = 0;
int64_t tsStreamMax = 0;
int32_t tsNumOfCores = 1;
char    tsTimezone[TSDB_TIMEZONE_LEN] = {0};
char    tsLocale[TSDB_LOCALE_LEN] = {0};
char    tsCharset[TSDB_LOCALE_LEN] = {0};  // default encode string

#if defined(_TD_WINDOWS_64) || defined(_TD_WINDOWS_32)

/*
 * windows implementation
 */

#if (_WIN64)
#include <iphlpapi.h>
#include <mswsock.h>
#include <psapi.h>
#include <stdio.h>
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Mswsock.lib ")
#endif

#include <objbase.h>

#pragma warning(push)
#pragma warning(disable : 4091)
#include <DbgHelp.h>
#pragma warning(pop)

static int32_t taosGetTotalMemory() {
  MEMORYSTATUSEX memsStat;
  memsStat.dwLength = sizeof(memsStat);
  if (!GlobalMemoryStatusEx(&memsStat)) {
    return 0;
  }

  float nMemTotal = memsStat.ullTotalPhys / (1024.0f * 1024.0f);
  return (int32_t)nMemTotal;
}

bool taosGetSysMemory(float *memoryUsedMB) {
  MEMORYSTATUSEX memsStat;
  memsStat.dwLength = sizeof(memsStat);
  if (!GlobalMemoryStatusEx(&memsStat)) {
    return false;
  }

  float nMemFree = memsStat.ullAvailPhys / (1024.0f * 1024.0f);
  float nMemTotal = memsStat.ullTotalPhys / (1024.0f * 1024.0f);

  *memoryUsedMB = nMemTotal - nMemFree;
  return true;
}

bool taosGetProcMemory(float *memoryUsedMB) {
  unsigned bytes_used = 0;

#if defined(_WIN64) && defined(_MSC_VER)
  PROCESS_MEMORY_COUNTERS pmc;
  HANDLE                  cur_proc = GetCurrentProcess();

  if (GetProcessMemoryInfo(cur_proc, &pmc, sizeof(pmc))) {
    bytes_used = (unsigned)(pmc.WorkingSetSize + pmc.PagefileUsage);
  }
#endif

  *memoryUsedMB = (float)bytes_used / 1024 / 1024;
  return true;
}

static void taosGetSystemTimezone() {
  // get and set default timezone
  char *tz = getenv("TZ");
  if (tz == NULL || strlen(tz) == 0) {
    strcpy(tsTimezone, "not configured");
  } else {
    strcpy(tsTimezone, tz);
  }
}

static void taosGetSystemLocale() {
  // get and set default locale
  char *locale = setlocale(LC_CTYPE, "chs");
  if (locale != NULL) {
    tstrncpy(tsLocale, locale, TSDB_LOCALE_LEN);
  }

  strcpy(tsCharset, "cp936");
}

int32_t taosGetCpuCores() {
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  return (int32_t)info.dwNumberOfProcessors;
}

bool taosGetCpuUsage(float *sysCpuUsage, float *procCpuUsage) {
  *sysCpuUsage = 0;
  *procCpuUsage = 0;
  return true;
}

124
int32_t taosGetDiskSize(char *dataDir, SDiskSize *diskSize) {
S
Shengliang Guan 已提交
125 126 127 128 129 130 131 132 133 134 135 136
  unsigned _int64 i64FreeBytesToCaller;
  unsigned _int64 i64TotalBytes;
  unsigned _int64 i64FreeBytes;

  BOOL fResult = GetDiskFreeSpaceExA(dataDir, (PULARGE_INTEGER)&i64FreeBytesToCaller, (PULARGE_INTEGER)&i64TotalBytes,
                                     (PULARGE_INTEGER)&i64FreeBytes);
  if (fResult) {
    diskSize->tsize = (int64_t)(i64TotalBytes);
    diskSize->avail = (int64_t)(i64FreeBytesToCaller);
    diskSize->used = (int64_t)(i64TotalBytes - i64FreeBytes);
    return 0;
  } else {
S
Shengliang Guan 已提交
137
    //printf("failed to get disk size, dataDir:%s errno:%s", tsDataDir, strerror(errno));
S
Shengliang Guan 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    terrno = TAOS_SYSTEM_ERROR(errno);
    return -1;
  }
}

bool taosGetCardInfo(int64_t *bytes, int64_t *rbytes, int64_t *tbytes) {
  if (bytes) *bytes = 0;
  if (rbytes) *rbytes = 0;
  if (tbytes) *tbytes = 0;
  return true;
}

bool taosGetBandSpeed(float *bandSpeedKb) {
  *bandSpeedKb = 0;
  return true;
}

bool taosReadProcIO(int64_t *readbyte, int64_t *writebyte) {
  IO_COUNTERS io_counter;
  if (GetProcessIoCounters(GetCurrentProcess(), &io_counter)) {
    if (readbyte) *readbyte = io_counter.ReadTransferCount;
    if (writebyte) *writebyte = io_counter.WriteTransferCount;
    return true;
  }
  return false;
}

bool taosGetProcIO(float *readKB, float *writeKB) {
  static int64_t lastReadbyte = -1;
  static int64_t lastWritebyte = -1;

  int64_t curReadbyte = 0;
  int64_t curWritebyte = 0;

  if (!taosReadProcIO(&curReadbyte, &curWritebyte)) {
    return false;
  }

  if (lastReadbyte == -1 || lastWritebyte == -1) {
    lastReadbyte = curReadbyte;
    lastWritebyte = curWritebyte;
    return false;
  }

  *readKB = (float)((double)(curReadbyte - lastReadbyte) / 1024);
  *writeKB = (float)((double)(curWritebyte - lastWritebyte) / 1024);
  if (*readKB < 0) *readKB = 0;
  if (*writeKB < 0) *writeKB = 0;

  lastReadbyte = curReadbyte;
  lastWritebyte = curWritebyte;

  return true;
}

void taosGetSystemInfo() {
  tsNumOfCores = taosGetCpuCores();
  tsTotalMemoryMB = taosGetTotalMemory();

  float tmp1, tmp2;
  // taosGetDisk();
  taosGetBandSpeed(&tmp1);
  taosGetCpuUsage(&tmp1, &tmp2);
  taosGetProcIO(&tmp1, &tmp2);

  taosGetSystemTimezone();
  taosGetSystemLocale();
}

void taosKillSystem() {
S
Shengliang Guan 已提交
208
  //printf("function taosKillSystem, exit!");
S
Shengliang Guan 已提交
209 210 211 212
  exit(0);
}

int taosSystem(const char *cmd) {
S
Shengliang Guan 已提交
213
  //printf("taosSystem not support");
S
Shengliang Guan 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  return -1;
}

LONG WINAPI FlCrashDump(PEXCEPTION_POINTERS ep) {
  typedef BOOL(WINAPI * FxMiniDumpWriteDump)(IN HANDLE hProcess, IN DWORD ProcessId, IN HANDLE hFile,
                                             IN MINIDUMP_TYPE                           DumpType,
                                             IN CONST PMINIDUMP_EXCEPTION_INFORMATION   ExceptionParam,
                                             IN CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
                                             IN CONST PMINIDUMP_CALLBACK_INFORMATION    CallbackParam);

  HMODULE dll = LoadLibrary("dbghelp.dll");
  if (dll == NULL) return EXCEPTION_CONTINUE_SEARCH;
  FxMiniDumpWriteDump mdwd = (FxMiniDumpWriteDump)(GetProcAddress(dll, "MiniDumpWriteDump"));
  if (mdwd == NULL) {
    FreeLibrary(dll);
    return EXCEPTION_CONTINUE_SEARCH;
  }

  TCHAR path[MAX_PATH];
  DWORD len = GetModuleFileName(NULL, path, _countof(path));
  path[len - 3] = 'd';
  path[len - 2] = 'm';
  path[len - 1] = 'p';

  HANDLE file = CreateFile(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  MINIDUMP_EXCEPTION_INFORMATION mei;
  mei.ThreadId = GetCurrentThreadId();
  mei.ExceptionPointers = ep;
  mei.ClientPointers = FALSE;

  (*mdwd)(GetCurrentProcess(), GetCurrentProcessId(), file, MiniDumpWithHandleData, &mei, NULL, NULL);

  CloseHandle(file);
  FreeLibrary(dll);

  return EXCEPTION_CONTINUE_SEARCH;
}

void taosSetCoreDump() { SetUnhandledExceptionFilter(&FlCrashDump); }

H
Haojun Liao 已提交
255
int32_t taosGetSystemUUID(char *uid, int32_t uidlen) {
S
Shengliang Guan 已提交
256 257 258 259 260 261
  GUID guid;
  CoCreateGuid(&guid);

  sprintf(uid, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0],
          guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);

S
Shengliang Guan 已提交
262
  return 0;
S
Shengliang Guan 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
}

char *taosGetCmdlineByPID(int pid) { return ""; }

#elif defined(_TD_DARWIN_64)

/*
 * darwin implementation
 */

#include <errno.h>
#include <libproc.h>

static void taosGetSystemTimezone() {
  /* load time zone string from /etc/localtime */
  char  buf[4096];
  char *tz = NULL;
  {
    int n = readlink("/etc/localtime", buf, sizeof(buf));
    if (n < 0) {
S
Shengliang Guan 已提交
283
      //printf("read /etc/localtime error, reason:%s", strerror(errno));
S
Shengliang Guan 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296
      return;
    }
    buf[n] = '\0';
    for (int i = n - 1; i >= 0; --i) {
      if (buf[i] == '/') {
        if (tz) {
          tz = buf + i + 1;
          break;
        }
        tz = buf + i + 1;
      }
    }
    if (!tz || 0 == strchr(tz, '/')) {
S
Shengliang Guan 已提交
297
      //printf("parsing /etc/localtime failed");
S
Shengliang Guan 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
      return;
    }

    setenv("TZ", tz, 1);
    tzset();
  }

  /*
   * NOTE: do not remove it.
   * Enforce set the correct daylight saving time(DST) flag according
   * to current time
   */
  time_t    tx1 = time(NULL);
  struct tm tm1;
  localtime_r(&tx1, &tm1);

  /*
   * format example:
   *
   * Asia/Shanghai   (CST, +0800)
   * Europe/London   (BST, +0100)
   */
  snprintf(tsTimezone, TSDB_TIMEZONE_LEN, "%s (%s, %+03ld00)", tz, tm1.tm_isdst ? tzname[daylight] : tzname[0],
           -timezone / 3600);

  // cfg_timezone->cfgStatus = TAOS_CFG_CSTATUS_DEFAULT;
S
Shengliang Guan 已提交
324
  //printf("timezone not configured, set to system default:%s", tsTimezone);
S
Shengliang Guan 已提交
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
}

/*
 * originally from src/os/src/detail/osSysinfo.c
 * POSIX format locale string:
 * (Language Strings)_(Country/Region Strings).(code_page)
 *
 * example: en_US.UTF-8, zh_CN.GB18030, zh_CN.UTF-8,
 *
 * if user does not specify the locale in taos.cfg the program use default LC_CTYPE as system locale.
 *
 * In case of some CentOS systems, their default locale is "en_US.utf8", which is not valid code_page
 * for libiconv that is employed to convert string in this system. This program will automatically use
 * UTF-8 instead as the charset.
 *
 * In case of windows client, the locale string is not valid POSIX format, user needs to set the
 * correct code_page for libiconv. Usually, the code_page of windows system with simple chinese is
 * CP936, CP437 for English charset.
 *
 */
static void taosGetSystemLocale() {  // get and set default locale
  char  sep = '.';
  char *locale = NULL;

  locale = setlocale(LC_CTYPE, "");
  if (locale == NULL) {
S
Shengliang Guan 已提交
351
    //printf("can't get locale from system, set it to en_US.UTF-8 since error:%d:%s", errno, strerror(errno));
S
Shengliang Guan 已提交
352 353 354
    strcpy(tsLocale, "en_US.UTF-8");
  } else {
    tstrncpy(tsLocale, locale, TSDB_LOCALE_LEN);
S
Shengliang Guan 已提交
355
    //printf("locale not configured, set to system default:%s", tsLocale);
S
Shengliang Guan 已提交
356 357 358 359 360 361 362 363 364 365 366
  }

  /* if user does not specify the charset, extract it from locale */
  char *str = strrchr(tsLocale, sep);
  if (str != NULL) {
    str++;

    char *revisedCharset = taosCharsetReplace(str);
    tstrncpy(tsCharset, revisedCharset, TSDB_LOCALE_LEN);

    free(revisedCharset);
S
Shengliang Guan 已提交
367
    //printf("charset not configured, set to system default:%s", tsCharset);
S
Shengliang Guan 已提交
368 369
  } else {
    strcpy(tsCharset, "UTF-8");
S
Shengliang Guan 已提交
370
    //printf("can't get locale and charset from system, set it to UTF-8");
S
Shengliang Guan 已提交
371 372 373 374
  }
}

void taosKillSystem() {
S
Shengliang Guan 已提交
375
  //printf("function taosKillSystem, exit!");
S
Shengliang Guan 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  exit(0);
}

int32_t taosGetCpuCores() { return sysconf(_SC_NPROCESSORS_ONLN); }

void taosGetSystemInfo() {
  // taosGetProcInfos();

  tsNumOfCores = sysconf(_SC_NPROCESSORS_ONLN);
  long physical_pages = sysconf(_SC_PHYS_PAGES);
  long page_size = sysconf(_SC_PAGESIZE);
  tsTotalMemoryMB = physical_pages * page_size / (1024 * 1024);
  tsPageSize = page_size;

  taosGetSystemTimezone();
  taosGetSystemLocale();
}

bool taosReadProcIO(int64_t *rchars, int64_t *wchars) {
  if (rchars) *rchars = 0;
  if (wchars) *wchars = 0;
  return true;
}

bool taosGetProcIO(float *readKB, float *writeKB) {
  *readKB = 0;
  *writeKB = 0;
  return true;
}

bool taosGetCardInfo(int64_t *bytes, int64_t *rbytes, int64_t *tbytes) {
  if (bytes) *bytes = 0;
  if (rbytes) *rbytes = 0;
  if (tbytes) *tbytes = 0;
  return true;
}

bool taosGetBandSpeed(float *bandSpeedKb) {
  *bandSpeedKb = 0;
  return true;
}

bool taosGetCpuUsage(float *sysCpuUsage, float *procCpuUsage) {
  *sysCpuUsage = 0;
  *procCpuUsage = 0;
  return true;
}

bool taosGetProcMemory(float *memoryUsedMB) {
  *memoryUsedMB = 0;
  return true;
}

bool taosGetSysMemory(float *memoryUsedMB) {
  *memoryUsedMB = 0;
  return true;
}

int taosSystem(const char *cmd) {
S
Shengliang Guan 已提交
435
  //printf("un support funtion");
S
Shengliang Guan 已提交
436 437 438 439 440
  return -1;
}

void taosSetCoreDump() {}

441
int32_t taosGetDiskSize(char *dataDir, SDiskSize *diskSize) {
S
Shengliang Guan 已提交
442 443
  struct statvfs info;
  if (statvfs(dataDir, &info)) {
S
Shengliang Guan 已提交
444
    //printf("failed to get disk size, dataDir:%s errno:%s", tsDataDir, strerror(errno));
S
Shengliang Guan 已提交
445 446 447 448 449 450 451 452 453 454
    terrno = TAOS_SYSTEM_ERROR(errno);
    return -1;
  } else {
    diskSize->tsize = info.f_blocks * info.f_frsize;
    diskSize->avail = info.f_bavail * info.f_frsize;
    diskSize->used = (info.f_blocks - info.f_bfree) * info.f_frsize;
    return 0;
  }
}

H
Haojun Liao 已提交
455
int32_t taosGetSystemUUID(char *uid, int32_t uidlen) {
S
Shengliang Guan 已提交
456 457 458 459
  uuid_t uuid = {0};
  uuid_generate(uuid);
  // it's caller's responsibility to make enough space for `uid`, that's 36-char + 1-null
  uuid_unparse_lower(uuid, uid);
S
Shengliang Guan 已提交
460
  return 0;
S
Shengliang Guan 已提交
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
}

char *taosGetCmdlineByPID(int pid) {
  static char cmdline[1024];
  errno = 0;

  if (proc_pidpath(pid, cmdline, sizeof(cmdline)) <= 0) {
    fprintf(stderr, "PID is %d, %s", pid, strerror(errno));
    return strerror(errno);
  }

  return cmdline;
}

#else

/*
 * linux implementation
 */

#include <argp.h>
#include <linux/sysctl.h>
#include <sys/file.h>
#include <sys/resource.h>
#include <sys/statvfs.h>
#include <sys/syscall.h>
#include <sys/utsname.h>
S
Shengliang Guan 已提交
488
#include <unistd.h>
S
Shengliang Guan 已提交
489 490 491 492 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

#define PROCESS_ITEM 12

typedef struct {
  uint64_t user;
  uint64_t nice;
  uint64_t system;
  uint64_t idle;
} SysCpuInfo;

typedef struct {
  uint64_t utime;   // user time
  uint64_t stime;   // kernel time
  uint64_t cutime;  // all user time
  uint64_t cstime;  // all dead time
} ProcCpuInfo;

static pid_t tsProcId;
static char  tsSysNetFile[] = "/proc/net/dev";
static char  tsSysCpuFile[] = "/proc/stat";
static char  tsProcCpuFile[25] = {0};
static char  tsProcMemFile[25] = {0};
static char  tsProcIOFile[25] = {0};
static float tsPageSizeKB = 0;

static void taosGetProcInfos() {
  tsPageSize = sysconf(_SC_PAGESIZE);
  tsOpenMax = sysconf(_SC_OPEN_MAX);
  tsStreamMax = sysconf(_SC_STREAM_MAX);

  tsProcId = (pid_t)syscall(SYS_gettid);
  tsPageSizeKB = (float)(sysconf(_SC_PAGESIZE)) / 1024;

  snprintf(tsProcMemFile, 25, "/proc/%d/status", tsProcId);
  snprintf(tsProcCpuFile, 25, "/proc/%d/stat", tsProcId);
  snprintf(tsProcIOFile, 25, "/proc/%d/io", tsProcId);
}

static int32_t taosGetTotalMemory() { return (int32_t)((float)sysconf(_SC_PHYS_PAGES) * tsPageSizeKB / 1024); }

bool taosGetSysMemory(float *memoryUsedMB) {
  float memoryAvailMB = (float)sysconf(_SC_AVPHYS_PAGES) * tsPageSizeKB / 1024;
  *memoryUsedMB = (float)tsTotalMemoryMB - memoryAvailMB;
  return true;
}

bool taosGetProcMemory(float *memoryUsedMB) {
  FILE *fp = fopen(tsProcMemFile, "r");
  if (fp == NULL) {
S
Shengliang Guan 已提交
538
    //printf("open file:%s failed", tsProcMemFile);
S
Shengliang Guan 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
    return false;
  }

  ssize_t _bytes = 0;
  size_t  len;
  char *  line = NULL;
  while (!feof(fp)) {
    tfree(line);
    len = 0;
    _bytes = getline(&line, &len, fp);
    if ((_bytes < 0) || (line == NULL)) {
      break;
    }
    if (strstr(line, "VmRSS:") != NULL) {
      break;
    }
  }

  if (line == NULL) {
S
Shengliang Guan 已提交
558
    //printf("read file:%s failed", tsProcMemFile);
S
Shengliang Guan 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    fclose(fp);
    return false;
  }

  int64_t memKB = 0;
  char    tmp[10];
  sscanf(line, "%s %" PRId64, tmp, &memKB);
  *memoryUsedMB = (float)((double)memKB / 1024);

  tfree(line);
  fclose(fp);
  return true;
}

static bool taosGetSysCpuInfo(SysCpuInfo *cpuInfo) {
  FILE *fp = fopen(tsSysCpuFile, "r");
  if (fp == NULL) {
S
Shengliang Guan 已提交
576
    //printf("open file:%s failed", tsSysCpuFile);
S
Shengliang Guan 已提交
577 578 579 580 581 582 583
    return false;
  }

  size_t  len;
  char *  line = NULL;
  ssize_t _bytes = getline(&line, &len, fp);
  if ((_bytes < 0) || (line == NULL)) {
S
Shengliang Guan 已提交
584
    //printf("read file:%s failed", tsSysCpuFile);
S
Shengliang Guan 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    fclose(fp);
    return false;
  }

  char cpu[10] = {0};
  sscanf(line, "%s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, cpu, &cpuInfo->user, &cpuInfo->nice, &cpuInfo->system,
         &cpuInfo->idle);

  tfree(line);
  fclose(fp);
  return true;
}

static bool taosGetProcCpuInfo(ProcCpuInfo *cpuInfo) {
  FILE *fp = fopen(tsProcCpuFile, "r");
  if (fp == NULL) {
S
Shengliang Guan 已提交
601
    //printf("open file:%s failed", tsProcCpuFile);
S
Shengliang Guan 已提交
602 603 604 605 606 607 608
    return false;
  }

  size_t  len = 0;
  char *  line = NULL;
  ssize_t _bytes = getline(&line, &len, fp);
  if ((_bytes < 0) || (line == NULL)) {
S
Shengliang Guan 已提交
609
    //printf("read file:%s failed", tsProcCpuFile);
S
Shengliang Guan 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    fclose(fp);
    return false;
  }

  for (int i = 0, blank = 0; line[i] != 0; ++i) {
    if (line[i] == ' ') blank++;
    if (blank == PROCESS_ITEM) {
      sscanf(line + i + 1, "%" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, &cpuInfo->utime, &cpuInfo->stime,
             &cpuInfo->cutime, &cpuInfo->cstime);
      break;
    }
  }

  tfree(line);
  fclose(fp);
  return true;
}

static void taosGetSystemTimezone() {
  /*
   * NOTE: do not remove it.
   * Enforce set the correct daylight saving time(DST) flag according
   * to current time
   */
  time_t    tx1 = time(NULL);
  struct tm tm1;
  localtime_r(&tx1, &tm1);

  /* load time zone string from /etc/timezone */
  FILE *f = fopen("/etc/timezone", "r");
  char  buf[68] = {0};
  if (f != NULL) {
    int len = fread(buf, 64, 1, f);
    if (len < 64 && ferror(f)) {
      fclose(f);
S
Shengliang Guan 已提交
645
      //printf("read /etc/timezone error, reason:%s", strerror(errno));
S
Shengliang Guan 已提交
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
      return;
    }

    fclose(f);

    buf[sizeof(buf) - 1] = 0;
    char *lineEnd = strstr(buf, "\n");
    if (lineEnd != NULL) {
      *lineEnd = 0;
    }

    // for CentOS system, /etc/timezone does not exist. Ignore the TZ environment variables
    if (strlen(buf) > 0) {
      setenv("TZ", buf, 1);
    }
  }
  // get and set default timezone
  tzset();

  /*
   * get CURRENT time zone.
   * system current time zone is affected by daylight saving time(DST)
   *
   * e.g., the local time zone of London in DST is GMT+01:00,
   * otherwise is GMT+00:00
   */
  int32_t tz = (-timezone * MILLISECOND_PER_SECOND) / MILLISECOND_PER_HOUR;
  tz += daylight;

  /*
   * format example:
   *
   * Asia/Shanghai   (CST, +0800)
   * Europe/London   (BST, +0100)
   */
  snprintf(tsTimezone, TSDB_TIMEZONE_LEN, "%s (%s, %s%02d00)", buf, tzname[daylight], tz >= 0 ? "+" : "-", abs(tz));

  // cfg_timezone->cfgStatus = TAOS_CFG_CSTATUS_DEFAULT;
S
Shengliang Guan 已提交
684
  //printf("timezone not configured, set to system default:%s", tsTimezone);
S
Shengliang Guan 已提交
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
}

/*
 * POSIX format locale string:
 * (Language Strings)_(Country/Region Strings).(code_page)
 *
 * example: en_US.UTF-8, zh_CN.GB18030, zh_CN.UTF-8,
 *
 * if user does not specify the locale in taos.cfg the program use default LC_CTYPE as system locale.
 *
 * In case of some CentOS systems, their default locale is "en_US.utf8", which is not valid code_page
 * for libiconv that is employed to convert string in this system. This program will automatically use
 * UTF-8 instead as the charset.
 *
 * In case of windows client, the locale string is not valid POSIX format, user needs to set the
 * correct code_page for libiconv. Usually, the code_page of windows system with simple chinese is
 * CP936, CP437 for English charset.
 *
 */
static void taosGetSystemLocale() {  // get and set default locale
  char  sep = '.';
  char *locale = NULL;

  locale = setlocale(LC_CTYPE, "");
  if (locale == NULL) {
S
Shengliang Guan 已提交
710
    //printf("can't get locale from system, set it to en_US.UTF-8 since error:%d:%s", errno, strerror(errno));
S
Shengliang Guan 已提交
711 712 713
    strcpy(tsLocale, "en_US.UTF-8");
  } else {
    tstrncpy(tsLocale, locale, TSDB_LOCALE_LEN);
S
Shengliang Guan 已提交
714
    //printf("locale not configured, set to system default:%s", tsLocale);
S
Shengliang Guan 已提交
715 716
  }

717
  // if user does not specify the charset, extract it from locale
S
Shengliang Guan 已提交
718 719 720 721 722 723 724 725
  char *str = strrchr(tsLocale, sep);
  if (str != NULL) {
    str++;

    char *revisedCharset = taosCharsetReplace(str);
    tstrncpy(tsCharset, revisedCharset, TSDB_LOCALE_LEN);

    free(revisedCharset);
S
Shengliang Guan 已提交
726
    //printf("charset not configured, set to system default:%s", tsCharset);
S
Shengliang Guan 已提交
727 728
  } else {
    strcpy(tsCharset, "UTF-8");
S
Shengliang Guan 已提交
729
    //printf("can't get locale and charset from system, set it to UTF-8");
S
Shengliang Guan 已提交
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 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
  }
}

int32_t taosGetCpuCores() { return (int32_t)sysconf(_SC_NPROCESSORS_ONLN); }

bool taosGetCpuUsage(float *sysCpuUsage, float *procCpuUsage) {
  static uint64_t lastSysUsed = 0;
  static uint64_t lastSysTotal = 0;
  static uint64_t lastProcTotal = 0;

  SysCpuInfo  sysCpu;
  ProcCpuInfo procCpu;
  if (!taosGetSysCpuInfo(&sysCpu)) {
    return false;
  }
  if (!taosGetProcCpuInfo(&procCpu)) {
    return false;
  }

  uint64_t curSysUsed = sysCpu.user + sysCpu.nice + sysCpu.system;
  uint64_t curSysTotal = curSysUsed + sysCpu.idle;
  uint64_t curProcTotal = procCpu.utime + procCpu.stime + procCpu.cutime + procCpu.cstime;

  if (lastSysUsed == 0 || lastSysTotal == 0 || lastProcTotal == 0) {
    lastSysUsed = curSysUsed > 1 ? curSysUsed : 1;
    lastSysTotal = curSysTotal > 1 ? curSysTotal : 1;
    lastProcTotal = curProcTotal > 1 ? curProcTotal : 1;
    return false;
  }

  if (curSysTotal == lastSysTotal) {
    return false;
  }

  *sysCpuUsage = (float)((double)(curSysUsed - lastSysUsed) / (double)(curSysTotal - lastSysTotal) * 100);
  *procCpuUsage = (float)((double)(curProcTotal - lastProcTotal) / (double)(curSysTotal - lastSysTotal) * 100);

  lastSysUsed = curSysUsed;
  lastSysTotal = curSysTotal;
  lastProcTotal = curProcTotal;

  return true;
}

774
int32_t taosGetDiskSize(char *dataDir, SDiskSize *diskSize) {
S
Shengliang Guan 已提交
775 776 777 778
  struct statvfs info;
  if (statvfs(dataDir, &info)) {
    return -1;
  } else {
779
    diskSize->total = info.f_blocks * info.f_frsize;
S
Shengliang Guan 已提交
780 781 782 783 784 785 786 787 788 789
    diskSize->avail = info.f_bavail * info.f_frsize;
    diskSize->used = (info.f_blocks - info.f_bfree) * info.f_frsize;
    return 0;
  }
}

bool taosGetCardInfo(int64_t *bytes, int64_t *rbytes, int64_t *tbytes) {
  *bytes = 0;
  FILE *fp = fopen(tsSysNetFile, "r");
  if (fp == NULL) {
S
Shengliang Guan 已提交
790
    //printf("open file:%s failed", tsSysNetFile);
S
Shengliang Guan 已提交
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 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    return false;
  }

  ssize_t _bytes = 0;
  size_t  len = 2048;
  char *  line = calloc(1, len);

  while (!feof(fp)) {
    memset(line, 0, len);

    int64_t o_rbytes = 0;
    int64_t rpackts = 0;
    int64_t o_tbytes = 0;
    int64_t tpackets = 0;
    int64_t nouse1 = 0;
    int64_t nouse2 = 0;
    int64_t nouse3 = 0;
    int64_t nouse4 = 0;
    int64_t nouse5 = 0;
    int64_t nouse6 = 0;
    char    nouse0[200] = {0};

    _bytes = getline(&line, &len, fp);
    if (_bytes < 0) {
      break;
    }

    line[len - 1] = 0;

    if (strstr(line, "lo:") != NULL) {
      continue;
    }

    sscanf(line,
           "%s %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64
           " %" PRId64,
           nouse0, &o_rbytes, &rpackts, &nouse1, &nouse2, &nouse3, &nouse4, &nouse5, &nouse6, &o_tbytes, &tpackets);
    if (rbytes) *rbytes = o_rbytes;
    if (tbytes) *tbytes = o_tbytes;
    *bytes += (o_rbytes + o_tbytes);
  }

  tfree(line);
  fclose(fp);

  return true;
}

bool taosGetBandSpeed(float *bandSpeedKb) {
  static int64_t lastBytes = 0;
  static time_t  lastTime = 0;
  int64_t        curBytes = 0;
  time_t         curTime = time(NULL);

  if (!taosGetCardInfo(&curBytes, NULL, NULL)) {
    return false;
  }

  if (lastTime == 0 || lastBytes == 0) {
    lastTime = curTime;
    lastBytes = curBytes;
    *bandSpeedKb = 0;
    return true;
  }

  if (lastTime >= curTime || lastBytes > curBytes) {
    lastTime = curTime;
    lastBytes = curBytes;
    *bandSpeedKb = 0;
    return true;
  }

  double totalBytes = (double)(curBytes - lastBytes) / 1024 * 8;  // Kb
  *bandSpeedKb = (float)(totalBytes / (double)(curTime - lastTime));

S
Shengliang Guan 已提交
866
  // //printf("bandwidth lastBytes:%ld, lastTime:%ld, curBytes:%ld, curTime:%ld,
S
Shengliang Guan 已提交
867 868 869 870 871 872 873 874 875 876 877
  // speed:%f", lastBytes, lastTime, curBytes, curTime, *bandSpeed);

  lastTime = curTime;
  lastBytes = curBytes;

  return true;
}

bool taosReadProcIO(int64_t *rchars, int64_t *wchars) {
  FILE *fp = fopen(tsProcIOFile, "r");
  if (fp == NULL) {
S
Shengliang Guan 已提交
878
    //printf("open file:%s failed", tsProcIOFile);
S
Shengliang Guan 已提交
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    return false;
  }

  ssize_t _bytes = 0;
  size_t  len;
  char *  line = NULL;
  char    tmp[10];
  int     readIndex = 0;

  while (!feof(fp)) {
    tfree(line);
    len = 0;
    _bytes = getline(&line, &len, fp);
    if ((_bytes < 0) || (line == NULL)) {
      break;
    }
    if (strstr(line, "rchar:") != NULL) {
      sscanf(line, "%s %" PRId64, tmp, rchars);
      readIndex++;
    } else if (strstr(line, "wchar:") != NULL) {
      sscanf(line, "%s %" PRId64, tmp, wchars);
      readIndex++;
    } else {
    }

    if (readIndex >= 2) break;
  }

  tfree(line);
  fclose(fp);

  if (readIndex < 2) {
S
Shengliang Guan 已提交
911
    //printf("read file:%s failed", tsProcIOFile);
S
Shengliang Guan 已提交
912 913 914 915 916 917 918 919 920 921 922 923 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 953 954 955 956 957 958 959 960 961 962 963 964 965
    return false;
  }

  return true;
}

bool taosGetProcIO(float *readKB, float *writeKB) {
  static int64_t lastReadbyte = -1;
  static int64_t lastWritebyte = -1;

  int64_t curReadbyte = 0;
  int64_t curWritebyte = 0;

  if (!taosReadProcIO(&curReadbyte, &curWritebyte)) {
    return false;
  }

  if (lastReadbyte == -1 || lastWritebyte == -1) {
    lastReadbyte = curReadbyte;
    lastWritebyte = curWritebyte;
    return false;
  }

  *readKB = (float)((double)(curReadbyte - lastReadbyte) / 1024);
  *writeKB = (float)((double)(curWritebyte - lastWritebyte) / 1024);
  if (*readKB < 0) *readKB = 0;
  if (*writeKB < 0) *writeKB = 0;

  lastReadbyte = curReadbyte;
  lastWritebyte = curWritebyte;

  return true;
}

void taosGetSystemInfo() {
  taosGetProcInfos();

  tsNumOfCores = taosGetCpuCores();
  tsTotalMemoryMB = taosGetTotalMemory();

  float tmp1, tmp2;
  taosGetSysMemory(&tmp1);
  taosGetProcMemory(&tmp2);
  // taosGetDisk();
  taosGetBandSpeed(&tmp1);
  taosGetCpuUsage(&tmp1, &tmp2);
  taosGetProcIO(&tmp1, &tmp2);

  taosGetSystemTimezone();
  taosGetSystemLocale();
}

void taosKillSystem() {
  // SIGINT
S
Shengliang Guan 已提交
966
  //printf("taosd will shut down soon");
S
Shengliang Guan 已提交
967 968 969 970 971 972 973 974
  kill(tsProcId, 2);
}

int taosSystem(const char *cmd) {
  FILE *fp;
  int   res;
  char  buf[1024];
  if (cmd == NULL) {
S
Shengliang Guan 已提交
975
    //printf("taosSystem cmd is NULL!");
S
Shengliang Guan 已提交
976 977 978 979
    return -1;
  }

  if ((fp = popen(cmd, "r")) == NULL) {
S
Shengliang Guan 已提交
980
    //printf("popen cmd:%s error: %s", cmd, strerror(errno));
S
Shengliang Guan 已提交
981 982 983
    return -1;
  } else {
    while (fgets(buf, sizeof(buf), fp)) {
S
Shengliang Guan 已提交
984
      //printf("popen result:%s", buf);
S
Shengliang Guan 已提交
985 986 987
    }

    if ((res = pclose(fp)) == -1) {
S
Shengliang Guan 已提交
988
      //printf("close popen file pointer fp error!");
S
Shengliang Guan 已提交
989
    } else {
S
Shengliang Guan 已提交
990
      //printf("popen res is :%d", res);
S
Shengliang Guan 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    }

    return res;
  }
}

void taosSetCoreDump(bool enable) {
  if (!enable) return;

  // 1. set ulimit -c unlimited
  struct rlimit rlim;
  struct rlimit rlim_new;
  if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
#ifndef _ALPINE
S
Shengliang Guan 已提交
1005
    //printf("the old unlimited para: rlim_cur=%" PRIu64 ", rlim_max=%" PRIu64, rlim.rlim_cur, rlim.rlim_max);
S
Shengliang Guan 已提交
1006
#else
S
Shengliang Guan 已提交
1007
    //printf("the old unlimited para: rlim_cur=%llu, rlim_max=%llu", rlim.rlim_cur, rlim.rlim_max);
S
Shengliang Guan 已提交
1008 1009 1010 1011
#endif
    rlim_new.rlim_cur = RLIM_INFINITY;
    rlim_new.rlim_max = RLIM_INFINITY;
    if (setrlimit(RLIMIT_CORE, &rlim_new) != 0) {
S
Shengliang Guan 已提交
1012
      //printf("set unlimited fail, error: %s", strerror(errno));
S
Shengliang Guan 已提交
1013 1014 1015 1016 1017 1018 1019 1020
      rlim_new.rlim_cur = rlim.rlim_max;
      rlim_new.rlim_max = rlim.rlim_max;
      (void)setrlimit(RLIMIT_CORE, &rlim_new);
    }
  }

  if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
#ifndef _ALPINE
S
Shengliang Guan 已提交
1021
    //printf("the new unlimited para: rlim_cur=%" PRIu64 ", rlim_max=%" PRIu64, rlim.rlim_cur, rlim.rlim_max);
S
Shengliang Guan 已提交
1022
#else
S
Shengliang Guan 已提交
1023
    //printf("the new unlimited para: rlim_cur=%llu, rlim_max=%llu", rlim.rlim_cur, rlim.rlim_max);
S
Shengliang Guan 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
#endif
  }

#ifndef _TD_ARM_
  // 2. set the path for saving core file
  struct __sysctl_args args;

  int    old_usespid = 0;
  size_t old_len = 0;
  int    new_usespid = 1;
  size_t new_len = sizeof(new_usespid);

  int name[] = {CTL_KERN, KERN_CORE_USES_PID};

  memset(&args, 0, sizeof(struct __sysctl_args));
  args.name = name;
  args.nlen = sizeof(name) / sizeof(name[0]);
  args.oldval = &old_usespid;
  args.oldlenp = &old_len;
  args.newval = &new_usespid;
  args.newlen = new_len;

  old_len = sizeof(old_usespid);

  if (syscall(SYS__sysctl, &args) == -1) {
S
Shengliang Guan 已提交
1049
    //printf("_sysctl(kern_core_uses_pid) set fail: %s", strerror(errno));
S
Shengliang Guan 已提交
1050 1051
  }

S
Shengliang Guan 已提交
1052
  //printf("The old core_uses_pid[%" PRIu64 "]: %d", old_len, old_usespid);
S
Shengliang Guan 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

  old_usespid = 0;
  old_len = 0;
  memset(&args, 0, sizeof(struct __sysctl_args));
  args.name = name;
  args.nlen = sizeof(name) / sizeof(name[0]);
  args.oldval = &old_usespid;
  args.oldlenp = &old_len;

  old_len = sizeof(old_usespid);

  if (syscall(SYS__sysctl, &args) == -1) {
S
Shengliang Guan 已提交
1065
    //printf("_sysctl(kern_core_uses_pid) get fail: %s", strerror(errno));
S
Shengliang Guan 已提交
1066 1067
  }

S
Shengliang Guan 已提交
1068
  //printf("The new core_uses_pid[%" PRIu64 "]: %d", old_len, old_usespid);
S
Shengliang Guan 已提交
1069 1070 1071
#endif
}

H
Haojun Liao 已提交
1072
int32_t taosGetSystemUUID(char *uid, int32_t uidlen) {
S
Shengliang Guan 已提交
1073 1074 1075 1076 1077
  int fd;
  int len = 0;

  fd = open("/proc/sys/kernel/random/uuid", 0);
  if (fd < 0) {
S
Shengliang Guan 已提交
1078
    return -1;
S
Shengliang Guan 已提交
1079 1080 1081 1082 1083 1084 1085
  } else {
    len = read(fd, uid, uidlen);
    close(fd);
  }

  if (len >= 36) {
    uid[36] = 0;
S
Shengliang Guan 已提交
1086
    return 0;
S
Shengliang Guan 已提交
1087
  }
S
Shengliang Guan 已提交
1088

D
dapan1121 已提交
1089
  return 0;
S
Shengliang Guan 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
}

char *taosGetCmdlineByPID(int pid) {
  static char cmdline[1024];
  sprintf(cmdline, "/proc/%d/cmdline", pid);

  int fd = open(cmdline, O_RDONLY);
  if (fd >= 0) {
    int n = read(fd, cmdline, sizeof(cmdline) - 1);
    if (n < 0) n = 0;

    if (n > 0 && cmdline[n - 1] == '\n') --n;

    cmdline[n] = 0;

    close(fd);
  } else {
    cmdline[0] = 0;
  }

  return cmdline;
}

#endif

#if !(defined(_TD_WINDOWS_64) || defined(_TD_WINDOWS_32))

SysNameInfo taosGetSysNameInfo() {
  SysNameInfo info = {0};

1120 1121
  struct utsname uts;
  if (!uname(&uts)) {
H
Haojun Liao 已提交
1122 1123 1124 1125 1126
    tstrncpy(info.sysname, uts.sysname, sizeof(info.sysname));
    tstrncpy(info.nodename, uts.nodename, sizeof(info.nodename));
    tstrncpy(info.release, uts.release, sizeof(info.release));
    tstrncpy(info.version, uts.version, sizeof(info.version));
    tstrncpy(info.machine, uts.machine, sizeof(info.machine));
S
Shengliang Guan 已提交
1127 1128 1129 1130
  }

  return info;
}
S
Shengliang Guan 已提交
1131

S
Shengliang Guan 已提交
1132
#endif