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

#include <assert.h>
S
Shengliang Guan 已提交
17
#include <math.h>
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>

#include "taos.h"
#include "taosdef.h"
#include "taoserror.h"
#include "tlog.h"
#include "types.h"

#define GREEN     "\033[1;32m"
#define NC        "\033[0m"
#define min(a, b) (((a) < (b)) ? (a) : (b))

#define MAX_SQL_STR_LEN         (1024 * 1024)
#define MAX_ROW_STR_LEN         (16 * 1024)
#define MAX_CONSUMER_THREAD_CNT (16)
#define MAX_VGROUP_CNT          (32)
S
Shengliang Guan 已提交
39
#define SEND_TIME_UNIT          10  // ms
40 41 42 43 44 45 46 47
#define MAX_SQL_LEN             1048576

typedef enum {
  NOTIFY_CMD_START_CONSUM,
  NOTIFY_CMD_START_COMMIT,
  NOTIFY_CMD_ID_BUTT,
} NOTIFY_CMD_ID;

S
Shengliang Guan 已提交
48
typedef enum enumQUERY_TYPE { NO_INSERT_TYPE, INSERT_TYPE, QUERY_TYPE_BUT } QUERY_TYPE;
49 50 51 52 53 54 55 56 57 58 59

typedef struct {
  TdThread thread;
  int32_t  consumerId;

  int32_t ifManualCommit;
  // int32_t  autoCommitIntervalMs;  // 1000 ms
  // char     autoCommit[8];         // true, false
  // char     autoOffsetRest[16];    // none, earliest, latest

  TdFilePtr pConsumeRowsFile;
S
Shengliang Guan 已提交
60
  TdFilePtr pConsumeMetaFile;
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
  int32_t   ifCheckData;
  int64_t   expectMsgCnt;

  int64_t consumeMsgCnt;
  int64_t consumeRowCnt;
  int64_t consumeLen;
  int32_t checkresult;

  char topicString[1024];
  char keyString[1024];

  int32_t numOfTopic;
  char    topics[32][64];

  int32_t numOfKey;
  char    key[32][64];
  char    value[32][64];

  tmq_t*      tmq;
  tmq_list_t* topicList;

  int32_t numOfVgroups;
  int32_t rowsOfPerVgroups[MAX_VGROUP_CNT][2];  // [i][0]: vgroup id, [i][1]: rows of consume
  int64_t ts;

S
Shengliang Guan 已提交
86
  TAOS* taos;
87 88

  // below parameters is used by omb test
S
Shengliang Guan 已提交
89 90 91
  int32_t producerRate;  // unit: msgs/s
  int64_t totalProduceMsgs;
  int64_t totalMsgsLen;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

} SThreadInfo;

typedef struct {
  // input from argvs
  char        cdbName[32];
  char        dbName[64];
  int32_t     showMsgFlag;
  int32_t     showRowFlag;
  int32_t     saveRowFlag;
  int32_t     consumeDelay;  // unit s
  int32_t     numOfThread;
  int32_t     useSnapshot;
  int64_t     nowTime;
  SThreadInfo stThreads[MAX_CONSUMER_THREAD_CNT];

  SThreadInfo stProdThreads[MAX_CONSUMER_THREAD_CNT];

  // below parameters is used by omb test
S
Shengliang Guan 已提交
111 112 113 114 115 116
  char    topic[64];
  int32_t producers;
  int32_t producerRate;
  int32_t runDurationMinutes;
  int32_t batchSize;
  int32_t payloadLen;
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
} SConfInfo;

static SConfInfo g_stConfInfo;
TdFilePtr        g_fp = NULL;
static int       running = 1;
char*            g_payload = NULL;

// char* g_pRowValue = NULL;
// TdFilePtr g_fp = NULL;

static void printHelp() {
  char indent[10] = "        ";
  printf("Used to test the tmq feature with sim cases\n");

  printf("%s%s\n", indent, "-c");
  printf("%s%s%s%s\n", indent, indent, "Configuration directory, default is ", configDir);
  printf("%s%s\n", indent, "-d");
  printf("%s%s%s\n", indent, indent, "The name of the database for cosumer, no default ");
  printf("%s%s\n", indent, "-g");
  printf("%s%s%s%d\n", indent, indent, "showMsgFlag, default is ", g_stConfInfo.showMsgFlag);
  printf("%s%s\n", indent, "-r");
  printf("%s%s%s%d\n", indent, indent, "showRowFlag, default is ", g_stConfInfo.showRowFlag);
  printf("%s%s\n", indent, "-s");
  printf("%s%s%s%d\n", indent, indent, "saveRowFlag, default is ", g_stConfInfo.saveRowFlag);
  printf("%s%s\n", indent, "-y");
  printf("%s%s%s%ds\n", indent, indent, "consume delay, default is ", g_stConfInfo.consumeDelay);
  printf("%s%s\n", indent, "-e");
  printf("%s%s%s%d\n", indent, indent, "snapshot, default is ", g_stConfInfo.useSnapshot);
S
Shengliang Guan 已提交
145

146 147 148 149 150 151 152
  printf("%s%s\n", indent, "-t");
  printf("%s%s%s\n", indent, indent, "topic name, default is null");

  printf("%s%s\n", indent, "-x");
  printf("%s%s%s\n", indent, indent, "consume thread number, default is 1");

  printf("%s%s\n", indent, "-l");
wmmhello's avatar
wmmhello 已提交
153
  printf("%s%s%s%d\n", indent, indent, "run duration unit is minutes, default is ", g_stConfInfo.runDurationMinutes);
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  printf("%s%s\n", indent, "-p");
  printf("%s%s%s\n", indent, indent, "producer thread number, default is 0");
  printf("%s%s\n", indent, "-b");
  printf("%s%s%s\n", indent, indent, "batch size, default is 1");
  printf("%s%s\n", indent, "-i");
  printf("%s%s%s\n", indent, indent, "produce rate unit is msgs /s, default is 100000");
  printf("%s%s\n", indent, "-n");
  printf("%s%s%s\n", indent, indent, "payload len unit is byte, default is 1000");

  exit(EXIT_SUCCESS);
}

char* getCurrentTimeString(char* timeString) {
  time_t    tTime = taosGetTimestampSec();
  struct tm tm;
169
  taosLocalTime(&tTime, &tm, NULL);
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  sprintf(timeString, "%d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
          tm.tm_min, tm.tm_sec);

  return timeString;
}

static void tmqStop(int signum, void* info, void* ctx) {
  running = 0;
  char tmpString[128];
  taosFprintfFile(g_fp, "%s tmqStop() receive stop signal[%d]\n", getCurrentTimeString(tmpString), signum);
}

static void tmqSetSignalHandle() { taosSetSignal(SIGINT, tmqStop); }

