• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #3526

10 Nov 2024 03:50AM UTC coverage: 60.225% (-0.6%) from 60.818%
#3526

push

travis-ci

web-flow
Merge pull request #28709 from taosdata/main

merge: from main to 3.0 branch

117031 of 249004 branches covered (47.0%)

Branch coverage included in aggregate %.

130 of 169 new or added lines in 23 files covered. (76.92%)

4149 existing lines in 176 files now uncovered.

197577 of 273386 relevant lines covered (72.27%)

5840219.36 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

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

16
#include <ttimer.h>
17
#include "cJSON.h"
18
#include "catalog.h"
19
#include "clientInt.h"
20
#include "clientLog.h"
21
#include "clientMonitor.h"
22
#include "functionMgt.h"
23
#include "os.h"
24
#include "osSleep.h"
25
#include "query.h"
26
#include "qworker.h"
27
#include "scheduler.h"
28
#include "tcache.h"
29
#include "tcompare.h"
30
#include "tglobal.h"
31
#include "thttp.h"
32
#include "tmsg.h"
33
#include "tqueue.h"
34
#include "tref.h"
35
#include "trpc.h"
36
#include "tsched.h"
37
#include "ttime.h"
38
#include "tversion.h"
39

40
#if defined(CUS_NAME) || defined(CUS_PROMPT) || defined(CUS_EMAIL)
41
#include "cus_name.h"
42
#endif
43

44
#define TSC_VAR_NOT_RELEASE 1
45
#define TSC_VAR_RELEASED    0
46

47
#define ENV_JSON_FALSE_CHECK(c)                     \
48
  do {                                              \
49
    if (!c) {                                       \
50
      tscError("faild to add item to JSON object"); \
51
      code = TSDB_CODE_TSC_FAIL_GENERATE_JSON;      \
52
      goto _end;                                    \
53
    }                                               \
54
  } while (0)
55

56
#define ENV_ERR_RET(c, info)          \
57
  do {                                \
58
    int32_t _code = c;                \
59
    if (_code != TSDB_CODE_SUCCESS) { \
60
      errno = _code;                  \
61
      tscInitRes = _code;             \
62
      tscError(info);                 \
63
      return;                         \
64
    }                                 \
65
  } while (0)
66

67
STscDbg  tscDbg = {0};
68
SAppInfo appInfo;
69
int64_t  lastClusterId = 0;
70
int32_t  clientReqRefPool = -1;
71
int32_t  clientConnRefPool = -1;
72
int32_t  clientStop = -1;
73

74
int32_t timestampDeltaLimit = 900;  // s
75

76
static TdThreadOnce tscinit = PTHREAD_ONCE_INIT;
77
volatile int32_t    tscInitRes = 0;
78

79
static int32_t registerRequest(SRequestObj *pRequest, STscObj *pTscObj) {
2,788,522✔
80
  int32_t code = TSDB_CODE_SUCCESS;
2,788,522✔
81
  // connection has been released already, abort creating request.
82
  pRequest->self = taosAddRef(clientReqRefPool, pRequest);
2,788,522✔
83
  if (pRequest->self < 0) {
2,788,531!
84
    tscError("failed to add ref to request");
×
85
    code = terrno;
×
86
    return code;
×
87
  }
88

89
  int32_t num = atomic_add_fetch_32(&pTscObj->numOfReqs, 1);
2,788,531✔
90

91
  if (pTscObj->pAppInfo) {
2,788,528!
92
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
2,788,529✔
93

94
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
2,788,529✔
95
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
2,788,529✔
96
    tscDebug("0x%" PRIx64 " new Request from connObj:0x%" PRIx64
2,788,529✔
97
             ", current:%d, app current:%d, total:%d,QID:0x%" PRIx64,
98
             pRequest->self, pRequest->pTscObj->id, num, currentInst, total, pRequest->requestId);
99
  }
100

101
  return code;
2,788,531✔
102
}
103

104
static void concatStrings(SArray *list, char *buf, int size) {
2✔
105
  int len = 0;
2✔
106
  for (int i = 0; i < taosArrayGetSize(list); i++) {
4✔
107
    char *db = taosArrayGet(list, i);
2✔
108
    if (NULL == db) {
2!
109
      tscError("get dbname failed, buf:%s", buf);
×
110
      break;
×
111
    }
112
    char *dot = strchr(db, '.');
2✔
113
    if (dot != NULL) {
2!
114
      db = dot + 1;
2✔
115
    }
116
    if (i != 0) {
2!
117
      (void)strncat(buf, ",", size - 1 - len);
×
118
      len += 1;
×
119
    }
120
    int ret = tsnprintf(buf + len, size - len, "%s", db);
2✔
121
    if (ret < 0) {
2!
122
      tscError("snprintf failed, buf:%s, ret:%d", buf, ret);
×
123
      break;
×
124
    }
125
    len += ret;
2✔
126
    if (len >= size) {
2!
127
      tscInfo("dbList is truncated, buf:%s, len:%d", buf, len);
×
128
      break;
×
129
    }
130
  }
131
}
2✔
132

133
static int32_t generateWriteSlowLog(STscObj *pTscObj, SRequestObj *pRequest, int32_t reqType, int64_t duration) {
2✔
134
  cJSON  *json = cJSON_CreateObject();
2✔
135
  int32_t code = TSDB_CODE_SUCCESS;
2✔
136
  if (json == NULL) {
2!
137
    tscError("[monitor] cJSON_CreateObject failed");
×
138
    return TSDB_CODE_OUT_OF_MEMORY;
×
139
  }
140
  char clusterId[32] = {0};
2✔
141
  if (snprintf(clusterId, sizeof(clusterId), "%" PRId64, pTscObj->pAppInfo->clusterId) < 0) {
2!
142
    tscError("failed to generate clusterId:%" PRId64, pTscObj->pAppInfo->clusterId);
×
143
    code = TSDB_CODE_FAILED;
×
144
    goto _end;
×
145
  }
146

147
  char startTs[32] = {0};
2✔
148
  if (snprintf(startTs, sizeof(startTs), "%" PRId64, pRequest->metric.start / 1000) < 0) {
2!
149
    tscError("failed to generate startTs:%" PRId64, pRequest->metric.start / 1000);
×
150
    code = TSDB_CODE_FAILED;
×
151
    goto _end;
×
152
  }
153

154
  char requestId[32] = {0};
2✔
155
  if (snprintf(requestId, sizeof(requestId), "%" PRIu64, pRequest->requestId) < 0) {
2!
156
    tscError("failed to generate requestId:%" PRIu64, pRequest->requestId);
×
157
    code = TSDB_CODE_FAILED;
×
158
    goto _end;
×
159
  }
160
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "cluster_id", cJSON_CreateString(clusterId)));
2!
161
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "start_ts", cJSON_CreateString(startTs)));
2!
162
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "request_id", cJSON_CreateString(requestId)));
2!
163
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "query_time", cJSON_CreateNumber(duration / 1000)));
2!
164
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "code", cJSON_CreateNumber(pRequest->code)));
2!
165
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "error_info", cJSON_CreateString(tstrerror(pRequest->code))));
2!
166
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "type", cJSON_CreateNumber(reqType)));
2!
167
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(
2!
168
      json, "rows_num", cJSON_CreateNumber(pRequest->body.resInfo.numOfRows + pRequest->body.resInfo.totalRows)));
