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

taosdata / TDengine / #5044

06 May 2026 02:35AM UTC coverage: 73.169% (+0.06%) from 73.107%
#5044

push

travis-ci

web-flow
feat: [6659794715] cpu limit (#35153)

244 of 275 new or added lines in 23 files covered. (88.73%)

526 existing lines in 141 files now uncovered.

277745 of 379596 relevant lines covered (73.17%)

133740972.66 hits per line

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

57.66
/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 ENV_JSON_FALSE_CHECK(c)                     \
45
  do {                                              \
46
    if (!c) {                                       \
47
      tscError("faild to add item to JSON object"); \
48
      code = TSDB_CODE_TSC_FAIL_GENERATE_JSON;      \
49
      goto _end;                                    \
50
    }                                               \
51
  } while (0)
52

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

64
STscDbg   tscDbg = {0};
65
SAppInfo  appInfo;
66
int64_t   lastClusterId = 0;
67
int32_t   clientReqRefPool = -1;
68
int32_t   clientConnRefPool = -1;
69
int32_t   clientStop = -1;
70
SHashObj *pTimezoneMap = NULL;
71

72
static TdThreadOnce tscinit = PTHREAD_ONCE_INIT;
73
volatile int32_t    tscInitRes = 0;
74

75
static int32_t registerRequest(SRequestObj *pRequest, STscObj *pTscObj) {
1,219,528,629✔
76
  int32_t code = TSDB_CODE_SUCCESS;
1,219,528,629✔
77
  // connection has been released already, abort creating request.
78
  if (!mayCreateAsyncWork()) {
1,219,528,629✔
79
    return TSDB_CODE_APP_IS_STOPPING;
6✔
80
  }
81
  pRequest->self = taosAddRef(clientReqRefPool, pRequest);
1,219,561,090✔
82
  if (pRequest->self < 0) {
1,219,574,441✔
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,219,563,711✔
89

90
  if (pTscObj->pAppInfo) {
1,219,602,680✔
91
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
1,219,609,538✔
92

93
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
1,219,602,255✔
94
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
1,219,597,102✔
95
    tscDebug("req:0x%" PRIx64 ", create request from conn:0x%" PRIx64
1,219,602,181✔
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,219,560,217✔
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) {
402,710✔
222
  if (pRequest->pDb != NULL) {
402,710✔
223
    return strcmp(pRequest->pDb, exceptDb) != 0;
222,208✔
224
  }
225

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

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

249
  STscObj            *pTscObj = pRequest->pTscObj;
1,219,345,325✔
250
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
1,219,368,807✔
251

252
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
1,219,370,691✔
253
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
1,219,419,618✔
254
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
1,219,420,639✔
255

256
  int64_t duration = taosGetTimestampUs() - pRequest->metric.start;
1,219,402,615✔
257
  tscDebug("req:0x%" PRIx64 ", free from conn:0x%" PRIx64 ", QID:0x%" PRIx64
1,219,407,790✔
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,219,407,790✔
262
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
1,219,361,360✔
263
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
724,382,686✔
264
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
556,709,512✔
265
      tscDebug("req:0x%" PRIx64 ", insert duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
731,586,579✔
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);
731,586,579✔
271
      reqType = SLOW_LOG_TYPE_INSERT;
731,589,321✔
272
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
487,811,928✔
273
      tscDebug("req:0x%" PRIx64 ", query duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
179,235,246✔
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);
179,234,700✔
280
      reqType = SLOW_LOG_TYPE_QUERY;
179,235,266✔
281
    }
282

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

288
#ifdef USE_REPORT
289
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
1,219,370,001✔
290
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
436,189✔
291
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
202,067✔
292
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
234,122✔
293
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
54,654✔
294
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
179,468✔
295
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
536✔
296
    }
297
  }
298

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

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

325
  void *pTransporter = pAppInfo->pTransporter;
1,625,871✔
326
  pAppInfo->pTransporter = NULL;
1,625,871✔
327

328
  tscDebug("free transporter:%p in app inst %p", pTransporter, pAppInfo);
1,625,871✔
329
  rpcClose(pTransporter);
1,625,871✔
330
}
331

332
static bool clientRpcRfp(int32_t code, tmsg_t msgType) {
41,734,142✔
333
  if (NEED_REDIRECT_ERROR(code)) {
41,734,142✔
334
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
15,377,726✔
335
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_QUERY_HEARTBEAT || msgType == TDMT_SCH_DROP_TASK ||
15,377,947✔
336
        msgType == TDMT_SCH_TASK_NOTIFY) {
337
      return false;
×
338
    }
339
    return true;
15,377,947✔
340
  } else if (code == TSDB_CODE_UTIL_QUEUE_OUT_OF_MEMORY || code == TSDB_CODE_OUT_OF_RPC_MEMORY_QUEUE ||
26,356,416✔
341
             code == TSDB_CODE_SYN_WRITE_STALL || code == TSDB_CODE_SYN_PROPOSE_NOT_READY ||
26,356,197✔
342
             code == TSDB_CODE_SYN_RESTORING) {
343
    tscDebug("client msg type %s should retry since %s", TMSG_INFO(msgType), tstrerror(code));
898✔
344
    return true;
×
345
  } else {
346
    return false;
26,355,518✔
347
  }
348
}
349

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

358
// TODO refactor
359
int32_t openTransporter(const char *user, const char *auth, int32_t numOfThread, void **pDnodeConn) {
1,626,016✔
360
  SRpcInit rpcInit;
1,607,489✔
361
  (void)memset(&rpcInit, 0, sizeof(rpcInit));
1,626,016✔
362
  rpcInit.localPort = 0;
1,626,016✔
363
  rpcInit.label = "TSC";
1,626,016✔
364
  rpcInit.numOfThreads = tsNumOfRpcThreads;
1,626,016✔
365
  rpcInit.cfp = processMsgFromServer;
1,626,016✔
366
  rpcInit.rfp = clientRpcRfp;
1,626,016✔
367
  rpcInit.sessions = 1024;
1,626,016✔
368
  rpcInit.connType = TAOS_CONN_CLIENT;
1,626,016✔
369
  rpcInit.user = (char *)(user ? user : auth);
1,626,016✔
370
  rpcInit.idleTime = tsShellActivityTimer * 1000;
1,626,016✔
371
  rpcInit.compressSize = tsCompressMsgSize;
1,626,016✔
372
  rpcInit.dfp = destroyAhandle;
1,626,016✔
373

374
  rpcInit.retryMinInterval = tsRedirectPeriod;
1,626,016✔
375
  rpcInit.retryStepFactor = tsRedirectFactor;
1,626,016✔
376
  rpcInit.retryMaxInterval = tsRedirectMaxPeriod;
1,626,016✔
377
  rpcInit.retryMaxTimeout = tsMaxRetryWaitTime;
1,626,016✔
378

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

392
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
1,626,016✔
393
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
1,626,016✔
394
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
1,626,016✔
395
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
1,626,016✔
396
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
1,626,016✔
397

398
  int32_t code = taosVersionStrToInt(td_version, &rpcInit.compatibilityVer);
1,626,016✔
399
  if (TSDB_CODE_SUCCESS != code) {
1,626,016✔
400
    tscError("invalid version string.");
×
401
    return code;
×
402
  }
403

404
  tscInfo("rpc max retry timeout %" PRId64 "", rpcInit.retryMaxTimeout);
1,626,016✔
405
  *pDnodeConn = rpcOpen(&rpcInit);
1,626,016✔
406
  if (*pDnodeConn == NULL) {
1,626,016✔
407
    tscError("failed to init connection to server since %s", tstrerror(terrno));
145✔
408
    code = terrno;
145✔
409
  }
410

411
  return code;
1,626,016✔
412
}
413

414
void destroyAllRequests(SHashObj *pRequests) {
87,236,885✔
415
  void *pIter = taosHashIterate(pRequests, NULL);
87,236,885✔
416
  while (pIter != NULL) {
87,238,063✔
417
    int64_t *rid = pIter;
×
418

419
    SRequestObj *pRequest = acquireRequest(*rid);
×
420
    if (pRequest) {
×
421
      destroyRequest(pRequest);
×
422
      (void)releaseRequest(*rid);  // ignore error
×
423
    }
424

425
    pIter = taosHashIterate(pRequests, pIter);
×
426
  }
427
}
87,238,063✔
428

UNCOV
429
void stopAllRequests(SHashObj *pRequests) {
×
UNCOV
430
  void *pIter = taosHashIterate(pRequests, NULL);
×
UNCOV
431
  while (pIter != NULL) {
×
432
    int64_t *rid = pIter;
×
433

434
    SRequestObj *pRequest = acquireRequest(*rid);
×
435
    if (pRequest) {
×
436
      taos_stop_query(pRequest);
×
437
      (void)releaseRequest(*rid);  // ignore error
×
438
    }
439

440
    pIter = taosHashIterate(pRequests, pIter);
×
441
  }
UNCOV
442
}
×
443

444
void destroyAppInst(void *info) {
1,625,871✔
445
  SAppInstInfo *pAppInfo = *(SAppInstInfo **)info;
1,625,871✔
446
  tscInfo("destroy app inst mgr %p", pAppInfo);
1,625,871✔
447

448
  int32_t code = taosThreadMutexLock(&appInfo.mutex);
1,625,871✔
449
  if (TSDB_CODE_SUCCESS != code) {
1,625,871✔
450
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
451
  }
452

453
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
1,625,871✔
454

455
  code = taosThreadMutexUnlock(&appInfo.mutex);
1,625,871✔
456
  if (TSDB_CODE_SUCCESS != code) {
1,625,871✔
457
    tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
458
  }
459

460
  taosMemoryFreeClear(pAppInfo->instKey);
1,625,871✔
461
  closeTransporter(pAppInfo);
1,625,871✔
462

463
  code = taosThreadMutexLock(&pAppInfo->qnodeMutex);
1,625,871✔
464
  if (TSDB_CODE_SUCCESS != code) {
1,625,871✔
465
    tscError("failed to lock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
466
  }
467

468
  taosArrayDestroy(pAppInfo->pQnodeList);
1,625,871✔
469
  code = taosThreadMutexUnlock(&pAppInfo->qnodeMutex);
1,625,871✔
470
  if (TSDB_CODE_SUCCESS != code) {
1,625,871✔
471
    tscError("failed to unlock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
472
  }
473

474
  taosMemoryFree(pAppInfo);
1,625,871✔
475
}
1,625,871✔
476

477
//  tscObj 1--->conn1
478
/// tscObj 2-->conn1
479
//  tscObj 3-->conn1
480

481
void destroyTscObj(void *pObj) {
87,236,508✔
482
  if (NULL == pObj) {
87,236,508✔
483
    return;
×
484
  }
485

486
  STscObj *pTscObj = pObj;
87,236,508✔
487
  int64_t  tscId = pTscObj->id;
87,236,508✔
488
  tscTrace("conn:%" PRIx64 ", begin destroy, p:%p", tscId, pTscObj);
87,236,535✔
489

490
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
87,236,535✔
491
  hbDeregisterConn(pTscObj, connKey);
87,236,508✔
492

493
  destroyAllRequests(pTscObj->pRequests);
87,238,087✔
494
  taosHashCleanup(pTscObj->pRequests);
87,238,006✔
495

496
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
87,237,899✔
497
  tscDebug("conn:0x%" PRIx64 ", p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
87,237,660✔
498
           pTscObj->pAppInfo->numOfConns);
499

500
  // In any cases, we should not free app inst here. Or an race condition rises.
501
  /*int64_t connNum = */ (void)atomic_sub_fetch_64(&pTscObj->pAppInfo->numOfConns, 1);
87,237,660✔
502

503
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
87,237,930✔
504
  taosMemoryFree(pTscObj);
87,237,376✔
505

506
  tscTrace("conn:0x%" PRIx64 ", end destroy, p:%p", tscId, pTscObj);
87,237,639✔
507
}
508

509
int32_t createTscObj(const char *user, const char *auth, const char *db, int32_t connType, SAppInstInfo *pAppInfo,
87,427,743✔
510
                     STscObj **pObj) {
511
  *pObj = (STscObj *)taosMemoryCalloc(1, sizeof(STscObj));
87,427,743✔
512
  if (NULL == *pObj) {
87,425,627✔
513
    return terrno;
×
514
  }
515

516
  (*pObj)->pRequests = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
87,425,627✔
517
  if (NULL == (*pObj)->pRequests) {
87,427,116✔
518
    taosMemoryFree(*pObj);
×
519
    return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
520
  }
521

522
  (*pObj)->connType = connType;
87,427,116✔
523
  (*pObj)->pAppInfo = pAppInfo;
87,427,116✔
524
  (*pObj)->appHbMgrIdx = pAppInfo->pAppHbMgr->idx;
87,427,493✔
525
  if (user == NULL) {
87,427,493✔
526
    (*pObj)->user[0] = 0;
2,448✔
527
    (*pObj)->pass[0] = 0;
2,448✔
528
    tstrncpy((*pObj)->token, auth, sizeof((*pObj)->token));
2,448✔
529
  } else {
530
    tstrncpy((*pObj)->user, user, sizeof((*pObj)->user));
87,425,045✔
531
    (void)memcpy((*pObj)->pass, auth, TSDB_PASSWORD_LEN);
87,425,045✔
532
  }
533
  (*pObj)->tokenName[0] = 0;
87,427,493✔
534
  (*pObj)->enable = 1;  // enabled by default
87,427,493✔
535

536
  if (db != NULL) {
87,427,493✔
537
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
87,428,671✔
538
  }
539

540
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
87,427,493✔
541

542
  int32_t code = TSDB_CODE_SUCCESS;
87,428,838✔
543

544
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
87,428,838✔
545
  if ((*pObj)->id < 0) {
87,428,005✔
546
    tscError("failed to add object to clientConnRefPool");
×
547
    code = terrno;
×
548
    taosMemoryFree(*pObj);
×
549
    return code;
×
550
  }
551

552
  (void)atomic_add_fetch_64(&(*pObj)->pAppInfo->numOfConns, 1);
87,427,754✔
553

554
  updateConnAccessInfo(&(*pObj)->sessInfo);
87,428,450✔
555
  tscInfo("conn:0x%" PRIx64 ", created, p:%p", (*pObj)->id, *pObj);
87,428,504✔
556
  return code;
87,428,690✔
557
}
558

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

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

568
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
1,219,542,662✔
569
  int32_t code = TSDB_CODE_SUCCESS;
1,219,542,662✔
570
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
1,219,542,662✔
571
  if (NULL == *pRequest) {
1,219,526,022✔
572
    return terrno;
×
573
  }
574

575
  STscObj *pTscObj = acquireTscObj(connId);
1,219,530,494✔
576
  if (pTscObj == NULL) {
1,219,611,390✔
577
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
578
  }
579
  if (pTscObj->enable == 0) {
1,219,611,390✔
580
    releaseTscObj(connId);
1,120✔
581
    TSC_ERR_JRET(TSDB_CODE_MND_USER_DISABLED);
1,120✔
582
  }
583
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
1,219,596,104✔
584
  if (interParam == NULL) {
1,219,591,178✔
585
    releaseTscObj(connId);
×
586
    TSC_ERR_JRET(terrno);
×
587
  }
588
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
1,219,591,178✔
589
  interParam->pRequest = *pRequest;
1,219,571,517✔
590
  (*pRequest)->body.interParam = interParam;
1,219,583,416✔
591

592
  (*pRequest)->resType = RES_TYPE__QUERY;
1,219,582,659✔
593
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
1,219,582,920✔
594
  (*pRequest)->metric.start = taosGetTimestampUs();
2,147,483,647✔
595
  (*pRequest)->execPhase = QUERY_PHASE_NONE;
1,219,591,638✔
596
  (*pRequest)->phaseStartTime = 0;
1,219,585,549✔
597

598
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
1,219,579,127✔
599
  (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt;
1,219,579,354✔
600
  (*pRequest)->type = type;
1,219,585,354✔
601
  (*pRequest)->allocatorRefId = -1;
1,219,591,761✔
602

603
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
1,219,594,375✔
604
  if (NULL == (*pRequest)->pDb) {
1,219,574,027✔
605
    TSC_ERR_JRET(terrno);
282,650,791✔
606
  }
607
  (*pRequest)->pTscObj = pTscObj;
1,219,565,412✔
608
  (*pRequest)->inCallback = false;
1,219,589,532✔
609
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
1,219,574,232✔
610
  if (NULL == (*pRequest)->msgBuf) {
1,219,506,375✔
611
    code = terrno;
×
612
    goto _return;
×
613
  }
614
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
1,219,533,696✔
615
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
1,219,548,196✔
616
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
1,219,551,111✔
617

618
  return TSDB_CODE_SUCCESS;
1,219,550,540✔
619
_return:
1,126✔
620
  if ((*pRequest)->pTscObj) {
1,126✔
621
    doDestroyRequest(*pRequest);
6✔
622
  } else {
623
    taosMemoryFree(*pRequest);
1,120✔
624
  }
625
  return code;
1,126✔
626
}
627

628
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
1,344,656,790✔
629
  taosMemoryFreeClear(pResInfo->pRspMsg);
1,344,656,790✔
630
  taosMemoryFreeClear(pResInfo->length);
1,344,680,520✔
631
  taosMemoryFreeClear(pResInfo->row);
1,344,659,655✔
632
  taosMemoryFreeClear(pResInfo->pCol);
1,344,666,107✔
633
  taosMemoryFreeClear(pResInfo->fields);
1,344,647,735✔
634
  taosMemoryFreeClear(pResInfo->userFields);
1,344,663,569✔
635
  taosMemoryFreeClear(pResInfo->convertJson);
1,344,661,073✔
636
  taosMemoryFreeClear(pResInfo->decompBuf);
1,344,669,582✔
637

638
  if (pResInfo->convertBuf != NULL) {
1,344,646,584✔
639
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
1,156,464,379✔
640
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
947,778,594✔
641
    }
642
    taosMemoryFreeClear(pResInfo->convertBuf);
208,690,452✔
643
  }
644
}
1,344,664,280✔
645

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

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

650
int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }
1,219,381,653✔
651