void initLogFile() {
  char filename[256];
  char tmpString[128];

  pid_t process_id = getpid();

  if (0 != strlen(g_stConfInfo.topic)) {
S
Shengliang Guan 已提交
191
    sprintf(filename, "/tmp/tmqlog-%d-%s.txt", process_id, getCurrentTimeString(tmpString));
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  } else {
    sprintf(filename, "%s/../log/tmqlog-%d-%s.txt", configDir, process_id, getCurrentTimeString(tmpString));
  }
#ifdef WINDOWS
  for (int i = 2; i < sizeof(filename); i++) {
    if (filename[i] == ':') filename[i] = '-';
    if (filename[i] == '\0') break;
  }
#endif
  TdFilePtr pFile = taosOpenFile(filename, TD_FILE_TEXT | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
  if (NULL == pFile) {
    fprintf(stderr, "Failed to open %s for save result\n", filename);
    exit(-1);
  }
  g_fp = pFile;
}

void saveConfigToLogFile() {
  taosFprintfFile(g_fp, "###################################################################\n");
  taosFprintfFile(g_fp, "# configDir:           %s\n", configDir);
  taosFprintfFile(g_fp, "# dbName:              %s\n", g_stConfInfo.dbName);
  taosFprintfFile(g_fp, "# cdbName:             %s\n", g_stConfInfo.cdbName);
  taosFprintfFile(g_fp, "# showMsgFlag:         %d\n", g_stConfInfo.showMsgFlag);
  taosFprintfFile(g_fp, "# showRowFlag:         %d\n", g_stConfInfo.showRowFlag);
  taosFprintfFile(g_fp, "# saveRowFlag:         %d\n", g_stConfInfo.saveRowFlag);
  taosFprintfFile(g_fp, "# consumeDelay:        %d\n", g_stConfInfo.consumeDelay);
  taosFprintfFile(g_fp, "# numOfThread:         %d\n", g_stConfInfo.numOfThread);

  for (int32_t i = 0; i < g_stConfInfo.numOfThread; i++) {
    taosFprintfFile(g_fp, "# consumer %d info:\n", g_stConfInfo.stThreads[i].consumerId);
    // taosFprintfFile(g_fp, "  auto commit:              %s\n", g_stConfInfo.stThreads[i].autoCommit);
    // taosFprintfFile(g_fp, "  auto commit interval ms:  %d\n", g_stConfInfo.stThreads[i].autoCommitIntervalMs);
    // taosFprintfFile(g_fp, "  auto offset rest:         %s\n", g_stConfInfo.stThreads[i].autoOffsetRest);
    taosFprintfFile(g_fp, "  Topics: ");
    for (int j = 0; j < g_stConfInfo.stThreads[i].numOfTopic; j++) {
      taosFprintfFile(g_fp, "%s, ", g_stConfInfo.stThreads[i].topics[j]);
    }
    taosFprintfFile(g_fp, "\n");
    taosFprintfFile(g_fp, "  Key: ");
    for (int k = 0; k < g_stConfInfo.stThreads[i].numOfKey; k++) {
      taosFprintfFile(g_fp, "%s:%s, ", g_stConfInfo.stThreads[i].key[k], g_stConfInfo.stThreads[i].value[k]);
    }
    taosFprintfFile(g_fp, "\n");
wmmhello's avatar
wmmhello 已提交
235
    taosFprintfFile(g_fp, "  expect rows: %" PRIx64 "\n", g_stConfInfo.stThreads[i].expectMsgCnt);
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
  }

  char tmpString[128];
  taosFprintfFile(g_fp, "# Test time:                %s\n", getCurrentTimeString(tmpString));
  taosFprintfFile(g_fp, "###################################################################\n");
}

void parseArgument(int32_t argc, char* argv[]) {
  memset(&g_stConfInfo, 0, sizeof(SConfInfo));
  g_stConfInfo.showMsgFlag = 0;
  g_stConfInfo.showRowFlag = 0;
  g_stConfInfo.saveRowFlag = 0;
  g_stConfInfo.consumeDelay = 5;
  g_stConfInfo.numOfThread = 1;
  g_stConfInfo.batchSize = 1;
  g_stConfInfo.producers = 0;

  g_stConfInfo.nowTime = taosGetTimestampMs();

  for (int32_t i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
      printHelp();
      exit(0);
    } else if (strcmp(argv[i], "-d") == 0) {
wmmhello's avatar
wmmhello 已提交
260
      tstrncpy(g_stConfInfo.dbName, argv[++i], sizeof(g_stConfInfo.dbName));
261
    } else if (strcmp(argv[i], "-w") == 0) {
wmmhello's avatar
wmmhello 已提交
262
      tstrncpy(g_stConfInfo.cdbName, argv[++i], sizeof(g_stConfInfo.cdbName));
263
    } else if (strcmp(argv[i], "-c") == 0) {
wmmhello's avatar
wmmhello 已提交
264
      tstrncpy(configDir, argv[++i], PATH_MAX);
265 266 267 268 269 270 271 272 273 274 275
    } else if (strcmp(argv[i], "-g") == 0) {
      g_stConfInfo.showMsgFlag = atol(argv[++i]);
    } else if (strcmp(argv[i], "-r") == 0) {
      g_stConfInfo.showRowFlag = atol(argv[++i]);
    } else if (strcmp(argv[i], "-s") == 0) {
      g_stConfInfo.saveRowFlag = atol(argv[++i]);
    } else if (strcmp(argv[i], "-y") == 0) {
      g_stConfInfo.consumeDelay = atol(argv[++i]);
    } else if (strcmp(argv[i], "-e") == 0) {
      g_stConfInfo.useSnapshot = atol(argv[++i]);
    } else if (strcmp(argv[i], "-t") == 0) {
wmmhello's avatar
wmmhello 已提交
276 277 278
      char tmpBuf[56] = {0};
      tstrncpy(tmpBuf, argv[++i], sizeof(tmpBuf));
      sprintf(g_stConfInfo.topic, "`%s`", tmpBuf);
279 280 281 282 283 284 285 286 287 288 289 290
    } else if (strcmp(argv[i], "-x") == 0) {
      g_stConfInfo.numOfThread = atol(argv[++i]);
    } else if (strcmp(argv[i], "-l") == 0) {
      g_stConfInfo.runDurationMinutes = atol(argv[++i]);
    } else if (strcmp(argv[i], "-p") == 0) {
      g_stConfInfo.producers = atol(argv[++i]);
    } else if (strcmp(argv[i], "-b") == 0) {
      g_stConfInfo.batchSize = atol(argv[++i]);
    } else if (strcmp(argv[i], "-i") == 0) {
      g_stConfInfo.producerRate = atol(argv[++i]);
    } else if (strcmp(argv[i], "-n") == 0) {
      g_stConfInfo.payloadLen = atol(argv[++i]);
S
Shengliang Guan 已提交
291
      if (g_stConfInfo.payloadLen <= 0 || g_stConfInfo.payloadLen > 1024 * 1024 * 1024) {
wmmhello's avatar
wmmhello 已提交
292 293 294
        pError("%s calloc size is too large: %s %s", GREEN, argv[++i], NC);
        exit(-1);
      }
295 296 297 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 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
    } else {
      pError("%s unknow para: %s %s", GREEN, argv[++i], NC);
      exit(-1);
    }
  }

  g_payload = taosMemoryCalloc(g_stConfInfo.payloadLen + 1, 1);
  if (NULL == g_payload) {
    pPrint("%s failed to malloc for payload %s", GREEN, NC);
    exit(-1);
  }

  for (int32_t i = 0; i < g_stConfInfo.payloadLen; i++) {
    strcpy(&g_payload[i], "a");
  }

  initLogFile();

  taosFprintfFile(g_fp, "====parseArgument() success\n");

#if 1
  pPrint("%s configDir:%s %s", GREEN, configDir, NC);
  pPrint("%s dbName:%s %s", GREEN, g_stConfInfo.dbName, NC);
  pPrint("%s cdbName:%s %s", GREEN, g_stConfInfo.cdbName, NC);
  pPrint("%s consumeDelay:%d %s", GREEN, g_stConfInfo.consumeDelay, NC);
  pPrint("%s showMsgFlag:%d %s", GREEN, g_stConfInfo.showMsgFlag, NC);
  pPrint("%s showRowFlag:%d %s", GREEN, g_stConfInfo.showRowFlag, NC);
  pPrint("%s saveRowFlag:%d %s", GREEN, g_stConfInfo.saveRowFlag, NC);

  pPrint("%s snapshot:%d %s", GREEN, g_stConfInfo.useSnapshot, NC);

  pPrint("%s omb topic:%s %s", GREEN, g_stConfInfo.topic, NC);
  pPrint("%s numOfThread:%d %s", GREEN, g_stConfInfo.numOfThread, NC);
#endif
}

void splitStr(char** arr, char* str, const char* del) {
  char* s = strtok(str, del);
  while (s != NULL) {
    *arr++ = s;
    s = strtok(NULL, del);
  }
}

void ltrim(char* str) {
  if (str == NULL || *str == '\0') {
    return;
  }
  int   len = 0;
  char* p = str;
  while (*p != '\0' && isspace(*p)) {
    ++p;
    ++len;
  }
  memmove(str, p, strlen(str) - len + 1);
  // return str;
}

int queryDB(TAOS* taos, char* command) {
S
Shengliang Guan 已提交
354 355 356
  int       retryCnt = 10;
  int       code = 0;
  TAOS_RES* pRes = NULL;
357 358 359 360 361 362 363

  while (retryCnt--) {
    pRes = taos_query(taos, command);
    code = taos_errno(pRes);
    if (code != 0) {
      taosSsleep(1);
      taos_free_result(pRes);
wmmhello's avatar
wmmhello 已提交
364
      pRes = NULL;
365 366 367
      continue;
    }
    taos_free_result(pRes);
wmmhello's avatar
wmmhello 已提交
368
    return 0;
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  }

  pError("failed to reason:%s, sql: %s", tstrerror(code), command);
  taos_free_result(pRes);
  return -1;
}

void addRowsToVgroupId(SThreadInfo* pInfo, int32_t vgroupId, int32_t rows) {
  int32_t i;
  for (i = 0; i < pInfo->numOfVgroups; i++) {
    if (vgroupId == pInfo->rowsOfPerVgroups[i][0]) {
      pInfo->rowsOfPerVgroups[i][1] += rows;
      return;
    }
  }

  pInfo->rowsOfPerVgroups[pInfo->numOfVgroups][0] = vgroupId;
  pInfo->rowsOfPerVgroups[pInfo->numOfVgroups][1] += rows;
  pInfo->numOfVgroups++;

D
dapan1121 已提交
389
  taosFprintfFile(g_fp, "consume id %d, add new vgroupId:%d\n", pInfo->consumerId, vgroupId);
390 391 392 393 394 395 396 397 398
  if (pInfo->numOfVgroups > MAX_VGROUP_CNT) {
    taosFprintfFile(g_fp, "====consume id %d, vgroup num %d over than 32. new vgroupId: %d\n", pInfo->consumerId,
                    pInfo->numOfVgroups, vgroupId);
    taosCloseFile(&g_fp);
    exit(-1);
  }
}