169
  if (pRequest->sqlstr != NULL && strlen(pRequest->sqlstr) > pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogMaxLen) {
2!
170
    char tmp = pRequest->sqlstr[pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogMaxLen];
×
171
    pRequest->sqlstr[pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogMaxLen] = '\0';
×
172
    ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "sql", cJSON_CreateString(pRequest->sqlstr)));
×
173
    pRequest->sqlstr[pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogMaxLen] = tmp;
×
174
  } else {
175
    ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "sql", cJSON_CreateString(pRequest->sqlstr)));
2!
176
  }
177

178
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "user", cJSON_CreateString(pTscObj->user)));
2!
179
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "process_name", cJSON_CreateString(appInfo.appName)));
2!
180
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "ip", cJSON_CreateString(tsLocalFqdn)));
2!
181

182
  char pid[32] = {0};
2✔
183
  if (snprintf(pid, sizeof(pid), "%d", appInfo.pid) < 0) {
2!
184
    tscError("failed to generate pid:%d", appInfo.pid);
×
185
    code = TSDB_CODE_FAILED;
×
186
    goto _end;
×
187
  }
188

189
  ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "process_id", cJSON_CreateString(pid)));
2!
190
  if (pRequest->dbList != NULL) {
2!
191
    char dbList[1024] = {0};
2✔
192
    concatStrings(pRequest->dbList, dbList, sizeof(dbList) - 1);
2✔
193
    ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "db", cJSON_CreateString(dbList)));
2!
194
  } else if (pRequest->pDb != NULL) {
×
195
    ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "db", cJSON_CreateString(pRequest->pDb)));
×
196
  } else {
197
    ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "db", cJSON_CreateString("")));
×
198
  }
199

200
  char *value = cJSON_PrintUnformatted(json);
2✔
201
  if (value == NULL) {
2!
202
    tscError("failed to print json");
×
203
    code = TSDB_CODE_FAILED;
×
204
    goto _end;
×
205
  }
206
  MonitorSlowLogData data = {0};
2✔
207
  data.clusterId = pTscObj->pAppInfo->clusterId;
2✔
208
  data.type = SLOW_LOG_WRITE;
2✔
209
  data.data = value;
2✔
210
  code = monitorPutData2MonitorQueue(data);
2✔
211
  if (TSDB_CODE_SUCCESS != code) {
2!
212
    taosMemoryFree(value);
×
213
    goto _end;
×
214
  }
215

216
_end:
2✔
217
  cJSON_Delete(json);
2✔
218
  return code;
2✔
219
}
220

221
static bool checkSlowLogExceptDb(SRequestObj *pRequest, char *exceptDb) {
625✔
222
  if (pRequest->pDb != NULL) {
625✔
223
    return strcmp(pRequest->pDb, exceptDb) != 0;
380✔
224
  }
225

226
  for (int i = 0; i < taosArrayGetSize(pRequest->dbList); i++) {
294✔
227
    char *db = taosArrayGet(pRequest->dbList, i);
49✔
228
    if (NULL == db) {
49!
229
      tscError("get dbname failed, exceptDb:%s", exceptDb);
×
230
      return false;
×
231
    }
232
    char *dot = strchr(db, '.');
49✔
233
    if (dot != NULL) {
49!
234
      db = dot + 1;
49✔
235
    }
236
    if (strcmp(db, exceptDb) == 0) {
49!
237
      return false;
×
238
    }
239
  }
240
  return true;
245✔
241
}
242

243
static void deregisterRequest(SRequestObj *pRequest) {
2,787,916✔
244
  if (pRequest == NULL) {
2,787,916!
245
    tscError("pRequest == NULL");
×
246
    return;
×
247
  }
248

249
  STscObj            *pTscObj = pRequest->pTscObj;
2,787,916✔
250
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
2,787,916✔
251

252
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
2,787,916✔
253
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
2,787,918✔
254
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
2,787,918✔
255

256
  int64_t duration = taosGetTimestampUs() - pRequest->metric.start;
2,787,918✔
257
  tscDebug("0x%" PRIx64 " free Request from connObj: 0x%" PRIx64 ",QID:0x%" PRIx64
2,787,918✔
258
           " elapsed:%.2f ms, "
259
           "current:%d, app current:%d",
260
           pRequest->self, pTscObj->id, pRequest->requestId, duration / 1000.0, num, currentInst);
261

262
  if (TSDB_CODE_SUCCESS == nodesSimAcquireAllocator(pRequest->allocatorRefId)) {
2,787,918!
263
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
2,787,914!
264
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
1,698,805✔
265
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
1,175,537✔
266
      tscDebug("insert duration %" PRId64 "us: parseCost:%" PRId64 "us, ctgCost:%" PRId64 "us, analyseCost:%" PRId64
1,699,132✔
267
               "us, planCost:%" PRId64 "us, exec:%" PRId64 "us",
268
               duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs, pRequest->metric.analyseCostUs,
269
               pRequest->metric.planCostUs, pRequest->metric.execCostUs);
270
      (void)atomic_add_fetch_64((int64_t *)&pActivity->insertElapsedTime, duration);
1,699,132✔
271
      reqType = SLOW_LOG_TYPE_INSERT;
1,699,133✔
272
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
1,088,782✔
273
      tscDebug("query duration %" PRId64 "us: parseCost:%" PRId64 "us, ctgCost:%" PRId64 "us, analyseCost:%" PRId64
763,845✔
274
               "us, planCost:%" PRId64 "us, exec:%" PRId64 "us",
275
               duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs, pRequest->metric.analyseCostUs,
276
               pRequest->metric.planCostUs, pRequest->metric.execCostUs);
277

278
      (void)atomic_add_fetch_64((int64_t *)&pActivity->queryElapsedTime, duration);
763,845✔
279
      reqType = SLOW_LOG_TYPE_QUERY;
763,847✔
280
    }
281

282
    if (TSDB_CODE_SUCCESS != nodesSimReleaseAllocator(pRequest->allocatorRefId)) {
2,787,917!
283
      tscError("failed to release allocator");
×
284
    }
285
  }
