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

taosdata / TDengine / #5006

29 Mar 2026 04:32AM UTC coverage: 72.274% (+0.1%) from 72.152%
#5006

push

travis-ci

web-flow
refactor: do some internal refactor for TDgpt. (#34955)

253711 of 351039 relevant lines covered (72.27%)

131490495.89 hits per line

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

56.62
/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 "clientSession.h"
42
#include "cus_name.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) {
1,029,236,919✔
79
  int32_t code = TSDB_CODE_SUCCESS;
1,029,236,919✔
80
  // connection has been released already, abort creating request.
81
  pRequest->self = taosAddRef(clientReqRefPool, pRequest);
1,029,236,919✔
82
  if (pRequest->self < 0) {
1,029,272,865✔
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);
1,029,260,228✔
89

90
  if (pTscObj->pAppInfo) {
1,029,264,931✔
91
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
1,029,271,337✔
92

93
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
1,029,260,580✔
94
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
1,029,269,509✔
95
    tscDebug("req:0x%" PRIx64 ", create request from conn:0x%" PRIx64
1,029,265,862✔
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;
1,029,255,211✔
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 = snprintf(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 || strlen(value) == 0) {
×
202
    tscError("failed to print json, data:%s", value == NULL ? "null" : value);
×
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) {
378,809✔
222
  if (pRequest->pDb != NULL) {
378,809✔
223
    return strcmp(pRequest->pDb, exceptDb) != 0;
203,550✔
224
  }
225

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

243
static void deregisterRequest(SRequestObj *pRequest) {
1,029,046,773✔
244
  if (pRequest == NULL) {
1,029,046,773✔
245
    tscError("pRequest == NULL");
×
246
    return;
×
247
  }
248

249
  STscObj            *pTscObj = pRequest->pTscObj;
1,029,046,773✔
250
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
1,029,048,241✔
251

252
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
1,029,049,408✔
253
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
1,029,090,060✔
254
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
1,029,087,813✔
255

256
  int64_t duration = taosGetTimestampUs() - pRequest->metric.start;
1,029,080,495✔
257
  tscDebug("req:0x%" PRIx64 ", free from conn:0x%" PRIx64 ", QID:0x%" PRIx64
1,029,079,960✔
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)) {
1,029,080,064✔
262
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
1,029,069,625✔
263
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
526,810,634✔
264
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
561,440,830✔
265
      tscDebug("req:0x%" PRIx64 ", insert duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
533,832,543✔
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);
533,832,543✔
271
      reqType = SLOW_LOG_TYPE_INSERT;
533,833,274✔
272
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
495,238,526✔
273
      tscDebug("req:0x%" PRIx64 ", query duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
173,524,721✔
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);
173,524,721✔
280
      reqType = SLOW_LOG_TYPE_QUERY;
173,524,768✔
281
    }
282

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

288
#ifdef USE_REPORT
289
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
1,029,052,645✔
290
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
487,198✔
291
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
218,953✔
292
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
268,245✔
293
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
52,652✔
294
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
215,593✔
295
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
926✔
296
    }
297
  }
298

299
  if ((duration >= pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogThreshold * 1000000UL) &&
1,029,432,257✔
300
      checkSlowLogExceptDb(pRequest, pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogExceptDb)) {
378,809✔
301
    (void)atomic_add_fetch_64((int64_t *)&pActivity->numOfSlowQueries, 1);
378,809✔
302
    if (pTscObj->pAppInfo->serverCfg.monitorParas.tsSlowLogScope & reqType) {
378,809✔
303
      taosPrintSlowLog("PID:%d, connId:%u, QID:0x%" PRIx64 ", Start:%" PRId64 "us, Duration:%" PRId64 "us, SQL:%s",
165,540✔
304
                       taosGetPId(), pTscObj->connId, pRequest->requestId, pRequest->metric.start, duration,
305
                       pRequest->sqlstr);
306
      if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
165,540✔
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);
1,029,052,928✔
317
}
318

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

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

329
static bool clientRpcRfp(int32_t code, tmsg_t msgType) {
17,987,223✔
330
  if (NEED_REDIRECT_ERROR(code)) {
17,987,223✔
331
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
14,052,744✔
332
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_QUERY_HEARTBEAT || msgType == TDMT_SCH_DROP_TASK ||
14,053,172✔
333
        msgType == TDMT_SCH_TASK_NOTIFY) {
334
      return false;
×
335
    }
336
    return true;
14,053,172✔
337
  } else if (code == TSDB_CODE_UTIL_QUEUE_OUT_OF_MEMORY || code == TSDB_CODE_OUT_OF_RPC_MEMORY_QUEUE ||
3,934,479✔
338
             code == TSDB_CODE_SYN_WRITE_STALL || code == TSDB_CODE_SYN_PROPOSE_NOT_READY ||
3,934,479✔
339
             code == TSDB_CODE_SYN_RESTORING) {
340
    tscDebug("client msg type %s should retry since %s", TMSG_INFO(msgType), tstrerror(code));
×
341
    return true;
×
342
  } else {
343
    return false;
3,934,479✔
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,482,207✔
357
  SRpcInit rpcInit;
1,463,696✔
358
  (void)memset(&rpcInit, 0, sizeof(rpcInit));
1,482,207✔
359
  rpcInit.localPort = 0;
1,482,207✔
360
  rpcInit.label = "TSC";
1,482,207✔
361
  rpcInit.numOfThreads = tsNumOfRpcThreads;
1,482,207✔
362
  rpcInit.cfp = processMsgFromServer;
1,482,207✔
363
  rpcInit.rfp = clientRpcRfp;
1,482,207✔
364
  rpcInit.sessions = 1024;
1,482,207✔
365
  rpcInit.connType = TAOS_CONN_CLIENT;
1,482,207✔
366
  rpcInit.user = (char *)(user ? user : auth);
1,482,207✔
367
  rpcInit.idleTime = tsShellActivityTimer * 1000;
1,482,207✔
368
  rpcInit.compressSize = tsCompressMsgSize;
1,482,207✔
369
  rpcInit.dfp = destroyAhandle;
1,482,207✔
370

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

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

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

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

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

408
  return code;
1,482,207✔
409
}
410

411
void destroyAllRequests(SHashObj *pRequests) {
92,350,256✔
412
  void *pIter = taosHashIterate(pRequests, NULL);
92,350,256✔
413
  while (pIter != NULL) {
92,350,250✔
414
    int64_t *rid = pIter;
×
415

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

422
    pIter = taosHashIterate(pRequests, pIter);
×
423
  }
424
}
92,350,250✔
425

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

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

437
    pIter = taosHashIterate(pRequests, pIter);
×
438
  }
439
}
98✔
440

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

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