TAOS* createNewTaosConnect() {
S
Shengliang Guan 已提交
399 400
  TAOS*   taos = NULL;
  int32_t retryCnt = 10;
401 402

  while (retryCnt--) {
H
Haojun Liao 已提交
403
    taos = taos_connect(NULL, "root", "taosdata", NULL, 0);
S
Shengliang Guan 已提交
404 405 406 407
    if (NULL != taos) {
      return taos;
    }
    taosSsleep(1);
408 409 410 411 412 413 414 415 416 417
  }

  taosFprintfFile(g_fp, "taos_connect() fail\n");
  return NULL;
}

int32_t saveConsumeContentToTbl(SThreadInfo* pInfo, char* buf) {
  char sqlStr[1100] = {0};

  if (strlen(buf) > 1024) {
wmmhello's avatar
wmmhello 已提交
418
    taosFprintfFile(g_fp, "The length of one row[%d] is overflow 1024\n", (int)strlen(buf));
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    taosCloseFile(&g_fp);
    return -1;
  }

  TAOS* pConn = taos_connect(NULL, "root", "taosdata", NULL, 0);
  if (pConn == NULL) {
    taosFprintfFile(g_fp, "taos_connect() fail, can not save consume result to main script\n");
    return -1;
  }

  sprintf(sqlStr, "insert into %s.content_%d values (%" PRId64 ", \'%s\')", g_stConfInfo.cdbName, pInfo->consumerId,
          pInfo->ts++, buf);
  int retCode = queryDB(pConn, sqlStr);
  if (retCode != 0) {
    taosFprintfFile(g_fp, "error in save consume content\n");
    taosCloseFile(&g_fp);
S
Shengliang Guan 已提交
435
    taos_close(pConn);
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    exit(-1);
  }

  taos_close(pConn);

  return 0;
}

static char* shellFormatTimestamp(char* buf, int64_t val, int32_t precision) {
  // if (shell.args.is_raw_time) {
  //   sprintf(buf, "%" PRId64, val);
  //   return buf;
  // }

  time_t  tt;
  int32_t ms = 0;
  if (precision == TSDB_TIME_PRECISION_NANO) {
    tt = (time_t)(val / 1000000000);
    ms = val % 1000000000;
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
    tt = (time_t)(val / 1000000);
    ms = val % 1000000;
  } else {
    tt = (time_t)(val / 1000);
    ms = val % 1000;
  }

  if (tt <= 0 && ms < 0) {
    tt--;
    if (precision == TSDB_TIME_PRECISION_NANO) {
      ms += 1000000000;
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
      ms += 1000000;
    } else {
      ms += 1000;
    }
  }

  struct tm ptm;
475
  if (taosLocalTime(&tt, &ptm, buf) == NULL) {
476 477
    return buf;
  }
S
Shengliang Guan 已提交
478
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

  if (precision == TSDB_TIME_PRECISION_NANO) {
    sprintf(buf + pos, ".%09d", ms);
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
    sprintf(buf + pos, ".%06d", ms);
  } else {
    sprintf(buf + pos, ".%03d", ms);
  }

  return buf;
}

static void shellDumpFieldToFile(TdFilePtr pFile, const char* val, TAOS_FIELD* field, int32_t length,
                                 int32_t precision) {
  if (val == NULL) {
X
Xiaoyu Wang 已提交
494
    taosFprintfFile(pFile, "NULL");
495 496 497
    return;
  }

X
Xiaoyu Wang 已提交
498 499 500 501
  char quotationStr[2];
  quotationStr[0] = '\"';
  quotationStr[1] = 0;

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 544
  int  n;
  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char*)val))) == 1) ? 1 : 0));
      break;
    case TSDB_DATA_TYPE_TINYINT:
      taosFprintfFile(pFile, "%d", *((int8_t*)val));
      break;
    case TSDB_DATA_TYPE_UTINYINT:
      taosFprintfFile(pFile, "%u", *((uint8_t*)val));
      break;
    case TSDB_DATA_TYPE_SMALLINT:
      taosFprintfFile(pFile, "%d", *((int16_t*)val));
      break;
    case TSDB_DATA_TYPE_USMALLINT:
      taosFprintfFile(pFile, "%u", *((uint16_t*)val));
      break;
    case TSDB_DATA_TYPE_INT:
      taosFprintfFile(pFile, "%d", *((int32_t*)val));
      break;
    case TSDB_DATA_TYPE_UINT:
      taosFprintfFile(pFile, "%u", *((uint32_t*)val));
      break;
    case TSDB_DATA_TYPE_BIGINT:
      taosFprintfFile(pFile, "%" PRId64, *((int64_t*)val));
      break;
    case TSDB_DATA_TYPE_UBIGINT:
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t*)val));
      break;
    case TSDB_DATA_TYPE_FLOAT:
      taosFprintfFile(pFile, "%.5f", GET_FLOAT_VAL(val));
      break;
    case TSDB_DATA_TYPE_DOUBLE:
      n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", length, GET_DOUBLE_VAL(val));
      if (n > TMAX(25, length)) {
        taosFprintfFile(pFile, "%*.15e", length, GET_DOUBLE_VAL(val));
      } else {
        taosFprintfFile(pFile, "%s", buf);
      }
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
S
Shengliang Guan 已提交
545 546 547 548 549 550
    case TSDB_DATA_TYPE_JSON: {
      int32_t bufIndex = 0;
      for (int32_t i = 0; i < length; i++) {
        buf[bufIndex] = val[i];
        bufIndex++;
        if (val[i] == '\"') {
551 552 553 554
          buf[bufIndex] = val[i];
          bufIndex++;
        }
      }
S
Shengliang Guan 已提交
555 556 557 558
      buf[bufIndex] = 0;

      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
    } break;
559 560
    case TSDB_DATA_TYPE_TIMESTAMP:
      shellFormatTimestamp(buf, *(int64_t*)val, precision);
X
Xiaoyu Wang 已提交
561
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
      break;
    default:
      break;
  }
}

static void dumpToFileForCheck(TdFilePtr pFile, TAOS_ROW row, TAOS_FIELD* fields, int32_t* length, int32_t num_fields,
                               int32_t precision) {
  for (int32_t i = 0; i < num_fields; i++) {
    if (i > 0) {
      taosFprintfFile(pFile, ",");
    }
    shellDumpFieldToFile(pFile, (const char*)row[i], fields + i, length[i], precision);
  }
  taosFprintfFile(pFile, "\n");
}

static int32_t data_msg_process(TAOS_RES* msg, SThreadInfo* pInfo, int32_t msgIndex) {
  char    buf[1024];
  int32_t totalRows = 0;

  int32_t     vgroupId = tmq_get_vgroup_id(msg);
  const char* dbName = tmq_get_db_name(msg);

wmmhello's avatar
wmmhello 已提交
586
  taosFprintfFile(g_fp, "consumerId: %d, msg index:%d\n", pInfo->consumerId, msgIndex);
D
dapan1121 已提交
587 588 589 590 591 592 593 594 595
  int32_t index = 0;
  for (index = 0; index < pInfo->numOfVgroups; index++) {
    if (vgroupId == pInfo->rowsOfPerVgroups[index][0]) {
      break;
    }
  }

  taosFprintfFile(g_fp, "dbName: %s, topic: %s, vgroupId:%d, currentRows:%d\n", dbName != NULL ? dbName : "invalid table",
                  tmq_get_topic_name(msg), vgroupId, pInfo->rowsOfPerVgroups[index][1]);
596 597 598

  while (1) {
    TAOS_ROW row = taos_fetch_row(msg);
D
dapan1121 已提交
599 600 601
    if (row == NULL) {
      break;
    }
602 603 604 605 606 607 608 609 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

    TAOS_FIELD* fields = taos_fetch_fields(msg);
    int32_t     numOfFields = taos_field_count(msg);
    int32_t*    length = taos_fetch_lengths(msg);
    int32_t     precision = taos_result_precision(msg);
    const char* tbName = tmq_get_table_name(msg);

#if 0
	// get schema
	//============================== stub =================================================//
	for (int32_t i = 0; i < numOfFields; i++) {
	  taosFprintfFile(g_fp, "%02d: name: %s, type: %d, len: %d\n", i, fields[i].name, fields[i].type, fields[i].bytes);
	}
	//============================== stub =================================================//
#endif

    dumpToFileForCheck(pInfo->pConsumeRowsFile, row, fields, length, numOfFields, precision);
    taos_print_row(buf, row, fields, numOfFields);

    if (0 != g_stConfInfo.showRowFlag) {
      taosFprintfFile(g_fp, "tbname:%s, rows[%d]: %s\n", (tbName != NULL ? tbName : "null table"), totalRows, buf);
      // if (0 != g_stConfInfo.saveRowFlag) {
      //   saveConsumeContentToTbl(pInfo, buf);
      // }
    }

    totalRows++;
  }

  addRowsToVgroupId(pInfo, vgroupId, totalRows);
  return totalRows;
}

