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

taosdata / TDengine / #4893

20 Dec 2025 01:15PM UTC coverage: 65.57% (-0.001%) from 65.571%
#4893

push

travis-ci

web-flow
feat: support taos_connect_with func (#33952)

* feat: support taos_connect_with

* refactor: enhance connection options and add tests for taos_set_option and taos_connect_with

* fix: handle NULL keys and values in taos_connect_with options

* fix: revert TAOSWS_GIT_TAG to default value "main"

* docs: add TLS configuration options for WebSocket connections in documentation

* docs: modify zh docs and add en docs

* chore: update taos.cfg

* docs: add examples

* docs: add error handling for connection failure in example code

2 of 82 new or added lines in 3 files covered. (2.44%)

1158 existing lines in 109 files now uncovered.

182854 of 278870 relevant lines covered (65.57%)

105213271.06 hits per line

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

54.48
/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 "tconv.h"
31
#include "tglobal.h"
32
#include "thttp.h"
33
#include "tmsg.h"
34
#include "tqueue.h"
35
#include "tref.h"
36
#include "trpc.h"
37
#include "tsched.h"
38
#include "ttime.h"
39
#include "tversion.h"
40

41
#include "cus_name.h"
42
#include "clientSession.h"
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
      terrno = _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
SHashObj *pTimezoneMap = NULL;
74

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

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

88
  int32_t num = atomic_add_fetch_32(&pTscObj->numOfReqs, 1);
655,801,435✔
89

90
  if (pTscObj->pAppInfo) {
655,810,877✔
91
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
655,810,659✔
92

93
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
655,806,526✔
94
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
655,809,148✔
95
    tscDebug("req:0x%" PRIx64 ", create request from conn:0x%" PRIx64
655,809,254✔
96
             ", current:%d, app current:%d, total:%d, QID:0x%" PRIx64,
97
             pRequest->self, pRequest->pTscObj->id, num, currentInst, total, pRequest->requestId);
98
  }
99

100
  return code;
655,805,901✔
101
}
102

103
static void concatStrings(SArray *list, char *buf, int size) {
×
104
  int len = 0;
×
105
  for (int i = 0; i < taosArrayGetSize(list); i++) {
×
106
    char *db = taosArrayGet(list, i);
×
107
    if (NULL == db) {
×
108
      tscError("get dbname failed, buf:%s", buf);
×
109
      break;
×
110
    }
111
    char *dot = strchr(db, '.');
×
112
    if (dot != NULL) {
×
113
      db = dot + 1;
×
114
    }
115
    if (i != 0) {
×
116
      (void)strncat(buf, ",", size - 1 - len);
×
117
      len += 1;
×
118
    }
119
    int ret = tsnprintf(buf + len, size - len, "%s", db);
×
120
    if (ret < 0) {
×
121
      tscError("snprintf failed, buf:%s, ret:%d", buf, ret);
×
122
      break;
×
123
    }
124
    len += ret;
×
125
    if (len >= size) {
×
126
      tscInfo("dbList is truncated, buf:%s, len:%d", buf, len);
×
127
      break;
×
128
    }
129
  }
130
}
×
131
#ifdef USE_REPORT
132
static int32_t generateWriteSlowLog(STscObj *pTscObj, SRequestObj *pRequest, int32_t reqType, int64_t duration) {
×
133
  cJSON  *json = cJSON_CreateObject();
×
134
  int32_t code = TSDB_CODE_SUCCESS;
×
135
  if (json == NULL) {
×
136
    tscError("failed to create monitor json");
×
137
    return TSDB_CODE_OUT_OF_MEMORY;
×
138
  }
139
  char clusterId[32] = {0};
×
140
  if (snprintf(clusterId, sizeof(clusterId), "%" PRId64, pTscObj->pAppInfo->clusterId) < 0) {
×
141
    tscError("failed to generate clusterId:%" PRId64, pTscObj->pAppInfo->clusterId);
×
142
    code = TSDB_CODE_FAILED;
×
143
    goto _end;
×
144
  }
145

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

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

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

182
  char pid[32] = {0};
×
183
  if (snprintf(pid, sizeof(pid), "%d", appInfo.pid) < 0) {
×
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)));
×
190
  if (pRequest->dbList != NULL) {
×
191
    char dbList[1024] = {0};
×
192
    concatStrings(pRequest->dbList, dbList, sizeof(dbList) - 1);
×
193
    ENV_JSON_FALSE_CHECK(cJSON_AddItemToObject(json, "db", cJSON_CreateString(dbList)));
×
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);
×
201
  if (value == NULL) {
×
202
    tscError("failed to print json");
×
203
    code = TSDB_CODE_FAILED;
×
204
    goto _end;
×
205
  }
206
  MonitorSlowLogData data = {0};
×
207
  data.clusterId = pTscObj->pAppInfo->clusterId;
×
208
  data.type = SLOW_LOG_WRITE;
×
209
  data.data = value;
×
210
  code = monitorPutData2MonitorQueue(data);
×
211
  if (TSDB_CODE_SUCCESS != code) {
×
212
    taosMemoryFree(value);
×
213
    goto _end;
×
214
  }
215

216
_end:
×
217
  cJSON_Delete(json);
×
218
  return code;