450
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
1,482,207✔
451

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

457
  taosMemoryFreeClear(pAppInfo->instKey);
1,482,207✔
458
  closeTransporter(pAppInfo);
1,482,207✔
459

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

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

471
  taosMemoryFree(pAppInfo);
1,482,207✔
472
}
1,482,207✔
473

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

478
void destroyTscObj(void *pObj) {
92,350,556✔
479
  if (NULL == pObj) {
92,350,556✔
480
    return;
×
481
  }
482

483
  STscObj *pTscObj = pObj;
92,350,556✔
484
  int64_t  tscId = pTscObj->id;
92,350,556✔
485
  tscTrace("conn:%" PRIx64 ", begin destroy, p:%p", tscId, pTscObj);
92,350,556✔
486

487
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
92,350,556✔
488
  hbDeregisterConn(pTscObj, connKey);
92,350,556✔
489

490
  destroyAllRequests(pTscObj->pRequests);
92,350,798✔
491
  taosHashCleanup(pTscObj->pRequests);
92,352,357✔
492

493
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
92,352,368✔
494
  tscDebug("conn:0x%" PRIx64 ", p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
92,352,218✔
495
           pTscObj->pAppInfo->numOfConns);
496

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

500
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
92,352,441✔
501
  taosMemoryFree(pTscObj);
92,351,920✔
502

503
  tscTrace("conn:0x%" PRIx64 ", end destroy, p:%p", tscId, pTscObj);
92,351,802✔
504
}
505

506
int32_t createTscObj(const char *user, const char *auth, const char *db, int32_t connType, SAppInstInfo *pAppInfo,
92,534,775✔
507
                     STscObj **pObj) {
508
  *pObj = (STscObj *)taosMemoryCalloc(1, sizeof(STscObj));
92,534,775✔
509
  if (NULL == *pObj) {
92,539,144✔
510
    return terrno;
×
511
  }
512

513
  (*pObj)->pRequests = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
92,539,144✔
514
  if (NULL == (*pObj)->pRequests) {
92,538,240✔
515
    taosMemoryFree(*pObj);
×
516
    return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
517
  }
518

519
  (*pObj)->connType = connType;
92,538,240✔
520
  (*pObj)->pAppInfo = pAppInfo;
92,538,240✔
521
  (*pObj)->appHbMgrIdx = pAppInfo->pAppHbMgr->idx;
92,538,240✔
522
  if (user == NULL) {
92,538,240✔
523
    (*pObj)->user[0] = 0;
2,255✔
524
    (*pObj)->pass[0] = 0;
2,255✔
525
    tstrncpy((*pObj)->token, auth, sizeof((*pObj)->token));
2,255✔
526
  } else {
527
    tstrncpy((*pObj)->user, user, sizeof((*pObj)->user));
92,535,985✔
528
    (void)memcpy((*pObj)->pass, auth, TSDB_PASSWORD_LEN);
92,535,985✔
529
  }
530
  (*pObj)->tokenName[0] = 0;
92,538,240✔
531

532
  if (db != NULL) {
92,538,240✔
533
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
92,539,775✔
534
  }
535

536
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
92,538,240✔
537

538
  int32_t code = TSDB_CODE_SUCCESS;
92,539,655✔
539

540
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
92,539,655✔
541
  if ((*pObj)->id < 0) {
92,539,858✔
542
    tscError("failed to add object to clientConnRefPool");
×
543
    code = terrno;
×
544
    taosMemoryFree(*pObj);
×
545
    return code;
×
546
  }
547

548
  (void)atomic_add_fetch_64(&(*pObj)->pAppInfo->numOfConns, 1);
92,539,858✔
549

550
  updateConnAccessInfo(&(*pObj)->sessInfo);
92,538,766✔
551
  tscInfo("conn:0x%" PRIx64 ", created, p:%p", (*pObj)->id, *pObj);
92,538,941✔
552
  return code;
92,539,579✔
553
}
554

555
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
2,147,483,647✔
556

557
void releaseTscObj(int64_t rid) {
2,147,483,647✔
558
  int32_t code = taosReleaseRef(clientConnRefPool, rid);
2,147,483,647✔
559
  if (TSDB_CODE_SUCCESS != code) {
2,147,483,647✔
560
    tscWarn("failed to release TscObj, code:%s", tstrerror(code));
×
561
  }
562
}
2,147,483,647✔
563

564
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
1,029,239,756✔
565
  int32_t code = TSDB_CODE_SUCCESS;
1,029,239,756✔
566
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
1,029,239,756✔
567
  if (NULL == *pRequest) {
1,029,239,043✔
568
    return terrno;
×
569
  }
570