static int32_t meta_msg_process(TAOS_RES* msg, SThreadInfo* pInfo, int32_t msgIndex) {
  char    buf[1024];
  int32_t totalRows = 0;

  // printf("topic: %s\n", tmq_get_topic_name(msg));
  int32_t     vgroupId = tmq_get_vgroup_id(msg);
  const char* dbName = tmq_get_db_name(msg);

wmmhello's avatar
wmmhello 已提交
643
  taosFprintfFile(g_fp, "consumerId: %d, msg index:%d\n", pInfo->consumerId, msgIndex);
644 645 646 647 648
  taosFprintfFile(g_fp, "dbName: %s, topic: %s, vgroupId: %d\n", dbName != NULL ? dbName : "invalid table",
                  tmq_get_topic_name(msg), vgroupId);

  {
    tmq_raw_data raw = {0};
S
Shengliang Guan 已提交
649 650 651 652 653 654 655 656 657 658 659 660
    int32_t      code = tmq_get_raw(msg, &raw);

    if (code == TSDB_CODE_SUCCESS) {
      //	  int retCode = queryDB(pInfo->taos, "use metadb");
      //	  if (retCode != 0) {
      //		taosFprintfFile(g_fp, "error when use metadb\n");
      //		taosCloseFile(&g_fp);
      //		exit(-1);
      //	  }
      //	  taosFprintfFile(g_fp, "raw:%p\n", &raw);
      //
      //      tmq_write_raw(pInfo->taos, raw);
661
    }
S
Shengliang Guan 已提交
662

663
    char* result = tmq_get_json_meta(msg);
S
Shengliang Guan 已提交
664 665 666
    if (result && strcmp(result, "") != 0) {
      // printf("meta result: %s\n", result);
      taosFprintfFile(pInfo->pConsumeMetaFile, "%s\n", result);
667
    }
668
    tmq_free_json_meta(result);
669 670 671 672 673 674 675 676 677 678 679 680 681
  }

  totalRows++;

  return totalRows;
}

static void appNothing(void* param, TAOS_RES* res, int32_t numOfRows) {}

int32_t notifyMainScript(SThreadInfo* pInfo, int32_t cmdId) {
  char sqlStr[1024] = {0};

  // schema: ts timestamp, consumerid int, consummsgcnt bigint, checkresult int
S
Shengliang Guan 已提交
682 683
  sprintf(sqlStr, "insert into %s.notifyinfo values (%" PRId64 ", %d, %d)", g_stConfInfo.cdbName,
          atomic_fetch_add_64(&g_stConfInfo.nowTime, 1), cmdId, pInfo->consumerId);
684 685 686 687 688 689 690 691 692 693

  taos_query_a(pInfo->taos, sqlStr, appNothing, NULL);

  taosFprintfFile(g_fp, "notifyMainScript success, sql: %s\n", sqlStr);

  return 0;
}

static int32_t g_once_commit_flag = 0;

D
dapan1121 已提交
694 695 696
static void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) {
  taosFprintfFile(g_fp, "tmq_commit_cb_print() commit %d\n", code);

697
  if (0 == g_once_commit_flag) {
D
dapan1121 已提交
698 699
    g_once_commit_flag = 1;
    notifyMainScript((SThreadInfo*)param, (int32_t)NOTIFY_CMD_START_COMMIT);
700 701
  }

D
dapan1121 已提交
702 703
  char tmpString[128];
  taosFprintfFile(g_fp, "%s tmq_commit_cb_print() be called\n", getCurrentTimeString(tmpString));
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
}

void build_consumer(SThreadInfo* pInfo) {
  tmq_conf_t* conf = tmq_conf_new();

  // tmq_conf_set(conf, "td.connect.ip", "localhost");
  // tmq_conf_set(conf, "td.connect.port", "6030");
  tmq_conf_set(conf, "td.connect.user", "root");
  tmq_conf_set(conf, "td.connect.pass", "taosdata");

  // tmq_conf_set(conf, "td.connect.db", g_stConfInfo.dbName);

  tmq_conf_set_auto_commit_cb(conf, tmq_commit_cb_print, pInfo);

  // tmq_conf_set(conf, "group.id", "cgrp1");
  for (int32_t i = 0; i < pInfo->numOfKey; i++) {
    tmq_conf_set(conf, pInfo->key[i], pInfo->value[i]);
  }

  tmq_conf_set(conf, "msg.with.table.name", "true");

  // tmq_conf_set(conf, "client.id", "c-001");

  // tmq_conf_set(conf, "enable.auto.commit", "true");
  // tmq_conf_set(conf, "enable.auto.commit", "false");

  // tmq_conf_set(conf, "auto.commit.interval.ms", "1000");

  // tmq_conf_set(conf, "auto.offset.reset", "none");
  // tmq_conf_set(conf, "auto.offset.reset", "earliest");
  // tmq_conf_set(conf, "auto.offset.reset", "latest");
  //
  if (g_stConfInfo.useSnapshot) {
    tmq_conf_set(conf, "experimental.snapshot.enable", "true");
  }

  pInfo->tmq = tmq_consumer_new(conf, NULL, 0);
  tmq_conf_destroy(conf);
  return;
}

void build_topic_list(SThreadInfo* pInfo) {
  pInfo->topicList = tmq_list_new();
  // tmq_list_append(topic_list, "test_stb_topic_1");
  for (int32_t i = 0; i < pInfo->numOfTopic; i++) {
    tmq_list_append(pInfo->topicList, pInfo->topics[i]);
  }
  return;
}

int32_t saveConsumeResult(SThreadInfo* pInfo) {
  char sqlStr[1024] = {0};
  // schema: ts timestamp, consumerid int, consummsgcnt bigint, checkresult int
  sprintf(sqlStr, "insert into %s.consumeresult values (%" PRId64 ", %d, %" PRId64 ", %" PRId64 ", %d)",
          g_stConfInfo.cdbName, atomic_fetch_add_64(&g_stConfInfo.nowTime, 1), pInfo->consumerId, pInfo->consumeMsgCnt,
          pInfo->consumeRowCnt, pInfo->checkresult);

  char tmpString[128];
  taosFprintfFile(g_fp, "%s, consume id %d result: %s\n", getCurrentTimeString(tmpString), pInfo->consumerId, sqlStr);

  int retCode = queryDB(pInfo->taos, sqlStr);
  if (retCode != 0) {
S
Shengliang Guan 已提交
766
    taosFprintfFile(g_fp, "consume id %d error in save consume result\n", pInfo->consumerId);
767 768 769 770 771 772 773 774 775
    return -1;
  }

  return 0;
}

void loop_consume(SThreadInfo* pInfo) {
  int32_t code;

776 777
  int32_t once_flag = 0;

778 779 780 781 782 783 784 785 786 787 788
  int64_t totalMsgs = 0;
  int64_t totalRows = 0;

  char tmpString[128];
  taosFprintfFile(g_fp, "%s consumer id %d start to loop pull msg\n", getCurrentTimeString(tmpString),
                  pInfo->consumerId);

  pInfo->ts = taosGetTimestampMs();

  if (pInfo->ifCheckData) {
    char filename[256] = {0};
H
Haojun Liao 已提交
789 790
    memset(tmpString, 0, tListLen(tmpString));

791 792 793 794 795
    // sprintf(filename, "%s/../log/consumerid_%d_%s.txt", configDir, pInfo->consumerId,
    // getCurrentTimeString(tmpString));
    sprintf(filename, "%s/../log/consumerid_%d.txt", configDir, pInfo->consumerId);
    pInfo->pConsumeRowsFile = taosOpenFile(filename, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);

S
Shengliang Guan 已提交
796 797 798
    sprintf(filename, "%s/../log/meta_consumerid_%d.txt", configDir, pInfo->consumerId);
    pInfo->pConsumeMetaFile = taosOpenFile(filename, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);

799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    if (pInfo->pConsumeRowsFile == NULL || pInfo->pConsumeMetaFile == NULL) {
      taosFprintfFile(g_fp, "%s create file fail for save rows or save meta\n", getCurrentTimeString(tmpString));
      return;
    }
  }

  int64_t  lastTotalMsgs = 0;
  uint64_t lastPrintTime = taosGetTimestampMs();
  uint64_t startTs = taosGetTimestampMs();

  int32_t consumeDelay = g_stConfInfo.consumeDelay == -1 ? -1 : (g_stConfInfo.consumeDelay * 1000);
  while (running) {
    TAOS_RES* tmqMsg = tmq_consumer_poll(pInfo->tmq, consumeDelay);
    if (tmqMsg) {
      if (0 != g_stConfInfo.showMsgFlag) {
S
Shengliang Guan 已提交
814 815 816 817 818 819 820 821 822
        tmq_res_t msgType = tmq_get_res_type(tmqMsg);
        if (msgType == TMQ_RES_TABLE_META) {
          totalRows += meta_msg_process(tmqMsg, pInfo, totalMsgs);
        } else if (msgType == TMQ_RES_DATA) {
          totalRows += data_msg_process(tmqMsg, pInfo, totalMsgs);
        } else if (msgType == TMQ_RES_METADATA) {
          meta_msg_process(tmqMsg, pInfo, totalMsgs);
          totalRows += data_msg_process(tmqMsg, pInfo, totalMsgs);
        }
823 824 825 826 827 828 829 830 831 832 833 834 835 836
      }

      taos_free_result(tmqMsg);
      totalMsgs++;

      int64_t currentPrintTime = taosGetTimestampMs();
      if (currentPrintTime - lastPrintTime > 10 * 1000) {
        taosFprintfFile(
            g_fp, "consumer id %d has currently poll total msgs: %" PRId64 ", period rate: %.3f msgs/second\n",
            pInfo->consumerId, totalMsgs, (totalMsgs - lastTotalMsgs) * 1000.0 / (currentPrintTime - lastPrintTime));
        lastPrintTime = currentPrintTime;
        lastTotalMsgs = totalMsgs;
      }

837 838
      if (0 == once_flag) {
        once_flag = 1;
839 840 841 842
        notifyMainScript(pInfo, NOTIFY_CMD_START_CONSUM);
      }

      if ((totalRows >= pInfo->expectMsgCnt) || (totalMsgs >= pInfo->expectMsgCnt)) {
H
Haojun Liao 已提交
843
        memset(tmpString, 0, tListLen(tmpString));
844 845 846 847
        taosFprintfFile(g_fp, "%s over than expect rows, so break consume\n", getCurrentTimeString(tmpString));
        break;
      }
    } else {
H
Haojun Liao 已提交
848
      memset(tmpString, 0, tListLen(tmpString));
849 850 851 852 853 854 855 856 857 858 859 860 861 862
      taosFprintfFile(g_fp, "%s no poll more msg when time over, break consume\n", getCurrentTimeString(tmpString));
      break;
    }
  }

  if (0 == running) {
    taosFprintfFile(g_fp, "receive stop signal and not continue consume\n");
  }

  pInfo->consumeMsgCnt = totalMsgs;
  pInfo->consumeRowCnt = totalRows;

  taosFprintfFile(g_fp, "==== consumerId: %d, consumeMsgCnt: %" PRId64 ", consumeRowCnt: %" PRId64 "\n",
                  pInfo->consumerId, pInfo->consumeMsgCnt, pInfo->consumeRowCnt);
S
Shengliang Guan 已提交
863

wmmhello's avatar
wmmhello 已提交
864 865 866
  if(taosFsyncFile(pInfo->pConsumeRowsFile) < 0){
    printf("taosFsyncFile error:%s", strerror(errno));
  }
S
Shengliang Guan 已提交
867
  taosCloseFile(&pInfo->pConsumeRowsFile);
868 869 870 871 872 873 874 875 876 877 878 879 880 881
}