286

287
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
2,787,916✔
288
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
445,625✔
289
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
413,301✔
290
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
32,324✔
291
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
20,782✔
292
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
11,542✔
293
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
112✔
294
    }
295
  }
296

297
  if ((duration >= pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogThreshold * 1000000UL) &&
2,788,541!
298
      checkSlowLogExceptDb(pRequest, pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogExceptDb)) {
625✔
299
    (void)atomic_add_fetch_64((int64_t *)&pActivity->numOfSlowQueries, 1);
625✔
300
    if (pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogScope & reqType) {
625✔
301
      taosPrintSlowLog("PID:%d, Conn:%u,QID:0x%" PRIx64 ", Start:%" PRId64 " us, Duration:%" PRId64 "us, SQL:%s",
168✔
302
                       taosGetPId(), pTscObj->connId, pRequest->requestId, pRequest->metric.start, duration,
303
                       pRequest->sqlstr);
304
      if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
168✔
305
        slowQueryLog(pTscObj->id, pRequest->killed, pRequest->code, duration);
2✔
306
        if (TSDB_CODE_SUCCESS != generateWriteSlowLog(pTscObj, pRequest, reqType, duration)) {
2!
307
          tscError("failed to generate write slow log");
×
308
        }
309
      }
310
    }
311
  }
312

313
  releaseTscObj(pTscObj->id);
2,787,916✔
314
}
315

316
// todo close the transporter properly
317
void closeTransporter(SAppInstInfo *pAppInfo) {
×
318
  if (pAppInfo == NULL || pAppInfo->pTransporter == NULL) {
×
319
    return;
×
320
  }
321

322
  tscDebug("free transporter:%p in app inst %p", pAppInfo->pTransporter, pAppInfo);
×
323
  rpcClose(pAppInfo->pTransporter);
×
324
}
325

326
static bool clientRpcRfp(int32_t code, tmsg_t msgType) {
82,345✔
327
  if (NEED_REDIRECT_ERROR(code)) {
82,345!
328
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
68,120!
329
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_QUERY_HEARTBEAT || msgType == TDMT_SCH_DROP_TASK ||
68,123!
330
        msgType == TDMT_SCH_TASK_NOTIFY) {
331
      return false;
×
332
    }
333
    return true;
68,123✔
334
  } else {
335
    return false;
14,225✔
336
  }
337
}
338

339
// start timer for particular msgType
340
static bool clientRpcTfp(int32_t code, tmsg_t msgType) {
×
341
  if (msgType == TDMT_VND_SUBMIT || msgType == TDMT_VND_CREATE_TABLE) {
×
342
    return true;
×
343
  }
344
  return false;
×
345
}
346

347
// TODO refactor
348
int32_t openTransporter(const char *user, const char *auth, int32_t numOfThread, void **pDnodeConn) {
3,538✔
349
  SRpcInit rpcInit;
350
  (void)memset(&rpcInit, 0, sizeof(rpcInit));
3,538✔
351
  rpcInit.localPort = 0;
3,538✔
352
  rpcInit.label = "TSC";
3,538✔
353
  rpcInit.numOfThreads = tsNumOfRpcThreads;
3,538✔
354
  rpcInit.cfp = processMsgFromServer;
3,538✔
355
  rpcInit.rfp = clientRpcRfp;
3,538✔
356
  rpcInit.sessions = 1024;
3,538✔
357
  rpcInit.connType = TAOS_CONN_CLIENT;
3,538✔
358
  rpcInit.user = (char *)user;
3,538✔
359
  rpcInit.idleTime = tsShellActivityTimer * 1000;
3,538✔
360
  rpcInit.compressSize = tsCompressMsgSize;
3,538✔
361
  rpcInit.dfp = destroyAhandle;
3,538✔
362

363
  rpcInit.retryMinInterval = tsRedirectPeriod;
3,538✔
364
  rpcInit.retryStepFactor = tsRedirectFactor;
3,538✔
365
  rpcInit.retryMaxInterval = tsRedirectMaxPeriod;
3,538✔
366
  rpcInit.retryMaxTimeout = tsMaxRetryWaitTime;
3,538✔
367

368
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
3,538✔
369
  connLimitNum = TMAX(connLimitNum, 10);
3,538✔
370
  connLimitNum = TMIN(connLimitNum, 1000);
3,538✔
371
  rpcInit.connLimitNum = connLimitNum;
3,538✔
372
  rpcInit.shareConnLimit = tsShareConnLimit;
3,538✔
373
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
3,538✔
374
  rpcInit.startReadTimer = 1;
3,538✔
375
  rpcInit.readTimeout = tsReadTimeout;
3,538✔
376

377
  int32_t code = taosVersionStrToInt(td_version, &rpcInit.compatibilityVer);
3,538✔
378
  if (TSDB_CODE_SUCCESS != code) {
3,538!
379
    tscError("invalid version string.");
×
380
    return code;
×
381
  }
382

383
  *pDnodeConn = rpcOpen(&rpcInit);
3,538✔
384
  if (*pDnodeConn == NULL) {
3,538!
385
    tscError("failed to init connection to server since %s", tstrerror(terrno));
×
386
    code = terrno;
×
387
  }
388

389
  return code;
3,538✔
390
}
391

392
void destroyAllRequests(SHashObj *pRequests) {
8,380✔
393
  void *pIter = taosHashIterate(pRequests, NULL);
8,380✔
394
  while (pIter != NULL) {
8,380!
395
    int64_t *rid = pIter;
×
396

397
    SRequestObj *pRequest = acquireRequest(*rid);
×
398
    if (pRequest) {
×
399
      destroyRequest(pRequest);
×
400
      (void)releaseRequest(*rid);  // ignore error
×
401
    }
402

403
    pIter = taosHashIterate(pRequests, pIter);
×
404
  }
405
}
8,380✔
406