571
  STscObj *pTscObj = acquireTscObj(connId);
1,029,240,711✔
572
  if (pTscObj == NULL) {
1,029,271,460✔
573
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
574
  }
575
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
1,029,271,460✔
576
  if (interParam == NULL) {
1,029,254,311✔
577
    releaseTscObj(connId);
×
578
    TSC_ERR_JRET(terrno);
×
579
  }
580
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
1,029,254,311✔
581
  interParam->pRequest = *pRequest;
1,029,264,161✔
582
  (*pRequest)->body.interParam = interParam;
1,029,259,251✔
583

584
  (*pRequest)->resType = RES_TYPE__QUERY;
1,029,264,836✔
585
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
1,029,260,206✔
586
  (*pRequest)->metric.start = taosGetTimestampUs();
1,768,188,338✔
587
  (*pRequest)->execPhase = QUERY_PHASE_NONE;
1,029,263,567✔
588
  (*pRequest)->phaseStartTime = 0;
1,029,269,317✔
589

590
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
1,029,263,818✔
591
  (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt;
1,029,260,608✔
592
  (*pRequest)->type = type;
1,029,269,305✔
593
  (*pRequest)->allocatorRefId = -1;
1,029,267,793✔
594

595
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
1,029,268,874✔
596
  if (NULL == (*pRequest)->pDb) {
1,029,262,756✔
597
    TSC_ERR_JRET(terrno);
288,786,019✔
598
  }
599
  (*pRequest)->pTscObj = pTscObj;
1,029,264,538✔
600
  (*pRequest)->inCallback = false;
1,029,257,996✔
601
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
1,029,259,524✔
602
  if (NULL == (*pRequest)->msgBuf) {
1,029,244,950✔
603
    code = terrno;
×
604
    goto _return;
×
605
  }
606
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
1,029,252,699✔
607
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
1,029,252,530✔
608
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
1,029,248,082✔
609

610
  return TSDB_CODE_SUCCESS;
1,029,254,277✔
611
_return:
×
612
  if ((*pRequest)->pTscObj) {
×
613
    doDestroyRequest(*pRequest);
×
614
  } else {
615
    taosMemoryFree(*pRequest);
×
616
  }
617
  return code;
×
618
}
619

620
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
1,077,257,032✔
621
  taosMemoryFreeClear(pResInfo->pRspMsg);
1,077,257,032✔
622
  taosMemoryFreeClear(pResInfo->length);
1,077,265,972✔
623
  taosMemoryFreeClear(pResInfo->row);
1,077,259,730✔
624
  taosMemoryFreeClear(pResInfo->pCol);
1,077,262,128✔
625
  taosMemoryFreeClear(pResInfo->fields);
1,077,259,550✔
626
  taosMemoryFreeClear(pResInfo->userFields);
1,077,265,521✔
627
  taosMemoryFreeClear(pResInfo->convertJson);
1,077,260,092✔
628
  taosMemoryFreeClear(pResInfo->decompBuf);
1,077,263,694✔
629

630
  if (pResInfo->convertBuf != NULL) {
1,077,256,526✔
631
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
898,627,922✔
632
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
728,428,682✔
633
    }
634
    taosMemoryFreeClear(pResInfo->convertBuf);
170,199,483✔
635
  }
636
}
1,077,261,116✔
637

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

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

642
int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }
1,029,074,128✔
643

644
/// return the most previous req ref id
645
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
1,029,069,660✔
646
  int64_t      mostPrevReqRefId = pRequest->self;
1,029,069,660✔
647
  SRequestObj *pTmp = pRequest;
1,029,072,958✔
648
  while (pTmp->relation.prevRefId) {
1,029,072,958✔
649
    pTmp = acquireRequest(pTmp->relation.prevRefId);
×
650
    if (pTmp) {
×
651
      mostPrevReqRefId = pTmp->self;
×
652
      (void)releaseRequest(mostPrevReqRefId);  // ignore error
×
653
    } else {
654
      break;
×
655
    }
656
  }
657
  (void)removeRequest(mostPrevReqRefId);  // ignore error
1,029,072,463✔
658
  return mostPrevReqRefId;
1,029,087,010✔
659
}
660

661
void destroyNextReq(int64_t nextRefId) {
1,029,066,343✔
662
  if (nextRefId) {
1,029,066,343✔
663
    SRequestObj *pObj = acquireRequest(nextRefId);
×
664
    if (pObj) {
×
665
      (void)releaseRequest(nextRefId);  // ignore error
×
666
      (void)releaseRequest(nextRefId);  // ignore error
×
667
    }
668
  }
669
}
1,029,066,343✔
670

671
void destroySubRequests(SRequestObj *pRequest) {
×
672
  int32_t      reqIdx = -1;
×
673
  SRequestObj *pReqList[16] = {NULL};
×
674
  uint64_t     tmpRefId = 0;
×
675

676
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
×
677
    return;
×
678
  }
679

680
  SRequestObj *pTmp = pRequest;
×
681
  while (pTmp->relation.prevRefId) {
×
682
    tmpRefId = pTmp->relation.prevRefId;
×
683
    pTmp = acquireRequest(tmpRefId);
×
684
    if (pTmp) {
×
685
      pReqList[++reqIdx] = pTmp;
×
686
      (void)releaseRequest(tmpRefId);  // ignore error
×
687
    } else {
688
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
689
      break;
×
690
    }
691
  }
692

693
  for (int32_t i = reqIdx; i >= 0; i--) {
×
694
    (void)removeRequest(pReqList[i]->self);  // ignore error
×
695
  }
696

697
  tmpRefId = pRequest->relation.nextRefId;