×
219
}
220
#endif
221
static bool checkSlowLogExceptDb(SRequestObj *pRequest, char *exceptDb) {
423,446✔
222
  if (pRequest->pDb != NULL) {
423,446✔
223
    return strcmp(pRequest->pDb, exceptDb) != 0;
283,693✔
224
  }
225

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

243
static void deregisterRequest(SRequestObj *pRequest) {
655,658,097✔
244
  if (pRequest == NULL) {
655,658,097✔
245
    tscError("pRequest == NULL");
×
246
    return;
×
247
  }
248

249
  STscObj            *pTscObj = pRequest->pTscObj;
655,658,097✔
250
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
655,659,808✔
251

252
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
655,660,315✔
253
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
655,660,315✔
254
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
655,660,315✔
255

256
  int64_t duration = taosGetTimestampUs() - pRequest->metric.start;
655,660,315✔
257
  tscDebug("req:0x%" PRIx64 ", free from conn:0x%" PRIx64 ", QID:0x%" PRIx64
655,658,263✔
258
           ", elapsed:%.2f ms, current:%d, app current:%d",
259
           pRequest->self, pTscObj->id, pRequest->requestId, duration / 1000.0, num, currentInst);
260

261
  if (TSDB_CODE_SUCCESS == nodesSimAcquireAllocator(pRequest->allocatorRefId)) {
655,658,263✔
262
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
655,660,315✔
263
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
520,975,468✔
264
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
185,909,715✔
265
      tscDebug("req:0x%" PRIx64 ", insert duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
521,991,126✔
266
               "us, analyseCost:%" PRId64 "us, planCost:%" PRId64 "us, exec:%" PRId64 "us, QID:0x%" PRIx64,
267
               pRequest->self, duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs,
268
               pRequest->metric.analyseCostUs, pRequest->metric.planCostUs, pRequest->metric.execCostUs,
269
               pRequest->requestId);
270
      (void)atomic_add_fetch_64((int64_t *)&pActivity->insertElapsedTime, duration);
521,991,126✔
271
      reqType = SLOW_LOG_TYPE_INSERT;
521,992,140✔
272
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
133,668,175✔
273
      tscDebug("req:0x%" PRIx64 ", query duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
92,638,557✔
274
               "us, analyseCost:%" PRId64 "us, planCost:%" PRId64 "us, exec:%" PRId64 "us, QID:0x%" PRIx64,
275
               pRequest->self, duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs,
276
               pRequest->metric.analyseCostUs, pRequest->metric.planCostUs, pRequest->metric.execCostUs,
277
               pRequest->requestId);
278

279
      (void)atomic_add_fetch_64((int64_t *)&pActivity->queryElapsedTime, duration);
92,638,557✔
280
      reqType = SLOW_LOG_TYPE_QUERY;
92,638,557✔
281
    }
282

283
    if (TSDB_CODE_SUCCESS != nodesSimReleaseAllocator(pRequest->allocatorRefId)) {
655,660,315✔
284
      tscError("failed to release allocator");
×
285
    }
286
  }
287

288
#ifdef USE_REPORT
289
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
655,659,531✔
290
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
357,983✔
291
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
333,227✔
292
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
24,756✔
293
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
7,992✔
294
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
16,764✔
295
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
×
296
    }
297
  }
298

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

316
  releaseTscObj(pTscObj->id);
655,659,531✔
317
}
318

319
// todo close the transporter properly
320
void closeTransporter(SAppInstInfo *pAppInfo) {
1,741,511✔
321
  if (pAppInfo == NULL || pAppInfo->pTransporter == NULL) {
1,741,511✔
322
    return;
×
323
  }
324

325
  tscDebug("free transporter:%p in app inst %p", pAppInfo->pTransporter, pAppInfo);
1,741,511✔
326
  rpcClose(pAppInfo->pTransporter);
1,741,511✔
327
}
328

329
static bool clientRpcRfp(int32_t code, tmsg_t msgType) {
18,234,559✔
330
  if (NEED_REDIRECT_ERROR(code)) {
18,234,559✔
331
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
14,804,581✔
332
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_QUERY_HEARTBEAT || msgType == TDMT_SCH_DROP_TASK ||
14,804,615✔
333
        msgType == TDMT_SCH_TASK_NOTIFY) {
334
      return false;
×
335
    }
336
    return true;
14,804,615✔
337
  } else if (code == TSDB_CODE_UTIL_QUEUE_OUT_OF_MEMORY || code == TSDB_CODE_OUT_OF_RPC_MEMORY_QUEUE ||
3,429,978✔
338
             code == TSDB_CODE_SYN_WRITE_STALL || code == TSDB_CODE_SYN_PROPOSE_NOT_READY ||
3,429,978✔
339
             code == TSDB_CODE_SYN_RESTORING) {
UNCOV
340
    tscDebug("client msg type %s should retry since %s", TMSG_INFO(msgType), tstrerror(code));
×
341
    return true;
×
342
  } else {
343
    return false;
3,429,978✔
344
  }
345
}
346

347
// start timer for particular msgType
348
static bool clientRpcTfp(int32_t code, tmsg_t msgType) {
×
349
  if (msgType == TDMT_VND_SUBMIT || msgType == TDMT_VND_CREATE_TABLE) {
×
350
    return true;
×
351
  }
352
  return false;
×
353
}
354

355
// TODO refactor
356
int32_t openTransporter(const char *user, const char *auth, int32_t numOfThread, void **pDnodeConn) {
1,741,563✔
357
  SRpcInit rpcInit;
1,722,488✔
358
  (void)memset(&rpcInit, 0, sizeof(rpcInit));
1,741,563✔
359
  rpcInit.localPort = 0;
1,741,563✔
360
  rpcInit.label = "TSC";
1,741,563✔
361
  rpcInit.numOfThreads = tsNumOfRpcThreads;
1,741,563✔
362
  rpcInit.cfp = processMsgFromServer;
1,741,563✔
363
  rpcInit.rfp = clientRpcRfp;
1,741,563✔
364
  rpcInit.sessions = 1024;
1,741,563✔
365
  rpcInit.connType = TAOS_CONN_CLIENT;
1,741,563✔
366
  rpcInit.user = (char *)user;
1,741,563✔
367
  rpcInit.idleTime = tsShellActivityTimer * 1000;
1,741,563✔
368
  rpcInit.compressSize = tsCompressMsgSize;
1,741,563✔
369
  rpcInit.dfp = destroyAhandle;
1,741,563✔
370

371
  rpcInit.retryMinInterval = tsRedirectPeriod;
1,741,563✔
372
  rpcInit.retryStepFactor = tsRedirectFactor;
1,741,563✔
373
  rpcInit.retryMaxInterval = tsRedirectMaxPeriod;
1,741,563✔
374
  rpcInit.retryMaxTimeout = tsMaxRetryWaitTime;
1,741,563✔
375

376
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
1,741,563✔
377
  connLimitNum = TMAX(connLimitNum, 10);
1,741,563✔
378
  connLimitNum = TMIN(connLimitNum, 1000);
1,741,563✔
379
  rpcInit.connLimitNum = connLimitNum;
1,741,563✔
380
  rpcInit.shareConnLimit = tsShareConnLimit;
1,741,563✔
381
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
1,741,563✔
382
  rpcInit.startReadTimer = 1;
1,741,563✔
383
  rpcInit.readTimeout = tsReadTimeout;
1,741,563✔
384
  rpcInit.ipv6 = tsEnableIpv6;
1,741,563✔
385
  rpcInit.enableSSL = tsEnableTLS;
1,741,563✔
386
  rpcInit.enableSasl = tsEnableSasl;
1,741,563✔
387

388
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
1,741,563✔
389
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
1,741,563✔
390
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
1,741,563✔
391
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
1,741,563✔
392
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
1,741,563✔
393

394
  int32_t code = taosVersionStrToInt(td_version, &rpcInit.compatibilityVer);
1,741,563✔
395
  if (TSDB_CODE_SUCCESS != code) {
1,741,563✔
396
    tscError("invalid version string.");
×
397
    return code;
×
398
  }
399

400
  tscInfo("rpc max retry timeout %" PRId64 "", rpcInit.retryMaxTimeout);
1,741,563✔
401
  *pDnodeConn = rpcOpen(&rpcInit);
1,741,563✔
402
  if (*pDnodeConn == NULL) {
1,741,563✔
403
    tscError("failed to init connection to server since %s", tstrerror(terrno));
52✔
404
    code = terrno;
52✔
405
  }
406

407
  return code;
1,741,563✔
408
}
409