void* consumeThreadFunc(void* param) {
  SThreadInfo* pInfo = (SThreadInfo*)param;

  pInfo->taos = createNewTaosConnect();
  if (pInfo->taos == NULL) {
    taosFprintfFile(g_fp, "taos_connect() fail, can not notify and save consume result to main scripte\n");
    return NULL;
  }

  build_consumer(pInfo);
  build_topic_list(pInfo);
  if ((NULL == pInfo->tmq) || (NULL == pInfo->topicList)) {
S
Shengliang Guan 已提交
882 883
    taosFprintfFile(g_fp, "create consumer fail! tmq is null or topicList is null\n");
    taos_close(pInfo->taos);
884 885 886 887 888 889 890 891
    pInfo->taos = NULL;
    return NULL;
  }

  int32_t err = tmq_subscribe(pInfo->tmq, pInfo->topicList);
  if (err != 0) {
    pError("tmq_subscribe() fail, reason: %s\n", tmq_err2str(err));
    taosFprintfFile(g_fp, "tmq_subscribe() fail! reason: %s\n", tmq_err2str(err));
S
Shengliang Guan 已提交
892
    taos_close(pInfo->taos);
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 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
    pInfo->taos = NULL;
    return NULL;
  }

  tmq_list_destroy(pInfo->topicList);
  pInfo->topicList = NULL;

  loop_consume(pInfo);

  if (pInfo->ifManualCommit) {
    pPrint("tmq_commit() manual commit when consume end.\n");
    /*tmq_commit(pInfo->tmq, NULL, 0);*/
    tmq_commit_sync(pInfo->tmq, NULL);
    taosFprintfFile(g_fp, "tmq_commit() manual commit over.\n");
    pPrint("tmq_commit() manual commit over.\n");
  }

  err = tmq_unsubscribe(pInfo->tmq);
  if (err != 0) {
    pError("tmq_unsubscribe() fail, reason: %s\n", tmq_err2str(err));
    taosFprintfFile(g_fp, "tmq_unsubscribe()! reason: %s\n", tmq_err2str(err));
  }

  err = tmq_consumer_close(pInfo->tmq);
  if (err != 0) {
    pError("tmq_consumer_close() fail, reason: %s\n", tmq_err2str(err));
    taosFprintfFile(g_fp, "tmq_consumer_close()! reason: %s\n", tmq_err2str(err));
  }
  pInfo->tmq = NULL;

  // save consume result into consumeresult table
  saveConsumeResult(pInfo);

  // save rows from per vgroup
  taosFprintfFile(g_fp, "======== consumerId: %d, consume rows from per vgroups ========\n", pInfo->consumerId);
  for (int32_t i = 0; i < pInfo->numOfVgroups; i++) {
    taosFprintfFile(g_fp, "vgroups: %04d, rows: %d\n", pInfo->rowsOfPerVgroups[i][0], pInfo->rowsOfPerVgroups[i][1]);
  }

  taos_close(pInfo->taos);
  pInfo->taos = NULL;

  return NULL;
}

void parseConsumeInfo() {
  char*      token;
  const char delim[2] = ",";
  const char ch = ':';

  for (int32_t i = 0; i < g_stConfInfo.numOfThread; i++) {
    token = strtok(g_stConfInfo.stThreads[i].topicString, delim);
    while (token != NULL) {
      // printf("%s\n", token );
S
Shengliang Guan 已提交
947 948
      tstrncpy(g_stConfInfo.stThreads[i].topics[g_stConfInfo.stThreads[i].numOfTopic], token,
               sizeof(g_stConfInfo.stThreads[i].topics[g_stConfInfo.stThreads[i].numOfTopic]));
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
      ltrim(g_stConfInfo.stThreads[i].topics[g_stConfInfo.stThreads[i].numOfTopic]);
      // printf("%s\n", g_stConfInfo.topics[g_stConfInfo.numOfTopic]);
      g_stConfInfo.stThreads[i].numOfTopic++;

      token = strtok(NULL, delim);
    }

    token = strtok(g_stConfInfo.stThreads[i].keyString, delim);
    while (token != NULL) {
      // printf("%s\n", token );
      {
        char* pstr = token;
        ltrim(pstr);
        char* ret = strchr(pstr, ch);
        memcpy(g_stConfInfo.stThreads[i].key[g_stConfInfo.stThreads[i].numOfKey], pstr, ret - pstr);
S
Shengliang Guan 已提交
964 965
        tstrncpy(g_stConfInfo.stThreads[i].value[g_stConfInfo.stThreads[i].numOfKey], ret + 1,
                 sizeof(g_stConfInfo.stThreads[i].value[g_stConfInfo.stThreads[i].numOfKey]));
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
        // printf("key: %s, value: %s\n", g_stConfInfo.key[g_stConfInfo.numOfKey],
        // g_stConfInfo.value[g_stConfInfo.numOfKey]);
        g_stConfInfo.stThreads[i].numOfKey++;
      }

      token = strtok(NULL, delim);
    }
  }
}

int32_t getConsumeInfo() {
  char sqlStr[1024] = {0};

  TAOS* pConn = createNewTaosConnect();
  if (pConn == NULL) {
    taosFprintfFile(g_fp, "taos_connect() fail, can not get consume info for start consumer\n");
    return -1;
  }

  sprintf(sqlStr, "select * from %s.consumeinfo", g_stConfInfo.cdbName);
S
Shengliang Guan 已提交
986
  TAOS_RES* pRes = taos_query(pConn, sqlStr);
987 988 989 990
  if (taos_errno(pRes) != 0) {
    taosFprintfFile(g_fp, "error in get consumeinfo for %s\n", taos_errstr(pRes));
    taosCloseFile(&g_fp);
    taos_free_result(pRes);
S
Shengliang Guan 已提交
991
    taos_close(pConn);
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 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    return -1;
  }

  TAOS_ROW    row = NULL;
  int         num_fields = taos_num_fields(pRes);
  TAOS_FIELD* fields = taos_fetch_fields(pRes);

  // schema: ts timestamp, consumerid int, topiclist binary(1024), keylist binary(1024), expectmsgcnt bigint,
  // ifcheckdata int

  int32_t numOfThread = 0;
  while ((row = taos_fetch_row(pRes))) {
    int32_t* lengths = taos_fetch_lengths(pRes);

    // set default value
    // g_stConfInfo.stThreads[numOfThread].autoCommitIntervalMs = 5000;
    // memcpy(g_stConfInfo.stThreads[numOfThread].autoCommit, "true", strlen("true"));
    // memcpy(g_stConfInfo.stThreads[numOfThread].autoOffsetRest, "earlieast", strlen("earlieast"));

    for (int i = 0; i < num_fields; ++i) {
      if (row[i] == NULL || 0 == i) {
        continue;
      }

      if ((1 == i) && (fields[i].type == TSDB_DATA_TYPE_INT)) {
        g_stConfInfo.stThreads[numOfThread].consumerId = *((int32_t*)row[i]);
      } else if ((2 == i) && (fields[i].type == TSDB_DATA_TYPE_BINARY)) {
        memcpy(g_stConfInfo.stThreads[numOfThread].topicString, row[i], lengths[i]);
      } else if ((3 == i) && (fields[i].type == TSDB_DATA_TYPE_BINARY)) {
        memcpy(g_stConfInfo.stThreads[numOfThread].keyString, row[i], lengths[i]);
      } else if ((4 == i) && (fields[i].type == TSDB_DATA_TYPE_BIGINT)) {
        g_stConfInfo.stThreads[numOfThread].expectMsgCnt = *((int64_t*)row[i]);
      } else if ((5 == i) && (fields[i].type == TSDB_DATA_TYPE_INT)) {
        g_stConfInfo.stThreads[numOfThread].ifCheckData = *((int32_t*)row[i]);
      } else if ((6 == i) && (fields[i].type == TSDB_DATA_TYPE_INT)) {
        g_stConfInfo.stThreads[numOfThread].ifManualCommit = *((int32_t*)row[i]);
      }
    }
    numOfThread++;
  }
  g_stConfInfo.numOfThread = numOfThread;

  taos_free_result(pRes);

  parseConsumeInfo();
  taos_close(pConn);

  return 0;
}