407
void stopAllRequests(SHashObj *pRequests) {
5✔
408
  void *pIter = taosHashIterate(pRequests, NULL);
5✔
409
  while (pIter != NULL) {
5!
410
    int64_t *rid = pIter;
×
411

412
    SRequestObj *pRequest = acquireRequest(*rid);
×
413
    if (pRequest) {
×
414
      taos_stop_query(pRequest);
×
415
      (void)releaseRequest(*rid);  // ignore error
×
416
    }
417

418
    pIter = taosHashIterate(pRequests, pIter);
×
419
  }
420
}
5✔
421

422
void destroyAppInst(void *info) {
×
423
  SAppInstInfo *pAppInfo = *(SAppInstInfo **)info;
×
424
  tscDebug("destroy app inst mgr %p", pAppInfo);
×
425

426
  int32_t code = taosThreadMutexLock(&appInfo.mutex);
×
427
  if (TSDB_CODE_SUCCESS != code) {
×
428
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
429
  }
430

431
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
×
432

433
  code = taosThreadMutexUnlock(&appInfo.mutex);
×
434
  if (TSDB_CODE_SUCCESS != code) {
×
435
    tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
436
  }
437

438
  taosMemoryFreeClear(pAppInfo->instKey);
×
439
  closeTransporter(pAppInfo);
×
440

441
  code = taosThreadMutexLock(&pAppInfo->qnodeMutex);
×
442
  if (TSDB_CODE_SUCCESS != code) {
×
443
    tscError("failed to lock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
444
  }
445

446
  taosArrayDestroy(pAppInfo->pQnodeList);
×
447
  code = taosThreadMutexUnlock(&pAppInfo->qnodeMutex);
×
448
  if (TSDB_CODE_SUCCESS != code) {
×
449
    tscError("failed to unlock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
450
  }
451

452
  taosMemoryFree(pAppInfo);
×
453
}
×
454

455
void destroyTscObj(void *pObj) {
8,380✔
456
  if (NULL == pObj) {
8,380!
457
    return;
×
458
  }
459

460
  STscObj *pTscObj = pObj;
8,380✔
461
  int64_t  tscId = pTscObj->id;
8,380✔
462
  tscTrace("begin to destroy tscObj %" PRIx64 " p:%p", tscId, pTscObj);
8,380✔
463

464
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
8,380✔
465
  hbDeregisterConn(pTscObj, connKey);
8,380✔
466

467
  destroyAllRequests(pTscObj->pRequests);
8,380✔
468
  taosHashCleanup(pTscObj->pRequests);
8,380✔
469

470
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
8,380✔
471
  tscDebug("connObj 0x%" PRIx64 " p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
8,380✔
472
           pTscObj->pAppInfo->numOfConns);
473

474
  // In any cases, we should not free app inst here. Or an race condition rises.
475
  /*int64_t connNum = */ (void)atomic_sub_fetch_64(&pTscObj->pAppInfo->numOfConns, 1);
8,380✔
476

477
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
8,380✔
478
  taosMemoryFree(pTscObj);
8,380✔
479

480
  tscTrace("end to destroy tscObj %" PRIx64 " p:%p", tscId, pTscObj);
8,380✔
481
}
482

483
int32_t createTscObj(const char *user, const char *auth, const char *db, int32_t connType, SAppInstInfo *pAppInfo,
9,045✔
484
                     STscObj **pObj) {
485
  *pObj = (STscObj *)taosMemoryCalloc(1, sizeof(STscObj));
9,045✔
486
  if (NULL == *pObj) {
9,045!
487
    return terrno;
×
488
  }
489

490
  (*pObj)->pRequests = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
9,045✔
491
  if (NULL == (*pObj)->pRequests) {
9,045!
492
    taosMemoryFree(*pObj);
×
493
    return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
494
  }
495

496
  (*pObj)->connType = connType;
9,045✔
497
  (*pObj)->pAppInfo = pAppInfo;
9,045✔
498
  (*pObj)->appHbMgrIdx = pAppInfo->pAppHbMgr->idx;
9,045✔
499
  tstrncpy((*pObj)->user, user, sizeof((*pObj)->user));
9,045✔
500
  (void)memcpy((*pObj)->pass, auth, TSDB_PASSWORD_LEN);
9,045✔
501

502
  if (db != NULL) {
9,045!
503
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
9,045✔
504
  }
505

506
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
9,045!
507

508
  int32_t code = TSDB_CODE_SUCCESS;
9,045✔
509

510
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
9,045✔
511
  if ((*pObj)->id < 0) {
9,045!
512
    tscError("failed to add object to clientConnRefPool");
×
513
    code = terrno;
×
514
    taosMemoryFree(*pObj);
×
515
    return code;
×
516
  }
517

518
  (void)atomic_add_fetch_64(&(*pObj)->pAppInfo->numOfConns, 1);
9,045✔
519

520
  tscDebug("connObj created, 0x%" PRIx64 ",p:%p", (*pObj)->id, *pObj);
9,045✔
521
  return code;
9,045✔
522
}
523

524
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
3,429,518✔
525

526
void releaseTscObj(int64_t rid) {
3,425,384✔
527
  int32_t code = taosReleaseRef(clientConnRefPool, rid);
3,425,384✔
528
  if (TSDB_CODE_SUCCESS != code) {
3,425,383!
529
    tscWarn("failed to release TscObj, code:%s", tstrerror(code));
×
530
  }
531
}
3,425,383✔
532

533
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
2,788,521✔
534
  int32_t code = TSDB_CODE_SUCCESS;
2,788,521✔
535
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
2,788,521✔
536
  if (NULL == *pRequest) {
2,788,525!
537
    return terrno;
×
538
  }
539

540
  STscObj *pTscObj = acquireTscObj(connId);
2,788,525✔
541
  if (pTscObj == NULL) {
2,788,531!
542
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
543
  }
544
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
2,788,531✔
545
  if (interParam == NULL) {
2,788,525!
546
    releaseTscObj(connId);
×
547
    TSC_ERR_JRET(terrno);
×
548
  }
549
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
2,788,525!
550
  interParam->pRequest = *pRequest;
2,788,531✔
551
  (*pRequest)->body.interParam = interParam;
2,788,531✔
552

553
  (*pRequest)->resType = RES_TYPE__QUERY;
2,788,531✔
554
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
2,788,531!
555
  (*pRequest)->metric.start = taosGetTimestampUs();
2,788,531✔
556

557
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
2,788,530✔
558
  (*pRequest)->type = type;
2,788,530✔
559
  (*pRequest)->allocatorRefId = -1;
2,788,530✔
560

561
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
2,788,530✔
562
  if (NULL == (*pRequest)->pDb) {
2,788,526✔
563
    TSC_ERR_JRET(terrno);
291,227!
564
  }
565
  (*pRequest)->pTscObj = pTscObj;
2,788,527✔
566
  (*pRequest)->inCallback = false;
2,788,527✔
567
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
2,788,527✔
568
  if (NULL == (*pRequest)->msgBuf) {
2,788,525!
569
    code = terrno;
×
570
    goto _return;
×
571
  }
572
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
2,788,525✔
573
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
2,788,525!
574
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
2,788,524!
575

576
  return TSDB_CODE_SUCCESS;
2,788,531✔
577
_return:
×
578
  if ((*pRequest)->pTscObj) {
×
579
    doDestroyRequest(*pRequest);
×
580
  } else {
581
    taosMemoryFree(*pRequest);
×
582
  }
583
  return code;
×
584
}
585

586
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
3,176,040✔
587
  taosMemoryFreeClear(pResInfo->pRspMsg);
3,176,040✔
588
  taosMemoryFreeClear(pResInfo->length);
3,176,041✔
589
  taosMemoryFreeClear(pResInfo->row);
3,176,044✔
590
  taosMemoryFreeClear(pResInfo->pCol);
3,176,042✔
591
  taosMemoryFreeClear(pResInfo->fields);
3,176,050✔
592
  taosMemoryFreeClear(pResInfo->userFields);
3,176,048✔
593
  taosMemoryFreeClear(pResInfo->convertJson);
3,176,047✔
594
  taosMemoryFreeClear(pResInfo->decompBuf);
3,176,047✔
595

596
  if (pResInfo->convertBuf != NULL) {
3,176,047✔
597
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
5,293,456✔
598
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
4,204,979✔
599
    }
600
    taosMemoryFreeClear(pResInfo->convertBuf);
1,088,477!
601
  }