652
/// return the most previous req ref id
653
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
1,219,377,081✔
654
  int64_t      mostPrevReqRefId = pRequest->self;
1,219,377,081✔
655
  SRequestObj *pTmp = pRequest;
1,219,395,806✔
656
  while (pTmp->relation.prevRefId) {
1,219,395,806✔
657
    pTmp = acquireRequest(pTmp->relation.prevRefId);
×
658
    if (pTmp) {
×
659
      mostPrevReqRefId = pTmp->self;
×
660
      (void)releaseRequest(mostPrevReqRefId);  // ignore error
×
661
    } else {
662
      break;
×
663
    }
664
  }
665
  (void)removeRequest(mostPrevReqRefId);  // ignore error
1,219,392,030✔
666
  return mostPrevReqRefId;
1,219,414,255✔
667
}
668

669
void destroyNextReq(int64_t nextRefId) {
1,219,380,447✔
670
  if (nextRefId) {
1,219,380,447✔
671
    SRequestObj *pObj = acquireRequest(nextRefId);
×
672
    if (pObj) {
×
673
      (void)releaseRequest(nextRefId);  // ignore error
×
674
      (void)releaseRequest(nextRefId);  // ignore error
×
675
    }
676
  }
677
}
1,219,380,447✔
678

679
void destroySubRequests(SRequestObj *pRequest) {
×
680
  int32_t      reqIdx = -1;
×
681
  SRequestObj *pReqList[16] = {NULL};
×
682
  uint64_t     tmpRefId = 0;
×
683

684
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
×
685
    return;
×
686
  }