410
void destroyAllRequests(SHashObj *pRequests) {
3,256,274✔
411
  void *pIter = taosHashIterate(pRequests, NULL);
3,256,274✔
412
  while (pIter != NULL) {
3,255,866✔
413
    int64_t *rid = pIter;
×
414

415
    SRequestObj *pRequest = acquireRequest(*rid);
×
416
    if (pRequest) {
×
417
      destroyRequest(pRequest);
×
418
      (void)releaseRequest(*rid);  // ignore error
×
419
    }
420

421
    pIter = taosHashIterate(pRequests, pIter);
×
422
  }
423
}
3,255,866✔
424

425
void stopAllRequests(SHashObj *pRequests) {
×
426
  void *pIter = taosHashIterate(pRequests, NULL);
×
427
  while (pIter != NULL) {
×
428
    int64_t *rid = pIter;
×
429

430
    SRequestObj *pRequest = acquireRequest(*rid);
×
431
    if (pRequest) {
×
432
      taos_stop_query(pRequest);
×
433
      (void)releaseRequest(*rid);  // ignore error
×
434
    }
435

436
    pIter = taosHashIterate(pRequests, pIter);
×
437
  }
438
}
×
439

440
void destroyAppInst(void *info) {
1,741,511✔
441
  SAppInstInfo *pAppInfo = *(SAppInstInfo **)info;
1,741,511✔
442
  tscInfo("destroy app inst mgr %p", pAppInfo);
1,741,511✔
443

444
  int32_t code = taosThreadMutexLock(&appInfo.mutex);
1,741,511✔
445
  if (TSDB_CODE_SUCCESS != code) {
1,741,511✔
446
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
447
  }
448

449
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
1,741,511✔
450

451
  code = taosThreadMutexUnlock(&appInfo.mutex);
1,741,511✔
452
  if (TSDB_CODE_SUCCESS != code) {
1,741,511✔
453
    tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
454
  }
455

456
  taosMemoryFreeClear(pAppInfo->instKey);
1,741,511✔
457
  closeTransporter(pAppInfo);
1,741,511✔
458

459
  code = taosThreadMutexLock(&pAppInfo->qnodeMutex);
1,741,511✔
460
  if (TSDB_CODE_SUCCESS != code) {
1,741,511✔
461
    tscError("failed to lock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
462
  }
463

464
  taosArrayDestroy(pAppInfo->pQnodeList);
1,741,511✔
465
  code = taosThreadMutexUnlock(&pAppInfo->qnodeMutex);
1,741,511✔
466
  if (TSDB_CODE_SUCCESS != code) {
1,741,511✔
467
    tscError("failed to unlock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
468
  }
469

470
  taosMemoryFree(pAppInfo);
1,741,511✔
471
}
1,741,511✔
472

473
//  tscObj 1--->conn1
474
/// tscObj 2-->conn1
475
//  tscObj 3-->conn1
476

477
void destroyTscObj(void *pObj) {
3,256,274✔
478
  if (NULL == pObj) {
3,256,274✔
479
    return;
×
480
  }
481

482
  STscObj *pTscObj = pObj;
3,256,274✔
483
  int64_t  tscId = pTscObj->id;
3,256,274✔
484
  tscTrace("conn:%" PRIx64 ", begin destroy, p:%p", tscId, pTscObj);
3,256,274✔
485

486
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
3,256,274✔
487
  hbDeregisterConn(pTscObj, connKey);
3,256,274✔
488

489
  destroyAllRequests(pTscObj->pRequests);
3,256,274✔
490
  taosHashCleanup(pTscObj->pRequests);
3,256,274✔
491

492
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
3,256,274✔
493
  tscDebug("conn:0x%" PRIx64 ", p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
3,256,274✔
494
           pTscObj->pAppInfo->numOfConns);
495

496
  // In any cases, we should not free app inst here. Or an race condition rises.
497
  /*int64_t connNum = */ (void)atomic_sub_fetch_64(&pTscObj->pAppInfo->numOfConns, 1);
3,256,274✔
498

499
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
3,256,274✔
500
  taosMemoryFree(pTscObj);
3,256,017✔
501

502
  tscTrace("conn:0x%" PRIx64 ", end destroy, p:%p", tscId, pTscObj);
3,256,274✔
503
}
504

505
int32_t createTscObj(const char *user, const char *auth, const char *db, int32_t connType, SAppInstInfo *pAppInfo,
3,432,595✔
506
                     STscObj **pObj) {
507
  *pObj = (STscObj *)taosMemoryCalloc(1, sizeof(STscObj));
3,432,595✔
508
  if (NULL == *pObj) {
3,432,595✔
509
    return terrno;
×
510
  }
511

512
  (*pObj)->pRequests = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
3,432,595✔
513
  if (NULL == (*pObj)->pRequests) {
3,432,595✔
514
    taosMemoryFree(*pObj);
×
515
    return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
516
  }
517

518
  (*pObj)->connType = connType;
3,432,595✔
519
  (*pObj)->pAppInfo = pAppInfo;
3,432,595✔
520
  (*pObj)->appHbMgrIdx = pAppInfo->pAppHbMgr->idx;
3,432,595✔
521
  tstrncpy((*pObj)->user, user, sizeof((*pObj)->user));
3,432,595✔
522
  (void)memcpy((*pObj)->pass, auth, TSDB_PASSWORD_LEN);
3,432,595✔
523

524
  if (db != NULL) {
3,432,595✔
525
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
3,432,582✔
526
  }
527

528
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
3,432,595✔
529

530
  int32_t code = TSDB_CODE_SUCCESS;
3,432,561✔
531

532
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
3,432,561✔
533
  if ((*pObj)->id < 0) {
3,432,595✔
534
    tscError("failed to add object to clientConnRefPool");
×
535
    code = terrno;
×
536
    taosMemoryFree(*pObj);
×
537
    return code;
×
538
  }
539

540
  (void)atomic_add_fetch_64(&(*pObj)->pAppInfo->numOfConns, 1);
3,432,595✔
541

542
  tscInfo("conn:0x%" PRIx64 ", created, p:%p", (*pObj)->id, *pObj);
3,432,481✔
543
  return code;
3,432,595✔
544
}
545

546
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
1,425,163,805✔
547

548
void releaseTscObj(int64_t rid) {
1,421,347,045✔
549
  int32_t code = taosReleaseRef(clientConnRefPool, rid);
1,421,347,045✔
550
  if (TSDB_CODE_SUCCESS != code) {
1,421,351,124✔
551
    tscWarn("failed to release TscObj, code:%s", tstrerror(code));
×
552
  }
553
}
1,421,351,124✔
554

555
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
655,798,097✔
556
  int32_t code = TSDB_CODE_SUCCESS;
655,798,097✔
557
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
655,798,097✔
558
  if (NULL == *pRequest) {
655,802,103✔
559
    return terrno;
×
560
  }
561

562
  STscObj *pTscObj = acquireTscObj(connId);
655,804,217✔
563
  if (pTscObj == NULL) {
655,811,406✔
564
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
565
  }
566
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
655,811,406✔
567
  if (interParam == NULL) {
655,810,311✔
568
    releaseTscObj(connId);
×
569
    TSC_ERR_JRET(terrno);
×
570
  }
571
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
655,810,311✔
572
  interParam->pRequest = *pRequest;
655,808,762✔
573
  (*pRequest)->body.interParam = interParam;
655,809,996✔
574

575
  (*pRequest)->resType = RES_TYPE__QUERY;
655,808,339✔
576
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
655,803,171✔
577
  (*pRequest)->metric.start = taosGetTimestampUs();
1,308,146,886✔
578

579
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
655,807,263✔
580
  (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt;
655,806,920✔
581
  (*pRequest)->type = type;
655,810,809✔
582
  (*pRequest)->allocatorRefId = -1;
655,810,809✔
583

584
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
655,811,263✔
585
  if (NULL == (*pRequest)->pDb) {
655,805,954✔
586
    TSC_ERR_JRET(terrno);
73,561,222✔
587
  }
588
  (*pRequest)->pTscObj = pTscObj;
655,802,335✔
589
  (*pRequest)->inCallback = false;
655,800,805✔
590
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
655,808,471✔
591
  if (NULL == (*pRequest)->msgBuf) {
655,799,133✔
592
    code = terrno;
×
593
    goto _return;
×
594
  }
595
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
655,800,400✔
596
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
655,808,575✔
597
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
655,804,683✔
598

599
  return TSDB_CODE_SUCCESS;
655,804,356✔
600
_return:
×
601
  if ((*pRequest)->pTscObj) {
×
602
    doDestroyRequest(*pRequest);
×
603
  } else {
604
    taosMemoryFree(*pRequest);
×
605
  }
606
  return code;
×
607
}
608

609
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
688,892,917✔
610
  taosMemoryFreeClear(pResInfo->pRspMsg);
688,892,917✔
611
  taosMemoryFreeClear(pResInfo->length);
688,897,158✔
612
  taosMemoryFreeClear(pResInfo->row);
688,892,780✔
613
  taosMemoryFreeClear(pResInfo->pCol);
688,893,664✔
614
  taosMemoryFreeClear(pResInfo->fields);
688,893,432✔
615
  taosMemoryFreeClear(pResInfo->userFields);
688,893,634✔
616
  taosMemoryFreeClear(pResInfo->convertJson);
688,890,659✔
617
  taosMemoryFreeClear(pResInfo->decompBuf);
688,893,645✔
618

619
  if (pResInfo->convertBuf != NULL) {
688,890,578✔
620
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
591,051,866✔
621
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
483,432,973✔
622
    }
623
    taosMemoryFreeClear(pResInfo->convertBuf);
107,622,552✔
624
  }
625
}
688,892,865✔
626