602
}
3,176,048✔
603

604
SRequestObj *acquireRequest(int64_t rid) { return (SRequestObj *)taosAcquireRef(clientReqRefPool, rid); }
15,815,073✔
605

606
int32_t releaseRequest(int64_t rid) { return taosReleaseRef(clientReqRefPool, rid); }
15,818,216✔
607

608
int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }
2,787,434✔
609

610
/// return the most previous req ref id
611
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
2,787,436✔
612
  int64_t      mostPrevReqRefId = pRequest->self;
2,787,436✔
613
  SRequestObj *pTmp = pRequest;
2,787,436✔
614
  while (pTmp->relation.prevRefId) {
2,787,917✔
615
    pTmp = acquireRequest(pTmp->relation.prevRefId);
481✔
616
    if (pTmp) {
481!
617
      mostPrevReqRefId = pTmp->self;
481✔
618
      (void)releaseRequest(mostPrevReqRefId);  // ignore error
481✔
619
    } else {
620
      break;
×
621
    }
622
  }
623
  (void)removeRequest(mostPrevReqRefId);  // ignore error
2,787,436✔
624
  return mostPrevReqRefId;
2,787,434✔
625
}
626

627
void destroyNextReq(int64_t nextRefId) {
2,787,910✔
628
  if (nextRefId) {
2,787,910✔
629
    SRequestObj *pObj = acquireRequest(nextRefId);
503✔
630
    if (pObj) {
503!
631
      (void)releaseRequest(nextRefId);  // ignore error
503✔
632
      (void)releaseRequest(nextRefId);  // ignore error
503✔
633
    }
634
  }
635
}
2,787,910✔
636

637
void destroySubRequests(SRequestObj *pRequest) {
×
638
  int32_t      reqIdx = -1;
×
639
  SRequestObj *pReqList[16] = {NULL};
×
640
  uint64_t     tmpRefId = 0;
×
641

642
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
×
643
    return;
×
644
  }
645

646
  SRequestObj *pTmp = pRequest;
×
647
  while (pTmp->relation.prevRefId) {
×
648
    tmpRefId = pTmp->relation.prevRefId;
×
649
    pTmp = acquireRequest(tmpRefId);
×
650
    if (pTmp) {
×
651
      pReqList[++reqIdx] = pTmp;
×
652
      (void)releaseRequest(tmpRefId);  // ignore error
×
653
    } else {
654
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
655
      break;
×
656
    }
657
  }
658

659
  for (int32_t i = reqIdx; i >= 0; i--) {
×
660
    (void)removeRequest(pReqList[i]->self);  // ignore error
×
661
  }
662

663
  tmpRefId = pRequest->relation.nextRefId;
×
664
  while (tmpRefId) {
×
665
    pTmp = acquireRequest(tmpRefId);
×
666
    if (pTmp) {
×
667
      tmpRefId = pTmp->relation.nextRefId;
×
668
      (void)removeRequest(pTmp->self);   // ignore error
×
669
      (void)releaseRequest(pTmp->self);  // ignore error
×
670
    } else {
671
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
672
      break;
×
673
    }
674
  }
675
}
676

677
void doDestroyRequest(void *p) {
2,787,916✔
678
  if (NULL == p) {
2,787,916!
679
    return;
×
680
  }
681

682
  SRequestObj *pRequest = (SRequestObj *)p;
2,787,916✔
683

684
  uint64_t reqId = pRequest->requestId;
2,787,916✔
685
  tscTrace("begin to destroy request %" PRIx64 " p:%p", reqId, pRequest);
2,787,916✔
686

687
  int64_t nextReqRefId = pRequest->relation.nextRefId;
2,787,916✔
688

689
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
2,787,916✔
690
  if (TSDB_CODE_SUCCESS != code) {
2,787,915✔
691
    tscWarn("failed to remove request from hash, code:%s", tstrerror(code));
9,045!
692
  }
693
  schedulerFreeJob(&pRequest->body.queryJob, 0);
2,787,915✔
694

695
  destorySqlCallbackWrapper(pRequest->pWrapper);
2,787,916✔
696

697
  taosMemoryFreeClear(pRequest->msgBuf);
2,787,916!
698

699
  doFreeReqResultInfo(&pRequest->body.resInfo);
2,787,915✔
700
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
2,787,916!
701
    tscError("failed to destroy semaphore");
×
702
  }
703

704
  taosArrayDestroy(pRequest->tableList);
2,787,915✔
705
  taosArrayDestroy(pRequest->targetTableList);
2,787,912✔
706
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
2,787,917✔
707

708
  if (pRequest->self) {
2,787,916!
709
    deregisterRequest(pRequest);
2,787,916✔
710
  }
711

712
  taosMemoryFreeClear(pRequest->pDb);