687

688
  SRequestObj *pTmp = pRequest;
×
689
  while (pTmp->relation.prevRefId) {
×
690
    tmpRefId = pTmp->relation.prevRefId;
×
691
    pTmp = acquireRequest(tmpRefId);
×
692
    if (pTmp) {
×
693
      pReqList[++reqIdx] = pTmp;
×
694
      (void)releaseRequest(tmpRefId);  // ignore error
×
695
    } else {
696
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
697
      break;
×
698
    }
699
  }
700

701
  for (int32_t i = reqIdx; i >= 0; i--) {
×
702
    (void)removeRequest(pReqList[i]->self);  // ignore error
×
703
  }
704

705
  tmpRefId = pRequest->relation.nextRefId;
×
706
  while (tmpRefId) {
×
707
    pTmp = acquireRequest(tmpRefId);
×
708
    if (pTmp) {
×
709
      tmpRefId = pTmp->relation.nextRefId;
×
710
      (void)removeRequest(pTmp->self);   // ignore error
×
711
      (void)releaseRequest(pTmp->self);  // ignore error
×
712
    } else {
713
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
714
      break;
×
715
    }
716
  }
717
}
718

719
void doDestroyRequest(void *p) {
1,219,393,137✔
720
  if (NULL == p) {
1,219,393,137✔
721
    return;
×
722
  }
723

724
  SRequestObj *pRequest = (SRequestObj *)p;
1,219,393,137✔
725

726
  uint64_t reqId = pRequest->requestId;
1,219,393,137✔
727
  tscTrace("QID:0x%" PRIx64 ", begin destroy request, res:%p", reqId, pRequest);
1,219,411,614✔
728

729
  int64_t nextReqRefId = pRequest->relation.nextRefId;
1,219,411,614✔
730

731
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
1,219,404,249✔
732
  if (TSDB_CODE_SUCCESS != code) {
1,219,420,758✔
733
    tscDebug("failed to remove request from hash since %s", tstrerror(code));
87,428,477✔
734
  }
735
  schedulerFreeJob(&pRequest->body.queryJob, 0);
1,219,420,758✔
736

737
  destorySqlCallbackWrapper(pRequest->pWrapper);
1,219,415,893✔
738

739
  taosMemoryFreeClear(pRequest->msgBuf);
1,219,375,021✔
740

741
  doFreeReqResultInfo(&pRequest->body.resInfo);
1,219,377,203✔
742
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
1,219,354,230✔
743
    tscError("failed to destroy semaphore");
×
744
  }