static int32_t omb_data_msg_process(TAOS_RES* msg, SThreadInfo* pInfo, int32_t msgIndex, int64_t* lenOfRows) {
S
Shengliang Guan 已提交
1043
  char    buf[16 * 1024];
1044 1045 1046 1047
  int32_t totalRows = 0;
  int32_t totalLen = 0;

  // printf("topic: %s\n", tmq_get_topic_name(msg));
S
Shengliang Guan 已提交
1048 1049
  // int32_t     vgroupId = tmq_get_vgroup_id(msg);
  // const char* dbName = tmq_get_db_name(msg);
1050

S
Shengliang Guan 已提交
1051 1052 1053
  // taosFprintfFile(g_fp, "consumerId: %d, msg index:%" PRId64 "\n", pInfo->consumerId, msgIndex);
  // taosFprintfFile(g_fp, "dbName: %s, topic: %s, vgroupId: %d\n", dbName != NULL ? dbName : "invalid table",
  //                 tmq_get_topic_name(msg), vgroupId);
1054 1055 1056 1057 1058 1059 1060 1061

  while (1) {
    TAOS_ROW row = taos_fetch_row(msg);

    if (row == NULL) break;

    TAOS_FIELD* fields = taos_fetch_fields(msg);
    int32_t     numOfFields = taos_field_count(msg);
S
Shengliang Guan 已提交
1062 1063 1064
    // int32_t*    length = taos_fetch_lengths(msg);
    // int32_t     precision = taos_result_precision(msg);
    // const char* tbName = tmq_get_table_name(msg);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085

    taos_print_row(buf, row, fields, numOfFields);
    totalLen += strlen(buf);
    totalRows++;
  }

  *lenOfRows = totalLen;
  return totalRows;
}

void omb_loop_consume(SThreadInfo* pInfo) {
  int32_t code;

  int32_t once_flag = 0;

  int64_t totalMsgs = 0;
  int64_t totalRows = 0;

  char tmpString[128];
  taosFprintfFile(g_fp, "%s consumer id %d start to loop pull msg\n", getCurrentTimeString(tmpString),
                  pInfo->consumerId);
S
Shengliang Guan 已提交
1086
  printf("%s consumer id %d start to loop pull msg\n", getCurrentTimeString(tmpString), pInfo->consumerId);
1087 1088 1089 1090 1091 1092 1093

  pInfo->ts = taosGetTimestampMs();

  int64_t  lastTotalMsgs = 0;
  uint64_t lastPrintTime = taosGetTimestampMs();
  uint64_t startTs = taosGetTimestampMs();

S
Shengliang Guan 已提交
1094 1095
  int64_t totalLenOfMsg = 0;
  int64_t lastTotalLenOfMsg = 0;
1096 1097 1098 1099
  int32_t consumeDelay = g_stConfInfo.consumeDelay == -1 ? -1 : (g_stConfInfo.consumeDelay * 1000);
  while (running) {
    TAOS_RES* tmqMsg = tmq_consumer_poll(pInfo->tmq, consumeDelay);
    if (tmqMsg) {
S
Shengliang Guan 已提交
1100
      int64_t lenOfMsg = 0;
1101
      totalRows += omb_data_msg_process(tmqMsg, pInfo, totalMsgs, &lenOfMsg);
S
Shengliang Guan 已提交
1102
      totalLenOfMsg += lenOfMsg;
1103 1104 1105 1106
      taos_free_result(tmqMsg);
      totalMsgs++;
      int64_t currentPrintTime = taosGetTimestampMs();
      if (currentPrintTime - lastPrintTime > 10 * 1000) {
S
Shengliang Guan 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
        int64_t currentLenOfMsg = totalLenOfMsg - lastTotalLenOfMsg;
        int64_t deltaTime = currentPrintTime - lastPrintTime;
        printf("consumer id %d has currently cons total rows: %" PRId64 ", msgs: %" PRId64
               ", rate: %.3f msgs/s, %.1f MB/s\n",
               pInfo->consumerId, totalRows, totalMsgs, (totalMsgs - lastTotalMsgs) * 1000.0 / deltaTime,
               currentLenOfMsg * 1000.0 / (1024 * 1024) / deltaTime);

        taosFprintfFile(g_fp,
                        "consumer id %d has currently poll total msgs: %" PRId64
                        ", period cons rate: %.3f msgs/s, %.1f MB/s\n",
                        pInfo->consumerId, totalMsgs, (totalMsgs - lastTotalMsgs) * 1000.0 / deltaTime,
                        currentLenOfMsg * 1000.0 / deltaTime);
1119 1120
        lastPrintTime = currentPrintTime;
        lastTotalMsgs = totalMsgs;
S
Shengliang Guan 已提交
1121
        lastTotalLenOfMsg = totalLenOfMsg;
1122 1123
      }
    } else {
H
Haojun Liao 已提交
1124
      memset(tmpString, 0, tListLen(tmpString));
1125
      taosFprintfFile(g_fp, "%s no poll more msg when time over, break consume\n", getCurrentTimeString(tmpString));
S
Shengliang Guan 已提交
1126
      printf("%s no poll more msg when time over, break consume\n", getCurrentTimeString(tmpString));
1127 1128
      int64_t currentPrintTime = taosGetTimestampMs();
      int64_t currentLenOfMsg = totalLenOfMsg - lastTotalLenOfMsg;
S
Shengliang Guan 已提交
1129 1130 1131 1132 1133
      int64_t deltaTime = currentPrintTime - lastPrintTime;
      printf("consumer id %d has currently cons total rows: %" PRId64 ", msgs: %" PRId64
             ", rate: %.3f msgs/s, %.1f MB/s\n",
             pInfo->consumerId, totalRows, totalMsgs, (totalMsgs - lastTotalMsgs) * 1000.0 / deltaTime,
             currentLenOfMsg * 1000.0 / (1024 * 1024) / deltaTime);
1134 1135 1136 1137 1138 1139
      break;
    }
  }

  pInfo->consumeMsgCnt = totalMsgs;
  pInfo->consumeRowCnt = totalRows;
S
Shengliang Guan 已提交
1140
  pInfo->consumeLen = totalLenOfMsg;
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
}