2,787,913✔
713
  taosArrayDestroy(pRequest->dbList);
2,787,917✔
714
  if (pRequest->body.interParam) {
2,787,916!
715
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
2,787,917!
716
      tscError("failed to destroy semaphore in pRequest");
×
717
    }
718
  }
719
  taosMemoryFree(pRequest->body.interParam);
2,787,916✔
720

721
  qDestroyQuery(pRequest->pQuery);
2,787,915✔
722
  nodesDestroyAllocator(pRequest->allocatorRefId);
2,787,912✔
723

724
  taosMemoryFreeClear(pRequest->effectiveUser);
2,787,917✔
725
  taosMemoryFreeClear(pRequest->sqlstr);
2,787,917✔
726
  taosMemoryFree(pRequest);
2,787,917✔
727
  tscTrace("end to destroy request %" PRIx64 " p:%p", reqId, pRequest);
2,787,916✔
728
  destroyNextReq(nextReqRefId);
2,787,916✔
729
}
730

731
void destroyRequest(SRequestObj *pRequest) {
2,787,411✔
732
  if (pRequest == NULL) {
2,787,411!
733
    return;
×
734
  }
735

736
  taos_stop_query(pRequest);
2,787,411✔
737
  (void)removeFromMostPrevReq(pRequest);
2,787,412✔
738
}
739

740
void taosStopQueryImpl(SRequestObj *pRequest) {
2,787,893✔
741
  pRequest->killed = true;
2,787,893✔
742

743
  // It is not a query, no need to stop.
744
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
2,787,893✔
745
    tscDebug("request 0x%" PRIx64 " no need to be killed since not query", pRequest->requestId);
294,162✔
746
    return;
294,163✔
747
  }
748

749
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
2,493,731✔
750
  tscDebug("request %" PRIx64 " killed", pRequest->requestId);
2,493,732✔
751
}
752

753
void stopAllQueries(SRequestObj *pRequest) {
2,787,411✔
754
  int32_t      reqIdx = -1;
2,787,411✔
755
  SRequestObj *pReqList[16] = {NULL};
2,787,411✔
756
  uint64_t     tmpRefId = 0;
2,787,411✔
757

758
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
2,787,411!
759
    return;
×
760
  }
761

762
  SRequestObj *pTmp = pRequest;
2,787,411✔
763
  while (pTmp->relation.prevRefId) {
2,787,892✔
764
    tmpRefId = pTmp->relation.prevRefId;
481✔
765
    pTmp = acquireRequest(tmpRefId);
481✔
766
    if (pTmp) {
481!
767
      pReqList[++reqIdx] = pTmp;
481✔
768
    } else {
769
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
770
      break;
×
771
    }
772
  }
773

774
  for (int32_t i = reqIdx; i >= 0; i--) {
2,787,894✔
775
    taosStopQueryImpl(pReqList[i]);
481✔
776
    (void)releaseRequest(pReqList[i]->self);  // ignore error
481✔
777
  }
778

779
  taosStopQueryImpl(pRequest);
2,787,413✔
780

781
  tmpRefId = pRequest->relation.nextRefId;
2,787,415✔
782
  while (tmpRefId) {
2,787,411!
783
    pTmp = acquireRequest(tmpRefId);
×
784
    if (pTmp) {
×
785
      tmpRefId = pTmp->relation.nextRefId;
×
786
      taosStopQueryImpl(pTmp);
×
787
      (void)releaseRequest(pTmp->self);  // ignore error
×
788
    } else {
789
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
790
      break;
×
791
    }
792
  }
793
}
794

795
void crashReportThreadFuncUnexpectedStopped(void) { atomic_store_32(&clientStop, -1); }
×
796

797
static void *tscCrashReportThreadFp(void *param) {
×
798
  setThreadName("client-crashReport");
×
799
  char filepath[PATH_MAX] = {0};
×
800
  (void)snprintf(filepath, sizeof(filepath), "%s%s.taosCrashLog", tsLogDir, TD_DIRSEP);
×
801
  char     *pMsg = NULL;
×
802
  int64_t   msgLen = 0;
×
803
  TdFilePtr pFile = NULL;
×
804
  bool      truncateFile = false;
×
805
  int32_t   sleepTime = 200;
×
806
  int32_t   reportPeriodNum = 3600 * 1000 / sleepTime;
×
807
  int32_t   loopTimes = reportPeriodNum;
×
808

809
#ifdef WINDOWS
810
  if (taosCheckCurrentInDll()) {
811
    atexit(crashReportThreadFuncUnexpectedStopped);
812
  }
813
#endif
814

815
  if (-1 != atomic_val_compare_exchange_32(&clientStop, -1, 0)) {
×
816
    return NULL;
×
817
  }
818

819
  while (1) {
820
    if (clientStop > 0) break;
×
821
    if (loopTimes++ < reportPeriodNum) {
×
822
      taosMsleep(sleepTime);
×
823
      continue;
×
824
    }
825

826
    taosReadCrashInfo(filepath, &pMsg, &msgLen, &pFile);
×
827
    if (pMsg && msgLen > 0) {
×
828
      if (taosSendHttpReport(tsTelemServer, tsClientCrashReportUri, tsTelemPort, pMsg, msgLen, HTTP_FLAT) != 0) {
×
829
        tscError("failed to send crash report");
×
830
        if (pFile) {
×
831
          taosReleaseCrashLogFile(pFile, false);
×
832
          pFile = NULL;
×
833

834
          taosMsleep(sleepTime);
×
835
          loopTimes = 0;
×
836
          continue;
×
837
        }
838
      } else {
839
        tscInfo("succeed to send crash report");
×
840
        truncateFile = true;
×
841
      }
842
    } else {
843
      tscDebug("no crash info");
×
844
    }
845

846
    taosMemoryFree(pMsg);
×
847

848
    if (pMsg && msgLen > 0) {
×
849
      pMsg = NULL;
×
850
      continue;
×
851
    }
852

853
    if (pFile) {
×
854
      taosReleaseCrashLogFile(pFile, truncateFile);
×
855
      pFile = NULL;
×
856
      truncateFile = false;
×
857
    }
858

859
    taosMsleep(sleepTime);
×
860
    loopTimes = 0;
×
861
  }
862

863
  clientStop = -2;
×
864
  return NULL;
×
865
}
866