745

746
  SSessParam para = {.type = SESSION_MAX_CONCURRENCY, .value = -1, .noCheck = 1};
1,219,396,733✔
747
  code = tscUpdateSessMetric(pRequest->pTscObj, &para);
1,219,360,374✔
748
  if (TSDB_CODE_SUCCESS != code) {
1,219,409,088✔
749
    tscError("failed to update session metric, code:%s", tstrerror(code));
×
750
  }
751

752
  taosArrayDestroy(pRequest->tableList);
1,219,409,088✔
753
  taosArrayDestroy(pRequest->targetTableList);
1,219,366,631✔
754
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
1,219,396,378✔
755

756
  if (pRequest->self) {
1,219,353,668✔
757
    deregisterRequest(pRequest);
1,219,402,158✔
758
  }
759

760
  taosMemoryFreeClear(pRequest->pDb);
1,219,402,085✔
761
  taosArrayDestroy(pRequest->dbList);
1,219,338,511✔
762
  if (pRequest->body.interParam) {
1,219,378,829✔
763
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
1,219,393,332✔
764
      tscError("failed to destroy semaphore in pRequest");
×
765
    }
766
  }
767
  taosMemoryFree(pRequest->body.interParam);
1,219,397,282✔
768

769
  qDestroyQuery(pRequest->pQuery);
1,219,386,300✔
770

771
  // `pRequest->parseMeta` may be filled during stmt parsing and must be released