void* ombConsumeThreadFunc(void* param) {
  SThreadInfo* pInfo = (SThreadInfo*)param;

  //################### set key ########################
  tmq_conf_t* conf = tmq_conf_new();
  // tmq_conf_set(conf, "td.connect.ip", "localhost");
  // tmq_conf_set(conf, "td.connect.port", "6030");
  tmq_conf_set(conf, "td.connect.user", "root");
  tmq_conf_set(conf, "td.connect.pass", "taosdata");
  // tmq_conf_set(conf, "td.connect.db", g_stConfInfo.dbName);
  tmq_conf_set_auto_commit_cb(conf, tmq_commit_cb_print, pInfo);
  tmq_conf_set(conf, "group.id", "ombCgrp");
  // tmq_conf_set(conf, "msg.with.table.name", "true");
  // tmq_conf_set(conf, "client.id", "c-001");
  // tmq_conf_set(conf, "enable.auto.commit", "true");
  tmq_conf_set(conf, "enable.auto.commit", "false");
  // tmq_conf_set(conf, "auto.commit.interval.ms", "1000");
  // tmq_conf_set(conf, "auto.offset.reset", "none");
  // tmq_conf_set(conf, "auto.offset.reset", "earliest");
  tmq_conf_set(conf, "auto.offset.reset", "earliest");
  //
  if (g_stConfInfo.useSnapshot) {
    tmq_conf_set(conf, "experimental.snapshot.enable", "true");
  }

  pInfo->tmq = tmq_consumer_new(conf, NULL, 0);

  tmq_conf_destroy(conf);

  //################### set topic ##########################
  pInfo->topicList = tmq_list_new();
  tmq_list_append(pInfo->topicList, g_stConfInfo.topic);

  if ((NULL == pInfo->tmq) || (NULL == pInfo->topicList)) {
    taosFprintfFile(g_fp, "create consumer fail! tmq is null or topicList is null\n");
    return NULL;
  }

  int32_t err = tmq_subscribe(pInfo->tmq, pInfo->topicList);
  if (err != 0) {
    pError("tmq_subscribe() fail, reason: %s\n", tmq_err2str(err));
    taosFprintfFile(g_fp, "tmq_subscribe() fail! reason: %s\n", tmq_err2str(err));
    return NULL;
  }

  tmq_list_destroy(pInfo->topicList);
  pInfo->topicList = NULL;

  omb_loop_consume(pInfo);

  err = tmq_unsubscribe(pInfo->tmq);
  if (err != 0) {
    pError("tmq_unsubscribe() fail, reason: %s\n", tmq_err2str(err));
    taosFprintfFile(g_fp, "tmq_unsubscribe()! reason: %s\n", tmq_err2str(err));
  }

  err = tmq_consumer_close(pInfo->tmq);
  if (err != 0) {
    pError("tmq_consumer_close() fail, reason: %s\n", tmq_err2str(err));
    taosFprintfFile(g_fp, "tmq_consumer_close()! reason: %s\n", tmq_err2str(err));
  }
  pInfo->tmq = NULL;

  return NULL;
}

S
Shengliang Guan 已提交
1209 1210 1211
static int queryDbExec(TAOS* taos, char* command, QUERY_TYPE type) {
  TAOS_RES* res = taos_query(taos, command);
  int32_t   code = taos_errno(res);
1212

S
Shengliang Guan 已提交
1213 1214 1215 1216 1217
  if (code != 0) {
    pPrint("%s Failed to execute <%s>, reason: %s %s", GREEN, command, taos_errstr(res), NC);
    taos_free_result(res);
    return -1;
  }
1218

S
Shengliang Guan 已提交
1219 1220
  if (INSERT_TYPE == type) {
    int affectedRows = taos_affected_rows(res);
1221
    taos_free_result(res);
S
Shengliang Guan 已提交
1222 1223 1224 1225 1226
    return affectedRows;
  }

  taos_free_result(res);
  return 0;
1227 1228 1229 1230 1231 1232 1233
}

void* ombProduceThreadFunc(void* param) {
  SThreadInfo* pInfo = (SThreadInfo*)param;

  pInfo->taos = createNewTaosConnect();
  if (pInfo->taos == NULL) {
S
Shengliang Guan 已提交
1234
    taosFprintfFile(g_fp, "taos_connect() fail, can not start producers!\n");
1235 1236 1237 1238 1239 1240
    return NULL;
  }

  int64_t affectedRowsTotal = 0;
  int64_t sendMsgs = 0;

S
Shengliang Guan 已提交
1241 1242 1243 1244
  uint32_t totalSendLoopTimes =
      g_stConfInfo.runDurationMinutes * 60 * 1000 / SEND_TIME_UNIT;  // send some msgs per 10ms
  uint32_t batchPerTblTimes = pInfo->producerRate / 100 / g_stConfInfo.batchSize;
  uint32_t remainder = (pInfo->producerRate / 100) % g_stConfInfo.batchSize;
1245
  if (remainder) {
S
Shengliang Guan 已提交
1246
    batchPerTblTimes += 1;
1247 1248 1249 1250 1251
  }

  char* sqlBuf = taosMemoryMalloc(MAX_SQL_LEN);
  if (NULL == sqlBuf) {
    printf("malloc fail for sqlBuf\n");
S
Shengliang Guan 已提交
1252
    taos_close(pInfo->taos);
1253
    pInfo->taos = NULL;
S
Shengliang Guan 已提交
1254
    return NULL;
1255 1256
  }

S
Shengliang Guan 已提交
1257 1258
  printf("Produce Info: totalSendLoopTimes: %d, batchPerTblTimes: %d, producerRate: %d\n", totalSendLoopTimes,
         batchPerTblTimes, pInfo->producerRate);
1259

1260
  char ctbName[128] = {0};
1261 1262
  sprintf(ctbName, "%s.ctb%d", g_stConfInfo.dbName, pInfo->consumerId);

S
Shengliang Guan 已提交
1263 1264 1265
  int64_t lastPrintTime = taosGetTimestampUs();
  int64_t totalMsgLen = 0;
  // int64_t timeStamp = taosGetTimestampUs();
1266
  while (totalSendLoopTimes) {
S
Shengliang Guan 已提交
1267
    int64_t startTs = taosGetTimestampUs();
1268
    for (int i = 0; i < batchPerTblTimes; ++i) {
S
Shengliang Guan 已提交
1269 1270 1271 1272
      uint32_t msgsOfSql = g_stConfInfo.batchSize;
      if ((i == batchPerTblTimes - 1) && (0 != remainder)) {
        msgsOfSql = remainder;
      }
1273
      int len = 0;
S
Shengliang Guan 已提交
1274
      len += snprintf(sqlBuf + len, MAX_SQL_LEN - len, "insert into %s values ", ctbName);
1275
      for (int j = 0; j < msgsOfSql; j++) {
S
Shengliang Guan 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
        int64_t timeStamp = taosGetTimestampNs();
        len += snprintf(sqlBuf + len, MAX_SQL_LEN - len, "(%" PRId64 ", \"%s\")", timeStamp, g_payload);
        sendMsgs++;
        pInfo->totalProduceMsgs++;
      }

      totalMsgLen += len;
      pInfo->totalMsgsLen += len;

      int64_t affectedRows = queryDbExec(pInfo->taos, sqlBuf, INSERT_TYPE);
      if (affectedRows < 0) {
        taos_close(pInfo->taos);
        pInfo->taos = NULL;
        taosMemoryFree(sqlBuf);
        return NULL;
      }

      affectedRowsTotal += affectedRows;

      // printf("Produce Info: affectedRows: %" PRId64 "\n", affectedRows);
1296 1297 1298
    }
    totalSendLoopTimes -= 1;

S
Shengliang Guan 已提交
1299 1300 1301 1302 1303 1304 1305 1306
    // calc spent time
    int64_t currentTs = taosGetTimestampUs();
    int64_t delta = currentTs - startTs;
    if (delta < SEND_TIME_UNIT * 1000) {
      int64_t sleepLen = (int32_t)(SEND_TIME_UNIT * 1000 - delta);
      // printf("sleep %" PRId64 " us, use time: %" PRId64 " us\n", sleepLen, delta);
      taosUsleep((int32_t)sleepLen);
    }
1307 1308 1309

    currentTs = taosGetTimestampUs();
    delta = currentTs - lastPrintTime;
S
Shengliang Guan 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    if (delta > 10 * 1000 * 1000) {
      printf("producer[%d] info: %" PRId64 " msgs, %" PRId64 " Byte, %" PRId64 " us, totalSendLoopTimes: %d\n",
             pInfo->consumerId, sendMsgs, totalMsgLen, delta, totalSendLoopTimes);
      printf("producer[%d] rate: %1.f msgs/s, %1.f KB/s\n", pInfo->consumerId, sendMsgs * 1000.0 * 1000 / delta,
             (totalMsgLen / 1024.0) / (delta / (1000 * 1000)));
      lastPrintTime = currentTs;
      sendMsgs = 0;
      totalMsgLen = 0;
    }
  }

  printf("affectedRowsTotal: %" PRId64 "\n", affectedRowsTotal);
1322 1323
  taos_close(pInfo->taos);
  pInfo->taos = NULL;
wmmhello's avatar
wmmhello 已提交
1324
  taosMemoryFree(sqlBuf);
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
  return NULL;
}

void printProduceInfo(int64_t start) {
  int64_t totalMsgs = 0;
  int64_t totalLenOfMsgs = 0;
  for (int i = 0; i < g_stConfInfo.producers; i++) {
    totalMsgs += g_stConfInfo.stProdThreads[i].totalProduceMsgs;
    totalLenOfMsgs += g_stConfInfo.stProdThreads[i].totalMsgsLen;
  }

  int64_t end = taosGetTimestampUs();

  int64_t t = end - start;
  if (0 == t) t = 1;

  double tInMs = (double)t / 1000000.0;
  printf("Spent %.3f seconds to prod %" PRIu64 " msgs, %" PRIu64 " Byte\n\n", tInMs, totalMsgs, totalLenOfMsgs);

  printf("Spent %.3f seconds to prod %" PRIu64 " msgs with %d producer(s), throughput: %.3f msgs/s, %.1f MB/s\n\n",
S
Shengliang Guan 已提交
1345 1346
         tInMs, totalMsgs, g_stConfInfo.producers, (double)totalMsgs / tInMs,
         (double)totalLenOfMsgs / (1024.0 * 1024) / tInMs);
1347 1348 1349 1350
  return;
}