867
int32_t tscCrashReportInit() {
3,272✔
868
  if (!tsEnableCrashReport) {
3,272!
869
    return TSDB_CODE_SUCCESS;
3,272✔
870
  }
871
  int32_t      code = TSDB_CODE_SUCCESS;
×
872
  TdThreadAttr thAttr;
873
  TSC_ERR_JRET(taosThreadAttrInit(&thAttr));
×
874
  TSC_ERR_JRET(taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE));
×
875
  TdThread crashReportThread;
876
  if (taosThreadCreate(&crashReportThread, &thAttr, tscCrashReportThreadFp, NULL) != 0) {
×
877
    tscError("failed to create crashReport thread since %s", strerror(errno));
×
878
    terrno = TAOS_SYSTEM_ERROR(errno);
×
879
    TSC_ERR_RET(errno);
×
880
  }
881

882
  (void)taosThreadAttrDestroy(&thAttr);
×
883
_return:
×
884
  if (code) {
×
885
    terrno = TAOS_SYSTEM_ERROR(errno);
×
886
    TSC_ERR_RET(terrno);
×
887
  }
888

889
  return code;
×
890
}
891

892
void tscStopCrashReport() {
3,272✔
893
  if (!tsEnableCrashReport) {
3,272!
894
    return;
3,272✔
895
  }
896

897
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
898
    tscDebug("crash report thread already stopped");
×
899
    return;
×
900
  }
901

902
  while (atomic_load_32(&clientStop) > 0) {
×
903
    taosMsleep(100);
×
904
  }
905
}
906

907
void tscWriteCrashInfo(int signum, void *sigInfo, void *context) {
×
908
  char       *pMsg = NULL;
×
909
  const char *flags = "UTL FATAL ";
×
910
  ELogLevel   level = DEBUG_FATAL;
×
911
  int32_t     dflag = 255;
×
912
  int64_t     msgLen = -1;
×
913

914
  if (tsEnableCrashReport) {
×
915
    if (taosGenCrashJsonMsg(signum, &pMsg, lastClusterId, appInfo.startTime)) {
×
916
      taosPrintLog(flags, level, dflag, "failed to generate crash json msg");
×
917
    } else {
918
      msgLen = strlen(pMsg);
×
919
    }
920
  }
921

922
  taosLogCrashInfo("taos", pMsg, msgLen, signum, sigInfo);
×
923
}
×
924

925
void taos_init_imp(void) {
3,272✔
926
#if defined(LINUX)
927
  if (tscDbg.memEnable) {
3,272!
928
    int32_t code = taosMemoryDbgInit();
×
929
    if (code) {
×
930
      (void)printf("failed to init memory dbg, error:%s\n", tstrerror(code));
×
931
    } else {
932
      tsAsyncLog = false;
×
933
      (void)printf("memory dbg enabled\n");
×
934
    }
935
  }
936
#endif
937

938
  // In the APIs of other program language, taos_cleanup is not available yet.
939
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
940
  (void)atexit(taos_cleanup);
3,272✔
941
  errno = TSDB_CODE_SUCCESS;
3,272✔
942
  taosSeedRand(taosGetTimestampSec());
3,272✔
943

944
  appInfo.pid = taosGetPId();
3,272✔
945
  appInfo.startTime = taosGetTimestampMs();
3,272✔
946
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
3,272✔
947
  appInfo.pInstMapByClusterId =
3,272✔
948
      taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);
3,272✔
949
  if (NULL == appInfo.pInstMap || NULL == appInfo.pInstMapByClusterId) {
3,272!
950
    (void)printf("failed to allocate memory when init appInfo\n");
×
951
    tscInitRes = TSDB_CODE_OUT_OF_MEMORY;
×
952
    return;
×
953
  }
954
  taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst);
3,272✔
955
  deltaToUtcInitOnce();
3,272✔
956

957
  char logDirName[64] = {0};
3,272✔
958
#ifdef CUS_PROMPT
959
  snprintf(logDirName, 64, "%slog", CUS_PROMPT);
960
#else
961
  (void)snprintf(logDirName, 64, "taoslog");
3,272✔
962
#endif
963
  if (taosCreateLog(logDirName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
3,272!
964
    (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logDirName, strerror(errno), configDir);
×
965
    tscInitRes = -1;
×
966
    return;
×
967
  }
968

969
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
3,272!
970

971
  initQueryModuleMsgHandle();
3,272✔
972
  ENV_ERR_RET(taosConvInit(), "failed to init conv");
3,272!
973
  ENV_ERR_RET(monitorInit(), "failed to init monitor");
3,272!
974
  ENV_ERR_RET(rpcInit(), "failed to init rpc");
3,272!
975

976
  if (InitRegexCache() != 0) {
3,272!
977
    tscInitRes = -1;
×
978
    (void)printf("failed to init regex cache\n");
×
979
    return;
×
980
  }
981

982
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
3,272✔
983
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
3,272!
984
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
3,272!
985
  ENV_ERR_RET(initClientId(), "failed to init clientId");
3,272!
986

987
  tscDebug("starting to initialize TAOS driver");
3,272✔
988

989
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
3,272!
990
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
3,272!
991
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
3,272!
992

993
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
3,272✔
994
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
3,272✔
995

996
  ENV_ERR_RET(taosGetAppName(appInfo.appName, NULL), "failed to get app name");
3,272!
997
  ENV_ERR_RET(taosThreadMutexInit(&appInfo.mutex, NULL), "failed to init thread mutex");
3,272!
998
  ENV_ERR_RET(tscCrashReportInit(), "failed to init crash report");
3,272!
999
  ENV_ERR_RET(qInitKeywordsTable(), "failed to init parser keywords table");
3,272!
1000

1001
  tscDebug("client is initialized successfully");
3,272✔
1002
}
1003

1004
int taos_init() {
10,548✔
1005
  (void)taosThreadOnce(&tscinit, taos_init_imp);
10,548✔
1006
  return tscInitRes;
10,548✔
1007
}
1008

1009
const char *getCfgName(TSDB_OPTION option) {
16✔
1010
  const char *name = NULL;
16✔
1011

1012
  switch (option) {
16!
UNCOV
1013
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
×
1014
      name = "shellActivityTimer";
×
1015
      break;
×
1016
    case TSDB_OPTION_LOCALE:
×
1017
      name = "locale";
×
1018
      break;
×
1019
    case TSDB_OPTION_CHARSET:
×
1020
      name = "charset";
×
1021
      break;
×
1022
    case TSDB_OPTION_TIMEZONE:
16✔
1023
      name = "timezone";
16✔
1024
      break;
16✔
UNCOV
1025
    case TSDB_OPTION_USE_ADAPTER:
×
1026
      name = "useAdapter";
×
1027
      break;
×
1028
    default:
×
1029
      break;
×
1030
  }
1031

1032
  return name;
16✔
1033
}
1034