772
  // when the request object is destroyed, otherwise LeakSanitizer will report
773
  // catalog async response result leaks.
774
  catalogFreeMetaData(&pRequest->parseMeta);
1,219,379,996✔
775
  TAOS_MEMSET(&pRequest->parseMeta, 0, sizeof(pRequest->parseMeta));
1,219,390,900✔
776
  nodesDestroyAllocator(pRequest->allocatorRefId);
1,219,384,834✔
777

778
  taosMemoryFreeClear(pRequest->effectiveUser);
1,219,358,251✔
779
  taosMemoryFreeClear(pRequest->sqlstr);
1,219,363,923✔
780
  taosMemoryFree(pRequest);
1,219,351,945✔
781
  tscTrace("QID:0x%" PRIx64 ", end destroy request, res:%p", reqId, pRequest);
1,219,380,534✔
782
  destroyNextReq(nextReqRefId);
1,219,380,534✔
783
}
784

785
void destroyRequest(SRequestObj *pRequest) {
1,219,384,224✔
786
  if (pRequest == NULL) return;
1,219,384,224✔
787

788
  taos_stop_query(pRequest);
1,219,384,224✔
789
  (void)removeFromMostPrevReq(pRequest);
1,219,405,790✔
790
}
791

792
void taosStopQueryImpl(SRequestObj *pRequest) {
1,219,385,353✔
793
  pRequest->killed = true;
1,219,385,353✔
794

795
  // It is not a query, no need to stop.
796
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
1,219,407,393✔
797
    tscDebug("QID:0x%" PRIx64 ", no need to be killed since not query", pRequest->requestId);
294,058,561✔
798
    return;
294,087,078✔
799
  }
800

801
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
925,326,721✔
802
  tscDebug("QID:0x%" PRIx64 ", killed", pRequest->requestId);
925,324,603✔
803
}
804

805
void stopAllQueries(SRequestObj *pRequest) {
1,219,383,880✔
806
  int32_t      reqIdx = -1;
1,219,383,880✔
807
  SRequestObj *pReqList[16] = {NULL};
1,219,383,880✔
808
  uint64_t     tmpRefId = 0;
1,219,393,043✔
809

810
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
1,219,393,043✔
811
    return;
×
812
  }
813

814
  SRequestObj *pTmp = pRequest;
1,219,399,612✔
815
  while (pTmp->relation.prevRefId) {
1,219,399,612✔
816
    tmpRefId = pTmp->relation.prevRefId;
×
817
    pTmp = acquireRequest(tmpRefId);
×
818
    if (pTmp) {
×
819
      pReqList[++reqIdx] = pTmp;
×
820
    } else {
821
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
822
      break;
×
823
    }
824
  }
825

826
  for (int32_t i = reqIdx; i >= 0; i--) {
1,219,393,424✔
827
    taosStopQueryImpl(pReqList[i]);
×
828
    (void)releaseRequest(pReqList[i]->self);  // ignore error
×
829
  }
830

831
  taosStopQueryImpl(pRequest);
1,219,393,424✔
832

833
  tmpRefId = pRequest->relation.nextRefId;
1,219,413,726✔
834
  while (tmpRefId) {
1,219,394,098✔
835
    pTmp = acquireRequest(tmpRefId);
×
836
    if (pTmp) {
×
837
      tmpRefId = pTmp->relation.nextRefId;
×
838
      taosStopQueryImpl(pTmp);
×
839
      (void)releaseRequest(pTmp->self);  // ignore error
×
840
    } else {
841
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
842
      break;
×
843
    }
844
  }
845
}
846
#ifdef USE_REPORT
847
void crashReportThreadFuncUnexpectedStopped(void) { atomic_store_32(&clientStop, -1); }
×
848

849
static void *tscCrashReportThreadFp(void *param) {
×
850
  int32_t code = 0;
×
851
  setThreadName("client-crashReport");
×
852
  char filepath[PATH_MAX] = {0};
×
853
  (void)snprintf(filepath, sizeof(filepath), "%s%s.taosCrashLog", tsLogDir, TD_DIRSEP);
×
854
  char     *pMsg = NULL;
×
855
  int64_t   msgLen = 0;
×
856
  TdFilePtr pFile = NULL;
×
857
  bool      truncateFile = false;
×
858
  int32_t   sleepTime = 200;
×
859
  int32_t   reportPeriodNum = 3600 * 1000 / sleepTime;
×
860
  int32_t   loopTimes = reportPeriodNum;
×
861

862
#ifdef WINDOWS
863
  if (taosCheckCurrentInDll()) {
864
    atexit(crashReportThreadFuncUnexpectedStopped);
865
  }
866
#endif
867

868
  if (-1 != atomic_val_compare_exchange_32(&clientStop, -1, 0)) {
×
869
    return NULL;
×
870
  }
871
  STelemAddrMgmt mgt;
×
872
  code = taosTelemetryMgtInit(&mgt, tsTelemServer);
×
873
  if (code) {
×
874
    tscError("failed to init telemetry management, code:%s", tstrerror(code));
×
875
    return NULL;
×
876
  }
877

878
  code = initCrashLogWriter();
×
879
  if (code) {
×
880
    tscError("failed to init crash log writer, code:%s", tstrerror(code));
×
881
    return NULL;
×
882
  }
883

884
  while (1) {
885
    checkAndPrepareCrashInfo();
×
886
    if (clientStop > 0 && reportThreadSetQuit()) break;
×
887
    if (loopTimes++ < reportPeriodNum) {
×
888
      if (loopTimes < 0) loopTimes = reportPeriodNum;
×
889
      taosMsleep(sleepTime);
×
890
      continue;
×
891
    }
892

893
    taosReadCrashInfo(filepath, &pMsg, &msgLen, &pFile);
×
894
    if (pMsg && msgLen > 0) {
×
895
      if (taosSendTelemReport(&mgt, tsClientCrashReportUri, tsTelemPort, pMsg, msgLen, HTTP_FLAT) != 0) {
×
896
        tscError("failed to send crash report");
×
897
        if (pFile) {
×
898
          taosReleaseCrashLogFile(pFile, false);
×
899
          pFile = NULL;
×
900

901
          taosMsleep(sleepTime);
×
902
          loopTimes = 0;
×
903
          continue;
×
904
        }
905
      } else {
906
        tscInfo("succeed to send crash report");
×
907
        truncateFile = true;
×
908
      }
909
    } else {
910
      tscInfo("no crash info was found");
×
911
    }
912

913
    taosMemoryFree(pMsg);
×
914

915
    if (pMsg && msgLen > 0) {
×
916
      pMsg = NULL;
×
917
      continue;
×
918
    }
919

920
    if (pFile) {
×
921
      taosReleaseCrashLogFile(pFile, truncateFile);
×
922
      pFile = NULL;
×
923
      truncateFile = false;
×
924
    }
925

926
    taosMsleep(sleepTime);
×
927
    loopTimes = 0;
×
928
  }
929
  taosTelemetryDestroy(&mgt);
×
930

931
  clientStop = -2;
×
932
  return NULL;
×
933
}
934

935
int32_t tscCrashReportInit() {
1,534,765✔
936
  if (!tsEnableCrashReport) {
1,534,765✔
937
    return TSDB_CODE_SUCCESS;
1,534,765✔
938
  }
939
  int32_t      code = TSDB_CODE_SUCCESS;
×
940
  TdThreadAttr thAttr;
×
941
  TSC_ERR_JRET(taosThreadAttrInit(&thAttr));
×
942
  TSC_ERR_JRET(taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE));
×
943
  TdThread crashReportThread;
×
944
  if (taosThreadCreate(&crashReportThread, &thAttr, tscCrashReportThreadFp, NULL) != 0) {
×
945
    tscError("failed to create crashReport thread since %s", strerror(ERRNO));
×
946
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
947
    TSC_ERR_RET(terrno);
×
948
  }
949

950
  (void)taosThreadAttrDestroy(&thAttr);
×
951
_return:
×
952
  if (code) {
×
953
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
954
    TSC_ERR_RET(terrno);
×
955
  }
956

957
  return code;
×
958
}
959

960
void tscStopCrashReport() {
1,534,804✔
961
  if (!tsEnableCrashReport) {
1,534,804✔
962
    return;
1,534,804✔
963
  }
964

965
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
966
    tscDebug("crash report thread already stopped");
×
967
    return;
×
968
  }
969

970
  while (atomic_load_32(&clientStop) > 0) {
×
971
    taosMsleep(100);
×
972
  }
973
}
974

975
void taos_write_crashinfo(int signum, void *sigInfo, void *context) {
×
976
  writeCrashLogToFile(signum, sigInfo, CUS_PROMPT, lastClusterId, appInfo.startTime);
×
977
}
×
978
#endif
979

980
#ifdef TAOSD_INTEGRATED
981
typedef struct {
982
  TdThread pid;
983
  int32_t  stat;  // < 0: start failed, 0: init(not start), 1: start successfully
984
} SDaemonObj;
985

986
extern int  dmStartDaemon(int argc, char const *argv[]);
987
extern void dmStopDaemon();
988

989
SDaemonObj daemonObj = {0};
990

991
typedef struct {
992
  int32_t argc;
993
  char  **argv;
994
} SExecArgs;
995

996
static void *dmStartDaemonFunc(void *param) {
997
  int32_t    code = 0;
998
  SExecArgs *pArgs = (SExecArgs *)param;
999
  int32_t    argc = pArgs->argc;
1000
  char     **argv = pArgs->argv;
1001

1002
  code = dmStartDaemon(argc, (const char **)argv);
1003
  if (code != 0) {
1004
    printf("failed to start taosd since %s\r\n", tstrerror(code));
1005
    goto _exit;
1006
  }
1007

1008
_exit:
1009
  if (code != 0) {
1010
    atomic_store_32(&daemonObj.stat, code);
1011
  }
1012
  return NULL;
1013
}
1014

1015
static int32_t shellStartDaemon(int argc, char *argv[]) {
1016
  int32_t    code = 0, lino = 0;
1017
  SExecArgs *pArgs = NULL;
1018
  int64_t    startMs = taosGetTimestampMs(), endMs = startMs;
1019

1020
  TdThreadAttr thAttr;
1021
  (void)taosThreadAttrInit(&thAttr);
1022
  (void)taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
1023
#ifdef TD_COMPACT_OS
1024
  (void)taosThreadAttrSetStackSize(&thAttr, STACK_SIZE_SMALL);
1025
#endif
1026
  pArgs = (SExecArgs *)taosMemoryCalloc(1, sizeof(SExecArgs));
1027
  if (pArgs == NULL) {
1028
    code = terrno;
1029
    TAOS_CHECK_EXIT(code);
1030
  }
1031
  pArgs->argc = argc;
1032
  pArgs->argv = argv;
1033

1034
#ifndef TD_AS_LIB
1035
  tsLogEmbedded = 1;
1036
#endif
1037

1038
  TAOS_CHECK_EXIT(taosThreadCreate(&daemonObj.pid, &thAttr, dmStartDaemonFunc, pArgs));
1039

1040
  while (true) {
1041
    if (atomic_load_64(&tsDndStart)) {
1042
      atomic_store_32(&daemonObj.stat, 1);
1043
      break;
1044
    }
1045
    int32_t daemonstat = atomic_load_32(&daemonObj.stat);
1046
    if (daemonstat < 0) {
1047
      code = daemonstat;
1048
      TAOS_CHECK_EXIT(code);
1049
    }
1050

1051
    if (daemonstat > 1) {
1052
      code = TSDB_CODE_APP_ERROR;
1053
      TAOS_CHECK_EXIT(code);
1054
    }
1055
    taosMsleep(1000);
1056
  }
1057

1058
_exit:
1059
  endMs = taosGetTimestampMs();
1060
  (void)taosThreadAttrDestroy(&thAttr);
1061
  taosMemoryFreeClear(pArgs);
1062
  if (code) {
1063
    printf("\r\n The daemon start failed at line %d since %s, cost %" PRIi64 " ms\r\n", lino, tstrerror(code),
1064
           endMs - startMs);
1065
  } else {
1066
    printf("\r\n The daemon started successfully, cost %" PRIi64 " ms\r\n", endMs - startMs);
1067
  }
1068
#ifndef TD_AS_LIB
1069
  tsLogEmbedded = 0;
1070
#endif
1071
  return code;
1072
}
1073

1074
void shellStopDaemon() {
1075
#ifndef TD_AS_LIB
1076
  tsLogEmbedded = 1;
1077
#endif
1078
  dmStopDaemon();
1079
  if (taosCheckPthreadValid(daemonObj.pid)) {
1080
    (void)taosThreadJoin(daemonObj.pid, NULL);
1081
    taosThreadClear(&daemonObj.pid);
1082
  }
1083
}
1084
#endif
1085

1086
void taos_init_imp(void) {
1,534,804✔
1087
#if defined(LINUX)
1088
  if (tscDbg.memEnable) {
1,534,804✔
1089
    int32_t code = taosMemoryDbgInit();
×
1090
    if (code) {
×
1091
      (void)printf("failed to init memory dbg, error:%s\n", tstrerror(code));
×
1092
    } else {
1093
      tsAsyncLog = false;
×
1094
      (void)printf("memory dbg enabled\n");
×
1095
    }
1096
  }
1097
#endif
1098

1099
  // In the APIs of other program language, taos_cleanup is not available yet.
1100
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
1101
  (void)atexit(taos_cleanup);
1,534,804✔
1102
  SET_ERRNO(TSDB_CODE_SUCCESS);
1,534,804✔
1103
  terrno = TSDB_CODE_SUCCESS;
1,534,804✔
1104
  taosSeedRand(taosGetTimestampSec());
1,534,804✔
1105

1106
  appInfo.pid = taosGetPId();
1,534,804✔
1107
  appInfo.startTime = taosGetTimestampMs();
1,534,804✔
1108
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
1,534,804✔
1109
  appInfo.pInstMapByClusterId =
1,534,804✔
1110
      taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);
1,534,804✔
1111
  if (NULL == appInfo.pInstMap || NULL == appInfo.pInstMapByClusterId) {
1,534,804✔
1112
    (void)printf("failed to allocate memory when init appInfo\n");
×
1113
    tscInitRes = terrno;
×
1114
    return;
×
1115
  }
1116
  taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst);
1,534,804✔
1117

1118
  const char *logName = CUS_PROMPT "log";
1,534,804✔
1119
  ENV_ERR_RET(taosInitLogOutput(&logName), "failed to init log output");
1,534,804✔
1120
  if (taosCreateLog(logName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
1,534,804✔
1121
    (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logName, strerror(ERRNO), configDir);
39✔
1122
    SET_ERROR_MSG("Create %s failed:%s. configDir=%s", logName, strerror(ERRNO), configDir);
39✔
1123
    tscInitRes = terrno;
39✔
1124
    return;
39✔
1125
  }
1126

1127
#ifdef TAOSD_INTEGRATED
1128
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0), "failed to init cfg");
1129
#else
1130
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
1,534,765✔
1131
#endif
1132

1133
  initQueryModuleMsgHandle();
1,534,765✔
1134
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
1135
  if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL) {
1,534,765✔
1136
    tscInitRes = terrno;
×
1137
    tscError("failed to init conv");
×
1138
    return;
×
1139
  }
1140
#endif
1141
#if !defined(TD_ASTRA)
1142
  ENV_ERR_RET(tzInit(), "failed to init timezone");
1,534,765✔
1143
#endif
1144
  ENV_ERR_RET(monitorInit(), "failed to init monitor");
1,534,765✔
1145
  ENV_ERR_RET(rpcInit(), "failed to init rpc");
1,534,765✔
1146

1147
  if (InitRegexCache() != 0) {
1,534,765✔
1148
    tscInitRes = terrno;
×
1149
    (void)printf("failed to init regex cache\n");
×
1150
    return;
×
1151
  }
1152

1153
  tscInfo("starting to initialize TAOS driver");
1,534,765✔
1154

1155
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
1,534,765✔
1156
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
1,534,765✔
1157
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
1,534,765✔
1158
  ENV_ERR_RET(initClientId(), "failed to init clientId");
1,534,765✔
1159

1160
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
1,534,765✔
1161
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
1,534,765✔
1162
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
1,534,765✔
1163

1164
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
1,534,765✔
1165
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
1,534,765✔
1166

1167
  ENV_ERR_RET(taosGetAppName(appInfo.appName, NULL), "failed to get app name");
1,534,765✔
1168
  ENV_ERR_RET(taosThreadMutexInit(&appInfo.mutex, NULL), "failed to init thread mutex");
1,534,765✔
1169
#ifdef USE_REPORT
1170
  ENV_ERR_RET(tscCrashReportInit(), "failed to init crash report");
1,534,765✔
1171
#endif
1172
  ENV_ERR_RET(qInitKeywordsTable(), "failed to init parser keywords table");
1,534,765✔
1173
#ifdef TAOSD_INTEGRATED
1174
  ENV_ERR_RET(shellStartDaemon(0, NULL), "failed to start taosd daemon");
1175
#endif
1176

1177
  if (tsSessionControl) {
1,534,765✔
1178
    ENV_ERR_RET(sessMgtInit(), "failed to init session management");
1,534,765✔
1179
  }
1180

1181
  tscInfo("TAOS driver is initialized successfully");
1,534,765✔
1182
}
1183

1184
int taos_init() {
87,268,771✔
1185
  (void)taosThreadOnce(&tscinit, taos_init_imp);
87,268,771✔
1186
  return tscInitRes;
87,271,396✔
1187
}
1188