627
SRequestObj *acquireRequest(int64_t rid) { return (SRequestObj *)taosAcquireRef(clientReqRefPool, rid); }
2,147,483,647✔
628

629
int32_t releaseRequest(int64_t rid) { return taosReleaseRef(clientReqRefPool, rid); }
2,147,483,647✔
630

631
int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }
655,655,376✔
632

633
/// return the most previous req ref id
634
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
655,656,061✔
635
  int64_t      mostPrevReqRefId = pRequest->self;
655,656,061✔
636
  SRequestObj *pTmp = pRequest;
655,657,912✔
637
  while (pTmp->relation.prevRefId) {
655,657,912✔
638
    pTmp = acquireRequest(pTmp->relation.prevRefId);
×
639
    if (pTmp) {
×
640
      mostPrevReqRefId = pTmp->self;
×
641
      (void)releaseRequest(mostPrevReqRefId);  // ignore error
×
642
    } else {
643
      break;
×
644
    }
645
  }
646
  (void)removeRequest(mostPrevReqRefId);  // ignore error
655,658,329✔
647
  return mostPrevReqRefId;
655,658,262✔
648
}
649

650
void destroyNextReq(int64_t nextRefId) {
655,656,204✔
651
  if (nextRefId) {
655,656,204✔
652
    SRequestObj *pObj = acquireRequest(nextRefId);
×
653
    if (pObj) {
×
654
      (void)releaseRequest(nextRefId);  // ignore error
×
655
      (void)releaseRequest(nextRefId);  // ignore error
×
656
    }
657
  }
658
}
655,656,204✔
659

660
void destroySubRequests(SRequestObj *pRequest) {
×
661
  int32_t      reqIdx = -1;
×
662
  SRequestObj *pReqList[16] = {NULL};
×
663
  uint64_t     tmpRefId = 0;
×
664

665
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
×
666
    return;
×
667
  }
668

669
  SRequestObj *pTmp = pRequest;
×
670
  while (pTmp->relation.prevRefId) {
×
671
    tmpRefId = pTmp->relation.prevRefId;
×
672
    pTmp = acquireRequest(tmpRefId);
×
673
    if (pTmp) {
×
674
      pReqList[++reqIdx] = pTmp;
×
675
      (void)releaseRequest(tmpRefId);  // ignore error
×
676
    } else {
677
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
678
      break;
×
679
    }
680
  }
681

682
  for (int32_t i = reqIdx; i >= 0; i--) {
×
683
    (void)removeRequest(pReqList[i]->self);  // ignore error
×
684
  }
685

686
  tmpRefId = pRequest->relation.nextRefId;
×
687
  while (tmpRefId) {
×
688
    pTmp = acquireRequest(tmpRefId);
×
689
    if (pTmp) {
×
690
      tmpRefId = pTmp->relation.nextRefId;
×
691
      (void)removeRequest(pTmp->self);   // ignore error
×
692
      (void)releaseRequest(pTmp->self);  // ignore error
×
693
    } else {
694
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
695
      break;
×
696
    }
697
  }
698
}
699

700
void doDestroyRequest(void *p) {
655,655,571✔
701
  if (NULL == p) {
655,655,571✔
702
    return;
×
703
  }
704

705
  SRequestObj *pRequest = (SRequestObj *)p;
655,655,571✔
706

707
  uint64_t reqId = pRequest->requestId;
655,655,571✔
708
  tscTrace("QID:0x%" PRIx64 ", begin destroy request, res:%p", reqId, pRequest);
655,656,168✔
709

710
  int64_t nextReqRefId = pRequest->relation.nextRefId;
655,656,168✔
711

712
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
655,655,183✔
713
  if (TSDB_CODE_SUCCESS != code) {
655,659,084✔
714
    tscDebug("failed to remove request from hash since %s", tstrerror(code));
3,432,561✔
715
  }
716
  schedulerFreeJob(&pRequest->body.queryJob, 0);
655,659,084✔
717

718
  destorySqlCallbackWrapper(pRequest->pWrapper);
655,658,762✔
719

720
  taosMemoryFreeClear(pRequest->msgBuf);
655,654,127✔
721

722
  doFreeReqResultInfo(&pRequest->body.resInfo);
655,651,528✔
723
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
655,651,667✔
724
    tscError("failed to destroy semaphore");
×
725
  }
726

727
  SSessParam para = {.type = SESSION_MAX_CONCURRENCY, .value = -1};
655,654,173✔
728
  code = tscUpdateSessMgtMetric(pRequest->pTscObj, &para);
655,649,646✔
729

730
  taosArrayDestroy(pRequest->tableList);
655,660,315✔
731
  taosArrayDestroy(pRequest->targetTableList);
655,660,315✔
732
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
655,660,315✔
733

734
  if (pRequest->self) {
655,660,315✔
735
    deregisterRequest(pRequest);
655,660,315✔
736
  }
737

738
  taosMemoryFreeClear(pRequest->pDb);
655,658,767✔
739
  taosArrayDestroy(pRequest->dbList);
655,658,980✔
740
  if (pRequest->body.interParam) {
655,659,780✔
741
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
655,660,315✔
742
      tscError("failed to destroy semaphore in pRequest");
×
743
    }
744
  }
745
  taosMemoryFree(pRequest->body.interParam);
655,659,243✔
746

747
  qDestroyQuery(pRequest->pQuery);
655,659,808✔
748
  nodesDestroyAllocator(pRequest->allocatorRefId);
655,654,291✔
749

750
  taosMemoryFreeClear(pRequest->effectiveUser);
655,657,886✔
751
  taosMemoryFreeClear(pRequest->sqlstr);
655,657,102✔
752
  taosMemoryFree(pRequest);
655,657,070✔
753
  tscTrace("QID:0x%" PRIx64 ", end destroy request, res:%p", reqId, pRequest);
655,658,055✔
754
  destroyNextReq(nextReqRefId);
655,658,055✔
755
}
756

757
void destroyRequest(SRequestObj *pRequest) {
655,657,825✔
758
  if (pRequest == NULL) return;
655,657,825✔
759

760
  taos_stop_query(pRequest);
655,657,825✔
761
  (void)removeFromMostPrevReq(pRequest);
655,658,267✔
762
}
763

764
void taosStopQueryImpl(SRequestObj *pRequest) {
655,656,305✔
765
  pRequest->killed = true;
655,656,305✔
766

767
  // It is not a query, no need to stop.
768
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
655,658,355✔
769
    tscDebug("QID:0x%" PRIx64 ", no need to be killed since not query", pRequest->requestId);
46,852,816✔
770
    return;
46,853,993✔
771
  }
772

773
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
608,804,755✔
774
  tscDebug("QID:0x%" PRIx64 ", killed", pRequest->requestId);
608,804,684✔
775
}
776

777
void stopAllQueries(SRequestObj *pRequest) {
655,653,716✔
778
  int32_t      reqIdx = -1;
655,653,716✔
779
  SRequestObj *pReqList[16] = {NULL};
655,653,716✔
780
  uint64_t     tmpRefId = 0;
655,653,748✔
781

782
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
655,653,748✔
783
    return;
×
784
  }
785

786
  SRequestObj *pTmp = pRequest;
655,656,555✔
787
  while (pTmp->relation.prevRefId) {
655,656,555✔
788
    tmpRefId = pTmp->relation.prevRefId;
×
789
    pTmp = acquireRequest(tmpRefId);
×
790
    if (pTmp) {
×
791
      pReqList[++reqIdx] = pTmp;
×
792
    } else {
793
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
794
      break;
×
795
    }
796
  }
797

798
  for (int32_t i = reqIdx; i >= 0; i--) {
655,656,856✔
799
    taosStopQueryImpl(pReqList[i]);
×
800
    (void)releaseRequest(pReqList[i]->self);  // ignore error
×
801
  }
802

803
  taosStopQueryImpl(pRequest);
655,656,856✔
804

805
  tmpRefId = pRequest->relation.nextRefId;
655,658,656✔
806
  while (tmpRefId) {
655,658,294✔
807
    pTmp = acquireRequest(tmpRefId);
×
808
    if (pTmp) {
×
809
      tmpRefId = pTmp->relation.nextRefId;
×
810
      taosStopQueryImpl(pTmp);
×
811
      (void)releaseRequest(pTmp->self);  // ignore error
×
812
    } else {
813
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
814
      break;
×
815
    }
816
  }
817
}
818
#ifdef USE_REPORT
819
void crashReportThreadFuncUnexpectedStopped(void) { atomic_store_32(&clientStop, -1); }
×
820