void startOmbConsume() {
S
Shengliang Guan 已提交
1351 1352 1353
  TdThreadAttr thattr;
  taosThreadAttrInit(&thattr);
  taosThreadAttrSetDetachState(&thattr, PTHREAD_CREATE_JOINABLE);
1354 1355 1356 1357 1358

  if (0 != g_stConfInfo.producers) {
    TAOS* taos = createNewTaosConnect();
    if (taos == NULL) {
      taosFprintfFile(g_fp, "taos_connect() fail, can not create db, stbl, ctbl, topic!\n");
S
Shengliang Guan 已提交
1359
      return;
1360 1361
    }

S
Shengliang Guan 已提交
1362 1363 1364
    char stbName[16] = "stb";
    char ctbPrefix[16] = "ctb";

1365 1366
    char sql[256] = {0};
    sprintf(sql, "drop database if exists %s", g_stConfInfo.dbName);
S
Shengliang Guan 已提交
1367
    printf("SQL: %s\n", sql);
1368
    queryDbExec(taos, sql, NO_INSERT_TYPE);
S
Shengliang Guan 已提交
1369 1370 1371 1372

    sprintf(sql, "create database if not exists %s precision 'ns' vgroups %d", g_stConfInfo.dbName,
            g_stConfInfo.producers);
    printf("SQL: %s\n", sql);
1373 1374
    queryDbExec(taos, sql, NO_INSERT_TYPE);

S
Shengliang Guan 已提交
1375 1376 1377
    sprintf(sql, "create stable %s.%s (ts timestamp, payload binary(%d)) tags (t bigint) ", g_stConfInfo.dbName,
            stbName, g_stConfInfo.payloadLen);
    printf("SQL: %s\n", sql);
1378 1379
    queryDbExec(taos, sql, NO_INSERT_TYPE);

S
Shengliang Guan 已提交
1380 1381 1382 1383
    for (int i = 0; i < g_stConfInfo.producers; i++) {
      sprintf(sql, "create table %s.%s%d using %s.stb tags(%d) ", g_stConfInfo.dbName, ctbPrefix, i,
              g_stConfInfo.dbName, i);
      printf("SQL: %s\n", sql);
1384
      queryDbExec(taos, sql, NO_INSERT_TYPE);
S
Shengliang Guan 已提交
1385
    }
1386

S
Shengliang Guan 已提交
1387
    // create topic
1388
    sprintf(sql, "create topic %s as stable %s.%s", g_stConfInfo.topic, g_stConfInfo.dbName, stbName);
S
Shengliang Guan 已提交
1389
    printf("SQL: %s\n", sql);
1390
    queryDbExec(taos, sql, NO_INSERT_TYPE);
S
Shengliang Guan 已提交
1391

H
Haojun Liao 已提交
1392
    int32_t producerRate = ceil(((double)g_stConfInfo.producerRate) / g_stConfInfo.producers);
S
Shengliang Guan 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403

    printf("==== create %d produce thread ====\n", g_stConfInfo.producers);
    for (int32_t i = 0; i < g_stConfInfo.producers; ++i) {
      g_stConfInfo.stProdThreads[i].consumerId = i;
      g_stConfInfo.stProdThreads[i].producerRate = producerRate;
      taosThreadCreate(&(g_stConfInfo.stProdThreads[i].thread), &thattr, ombProduceThreadFunc,
                       (void*)(&(g_stConfInfo.stProdThreads[i])));
    }

    if (0 == g_stConfInfo.numOfThread) {
      int64_t start = taosGetTimestampUs();
1404 1405 1406 1407 1408
      for (int32_t i = 0; i < g_stConfInfo.producers; i++) {
        taosThreadJoin(g_stConfInfo.stProdThreads[i].thread, NULL);
        taosThreadClear(&g_stConfInfo.stProdThreads[i].thread);
      }

S
Shengliang Guan 已提交
1409 1410 1411 1412 1413
      printProduceInfo(start);

      taosFprintfFile(g_fp, "==== close tmqlog ====\n");
      taosCloseFile(&g_fp);
      taos_close(taos);
1414
      return;
S
Shengliang Guan 已提交
1415
    }
1416

S
Shengliang Guan 已提交
1417
    taos_close(taos);
1418 1419 1420 1421 1422
  }

  // pthread_create one thread to consume
  taosFprintfFile(g_fp, "==== create %d consume thread ====\n", g_stConfInfo.numOfThread);
  for (int32_t i = 0; i < g_stConfInfo.numOfThread; ++i) {
S
Shengliang Guan 已提交
1423
    g_stConfInfo.stThreads[i].consumerId = i;
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
    taosThreadCreate(&(g_stConfInfo.stThreads[i].thread), &thattr, ombConsumeThreadFunc,
                     (void*)(&(g_stConfInfo.stThreads[i])));
  }

  int64_t start = taosGetTimestampUs();

  for (int32_t i = 0; i < g_stConfInfo.numOfThread; i++) {
    taosThreadJoin(g_stConfInfo.stThreads[i].thread, NULL);
    taosThreadClear(&g_stConfInfo.stThreads[i].thread);
  }

  int64_t end = taosGetTimestampUs();

  int64_t totalRows = 0;
  int64_t totalMsgs = 0;
  int64_t totalLenOfMsgs = 0;
  for (int32_t i = 0; i < g_stConfInfo.numOfThread; i++) {
    totalMsgs += g_stConfInfo.stThreads[i].consumeMsgCnt;
S
Shengliang Guan 已提交
1442 1443
    totalLenOfMsgs += g_stConfInfo.stThreads[i].consumeLen;
    totalRows += g_stConfInfo.stThreads[i].consumeRowCnt;
1444 1445 1446 1447 1448 1449
  }

  int64_t t = end - start;
  if (0 == t) t = 1;

  double tInMs = (double)t / 1000000.0;
S
Shengliang Guan 已提交
1450 1451 1452 1453
  taosFprintfFile(
      g_fp, "Spent %.3f seconds to poll msgs: %" PRIu64 " with %d thread(s), throughput: %.3f msgs/s, %.1f MB/s\n\n",
      tInMs, totalMsgs, g_stConfInfo.numOfThread, (double)(totalMsgs / tInMs),
      (double)totalLenOfMsgs / (1024 * 1024) / tInMs);
1454

S
Shengliang Guan 已提交
1455 1456 1457 1458
  printf("Spent %.3f seconds to cons rows: %" PRIu64 " msgs: %" PRIu64
         " with %d thread(s), throughput: %.3f msgs/s, %.1f MB/s\n\n",
         tInMs, totalRows, totalMsgs, g_stConfInfo.numOfThread, (double)(totalMsgs / tInMs),
         (double)totalLenOfMsgs / (1024 * 1024) / tInMs);
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470

  taosFprintfFile(g_fp, "==== close tmqlog ====\n");
  taosCloseFile(&g_fp);

  return;
}

int main(int32_t argc, char* argv[]) {
  parseArgument(argc, argv);

  if (0 != strlen(g_stConfInfo.topic)) {
    startOmbConsume();
S
Shengliang Guan 已提交
1471
    return 0;
1472
  }
S
Shengliang Guan 已提交
1473

1474 1475 1476 1477
  int32_t retCode = getConsumeInfo();
  if (0 != retCode) {
    return -1;
  }
S
Shengliang Guan 已提交
1478

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
  saveConfigToLogFile();

  tmqSetSignalHandle();

  TdThreadAttr thattr;
  taosThreadAttrInit(&thattr);
  taosThreadAttrSetDetachState(&thattr, PTHREAD_CREATE_JOINABLE);

  // pthread_create one thread to consume
  taosFprintfFile(g_fp, "==== create %d consume thread ====\n", g_stConfInfo.numOfThread);
  for (int32_t i = 0; i < g_stConfInfo.numOfThread; ++i) {
    taosThreadCreate(&(g_stConfInfo.stThreads[i].thread), &thattr, consumeThreadFunc,
                     (void*)(&(g_stConfInfo.stThreads[i])));
  }

  int64_t start = taosGetTimestampUs();

  for (int32_t i = 0; i < g_stConfInfo.numOfThread; i++) {
    taosThreadJoin(g_stConfInfo.stThreads[i].thread, NULL);
    taosThreadClear(&g_stConfInfo.stThreads[i].thread);
  }

  int64_t end = taosGetTimestampUs();

  int64_t totalMsgs = 0;
  for (int32_t i = 0; i < g_stConfInfo.numOfThread; i++) {
    totalMsgs += g_stConfInfo.stThreads[i].consumeMsgCnt;
  }

  int64_t t = end - start;
  if (0 == t) t = 1;

  double tInMs = (double)t / 1000000.0;
  taosFprintfFile(g_fp,
                  "Spent %.3f seconds to poll msgs: %" PRIu64 " with %d thread(s), throughput: %.3f msgs/second\n\n",
                  tInMs, totalMsgs, g_stConfInfo.numOfThread, (double)(totalMsgs / tInMs));

  taosFprintfFile(g_fp, "==== close tmqlog ====\n");
  taosCloseFile(&g_fp);

  return 0;
}