1189
const char *getCfgName(TSDB_OPTION option) {
4,151✔
1190
  const char *name = NULL;
4,151✔
1191

1192
  switch (option) {
4,151✔
1193
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
133✔
1194
      name = "shellActivityTimer";
133✔
1195
      break;
133✔
1196
    case TSDB_OPTION_LOCALE:
×
1197
      name = "locale";
×
1198
      break;
×
1199
    case TSDB_OPTION_CHARSET:
×
1200
      name = "charset";
×
1201
      break;
×
1202
    case TSDB_OPTION_TIMEZONE:
3,618✔
1203
      name = "timezone";
3,618✔
1204
      break;
3,618✔
1205
    case TSDB_OPTION_USE_ADAPTER:
100✔
1206
      name = "useAdapter";
100✔
1207
      break;
100✔
1208
    default:
300✔
1209
      break;
300✔
1210
  }
1211

1212
  return name;
4,151✔
1213
}
1214

1215
int taos_options_imp(TSDB_OPTION option, const char *str) {
85,067,074✔
1216
  if (option == TSDB_OPTION_CONFIGDIR) {
85,067,074✔
1217
#ifndef WINDOWS
1218
    char newstr[PATH_MAX];
691,806✔
1219
    int  len = strlen(str);
85,062,923✔
1220
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
85,062,923✔
1221
      if (len + 2 >= PATH_MAX) {
85,061,609✔
1222
        tscError("Too long path %s", str);
×
1223
        return -1;
×
1224
      }
1225
      newstr[0] = '"';
85,061,609✔
1226
      (void)memcpy(newstr + 1, str, len);
85,061,609✔
1227
      newstr[len + 1] = '"';
85,061,609✔
1228
      newstr[len + 2] = '\0';
85,061,609✔
1229
      str = newstr;
85,061,609✔
1230
    }
1231
#endif
1232
    tstrncpy(configDir, str, PATH_MAX);
85,062,923✔
1233
    tscInfo("set cfg:%s to %s", configDir, str);
85,062,923✔
1234
    return 0;
85,062,923✔
1235
  }
1236

1237
  // initialize global config
1238
  if (taos_init() != 0) {
4,151✔
1239
    return -1;
×
1240
  }
1241

1242
  SConfig     *pCfg = taosGetCfg();
4,151✔
1243
  SConfigItem *pItem = NULL;
4,151✔
1244
  const char  *name = getCfgName(option);
4,151✔
1245

1246
  if (name == NULL) {
4,151✔
1247
    tscError("Invalid option %d", option);
300✔
1248
    return -1;
300✔
1249
  }
1250

1251
  pItem = cfgGetItem(pCfg, name);
3,851✔
1252
  if (pItem == NULL) {
3,851✔
1253
    tscError("Invalid option %d", option);
×
1254
    return -1;
×
1255
  }
1256

1257
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
3,851✔
1258
  if (code != 0) {
3,851✔
1259
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
133✔
1260
  } else {
1261
    tscInfo("set cfg:%s to %s", name, str);
3,718✔
1262
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
3,718✔
1263
      code = taosCfgDynamicOptions(pCfg, name, false);
100✔
1264
    }
1265
  }
1266

1267
  return code;
3,851✔
1268
}
1269

1270
/**
1271
 * The request id is an unsigned integer format of 64bit.
1272
 *+------------+-----+-----------+---------------+
1273
 *| uid|localIp| PId | timestamp | serial number |
1274
 *+------------+-----+-----------+---------------+
1275
 *| 12bit      |12bit|24bit      |16bit          |
1276
 *+------------+-----+-----------+---------------+
1277
 * @return
1278
 */
1279
uint64_t generateRequestId() {
1,602,444,753✔
1280
  static uint32_t hashId = 0;
1281
  static int32_t  requestSerialId = 0;
1282

1283
  if (hashId == 0) {
1,602,444,753✔
1284
    int32_t code = taosGetSystemUUIDU32(&hashId);
1,533,267✔
1285
    if (code != TSDB_CODE_SUCCESS) {
1,533,267✔
1286
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1287
               tstrerror(code));
1288
    }
1289
  }
1290

1291
  uint64_t id = 0;
1,602,441,989✔
1292

1293
  while (true) {
×
1294
    int64_t  ts = taosGetTimestampMs();
1,602,481,881✔
1295
    uint64_t pid = taosGetPId();
1,602,481,881✔
1296
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
1,602,426,511✔
1297
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
1,602,495,482✔
1298

1299
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
1,602,504,005✔
1300
    if (id) {
1,602,504,005✔
1301
      break;
1,602,504,005✔
1302
    }
1303
  }
1304
  return id;
1,602,504,005✔
1305
}
1306

1307
#if 0
1308
#include "cJSON.h"
1309
static setConfRet taos_set_config_imp(const char *config){
1310
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
1311
  static bool setConfFlag = false;
1312
  if (setConfFlag) {
1313
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
1314
    tstrncpy(ret.retMsg, "configuration can only set once", RET_MSG_LENGTH);
1315
    return ret;
1316
  }
1317
  taosInitGlobalCfg();
1318
  cJSON *root = cJSON_Parse(config);
1319
  if (root == NULL){
1320
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
1321
    tstrncpy(ret.retMsg, "parse json error", RET_MSG_LENGTH);
1322
    return ret;
1323
  }
1324

1325
  int size = cJSON_GetArraySize(root);
1326
  if(!cJSON_IsObject(root) || size == 0) {
1327
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
1328
    tstrncpy(ret.retMsg, "json content is invalid, must be not empty object", RET_MSG_LENGTH);
1329
    return ret;
1330
  }
1331

1332
  if(size >= 1000) {
1333
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
1334
    tstrncpy(ret.retMsg, "json object size is too long", RET_MSG_LENGTH);
1335
    return ret;
1336
  }
1337

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

1364
setConfRet taos_set_config(const char *config){
1365
  taosThreadMutexLock(&setConfMutex);
1366
  setConfRet ret = taos_set_config_imp(config);
1367
  taosThreadMutexUnlock(&setConfMutex);
1368
  return ret;
1369
}
1370
#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