821
static void *tscCrashReportThreadFp(void *param) {
×
822
  int32_t code = 0;
×
823
  setThreadName("client-crashReport");
×
824
  char filepath[PATH_MAX] = {0};
×
825
  (void)snprintf(filepath, sizeof(filepath), "%s%s.taosCrashLog", tsLogDir, TD_DIRSEP);
×
826
  char     *pMsg = NULL;
×
827
  int64_t   msgLen = 0;
×
828
  TdFilePtr pFile = NULL;
×
829
  bool      truncateFile = false;
×
830
  int32_t   sleepTime = 200;
×
831
  int32_t   reportPeriodNum = 3600 * 1000 / sleepTime;
×
832
  int32_t   loopTimes = reportPeriodNum;
×
833

834
#ifdef WINDOWS
835
  if (taosCheckCurrentInDll()) {
836
    atexit(crashReportThreadFuncUnexpectedStopped);
837
  }
838
#endif
839

840
  if (-1 != atomic_val_compare_exchange_32(&clientStop, -1, 0)) {
×
841
    return NULL;
×
842
  }
843
  STelemAddrMgmt mgt;
×
844
  code = taosTelemetryMgtInit(&mgt, tsTelemServer);
×
845
  if (code) {
×
846
    tscError("failed to init telemetry management, code:%s", tstrerror(code));
×
847
    return NULL;
×
848
  }
849

850
  code = initCrashLogWriter();
×
851
  if (code) {
×
852
    tscError("failed to init crash log writer, code:%s", tstrerror(code));
×
853
    return NULL;
×
854
  }
855

856
  while (1) {
857
    checkAndPrepareCrashInfo();
×
858
    if (clientStop > 0 && reportThreadSetQuit()) break;
×
859
    if (loopTimes++ < reportPeriodNum) {
×
860
      if (loopTimes < 0) loopTimes = reportPeriodNum;
×
861
      taosMsleep(sleepTime);
×
862
      continue;
×
863
    }
864

865
    taosReadCrashInfo(filepath, &pMsg, &msgLen, &pFile);
×
866
    if (pMsg && msgLen > 0) {
×
867
      if (taosSendTelemReport(&mgt, tsClientCrashReportUri, tsTelemPort, pMsg, msgLen, HTTP_FLAT) != 0) {
×
868
        tscError("failed to send crash report");
×
869
        if (pFile) {
×
870
          taosReleaseCrashLogFile(pFile, false);
×
871
          pFile = NULL;
×
872

873
          taosMsleep(sleepTime);
×
874
          loopTimes = 0;
×
875
          continue;
×
876
        }
877
      } else {
878
        tscInfo("succeed to send crash report");
×
879
        truncateFile = true;
×
880
      }
881
    } else {
882
      tscInfo("no crash info was found");
×
883
    }
884

885
    taosMemoryFree(pMsg);
×
886

887
    if (pMsg && msgLen > 0) {
×
888
      pMsg = NULL;
×
889
      continue;
×
890
    }
891

892
    if (pFile) {
×
893
      taosReleaseCrashLogFile(pFile, truncateFile);
×
894
      pFile = NULL;
×
895
      truncateFile = false;
×
896
    }
897

898
    taosMsleep(sleepTime);
×
899
    loopTimes = 0;
×
900
  }
901
  taosTelemetryDestroy(&mgt);
×
902

903
  clientStop = -2;
×
904
  return NULL;
×
905
}
906

907
int32_t tscCrashReportInit() {
1,680,342✔
908
  if (!tsEnableCrashReport) {
1,680,342✔
909
    return TSDB_CODE_SUCCESS;
1,680,342✔
910
  }
911
  int32_t      code = TSDB_CODE_SUCCESS;
×
912
  TdThreadAttr thAttr;
×
913
  TSC_ERR_JRET(taosThreadAttrInit(&thAttr));
×
914
  TSC_ERR_JRET(taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE));
×
915
  TdThread crashReportThread;
×
916
  if (taosThreadCreate(&crashReportThread, &thAttr, tscCrashReportThreadFp, NULL) != 0) {
×
917
    tscError("failed to create crashReport thread since %s", strerror(ERRNO));
×
918
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
919
    TSC_ERR_RET(terrno);
×
920
  }
921

922
  (void)taosThreadAttrDestroy(&thAttr);
×
923
_return:
×
924
  if (code) {
×
925
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
926
    TSC_ERR_RET(terrno);
×
927
  }
928

929
  return code;
×
930
}
931

932
void tscStopCrashReport() {
1,680,377✔
933
  if (!tsEnableCrashReport) {
1,680,377✔
934
    return;
1,680,377✔
935
  }
936

937
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
938
    tscDebug("crash report thread already stopped");
×
939
    return;
×
940
  }
941

942
  while (atomic_load_32(&clientStop) > 0) {
×
943
    taosMsleep(100);
×
944
  }
945
}
946

947
void taos_write_crashinfo(int signum, void *sigInfo, void *context) {
×
948
  writeCrashLogToFile(signum, sigInfo, CUS_PROMPT, lastClusterId, appInfo.startTime);
×
949
}
×
950
#endif
951

952
#ifdef TAOSD_INTEGRATED
953
typedef struct {
954
  TdThread pid;
955
  int32_t  stat;  // < 0: start failed, 0: init(not start), 1: start successfully
956
} SDaemonObj;
957

958
extern int  dmStartDaemon(int argc, char const *argv[]);
959
extern void dmStopDaemon();
960

961
SDaemonObj daemonObj = {0};
962

963
typedef struct {
964
  int32_t argc;
965
  char  **argv;
966
} SExecArgs;
967

968
static void *dmStartDaemonFunc(void *param) {
969
  int32_t    code = 0;
970
  SExecArgs *pArgs = (SExecArgs *)param;
971
  int32_t    argc = pArgs->argc;
972
  char     **argv = pArgs->argv;
973

974
  code = dmStartDaemon(argc, (const char **)argv);
975
  if (code != 0) {
976
    printf("failed to start taosd since %s\r\n", tstrerror(code));
977
    goto _exit;
978
  }
979

980
_exit:
981
  if (code != 0) {
982
    atomic_store_32(&daemonObj.stat, code);
983
  }
984
  return NULL;
985
}
986

987
static int32_t shellStartDaemon(int argc, char *argv[]) {
988
  int32_t    code = 0, lino = 0;
989
  SExecArgs *pArgs = NULL;
990
  int64_t    startMs = taosGetTimestampMs(), endMs = startMs;
991

992
  TdThreadAttr thAttr;
993
  (void)taosThreadAttrInit(&thAttr);
994
  (void)taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
995
#ifdef TD_COMPACT_OS
996
  (void)taosThreadAttrSetStackSize(&thAttr, STACK_SIZE_SMALL);
997
#endif
998
  pArgs = (SExecArgs *)taosMemoryCalloc(1, sizeof(SExecArgs));
999
  if (pArgs == NULL) {
1000
    code = terrno;
1001
    TAOS_CHECK_EXIT(code);
1002
  }
1003
  pArgs->argc = argc;
1004
  pArgs->argv = argv;
1005

1006
#ifndef TD_AS_LIB
1007
  tsLogEmbedded = 1;
1008
#endif
1009

1010
  TAOS_CHECK_EXIT(taosThreadCreate(&daemonObj.pid, &thAttr, dmStartDaemonFunc, pArgs));
1011

1012
  while (true) {
1013
    if (atomic_load_64(&tsDndStart)) {
1014
      atomic_store_32(&daemonObj.stat, 1);
1015
      break;
1016
    }
1017
    int32_t daemonstat = atomic_load_32(&daemonObj.stat);
1018
    if (daemonstat < 0) {
1019
      code = daemonstat;
1020
      TAOS_CHECK_EXIT(code);
1021
    }
1022

1023
    if (daemonstat > 1) {
1024
      code = TSDB_CODE_APP_ERROR;
1025
      TAOS_CHECK_EXIT(code);
1026
    }
1027
    taosMsleep(1000);
1028
  }
1029

1030
_exit:
1031
  endMs = taosGetTimestampMs();
1032
  (void)taosThreadAttrDestroy(&thAttr);
1033
  taosMemoryFreeClear(pArgs);
1034
  if (code) {
1035
    printf("\r\n The daemon start failed at line %d since %s, cost %" PRIi64 " ms\r\n", lino, tstrerror(code),
1036
           endMs - startMs);
1037
  } else {
1038
    printf("\r\n The daemon started successfully, cost %" PRIi64 " ms\r\n", endMs - startMs);
1039
  }
1040
#ifndef TD_AS_LIB
1041
  tsLogEmbedded = 0;
1042
#endif
1043
  return code;
1044
}
1045

1046
void shellStopDaemon() {
1047
#ifndef TD_AS_LIB
1048
  tsLogEmbedded = 1;
1049
#endif
1050
  dmStopDaemon();
1051
  if (taosCheckPthreadValid(daemonObj.pid)) {
1052
    (void)taosThreadJoin(daemonObj.pid, NULL);
1053
    taosThreadClear(&daemonObj.pid);
1054
  }
1055
}
1056
#endif
1057

1058
void taos_init_imp(void) {
1,680,377✔
1059
#if defined(LINUX)
1060
  if (tscDbg.memEnable) {
1,680,377✔
1061
    int32_t code = taosMemoryDbgInit();
×
1062
    if (code) {
×
1063
      (void)printf("failed to init memory dbg, error:%s\n", tstrerror(code));
×
1064
    } else {
1065
      tsAsyncLog = false;
×
1066
      (void)printf("memory dbg enabled\n");
×
1067
    }
1068
  }
1069
#endif
1070

1071
  // In the APIs of other program language, taos_cleanup is not available yet.
1072
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
1073
  (void)atexit(taos_cleanup);
1,680,377✔
1074
  SET_ERRNO(TSDB_CODE_SUCCESS);
1,680,377✔
1075
  terrno = TSDB_CODE_SUCCESS;
1,680,377✔
1076
  taosSeedRand(taosGetTimestampSec());
1,680,377✔
1077

1078
  appInfo.pid = taosGetPId();
1,680,377✔
1079
  appInfo.startTime = taosGetTimestampMs();
1,680,377✔
1080
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
1,680,377✔
1081
  appInfo.pInstMapByClusterId =
1,680,377✔
1082
      taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);
1,680,377✔
1083
  if (NULL == appInfo.pInstMap || NULL == appInfo.pInstMapByClusterId) {
1,680,377✔
1084
    (void)printf("failed to allocate memory when init appInfo\n");
×
1085
    tscInitRes = terrno;
×
1086
    return;
35✔
1087
  }
1088
  taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst);
1,680,377✔
1089

1090
  const char *logName = CUS_PROMPT "log";
1,680,377✔
1091
  ENV_ERR_RET(taosInitLogOutput(&logName), "failed to init log output");
1,680,377✔
1092
  if (taosCreateLog(logName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
1,680,377✔
1093
    (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logName, strerror(ERRNO), configDir);
35✔
1094
    SET_ERROR_MSG("Create %s failed:%s. configDir=%s", logName, strerror(ERRNO), configDir);
35✔
1095
    tscInitRes = terrno;
35✔
1096
    return;
35✔
1097
  }
1098

1099
#ifdef TAOSD_INTEGRATED
1100
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0), "failed to init cfg");
1101
#else
1102
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
1,680,342✔
1103
#endif
1104

1105
  initQueryModuleMsgHandle();
1,680,342✔
1106
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
1107
  if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL) {
1,680,342✔
1108
    tscInitRes = terrno;
×
1109
    tscError("failed to init conv");
×
1110
    return;
×
1111
  }
1112
#endif
1113
#if !defined(WINDOWS) && !defined(TD_ASTRA)
1114
  ENV_ERR_RET(tzInit(), "failed to init timezone");
1,680,342✔
1115
#endif
1116
  ENV_ERR_RET(monitorInit(), "failed to init monitor");
1,680,342✔
1117
  ENV_ERR_RET(rpcInit(), "failed to init rpc");
1,680,342✔
1118

1119
  if (InitRegexCache() != 0) {
1,680,342✔
1120
    tscInitRes = terrno;
×
1121
    (void)printf("failed to init regex cache\n");
×
1122
    return;
×
1123
  }
1124

1125
  tscInfo("starting to initialize TAOS driver");
1,680,342✔
1126

1127
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
1,680,342✔
1128
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
1,680,342✔
1129
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
1,680,342✔
1130
  ENV_ERR_RET(initClientId(), "failed to init clientId");
1,680,342✔
1131

1132
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
1,680,342✔
1133
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
1,680,342✔
1134
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
1,680,342✔
1135

1136
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
1,680,342✔
1137
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
1,680,342✔
1138

1139
  ENV_ERR_RET(taosGetAppName(appInfo.appName, NULL), "failed to get app name");
1,680,342✔
1140
  ENV_ERR_RET(taosThreadMutexInit(&appInfo.mutex, NULL), "failed to init thread mutex");
1,680,342✔
1141
#ifdef USE_REPORT
1142
  ENV_ERR_RET(tscCrashReportInit(), "failed to init crash report");
1,680,342✔
1143
#endif
1144
  ENV_ERR_RET(qInitKeywordsTable(), "failed to init parser keywords table");
1,680,342✔
1145
#ifdef TAOSD_INTEGRATED
1146
  ENV_ERR_RET(shellStartDaemon(0, NULL), "failed to start taosd daemon");
1147
#endif
1148

1149
  ENV_ERR_RET(sessMgtInit(), "failed to init session management");
1,680,342✔
1150
  
1151
  tscInfo("TAOS driver is initialized successfully");
1,680,342✔
1152
}
1153

1154
int taos_init() {
2,347,643✔
1155
  (void)taosThreadOnce(&tscinit, taos_init_imp);
2,347,643✔
1156
  return tscInitRes;
2,347,715✔
1157
}
1158

1159
const char *getCfgName(TSDB_OPTION option) {
1,728✔
1160
  const char *name = NULL;
1,728✔
1161

1162
  switch (option) {
1,728✔
1163
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
588✔
1164
      name = "shellActivityTimer";
588✔
1165
      break;
588✔
1166
    case TSDB_OPTION_LOCALE:
×
1167
      name = "locale";
×
1168
      break;
×
1169
    case TSDB_OPTION_CHARSET:
×
1170
      name = "charset";
×
1171
      break;
×
1172
    case TSDB_OPTION_TIMEZONE:
1,140✔
1173
      name = "timezone";
1,140✔
1174
      break;
1,140✔
1175
    case TSDB_OPTION_USE_ADAPTER:
×
1176
      name = "useAdapter";
×
1177
      break;
×
1178
    default:
×
1179
      break;
×
1180
  }
1181

1182
  return name;
1,728✔
1183
}
1184

1185
int taos_options_imp(TSDB_OPTION option, const char *str) {
573,523✔
1186
  if (option == TSDB_OPTION_CONFIGDIR) {
573,523✔
1187
#ifndef WINDOWS
1188
    char newstr[PATH_MAX];
565,529✔
1189
    int  len = strlen(str);
571,795✔
1190
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
571,795✔
1191
      if (len + 2 >= PATH_MAX) {
571,474✔
1192
        tscError("Too long path %s", str);
×
1193
        return -1;
×
1194
      }
1195
      newstr[0] = '"';
571,474✔
1196
      (void)memcpy(newstr + 1, str, len);
571,474✔
1197
      newstr[len + 1] = '"';
571,474✔
1198
      newstr[len + 2] = '\0';
571,474✔
1199
      str = newstr;
571,474✔
1200
    }
1201
#endif
1202
    tstrncpy(configDir, str, PATH_MAX);
571,795✔
1203
    tscInfo("set cfg:%s to %s", configDir, str);
571,795✔
1204
    return 0;
571,795✔
1205
  }
1206

1207
  // initialize global config
1208
  if (taos_init() != 0) {
1,728✔
1209
    return -1;
×
1210
  }
1211

1212
  SConfig     *pCfg = taosGetCfg();
1,728✔
1213
  SConfigItem *pItem = NULL;
1,728✔
1214
  const char  *name = getCfgName(option);
1,728✔
1215

1216
  if (name == NULL) {
1,728✔
1217
    tscError("Invalid option %d", option);
×
1218
    return -1;
×
1219
  }
1220

1221
  pItem = cfgGetItem(pCfg, name);
1,728✔
1222
  if (pItem == NULL) {
1,728✔
1223
    tscError("Invalid option %d", option);
×
1224
    return -1;
×
1225
  }
1226

1227
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
1,728✔
1228
  if (code != 0) {
1,728✔
1229
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
588✔
1230
  } else {
1231
    tscInfo("set cfg:%s to %s", name, str);
1,140✔
1232
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
1,140✔
1233
      code = taosCfgDynamicOptions(pCfg, name, false);
×
1234
    }
1235
  }
1236

1237
  return code;
1,728✔
1238
}
1239

1240
/**
1241
 * The request id is an unsigned integer format of 64bit.
1242
 *+------------+-----+-----------+---------------+
1243
 *| uid|localIp| PId | timestamp | serial number |
1244
 *+------------+-----+-----------+---------------+
1245
 *| 12bit      |12bit|24bit      |16bit          |
1246
 *+------------+-----+-----------+---------------+
1247
 * @return
1248
 */
1249
uint64_t generateRequestId() {
694,682,888✔
1250
  static uint32_t hashId = 0;
1251
  static int32_t  requestSerialId = 0;
1252

1253
  if (hashId == 0) {
694,682,888✔
1254
    int32_t code = taosGetSystemUUIDU32(&hashId);
1,679,443✔
1255
    if (code != TSDB_CODE_SUCCESS) {
1,679,443✔
1256
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1257
               tstrerror(code));
1258
    }
1259
  }
1260

1261
  uint64_t id = 0;
694,682,345✔
1262

1263
  while (true) {
×
1264
    int64_t  ts = taosGetTimestampMs();
694,689,354✔
1265
    uint64_t pid = taosGetPId();
694,689,354✔
1266
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
694,682,330✔
1267
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
694,690,972✔
1268

1269
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
694,692,271✔
1270
    if (id) {
694,692,271✔
1271
      break;
694,692,271✔
1272
    }
1273
  }
1274
  return id;
694,692,271✔
1275
}
1276

1277
#if 0
1278
#include "cJSON.h"
1279
static setConfRet taos_set_config_imp(const char *config){
1280
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
1281
  static bool setConfFlag = false;
1282
  if (setConfFlag) {
1283
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
1284
    tstrncpy(ret.retMsg, "configuration can only set once", RET_MSG_LENGTH);
1285
    return ret;
1286
  }
1287
  taosInitGlobalCfg();
1288
  cJSON *root = cJSON_Parse(config);
1289
  if (root == NULL){
1290
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
1291
    tstrncpy(ret.retMsg, "parse json error", RET_MSG_LENGTH);
1292
    return ret;
1293
  }
1294

1295
  int size = cJSON_GetArraySize(root);
1296
  if(!cJSON_IsObject(root) || size == 0) {
1297
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
1298
    tstrncpy(ret.retMsg, "json content is invalid, must be not empty object", RET_MSG_LENGTH);
1299
    return ret;
1300
  }
1301

1302
  if(size >= 1000) {
1303
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
1304
    tstrncpy(ret.retMsg, "json object size is too long", RET_MSG_LENGTH);
1305
    return ret;
1306
  }
1307

1308
  for(int i = 0; i < size; i++){
1309
    cJSON *item = cJSON_GetArrayItem(root, i);
1310
    if(!item) {
1311
      ret.retCode = SET_CONF_RET_ERR_INNER;
1312
      tstrncpy(ret.retMsg, "inner error", RET_MSG_LENGTH);
1313
      return ret;
1314
    }
1315
    if(!taosReadConfigOption(item->string, item->valuestring, NULL, NULL, TAOS_CFG_CSTATUS_OPTION, TSDB_CFG_CTYPE_B_CLIENT)){
1316
      ret.retCode = SET_CONF_RET_ERR_PART;
1317
      if (strlen(ret.retMsg) == 0){
1318
        snprintf(ret.retMsg, RET_MSG_LENGTH, "part error|%s", item->string);
1319
      }else{
1320
        int tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1321
        size_t leftSize = tmp >= 0 ? tmp : 0;
1322
        strncat(ret.retMsg, "|",  leftSize);
1323
        tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1324
        leftSize = tmp >= 0 ? tmp : 0;
1325
        strncat(ret.retMsg, item->string, leftSize);
1326
      }
1327
    }
1328
  }
1329
  cJSON_Delete(root);
1330
  setConfFlag = true;
1331
  return ret;
1332
}
1333

1334
setConfRet taos_set_config(const char *config){
1335
  taosThreadMutexLock(&setConfMutex);
1336
  setConfRet ret = taos_set_config_imp(config);
1337
  taosThreadMutexUnlock(&setConfMutex);
1338
  return ret;
1339
}
1340
#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