×
698
  while (tmpRefId) {
×
699
    pTmp = acquireRequest(tmpRefId);
×
700
    if (pTmp) {
×
701
      tmpRefId = pTmp->relation.nextRefId;
×
702
      (void)removeRequest(pTmp->self);   // ignore error
×
703
      (void)releaseRequest(pTmp->self);  // ignore error
×
704
    } else {
705
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
706
      break;
×
707
    }
708
  }
709
}
710

711
void doDestroyRequest(void *p) {
1,029,074,687✔
712
  if (NULL == p) {
1,029,074,687✔
713
    return;
×
714
  }
715

716
  SRequestObj *pRequest = (SRequestObj *)p;
1,029,074,687✔
717

718
  uint64_t reqId = pRequest->requestId;
1,029,074,687✔
719
  tscTrace("QID:0x%" PRIx64 ", begin destroy request, res:%p", reqId, pRequest);
1,029,080,422✔
720

721
  int64_t nextReqRefId = pRequest->relation.nextRefId;
1,029,080,422✔
722

723
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
1,029,070,131✔
724
  if (TSDB_CODE_SUCCESS != code) {
1,029,087,750✔
725
    tscDebug("failed to remove request from hash since %s", tstrerror(code));
92,540,372✔
726
  }
727
  schedulerFreeJob(&pRequest->body.queryJob, 0);
1,029,087,750✔
728

729
  destorySqlCallbackWrapper(pRequest->pWrapper);
1,029,078,189✔
730

731
  taosMemoryFreeClear(pRequest->msgBuf);
1,029,069,089✔
732

733
  doFreeReqResultInfo(&pRequest->body.resInfo);
1,029,060,711✔
734
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
1,029,045,172✔
735
    tscError("failed to destroy semaphore");
×
736
  }
737

738
  SSessParam para = {.type = SESSION_MAX_CONCURRENCY, .value = -1, .noCheck = 1};
1,029,068,468✔
739
  code = tscUpdateSessMetric(pRequest->pTscObj, &para);
1,029,062,080✔
740
  if (TSDB_CODE_SUCCESS != code) {
1,029,087,642✔
741
    tscError("failed to update session metric, code:%s", tstrerror(code));
×
742
  }
743

744
  taosArrayDestroy(pRequest->tableList);
1,029,087,642✔
745
  taosArrayDestroy(pRequest->targetTableList);
1,029,059,360✔
746
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
1,029,073,979✔
747

748
  if (pRequest->self) {
1,029,059,131✔
749
    deregisterRequest(pRequest);
1,029,077,899✔
750
  }
751

752
  taosMemoryFreeClear(pRequest->pDb);
1,029,076,157✔
753
  taosArrayDestroy(pRequest->dbList);
1,029,063,265✔
754
  if (pRequest->body.interParam) {
1,029,064,207✔
755
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
1,029,078,772✔
756
      tscError("failed to destroy semaphore in pRequest");
×
757
    }
758
  }
759
  taosMemoryFree(pRequest->body.interParam);
1,029,071,349✔
760

761
  qDestroyQuery(pRequest->pQuery);
1,029,074,625✔
762

763
  // `pRequest->parseMeta` may be filled during stmt parsing and must be released
764
  // when the request object is destroyed, otherwise LeakSanitizer will report
765
  // catalog async response result leaks.
766
  catalogFreeMetaData(&pRequest->parseMeta);
1,029,058,496✔
767
  TAOS_MEMSET(&pRequest->parseMeta, 0, sizeof(pRequest->parseMeta));
1,029,065,793✔
768
  nodesDestroyAllocator(pRequest->allocatorRefId);
1,029,067,152✔
769

770
  taosMemoryFreeClear(pRequest->effectiveUser);
1,029,052,501✔
771
  taosMemoryFreeClear(pRequest->sqlstr);
1,029,052,503✔
772
  taosMemoryFree(pRequest);
1,029,056,096✔
773
  tscTrace("QID:0x%" PRIx64 ", end destroy request, res:%p", reqId, pRequest);
1,029,068,985✔
774
  destroyNextReq(nextReqRefId);
1,029,068,985✔
775
}
776

777
void destroyRequest(SRequestObj *pRequest) {
1,029,066,305✔
778
  if (pRequest == NULL) return;
1,029,066,305✔
779

780
  taos_stop_query(pRequest);
1,029,066,305✔
781
  (void)removeFromMostPrevReq(pRequest);
1,029,080,289✔
782
}
783

784
void taosStopQueryImpl(SRequestObj *pRequest) {
1,029,069,941✔
785
  pRequest->killed = true;
1,029,069,941✔
786

787
  // It is not a query, no need to stop.
788
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
1,029,073,139✔
789
    tscDebug("QID:0x%" PRIx64 ", no need to be killed since not query", pRequest->requestId);
305,599,094✔
790
    return;
305,616,521✔
791
  }
792

793
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
723,462,659✔
794
  tscDebug("QID:0x%" PRIx64 ", killed", pRequest->requestId);
723,465,852✔
795
}
796

797
void stopAllQueries(SRequestObj *pRequest) {
1,029,069,143✔
798
  int32_t      reqIdx = -1;
1,029,069,143✔
799
  SRequestObj *pReqList[16] = {NULL};
1,029,069,143✔
800
  uint64_t     tmpRefId = 0;
1,029,071,951✔
801

802
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
1,029,071,951✔
803
    return;
×
804
  }
805

806
  SRequestObj *pTmp = pRequest;
1,029,075,206✔
807
  while (pTmp->relation.prevRefId) {
1,029,075,206✔
808
    tmpRefId = pTmp->relation.prevRefId;
×
809
    pTmp = acquireRequest(tmpRefId);
×
810
    if (pTmp) {
×
811
      pReqList[++reqIdx] = pTmp;
×
812
    } else {
813
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
814
      break;
×
815
    }
816
  }
817

818
  for (int32_t i = reqIdx; i >= 0; i--) {
1,029,075,470✔
819
    taosStopQueryImpl(pReqList[i]);
×
820
    (void)releaseRequest(pReqList[i]->self);  // ignore error
×
821
  }
822

823
  taosStopQueryImpl(pRequest);
1,029,075,470✔
824

825
  tmpRefId = pRequest->relation.nextRefId;
1,029,079,388✔
826
  while (tmpRefId) {
1,029,078,186✔
827
    pTmp = acquireRequest(tmpRefId);
×
828
    if (pTmp) {
×
829
      tmpRefId = pTmp->relation.nextRefId;
×
830
      taosStopQueryImpl(pTmp);
×
831
      (void)releaseRequest(pTmp->self);  // ignore error
×
832
    } else {
833
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
834
      break;
×
835
    }
836
  }
837
}
838
#ifdef USE_REPORT
839
void crashReportThreadFuncUnexpectedStopped(void) { atomic_store_32(&clientStop, -1); }
×
840

841
static void *tscCrashReportThreadFp(void *param) {
×
842
  int32_t code = 0;
×
843
  setThreadName("client-crashReport");
×
844
  char filepath[PATH_MAX] = {0};
×
845
  (void)snprintf(filepath, sizeof(filepath), "%s%s.taosCrashLog", tsLogDir, TD_DIRSEP);
×
846
  char     *pMsg = NULL;
×
847
  int64_t   msgLen = 0;
×
848
  TdFilePtr pFile = NULL;
×
849
  bool      truncateFile = false;
×
850
  int32_t   sleepTime = 200;
×
851
  int32_t   reportPeriodNum = 3600 * 1000 / sleepTime;
×
852
  int32_t   loopTimes = reportPeriodNum;
×
853

854
#ifdef WINDOWS
855
  if (taosCheckCurrentInDll()) {
856
    atexit(crashReportThreadFuncUnexpectedStopped);
857
  }
858
#endif
859

860
  if (-1 != atomic_val_compare_exchange_32(&clientStop, -1, 0)) {
×
861
    return NULL;
×
862
  }
863
  STelemAddrMgmt mgt;
×
864
  code = taosTelemetryMgtInit(&mgt, tsTelemServer);
×
865
  if (code) {
×
866
    tscError("failed to init telemetry management, code:%s", tstrerror(code));
×
867
    return NULL;
×
868
  }
869

870
  code = initCrashLogWriter();
×
871
  if (code) {
×
872
    tscError("failed to init crash log writer, code:%s", tstrerror(code));
×
873
    return NULL;
×
874
  }
875

876
  while (1) {
877
    checkAndPrepareCrashInfo();
×
878
    if (clientStop > 0 && reportThreadSetQuit()) break;
×
879
    if (loopTimes++ < reportPeriodNum) {
×
880
      if (loopTimes < 0) loopTimes = reportPeriodNum;
×
881
      taosMsleep(sleepTime);
×
882
      continue;
×
883
    }
884

885
    taosReadCrashInfo(filepath, &pMsg, &msgLen, &pFile);
×
886
    if (pMsg && msgLen > 0) {
×
887
      if (taosSendTelemReport(&mgt, tsClientCrashReportUri, tsTelemPort, pMsg, msgLen, HTTP_FLAT) != 0) {
×
888
        tscError("failed to send crash report");
×
889
        if (pFile) {
×
890
          taosReleaseCrashLogFile(pFile, false);
×
891
          pFile = NULL;
×
892

893
          taosMsleep(sleepTime);
×
894
          loopTimes = 0;
×
895
          continue;
×
896
        }
897
      } else {
898
        tscInfo("succeed to send crash report");
×
899
        truncateFile = true;
×
900
      }
901
    } else {
902
      tscInfo("no crash info was found");
×
903
    }
904

905
    taosMemoryFree(pMsg);
×
906

907
    if (pMsg && msgLen > 0) {
×
908
      pMsg = NULL;
×
909
      continue;
×
910
    }
911

912
    if (pFile) {
×
913
      taosReleaseCrashLogFile(pFile, truncateFile);
×
914
      pFile = NULL;
×
915
      truncateFile = false;
×
916
    }
917

918
    taosMsleep(sleepTime);
×
919
    loopTimes = 0;
×
920
  }
921
  taosTelemetryDestroy(&mgt);
×
922

923
  clientStop = -2;
×
924
  return NULL;
×
925
}
926

927
int32_t tscCrashReportInit() {
1,402,932✔
928
  if (!tsEnableCrashReport) {
1,402,932✔
929
    return TSDB_CODE_SUCCESS;
1,402,932✔
930
  }
931
  int32_t      code = TSDB_CODE_SUCCESS;
×
932
  TdThreadAttr thAttr;
×
933
  TSC_ERR_JRET(taosThreadAttrInit(&thAttr));
×
934
  TSC_ERR_JRET(taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE));
×
935
  TdThread crashReportThread;
×
936
  if (taosThreadCreate(&crashReportThread, &thAttr, tscCrashReportThreadFp, NULL) != 0) {
×
937
    tscError("failed to create crashReport thread since %s", strerror(ERRNO));
×
938
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
939
    TSC_ERR_RET(terrno);
×
940
  }
941

942
  (void)taosThreadAttrDestroy(&thAttr);
×
943
_return:
×
944
  if (code) {
×
945
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
946
    TSC_ERR_RET(terrno);
×
947
  }
948

949
  return code;
×
950
}
951

952
void tscStopCrashReport() {
1,402,974✔
953
  if (!tsEnableCrashReport) {
1,402,974✔
954
    return;
1,402,974✔
955
  }
956

957
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
958
    tscDebug("crash report thread already stopped");
×
959
    return;
×
960
  }
961

962
  while (atomic_load_32(&clientStop) > 0) {
×
963
    taosMsleep(100);
×
964
  }
965
}
966

967
void taos_write_crashinfo(int signum, void *sigInfo, void *context) {
×
968
  writeCrashLogToFile(signum, sigInfo, CUS_PROMPT, lastClusterId, appInfo.startTime);
×
969
}
×
970
#endif
971

972
#ifdef TAOSD_INTEGRATED
973
typedef struct {
974
  TdThread pid;
975
  int32_t  stat;  // < 0: start failed, 0: init(not start), 1: start successfully
976
} SDaemonObj;
977

978
extern int  dmStartDaemon(int argc, char const *argv[]);
979
extern void dmStopDaemon();
980

981
SDaemonObj daemonObj = {0};
982

983
typedef struct {
984
  int32_t argc;
985
  char  **argv;
986
} SExecArgs;
987

988
static void *dmStartDaemonFunc(void *param) {
989
  int32_t    code = 0;
990
  SExecArgs *pArgs = (SExecArgs *)param;
991
  int32_t    argc = pArgs->argc;
992
  char     **argv = pArgs->argv;
993

994
  code = dmStartDaemon(argc, (const char **)argv);
995
  if (code != 0) {
996
    printf("failed to start taosd since %s\r\n", tstrerror(code));
997
    goto _exit;
998
  }
999

1000
_exit:
1001
  if (code != 0) {
1002
    atomic_store_32(&daemonObj.stat, code);
1003
  }
1004
  return NULL;
1005
}
1006

1007
static int32_t shellStartDaemon(int argc, char *argv[]) {
1008
  int32_t    code = 0, lino = 0;
1009
  SExecArgs *pArgs = NULL;
1010
  int64_t    startMs = taosGetTimestampMs(), endMs = startMs;
1011

1012
  TdThreadAttr thAttr;
1013
  (void)taosThreadAttrInit(&thAttr);
1014
  (void)taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
1015
#ifdef TD_COMPACT_OS
1016
  (void)taosThreadAttrSetStackSize(&thAttr, STACK_SIZE_SMALL);
1017
#endif
1018
  pArgs = (SExecArgs *)taosMemoryCalloc(1, sizeof(SExecArgs));
1019
  if (pArgs == NULL) {
1020
    code = terrno;
1021
    TAOS_CHECK_EXIT(code);
1022
  }
1023
  pArgs->argc = argc;
1024
  pArgs->argv = argv;
1025

1026
#ifndef TD_AS_LIB
1027
  tsLogEmbedded = 1;
1028
#endif
1029

1030
  TAOS_CHECK_EXIT(taosThreadCreate(&daemonObj.pid, &thAttr, dmStartDaemonFunc, pArgs));
1031

1032
  while (true) {
1033
    if (atomic_load_64(&tsDndStart)) {
1034
      atomic_store_32(&daemonObj.stat, 1);
1035
      break;
1036
    }
1037
    int32_t daemonstat = atomic_load_32(&daemonObj.stat);
1038
    if (daemonstat < 0) {
1039
      code = daemonstat;
1040
      TAOS_CHECK_EXIT(code);
1041
    }
1042

1043
    if (daemonstat > 1) {
1044
      code = TSDB_CODE_APP_ERROR;
1045
      TAOS_CHECK_EXIT(code);
1046
    }
1047
    taosMsleep(1000);
1048
  }
1049

1050
_exit:
1051
  endMs = taosGetTimestampMs();
1052
  (void)taosThreadAttrDestroy(&thAttr);
1053
  taosMemoryFreeClear(pArgs);
1054
  if (code) {
1055
    printf("\r\n The daemon start failed at line %d since %s, cost %" PRIi64 " ms\r\n", lino, tstrerror(code),
1056
           endMs - startMs);
1057
  } else {
1058
    printf("\r\n The daemon started successfully, cost %" PRIi64 " ms\r\n", endMs - startMs);
1059
  }
1060
#ifndef TD_AS_LIB
1061
  tsLogEmbedded = 0;
1062
#endif
1063
  return code;
1064
}
1065

1066
void shellStopDaemon() {
1067
#ifndef TD_AS_LIB
1068
  tsLogEmbedded = 1;
1069
#endif
1070
  dmStopDaemon();
1071
  if (taosCheckPthreadValid(daemonObj.pid)) {
1072
    (void)taosThreadJoin(daemonObj.pid, NULL);
1073
    taosThreadClear(&daemonObj.pid);
1074
  }
1075
}
1076
#endif
1077

1078
void taos_init_imp(void) {
1,402,974✔
1079
#if defined(LINUX)
1080
  if (tscDbg.memEnable) {
1,402,974✔
1081
    int32_t code = taosMemoryDbgInit();
×
1082
    if (code) {
×
1083
      (void)printf("failed to init memory dbg, error:%s\n", tstrerror(code));
×
1084
    } else {
1085
      tsAsyncLog = false;
×
1086
      (void)printf("memory dbg enabled\n");
×
1087
    }
1088
  }
1089
#endif
1090

1091
  // In the APIs of other program language, taos_cleanup is not available yet.
1092
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
1093
  (void)atexit(taos_cleanup);
1,402,974✔
1094
  SET_ERRNO(TSDB_CODE_SUCCESS);
1,402,974✔
1095
  terrno = TSDB_CODE_SUCCESS;
1,402,974✔
1096
  taosSeedRand(taosGetTimestampSec());
1,402,974✔
1097

1098
  appInfo.pid = taosGetPId();
1,402,974✔
1099
  appInfo.startTime = taosGetTimestampMs();
1,402,974✔
1100
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
1,402,974✔
1101
  appInfo.pInstMapByClusterId =
1,402,974✔
1102
      taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);
1,402,974✔
1103
  if (NULL == appInfo.pInstMap || NULL == appInfo.pInstMapByClusterId) {
1,402,974✔
1104
    (void)printf("failed to allocate memory when init appInfo\n");
×
1105
    tscInitRes = terrno;
×
1106
    return;
×
1107
  }
1108
  taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst);
1,402,974✔
1109

1110
  const char *logName = CUS_PROMPT "log";
1,402,974✔
1111
  ENV_ERR_RET(taosInitLogOutput(&logName), "failed to init log output");
1,402,974✔
1112
  if (taosCreateLog(logName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
1,402,974✔
1113
    (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logName, strerror(ERRNO), configDir);
42✔
1114
    SET_ERROR_MSG("Create %s failed:%s. configDir=%s", logName, strerror(ERRNO), configDir);
42✔
1115
    tscInitRes = terrno;
42✔
1116
    return;
42✔
1117
  }
1118

1119
#ifdef TAOSD_INTEGRATED
1120
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0), "failed to init cfg");
1121
#else
1122
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
1,402,932✔
1123
#endif
1124

1125
  initQueryModuleMsgHandle();
1,402,932✔
1126
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
1127
  if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL) {
1,402,932✔
1128
    tscInitRes = terrno;
×
1129
    tscError("failed to init conv");
×
1130
    return;
×
1131
  }
1132
#endif
1133
#if !defined(TD_ASTRA)
1134
  ENV_ERR_RET(tzInit(), "failed to init timezone");
1,402,932✔
1135
#endif
1136
  ENV_ERR_RET(monitorInit(), "failed to init monitor");
1,402,932✔
1137
  ENV_ERR_RET(rpcInit(), "failed to init rpc");
1,402,932✔
1138

1139
  if (InitRegexCache() != 0) {
1,402,932✔
1140
    tscInitRes = terrno;
×
1141
    (void)printf("failed to init regex cache\n");
×
1142
    return;
×
1143
  }
1144

1145
  tscInfo("starting to initialize TAOS driver");
1,402,932✔
1146

1147
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
1,402,932✔
1148
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
1,402,932✔
1149
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
1,402,932✔
1150
  ENV_ERR_RET(initClientId(), "failed to init clientId");
1,402,932✔
1151

1152
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
1,402,932✔
1153
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
1,402,932✔
1154
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
1,402,932✔
1155

1156
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
1,402,932✔
1157
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
1,402,932✔
1158

1159
  ENV_ERR_RET(taosGetAppName(appInfo.appName, NULL), "failed to get app name");
1,402,932✔
1160
  ENV_ERR_RET(taosThreadMutexInit(&appInfo.mutex, NULL), "failed to init thread mutex");
1,402,932✔
1161
#ifdef USE_REPORT
1162
  ENV_ERR_RET(tscCrashReportInit(), "failed to init crash report");
1,402,932✔
1163
#endif
1164
  ENV_ERR_RET(qInitKeywordsTable(), "failed to init parser keywords table");
1,402,932✔
1165
#ifdef TAOSD_INTEGRATED
1166
  ENV_ERR_RET(shellStartDaemon(0, NULL), "failed to start taosd daemon");
1167
#endif
1168

1169
  if (tsSessionControl) {
1,402,932✔
1170
    ENV_ERR_RET(sessMgtInit(), "failed to init session management");
1,402,932✔
1171
  }
1172

1173
  tscInfo("TAOS driver is initialized successfully");
1,402,932✔
1174
}
1175

1176
int taos_init() {
92,353,564✔
1177
  (void)taosThreadOnce(&tscinit, taos_init_imp);
92,353,564✔
1178
  return tscInitRes;
92,355,261✔
1179
}
1180

1181
const char *getCfgName(TSDB_OPTION option) {
4,153✔
1182
  const char *name = NULL;
4,153✔
1183

1184
  switch (option) {
4,153✔
1185
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
168✔
1186
      name = "shellActivityTimer";
168✔
1187
      break;
168✔
1188
    case TSDB_OPTION_LOCALE:
×
1189
      name = "locale";
×
1190
      break;
×
1191
    case TSDB_OPTION_CHARSET:
×
1192
      name = "charset";
×
1193
      break;
×
1194
    case TSDB_OPTION_TIMEZONE:
3,209✔
1195
      name = "timezone";
3,209✔
1196
      break;
3,209✔
1197
    case TSDB_OPTION_USE_ADAPTER:
194✔
1198
      name = "useAdapter";
194✔
1199
      break;
194✔
1200
    default:
582✔
1201
      break;
582✔
1202
  }
1203

1204
  return name;
4,153✔
1205
}
1206

1207
int taos_options_imp(TSDB_OPTION option, const char *str) {
90,458,961✔
1208
  if (option == TSDB_OPTION_CONFIGDIR) {
90,458,961✔
1209
#ifndef WINDOWS
1210
    char newstr[PATH_MAX];
650,659✔
1211
    int  len = strlen(str);
90,454,808✔
1212
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
90,454,808✔
1213
      if (len + 2 >= PATH_MAX) {
90,453,741✔
1214
        tscError("Too long path %s", str);
×
1215
        return -1;
×
1216
      }
1217
      newstr[0] = '"';
90,453,741✔
1218
      (void)memcpy(newstr + 1, str, len);
90,453,741✔
1219
      newstr[len + 1] = '"';
90,453,741✔
1220
      newstr[len + 2] = '\0';
90,453,741✔
1221
      str = newstr;
90,453,741✔
1222
    }
1223
#endif
1224
    tstrncpy(configDir, str, PATH_MAX);
90,454,808✔
1225
    tscInfo("set cfg:%s to %s", configDir, str);
90,454,808✔
1226
    return 0;
90,454,808✔
1227
  }
1228

1229
  // initialize global config
1230
  if (taos_init() != 0) {
4,153✔
1231
    return -1;
×
1232
  }
1233

1234
  SConfig     *pCfg = taosGetCfg();
4,153✔
1235
  SConfigItem *pItem = NULL;
4,153✔
1236
  const char  *name = getCfgName(option);
4,153✔
1237

1238
  if (name == NULL) {
4,153✔
1239
    tscError("Invalid option %d", option);
582✔
1240
    return -1;
582✔
1241
  }
1242

1243
  pItem = cfgGetItem(pCfg, name);
3,571✔
1244
  if (pItem == NULL) {
3,571✔
1245
    tscError("Invalid option %d", option);
×
1246
    return -1;
×
1247
  }
1248

1249
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
3,571✔
1250
  if (code != 0) {
3,571✔
1251
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
168✔
1252
  } else {
1253
    tscInfo("set cfg:%s to %s", name, str);
3,403✔
1254
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
3,403✔
1255
      code = taosCfgDynamicOptions(pCfg, name, false);
194✔
1256
    }
1257
  }
1258

1259
  return code;
3,571✔
1260
}
1261

1262
/**
1263
 * The request id is an unsigned integer format of 64bit.
1264
 *+------------+-----+-----------+---------------+
1265
 *| uid|localIp| PId | timestamp | serial number |
1266
 *+------------+-----+-----------+---------------+
1267
 *| 12bit      |12bit|24bit      |16bit          |
1268
 *+------------+-----+-----------+---------------+
1269
 * @return
1270
 */
1271
uint64_t generateRequestId() {
1,084,528,225✔
1272
  static uint32_t hashId = 0;
1273
  static int32_t  requestSerialId = 0;
1274

1275
  if (hashId == 0) {
1,084,528,225✔
1276
    int32_t code = taosGetSystemUUIDU32(&hashId);
1,401,257✔
1277
    if (code != TSDB_CODE_SUCCESS) {
1,401,257✔
1278
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1279
               tstrerror(code));
1280
    }
1281
  }
1282

1283
  uint64_t id = 0;
1,084,536,185✔
1284

1285
  while (true) {
×
1286
    int64_t  ts = taosGetTimestampMs();
1,084,542,914✔
1287
    uint64_t pid = taosGetPId();
1,084,542,914✔
1288
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
1,084,538,003✔
1289
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
1,084,550,137✔
1290

1291
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
1,084,552,297✔
1292
    if (id) {
1,084,552,297✔
1293
      break;
1,084,552,297✔
1294
    }
1295
  }
1296
  return id;
1,084,552,297✔
1297
}
1298

1299
#if 0
1300
#include "cJSON.h"
1301
static setConfRet taos_set_config_imp(const char *config){
1302
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
1303
  static bool setConfFlag = false;
1304
  if (setConfFlag) {
1305
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
1306
    tstrncpy(ret.retMsg, "configuration can only set once", RET_MSG_LENGTH);
1307
    return ret;
1308
  }
1309
  taosInitGlobalCfg();
1310
  cJSON *root = cJSON_Parse(config);
1311
  if (root == NULL){
1312
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
1313
    tstrncpy(ret.retMsg, "parse json error", RET_MSG_LENGTH);
1314
    return ret;
1315
  }
1316

1317
  int size = cJSON_GetArraySize(root);
1318
  if(!cJSON_IsObject(root) || size == 0) {
1319
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
1320
    tstrncpy(ret.retMsg, "json content is invalid, must be not empty object", RET_MSG_LENGTH);
1321
    return ret;
1322
  }
1323

1324
  if(size >= 1000) {
1325
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
1326
    tstrncpy(ret.retMsg, "json object size is too long", RET_MSG_LENGTH);
1327
    return ret;
1328
  }
1329

1330
  for(int i = 0; i < size; i++){
1331
    cJSON *item = cJSON_GetArrayItem(root, i);
1332
    if(!item) {
1333
      ret.retCode = SET_CONF_RET_ERR_INNER;
1334
      tstrncpy(ret.retMsg, "inner error", RET_MSG_LENGTH);
1335
      return ret;
1336
    }
1337
    if(!taosReadConfigOption(item->string, item->valuestring, NULL, NULL, TAOS_CFG_CSTATUS_OPTION, TSDB_CFG_CTYPE_B_CLIENT)){
1338
      ret.retCode = SET_CONF_RET_ERR_PART;
1339
      if (strlen(ret.retMsg) == 0){
1340
        snprintf(ret.retMsg, RET_MSG_LENGTH, "part error|%s", item->string);
1341
      }else{
1342
        int tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1343
        size_t leftSize = tmp >= 0 ? tmp : 0;
1344
        strncat(ret.retMsg, "|",  leftSize);
1345
        tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1346
        leftSize = tmp >= 0 ? tmp : 0;
1347
        strncat(ret.retMsg, item->string, leftSize);
1348
      }
1349
    }
1350
  }
1351
  cJSON_Delete(root);
1352
  setConfFlag = true;
1353
  return ret;
1354
}
1355

1356
setConfRet taos_set_config(const char *config){
1357
  taosThreadMutexLock(&setConfMutex);
1358
  setConfRet ret = taos_set_config_imp(config);
1359
  taosThreadMutexUnlock(&setConfMutex);
1360
  return ret;
1361
}
1362
#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