1035
int taos_options_imp(TSDB_OPTION option, const char *str) {
1,963✔
1036
  if (option == TSDB_OPTION_CONFIGDIR) {
1,963✔
1037
#ifndef WINDOWS
1038
    char newstr[PATH_MAX];
1039
    int  len = strlen(str);
1,947✔
1040
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
1,947!
1041
      if (len + 2 >= PATH_MAX) {
1,942!
UNCOV
1042
        tscError("Too long path %s", str);
×
1043
        return -1;
×
1044
      }
1045
      newstr[0] = '"';
1,942✔
1046
      (void)memcpy(newstr + 1, str, len);
1,942✔
1047
      newstr[len + 1] = '"';
1,942✔
1048
      newstr[len + 2] = '\0';
1,942✔
1049
      str = newstr;
1,942✔
1050
    }
1051
#endif
1052
    tstrncpy(configDir, str, PATH_MAX);
1,947✔
1053
    tscInfo("set cfg:%s to %s", configDir, str);
1,947!
1054
    return 0;
1,947✔
1055
  }
1056

1057
  // initialize global config
1058
  if (taos_init() != 0) {
16!
UNCOV
1059
    return -1;
×
1060
  }
1061

1062
  SConfig     *pCfg = taosGetCfg();
16✔
1063
  SConfigItem *pItem = NULL;
16✔
1064
  const char  *name = getCfgName(option);
16✔
1065

1066
  if (name == NULL) {
16!
UNCOV
1067
    tscError("Invalid option %d", option);
×
1068
    return -1;
×
1069
  }
1070

1071
  pItem = cfgGetItem(pCfg, name);
16✔
1072
  if (pItem == NULL) {
16!
UNCOV
1073
    tscError("Invalid option %d", option);
×
1074
    return -1;
×
1075
  }
1076

1077
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
16✔
1078
  if (code != 0) {
16!
UNCOV
1079
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
×
1080
  } else {
1081
    tscInfo("set cfg:%s to %s", name, str);
16!
1082
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
16!
UNCOV
1083
      code = taosCfgDynamicOptions(pCfg, name, false);
×
1084
    }
1085
  }
1086

1087
  return code;
16✔
1088
}
1089

1090
/**
1091
 * The request id is an unsigned integer format of 64bit.
1092
 *+------------+-----+-----------+---------------+
1093
 *| uid|localIp| PId | timestamp | serial number |
1094
 *+------------+-----+-----------+---------------+
1095
 *| 12bit      |12bit|24bit      |16bit          |
1096
 *+------------+-----+-----------+---------------+
1097
 * @return
1098
 */
1099
uint64_t generateRequestId() {
2,900,937✔
1100
  static uint32_t hashId = 0;
1101
  static int32_t requestSerialId = 0;
1102

1103
  if (hashId == 0) {
2,900,937✔
1104
    int32_t code = taosGetSystemUUIDU32(&hashId);
3,265✔
1105
    if (code != TSDB_CODE_SUCCESS) {
3,265!
UNCOV
1106
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1107
               tstrerror(code));
1108
    }
1109
  }
1110

1111
  uint64_t id = 0;
2,900,940✔
1112

UNCOV
1113
  while (true) {
×
1114
    int64_t  ts = taosGetTimestampMs();
2,900,942✔
1115
    uint64_t pid = taosGetPId();
2,900,942✔
1116
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
2,900,931✔
1117
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
2,900,948✔
1118

1119
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
2,900,950✔
1120
    if (id) {
2,900,950!
1121
      break;
2,900,950✔
1122
    }
1123
  }
1124
  return id;
2,900,950✔
1125
}
1126

1127
#if 0
1128
#include "cJSON.h"
1129
static setConfRet taos_set_config_imp(const char *config){
1130
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
1131
  static bool setConfFlag = false;
1132
  if (setConfFlag) {
1133
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
1134
    tstrncpy(ret.retMsg, "configuration can only set once", RET_MSG_LENGTH);
1135
    return ret;
1136
  }
1137
  taosInitGlobalCfg();
1138
  cJSON *root = cJSON_Parse(config);
1139
  if (root == NULL){
1140
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
1141
    tstrncpy(ret.retMsg, "parse json error", RET_MSG_LENGTH);
1142
    return ret;
1143
  }
1144

1145
  int size = cJSON_GetArraySize(root);
1146
  if(!cJSON_IsObject(root) || size == 0) {
1147
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
1148
    tstrncpy(ret.retMsg, "json content is invalid, must be not empty object", RET_MSG_LENGTH);
1149
    return ret;
1150
  }
1151

1152
  if(size >= 1000) {
1153
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
1154
    tstrncpy(ret.retMsg, "json object size is too long", RET_MSG_LENGTH);
1155
    return ret;
1156
  }
1157

1158
  for(int i = 0; i < size; i++){
1159
    cJSON *item = cJSON_GetArrayItem(root, i);
1160
    if(!item) {
1161
      ret.retCode = SET_CONF_RET_ERR_INNER;
1162
      tstrncpy(ret.retMsg, "inner error", RET_MSG_LENGTH);
1163
      return ret;
1164
    }
1165
    if(!taosReadConfigOption(item->string, item->valuestring, NULL, NULL, TAOS_CFG_CSTATUS_OPTION, TSDB_CFG_CTYPE_B_CLIENT)){
1166
      ret.retCode = SET_CONF_RET_ERR_PART;
1167
      if (strlen(ret.retMsg) == 0){
1168
        snprintf(ret.retMsg, RET_MSG_LENGTH, "part error|%s", item->string);
1169
      }else{
1170
        int tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1171
        size_t leftSize = tmp >= 0 ? tmp : 0;
1172
        strncat(ret.retMsg, "|",  leftSize);
1173
        tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1174
        leftSize = tmp >= 0 ? tmp : 0;
1175
        strncat(ret.retMsg, item->string, leftSize);
1176
      }
1177
    }
1178
  }
1179
  cJSON_Delete(root);
1180
  setConfFlag = true;
1181
  return ret;
1182
}
1183

1184
setConfRet taos_set_config(const char *config){
1185
  taosThreadMutexLock(&setConfMutex);
1186
  setConfRet ret = taos_set_config_imp(config);
1187
  taosThreadMutexUnlock(&setConfMutex);
1188
  return ret;
1189
}
1190
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc