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

taosdata / TDengine / #4908

30 Dec 2025 10:52AM UTC coverage: 65.386% (-0.2%) from 65.541%
#4908

push

travis-ci

web-flow
enh: drop multi-stream (#33962)

60 of 106 new or added lines in 4 files covered. (56.6%)

1330 existing lines in 113 files now uncovered.

193461 of 295877 relevant lines covered (65.39%)

115765274.47 hits per line

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

55.4
/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) {
727,873,965✔
79
  int32_t code = TSDB_CODE_SUCCESS;
727,873,965✔
80
  // connection has been released already, abort creating request.
81
  pRequest->self = taosAddRef(clientReqRefPool, pRequest);
727,873,965✔
82
  if (pRequest->self < 0) {
727,880,096✔
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);
727,875,113✔
89

90
  if (pTscObj->pAppInfo) {
727,879,943✔
91
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
727,878,972✔
92

93
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
727,878,542✔
94
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
727,881,199✔
95
    tscDebug("req:0x%" PRIx64 ", create request from conn:0x%" PRIx64
727,881,572✔
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;
727,879,637✔
101
}
102

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

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

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

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

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

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

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

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

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

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

249
  STscObj            *pTscObj = pRequest->pTscObj;
727,726,577✔
250
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
727,728,761✔
251

252
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
727,730,320✔
253
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
727,728,604✔
254
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
727,729,228✔
255

256
  int64_t duration = taosGetTimestampUs() - pRequest->metric.start;
727,730,930✔
257
  tscDebug("req:0x%" PRIx64 ", free from conn:0x%" PRIx64 ", QID:0x%" PRIx64
727,731,110✔
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)) {
727,731,110✔
262
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
727,728,360✔
263
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
536,874,913✔
264
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
252,401,503✔
265
      tscDebug("req:0x%" PRIx64 ", insert duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
540,055,832✔
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);
540,055,832✔
271
      reqType = SLOW_LOG_TYPE_INSERT;
540,060,253✔
272
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
187,669,756✔
273
      tscDebug("req:0x%" PRIx64 ", query duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
139,091,108✔
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);
139,091,108✔
280
      reqType = SLOW_LOG_TYPE_QUERY;
139,091,194✔
281
    }
282

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

288
#ifdef USE_REPORT
289
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
727,730,736✔
290
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
137,110✔
291
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
131,290✔
292
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
5,820✔
293
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
1,740✔
294
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
4,080✔
295
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
×
296
    }
297
  }
298

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

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

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

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

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

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

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

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

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

408
  return code;
1,174,477✔
409
}
410

411
void destroyAllRequests(SHashObj *pRequests) {
1,810,553✔
412
  void *pIter = taosHashIterate(pRequests, NULL);
1,810,553✔
413
  while (pIter != NULL) {
1,810,553✔
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
}
1,810,553✔
425

426
void stopAllRequests(SHashObj *pRequests) {
133✔
427
  void *pIter = taosHashIterate(pRequests, NULL);
133✔
428
  while (pIter != NULL) {
133✔
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
}
133✔
440

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

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

450
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
1,174,477✔
451

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

457
  taosMemoryFreeClear(pAppInfo->instKey);
1,174,477✔
458
  closeTransporter(pAppInfo);
1,174,477✔
459

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

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

471
  taosMemoryFree(pAppInfo);
1,174,477✔
472
}
1,174,477✔
473

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

478
void destroyTscObj(void *pObj) {
1,809,789✔
479
  if (NULL == pObj) {
1,809,789✔
480
    return;
×
481
  }
482

483
  STscObj *pTscObj = pObj;
1,809,789✔
484
  int64_t  tscId = pTscObj->id;
1,809,789✔
485
  tscTrace("conn:%" PRIx64 ", begin destroy, p:%p", tscId, pTscObj);
1,810,516✔
486

487
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
1,810,516✔
488
  hbDeregisterConn(pTscObj, connKey);
1,810,516✔
489

490
  destroyAllRequests(pTscObj->pRequests);
1,810,553✔
491
  taosHashCleanup(pTscObj->pRequests);
1,810,553✔
492

493
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
1,810,553✔
494
  tscDebug("conn:0x%" PRIx64 ", p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
1,810,553✔
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);
1,810,553✔
499

500
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
1,810,553✔
501
  taosMemoryFree(pTscObj);
1,810,553✔
502

503
  tscTrace("conn:0x%" PRIx64 ", end destroy, p:%p", tscId, pTscObj);
1,810,553✔
504
}
505

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

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

519
  (*pObj)->connType = connType;
1,971,484✔
520
  (*pObj)->pAppInfo = pAppInfo;
1,971,484✔
521
  (*pObj)->appHbMgrIdx = pAppInfo->pAppHbMgr->idx;
1,971,484✔
522
  if (user == NULL) {
1,971,290✔
523
    (*pObj)->user[0] = 0;
26✔
524
    (*pObj)->pass[0] = 0;
26✔
525
    tstrncpy((*pObj)->token, auth, sizeof((*pObj)->token));
26✔
526
  } else {
527
    tstrncpy((*pObj)->user, user, sizeof((*pObj)->user));
1,971,264✔
528
    (void)memcpy((*pObj)->pass, auth, TSDB_PASSWORD_LEN);
1,971,458✔
529
  }
530
  (*pObj)->tokenName[0] = 0;
1,971,290✔
531

532
  if (db != NULL) {
1,971,484✔
533
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
1,971,290✔
534
  }
535

536
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
1,971,678✔
537

538
  int32_t code = TSDB_CODE_SUCCESS;
1,970,779✔
539

540
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
1,970,779✔
541
  if ((*pObj)->id < 0) {
1,971,484✔
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);
1,971,290✔
549

550
  updateConnAccessInfo(&(*pObj)->sessInfo);
1,971,484✔
551
  tscInfo("conn:0x%" PRIx64 ", created, p:%p", (*pObj)->id, *pObj);
1,971,447✔
552
  return code;
1,971,484✔
553
}
554

555
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
1,526,397,297✔
556

557
void releaseTscObj(int64_t rid) {
1,524,198,683✔
558
  int32_t code = taosReleaseRef(clientConnRefPool, rid);
1,524,198,683✔
559
  if (TSDB_CODE_SUCCESS != code) {
1,524,207,049✔
560
    tscWarn("failed to release TscObj, code:%s", tstrerror(code));
×
561
  }
562
}
1,524,207,049✔
563

564
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
727,874,386✔
565
  int32_t code = TSDB_CODE_SUCCESS;
727,874,386✔
566
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
727,874,386✔
567
  if (NULL == *pRequest) {
727,872,494✔
568
    return terrno;
×
569
  }
570

571
  STscObj *pTscObj = acquireTscObj(connId);
727,874,179✔
572
  if (pTscObj == NULL) {
727,881,143✔
573
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
574
  }
575
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
727,881,143✔
576
  if (interParam == NULL) {
727,874,171✔
577
    releaseTscObj(connId);
×
578
    TSC_ERR_JRET(terrno);
×
579
  }
580
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
727,874,171✔
581
  interParam->pRequest = *pRequest;
727,875,702✔
582
  (*pRequest)->body.interParam = interParam;
727,873,461✔
583

584
  (*pRequest)->resType = RES_TYPE__QUERY;
727,878,311✔
585
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
727,877,758✔
586
  (*pRequest)->metric.start = taosGetTimestampUs();
1,452,684,592✔
587

588
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
727,876,256✔
589
  (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt;
727,877,357✔
590
  (*pRequest)->type = type;
727,878,310✔
591
  (*pRequest)->allocatorRefId = -1;
727,878,447✔
592

593
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
727,879,860✔
594
  if (NULL == (*pRequest)->pDb) {
727,876,862✔
595
    TSC_ERR_JRET(terrno);
74,901,561✔
596
  }
597
  (*pRequest)->pTscObj = pTscObj;
727,877,489✔
598
  (*pRequest)->inCallback = false;
727,874,752✔
599
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
727,871,935✔
600
  if (NULL == (*pRequest)->msgBuf) {
727,873,606✔
601
    code = terrno;
×
602
    goto _return;
×
603
  }
604
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
727,875,798✔
605
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
727,876,529✔
606
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
727,874,582✔
607

608
  return TSDB_CODE_SUCCESS;
727,881,031✔
609
_return:
×
610
  if ((*pRequest)->pTscObj) {
×
611
    doDestroyRequest(*pRequest);
×
612
  } else {
613
    taosMemoryFree(*pRequest);
×
614
  }
615
  return code;
×
616
}
617

618
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
840,322,204✔
619
  taosMemoryFreeClear(pResInfo->pRspMsg);
840,322,204✔
620
  taosMemoryFreeClear(pResInfo->length);
840,334,760✔
621
  taosMemoryFreeClear(pResInfo->row);
840,330,811✔
622
  taosMemoryFreeClear(pResInfo->pCol);
840,327,324✔
623
  taosMemoryFreeClear(pResInfo->fields);
840,325,857✔
624
  taosMemoryFreeClear(pResInfo->userFields);
840,324,537✔
625
  taosMemoryFreeClear(pResInfo->convertJson);
840,323,100✔
626
  taosMemoryFreeClear(pResInfo->decompBuf);
840,322,967✔
627

628
  if (pResInfo->convertBuf != NULL) {
840,318,589✔
629
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
1,081,078,558✔
630
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
891,201,132✔
631
    }
632
    taosMemoryFreeClear(pResInfo->convertBuf);
189,882,551✔
633
  }
634
}
840,326,246✔
635

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

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

640
int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }
727,726,623✔
641

642
/// return the most previous req ref id
643
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
727,730,271✔
644
  int64_t      mostPrevReqRefId = pRequest->self;
727,730,271✔
645
  SRequestObj *pTmp = pRequest;
727,730,850✔
646
  while (pTmp->relation.prevRefId) {
727,730,850✔
647
    pTmp = acquireRequest(pTmp->relation.prevRefId);
×
648
    if (pTmp) {
×
649
      mostPrevReqRefId = pTmp->self;
×
650
      (void)releaseRequest(mostPrevReqRefId);  // ignore error
×
651
    } else {
652
      break;
×
653
    }
654
  }
655
  (void)removeRequest(mostPrevReqRefId);  // ignore error
727,731,085✔
656
  return mostPrevReqRefId;
727,731,062✔
657
}
658

659
void destroyNextReq(int64_t nextRefId) {
727,716,528✔
660
  if (nextRefId) {
727,716,528✔
661
    SRequestObj *pObj = acquireRequest(nextRefId);
×
662
    if (pObj) {
×
663
      (void)releaseRequest(nextRefId);  // ignore error
×
664
      (void)releaseRequest(nextRefId);  // ignore error
×
665
    }
666
  }
667
}
727,716,528✔
668

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

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

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

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

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

709
void doDestroyRequest(void *p) {
727,729,287✔
710
  if (NULL == p) {
727,729,287✔
711
    return;
×
712
  }
713

714
  SRequestObj *pRequest = (SRequestObj *)p;
727,729,287✔
715

716
  uint64_t reqId = pRequest->requestId;
727,729,287✔
717
  tscTrace("QID:0x%" PRIx64 ", begin destroy request, res:%p", reqId, pRequest);
727,733,621✔
718

719
  int64_t nextReqRefId = pRequest->relation.nextRefId;
727,733,621✔
720

721
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
727,732,227✔
722
  if (TSDB_CODE_SUCCESS != code) {
727,732,913✔
723
    tscDebug("failed to remove request from hash since %s", tstrerror(code));
1,971,484✔
724
  }
725
  schedulerFreeJob(&pRequest->body.queryJob, 0);
727,732,913✔
726

727
  destorySqlCallbackWrapper(pRequest->pWrapper);
727,732,834✔
728

729
  taosMemoryFreeClear(pRequest->msgBuf);
727,728,318✔
730

731
  doFreeReqResultInfo(&pRequest->body.resInfo);
727,719,736✔
732
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
727,724,790✔
733
    tscError("failed to destroy semaphore");
×
734
  }
735

736
  SSessParam para = {.type = SESSION_MAX_CONCURRENCY, .value = -1, .noCheck = 1};
727,725,745✔
737
  code = tscUpdateSessMetric(pRequest->pTscObj, &para);
727,722,357✔
738
  if (TSDB_CODE_SUCCESS != code) {
727,728,496✔
739
    tscError("failed to update session metric, code:%s", tstrerror(code));
×
740
  }
741

742
  taosArrayDestroy(pRequest->tableList);
727,728,496✔
743
  taosArrayDestroy(pRequest->targetTableList);
727,724,098✔
744
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
727,727,339✔
745

746
  if (pRequest->self) {
727,717,760✔
747
    deregisterRequest(pRequest);
727,724,110✔
748
  }
749

750
  taosMemoryFreeClear(pRequest->pDb);
727,730,883✔
751
  taosArrayDestroy(pRequest->dbList);
727,717,952✔
752
  if (pRequest->body.interParam) {
727,724,552✔
753
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
727,728,694✔
754
      tscError("failed to destroy semaphore in pRequest");
×
755
    }
756
  }
757
  taosMemoryFree(pRequest->body.interParam);
727,724,536✔
758

759
  qDestroyQuery(pRequest->pQuery);
727,717,935✔
760
  nodesDestroyAllocator(pRequest->allocatorRefId);
727,721,557✔
761

762
  taosMemoryFreeClear(pRequest->effectiveUser);
727,724,960✔
763
  taosMemoryFreeClear(pRequest->sqlstr);
727,725,731✔
764
  taosMemoryFree(pRequest);
727,715,269✔
765
  tscTrace("QID:0x%" PRIx64 ", end destroy request, res:%p", reqId, pRequest);
727,719,486✔
766
  destroyNextReq(nextReqRefId);
727,719,486✔
767
}
768

769
void destroyRequest(SRequestObj *pRequest) {
727,730,089✔
770
  if (pRequest == NULL) return;
727,730,089✔
771

772
  taos_stop_query(pRequest);
727,730,089✔
773
  (void)removeFromMostPrevReq(pRequest);
727,729,433✔
774
}
775

776
void taosStopQueryImpl(SRequestObj *pRequest) {
727,730,140✔
777
  pRequest->killed = true;
727,730,140✔
778

779
  // It is not a query, no need to stop.
780
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
727,732,031✔
781
    tscDebug("QID:0x%" PRIx64 ", no need to be killed since not query", pRequest->requestId);
74,197,595✔
782
    return;
74,196,772✔
783
  }
784

785
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
653,529,983✔
786
  tscDebug("QID:0x%" PRIx64 ", killed", pRequest->requestId);
653,530,745✔
787
}
788

789
void stopAllQueries(SRequestObj *pRequest) {
727,728,036✔
790
  int32_t      reqIdx = -1;
727,728,036✔
791
  SRequestObj *pReqList[16] = {NULL};
727,728,036✔
792
  uint64_t     tmpRefId = 0;
727,729,667✔
793

794
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
727,729,667✔
795
    return;
×
796
  }
797

798
  SRequestObj *pTmp = pRequest;
727,729,835✔
799
  while (pTmp->relation.prevRefId) {
727,729,835✔
800
    tmpRefId = pTmp->relation.prevRefId;
×
801
    pTmp = acquireRequest(tmpRefId);
×
802
    if (pTmp) {
×
803
      pReqList[++reqIdx] = pTmp;
×
804
    } else {
805
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
806
      break;
×
807
    }
808
  }
809

810
  for (int32_t i = reqIdx; i >= 0; i--) {
727,730,401✔
811
    taosStopQueryImpl(pReqList[i]);
×
812
    (void)releaseRequest(pReqList[i]->self);  // ignore error
×
813
  }
814

815
  taosStopQueryImpl(pRequest);
727,730,401✔
816

817
  tmpRefId = pRequest->relation.nextRefId;
727,728,545✔
818
  while (tmpRefId) {
727,728,018✔
819
    pTmp = acquireRequest(tmpRefId);
×
820
    if (pTmp) {
×
821
      tmpRefId = pTmp->relation.nextRefId;
×
822
      taosStopQueryImpl(pTmp);
×
823
      (void)releaseRequest(pTmp->self);  // ignore error
×
824
    } else {
825
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
826
      break;
×
827
    }
828
  }
829
}
830
#ifdef USE_REPORT
831
void crashReportThreadFuncUnexpectedStopped(void) { atomic_store_32(&clientStop, -1); }
×
832

833
static void *tscCrashReportThreadFp(void *param) {
×
834
  int32_t code = 0;
×
835
  setThreadName("client-crashReport");
×
836
  char filepath[PATH_MAX] = {0};
×
837
  (void)snprintf(filepath, sizeof(filepath), "%s%s.taosCrashLog", tsLogDir, TD_DIRSEP);
×
838
  char     *pMsg = NULL;
×
839
  int64_t   msgLen = 0;
×
840
  TdFilePtr pFile = NULL;
×
841
  bool      truncateFile = false;
×
842
  int32_t   sleepTime = 200;
×
843
  int32_t   reportPeriodNum = 3600 * 1000 / sleepTime;
×
844
  int32_t   loopTimes = reportPeriodNum;
×
845

846
#ifdef WINDOWS
847
  if (taosCheckCurrentInDll()) {
848
    atexit(crashReportThreadFuncUnexpectedStopped);
849
  }
850
#endif
851

852
  if (-1 != atomic_val_compare_exchange_32(&clientStop, -1, 0)) {
×
853
    return NULL;
×
854
  }
855
  STelemAddrMgmt mgt;
×
856
  code = taosTelemetryMgtInit(&mgt, tsTelemServer);
×
857
  if (code) {
×
858
    tscError("failed to init telemetry management, code:%s", tstrerror(code));
×
859
    return NULL;
×
860
  }
861

862
  code = initCrashLogWriter();
×
863
  if (code) {
×
864
    tscError("failed to init crash log writer, code:%s", tstrerror(code));
×
865
    return NULL;
×
866
  }
867

868
  while (1) {
869
    checkAndPrepareCrashInfo();
×
870
    if (clientStop > 0 && reportThreadSetQuit()) break;
×
871
    if (loopTimes++ < reportPeriodNum) {
×
872
      if (loopTimes < 0) loopTimes = reportPeriodNum;
×
873
      taosMsleep(sleepTime);
×
874
      continue;
×
875
    }
876

877
    taosReadCrashInfo(filepath, &pMsg, &msgLen, &pFile);
×
878
    if (pMsg && msgLen > 0) {
×
879
      if (taosSendTelemReport(&mgt, tsClientCrashReportUri, tsTelemPort, pMsg, msgLen, HTTP_FLAT) != 0) {
×
880
        tscError("failed to send crash report");
×
881
        if (pFile) {
×
882
          taosReleaseCrashLogFile(pFile, false);
×
883
          pFile = NULL;
×
884

885
          taosMsleep(sleepTime);
×
886
          loopTimes = 0;
×
887
          continue;
×
888
        }
889
      } else {
890
        tscInfo("succeed to send crash report");
×
891
        truncateFile = true;
×
892
      }
893
    } else {
894
      tscInfo("no crash info was found");
×
895
    }
896

897
    taosMemoryFree(pMsg);
×
898

899
    if (pMsg && msgLen > 0) {
×
900
      pMsg = NULL;
×
901
      continue;
×
902
    }
903

904
    if (pFile) {
×
905
      taosReleaseCrashLogFile(pFile, truncateFile);
×
906
      pFile = NULL;
×
907
      truncateFile = false;
×
908
    }
909

910
    taosMsleep(sleepTime);
×
911
    loopTimes = 0;
×
912
  }
913
  taosTelemetryDestroy(&mgt);
×
914

915
  clientStop = -2;
×
916
  return NULL;
×
917
}
918

919
int32_t tscCrashReportInit() {
1,122,341✔
920
  if (!tsEnableCrashReport) {
1,122,341✔
921
    return TSDB_CODE_SUCCESS;
1,122,341✔
922
  }
923
  int32_t      code = TSDB_CODE_SUCCESS;
×
924
  TdThreadAttr thAttr;
×
925
  TSC_ERR_JRET(taosThreadAttrInit(&thAttr));
×
926
  TSC_ERR_JRET(taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE));
×
927
  TdThread crashReportThread;
×
928
  if (taosThreadCreate(&crashReportThread, &thAttr, tscCrashReportThreadFp, NULL) != 0) {
×
929
    tscError("failed to create crashReport thread since %s", strerror(ERRNO));
×
930
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
931
    TSC_ERR_RET(terrno);
×
932
  }
933

934
  (void)taosThreadAttrDestroy(&thAttr);
×
935
_return:
×
936
  if (code) {
×
937
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
938
    TSC_ERR_RET(terrno);
×
939
  }
940

941
  return code;
×
942
}
943

944
void tscStopCrashReport() {
1,122,355✔
945
  if (!tsEnableCrashReport) {
1,122,355✔
946
    return;
1,122,355✔
947
  }
948

949
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
950
    tscDebug("crash report thread already stopped");
×
951
    return;
×
952
  }
953

954
  while (atomic_load_32(&clientStop) > 0) {
×
955
    taosMsleep(100);
×
956
  }
957
}
958

959
void taos_write_crashinfo(int signum, void *sigInfo, void *context) {
×
960
  writeCrashLogToFile(signum, sigInfo, CUS_PROMPT, lastClusterId, appInfo.startTime);
×
961
}
×
962
#endif
963

964
#ifdef TAOSD_INTEGRATED
965
typedef struct {
966
  TdThread pid;
967
  int32_t  stat;  // < 0: start failed, 0: init(not start), 1: start successfully
968
} SDaemonObj;
969

970
extern int  dmStartDaemon(int argc, char const *argv[]);
971
extern void dmStopDaemon();
972

973
SDaemonObj daemonObj = {0};
974

975
typedef struct {
976
  int32_t argc;
977
  char  **argv;
978
} SExecArgs;
979

980
static void *dmStartDaemonFunc(void *param) {
981
  int32_t    code = 0;
982
  SExecArgs *pArgs = (SExecArgs *)param;
983
  int32_t    argc = pArgs->argc;
984
  char     **argv = pArgs->argv;
985

986
  code = dmStartDaemon(argc, (const char **)argv);
987
  if (code != 0) {
988
    printf("failed to start taosd since %s\r\n", tstrerror(code));
989
    goto _exit;
990
  }
991

992
_exit:
993
  if (code != 0) {
994
    atomic_store_32(&daemonObj.stat, code);
995
  }
996
  return NULL;
997
}
998

999
static int32_t shellStartDaemon(int argc, char *argv[]) {
1000
  int32_t    code = 0, lino = 0;
1001
  SExecArgs *pArgs = NULL;
1002
  int64_t    startMs = taosGetTimestampMs(), endMs = startMs;
1003

1004
  TdThreadAttr thAttr;
1005
  (void)taosThreadAttrInit(&thAttr);
1006
  (void)taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
1007
#ifdef TD_COMPACT_OS
1008
  (void)taosThreadAttrSetStackSize(&thAttr, STACK_SIZE_SMALL);
1009
#endif
1010
  pArgs = (SExecArgs *)taosMemoryCalloc(1, sizeof(SExecArgs));
1011
  if (pArgs == NULL) {
1012
    code = terrno;
1013
    TAOS_CHECK_EXIT(code);
1014
  }
1015
  pArgs->argc = argc;
1016
  pArgs->argv = argv;
1017

1018
#ifndef TD_AS_LIB
1019
  tsLogEmbedded = 1;
1020
#endif
1021

1022
  TAOS_CHECK_EXIT(taosThreadCreate(&daemonObj.pid, &thAttr, dmStartDaemonFunc, pArgs));
1023

1024
  while (true) {
1025
    if (atomic_load_64(&tsDndStart)) {
1026
      atomic_store_32(&daemonObj.stat, 1);
1027
      break;
1028
    }
1029
    int32_t daemonstat = atomic_load_32(&daemonObj.stat);
1030
    if (daemonstat < 0) {
1031
      code = daemonstat;
1032
      TAOS_CHECK_EXIT(code);
1033
    }
1034

1035
    if (daemonstat > 1) {
1036
      code = TSDB_CODE_APP_ERROR;
1037
      TAOS_CHECK_EXIT(code);
1038
    }
1039
    taosMsleep(1000);
1040
  }
1041

1042
_exit:
1043
  endMs = taosGetTimestampMs();
1044
  (void)taosThreadAttrDestroy(&thAttr);
1045
  taosMemoryFreeClear(pArgs);
1046
  if (code) {
1047
    printf("\r\n The daemon start failed at line %d since %s, cost %" PRIi64 " ms\r\n", lino, tstrerror(code),
1048
           endMs - startMs);
1049
  } else {
1050
    printf("\r\n The daemon started successfully, cost %" PRIi64 " ms\r\n", endMs - startMs);
1051
  }
1052
#ifndef TD_AS_LIB
1053
  tsLogEmbedded = 0;
1054
#endif
1055
  return code;
1056
}
1057

1058
void shellStopDaemon() {
1059
#ifndef TD_AS_LIB
1060
  tsLogEmbedded = 1;
1061
#endif
1062
  dmStopDaemon();
1063
  if (taosCheckPthreadValid(daemonObj.pid)) {
1064
    (void)taosThreadJoin(daemonObj.pid, NULL);
1065
    taosThreadClear(&daemonObj.pid);
1066
  }
1067
}
1068
#endif
1069

1070
void taos_init_imp(void) {
1,122,355✔
1071
#if defined(LINUX)
1072
  if (tscDbg.memEnable) {
1,122,355✔
1073
    int32_t code = taosMemoryDbgInit();
×
1074
    if (code) {
×
1075
      (void)printf("failed to init memory dbg, error:%s\n", tstrerror(code));
×
1076
    } else {
1077
      tsAsyncLog = false;
×
1078
      (void)printf("memory dbg enabled\n");
×
1079
    }
1080
  }
1081
#endif
1082

1083
  // In the APIs of other program language, taos_cleanup is not available yet.
1084
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
1085
  (void)atexit(taos_cleanup);
1,122,355✔
1086
  SET_ERRNO(TSDB_CODE_SUCCESS);
1,122,355✔
1087
  terrno = TSDB_CODE_SUCCESS;
1,122,355✔
1088
  taosSeedRand(taosGetTimestampSec());
1,122,355✔
1089

1090
  appInfo.pid = taosGetPId();
1,122,355✔
1091
  appInfo.startTime = taosGetTimestampMs();
1,122,355✔
1092
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
1,122,355✔
1093
  appInfo.pInstMapByClusterId =
1,122,355✔
1094
      taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);
1,122,355✔
1095
  if (NULL == appInfo.pInstMap || NULL == appInfo.pInstMapByClusterId) {
1,122,355✔
1096
    (void)printf("failed to allocate memory when init appInfo\n");
×
1097
    tscInitRes = terrno;
×
1098
    return;
14✔
1099
  }
1100
  taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst);
1,122,355✔
1101

1102
  const char *logName = CUS_PROMPT "log";
1,122,355✔
1103
  ENV_ERR_RET(taosInitLogOutput(&logName), "failed to init log output");
1,122,355✔
1104
  if (taosCreateLog(logName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
1,122,355✔
1105
    (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logName, strerror(ERRNO), configDir);
14✔
1106
    SET_ERROR_MSG("Create %s failed:%s. configDir=%s", logName, strerror(ERRNO), configDir);
14✔
1107
    tscInitRes = terrno;
14✔
1108
    return;
14✔
1109
  }
1110

1111
#ifdef TAOSD_INTEGRATED
1112
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0), "failed to init cfg");
1113
#else
1114
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
1,122,341✔
1115
#endif
1116

1117
  initQueryModuleMsgHandle();
1,122,341✔
1118
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
1119
  if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL) {
1,122,341✔
1120
    tscInitRes = terrno;
×
1121
    tscError("failed to init conv");
×
1122
    return;
×
1123
  }
1124
#endif
1125
#if !defined(WINDOWS) && !defined(TD_ASTRA)
1126
  ENV_ERR_RET(tzInit(), "failed to init timezone");
1,122,341✔
1127
#endif
1128
  ENV_ERR_RET(monitorInit(), "failed to init monitor");
1,122,341✔
1129
  ENV_ERR_RET(rpcInit(), "failed to init rpc");
1,122,341✔
1130

1131
  if (InitRegexCache() != 0) {
1,122,341✔
1132
    tscInitRes = terrno;
×
1133
    (void)printf("failed to init regex cache\n");
×
1134
    return;
×
1135
  }
1136

1137
  tscInfo("starting to initialize TAOS driver");
1,122,341✔
1138

1139
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
1,122,341✔
1140
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
1,122,341✔
1141
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
1,122,341✔
1142
  ENV_ERR_RET(initClientId(), "failed to init clientId");
1,122,341✔
1143

1144
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
1,122,341✔
1145
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
1,122,341✔
1146
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
1,122,341✔
1147

1148
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
1,122,341✔
1149
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
1,122,341✔
1150

1151
  ENV_ERR_RET(taosGetAppName(appInfo.appName, NULL), "failed to get app name");
1,122,341✔
1152
  ENV_ERR_RET(taosThreadMutexInit(&appInfo.mutex, NULL), "failed to init thread mutex");
1,122,341✔
1153
#ifdef USE_REPORT
1154
  ENV_ERR_RET(tscCrashReportInit(), "failed to init crash report");
1,122,341✔
1155
#endif
1156
  ENV_ERR_RET(qInitKeywordsTable(), "failed to init parser keywords table");
1,122,341✔
1157
#ifdef TAOSD_INTEGRATED
1158
  ENV_ERR_RET(shellStartDaemon(0, NULL), "failed to start taosd daemon");
1159
#endif
1160

1161
  if (tsSessionControl) {
1,122,341✔
1162
    ENV_ERR_RET(sessMgtInit(), "failed to init session management");
1,122,341✔
1163
  }
1164

1165
  tscInfo("TAOS driver is initialized successfully");
1,122,341✔
1166
}
1167

1168
int taos_init() {
1,799,148✔
1169
  (void)taosThreadOnce(&tscinit, taos_init_imp);
1,799,148✔
1170
  return tscInitRes;
1,799,148✔
1171
}
1172

1173
const char *getCfgName(TSDB_OPTION option) {
1,988✔
1174
  const char *name = NULL;
1,988✔
1175

1176
  switch (option) {
1,988✔
1177
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
146✔
1178
      name = "shellActivityTimer";
146✔
1179
      break;
146✔
1180
    case TSDB_OPTION_LOCALE:
×
1181
      name = "locale";
×
1182
      break;
×
1183
    case TSDB_OPTION_CHARSET:
×
1184
      name = "charset";
×
1185
      break;
×
1186
    case TSDB_OPTION_TIMEZONE:
1,842✔
1187
      name = "timezone";
1,842✔
1188
      break;
1,842✔
1189
    case TSDB_OPTION_USE_ADAPTER:
×
1190
      name = "useAdapter";
×
1191
      break;
×
1192
    default:
×
1193
      break;
×
1194
  }
1195

1196
  return name;
1,988✔
1197
}
1198

1199
int taos_options_imp(TSDB_OPTION option, const char *str) {
414,947✔
1200
  if (option == TSDB_OPTION_CONFIGDIR) {
414,947✔
1201
#ifndef WINDOWS
1202
    char newstr[PATH_MAX];
409,068✔
1203
    int  len = strlen(str);
412,959✔
1204
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
412,959✔
1205
      if (len + 2 >= PATH_MAX) {
412,037✔
1206
        tscError("Too long path %s", str);
×
1207
        return -1;
×
1208
      }
1209
      newstr[0] = '"';
412,037✔
1210
      (void)memcpy(newstr + 1, str, len);
412,037✔
1211
      newstr[len + 1] = '"';
412,037✔
1212
      newstr[len + 2] = '\0';
412,037✔
1213
      str = newstr;
412,037✔
1214
    }
1215
#endif
1216
    tstrncpy(configDir, str, PATH_MAX);
412,959✔
1217
    tscInfo("set cfg:%s to %s", configDir, str);
412,959✔
1218
    return 0;
412,959✔
1219
  }
1220

1221
  // initialize global config
1222
  if (taos_init() != 0) {
1,988✔
1223
    return -1;
×
1224
  }
1225

1226
  SConfig     *pCfg = taosGetCfg();
1,988✔
1227
  SConfigItem *pItem = NULL;
1,988✔
1228
  const char  *name = getCfgName(option);
1,988✔
1229

1230
  if (name == NULL) {
1,988✔
1231
    tscError("Invalid option %d", option);
×
1232
    return -1;
×
1233
  }
1234

1235
  pItem = cfgGetItem(pCfg, name);
1,988✔
1236
  if (pItem == NULL) {
1,988✔
1237
    tscError("Invalid option %d", option);
×
1238
    return -1;
×
1239
  }
1240

1241
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
1,988✔
1242
  if (code != 0) {
1,988✔
1243
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
146✔
1244
  } else {
1245
    tscInfo("set cfg:%s to %s", name, str);
1,842✔
1246
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
1,842✔
1247
      code = taosCfgDynamicOptions(pCfg, name, false);
×
1248
    }
1249
  }
1250

1251
  return code;
1,988✔
1252
}
1253

1254
/**
1255
 * The request id is an unsigned integer format of 64bit.
1256
 *+------------+-----+-----------+---------------+
1257
 *| uid|localIp| PId | timestamp | serial number |
1258
 *+------------+-----+-----------+---------------+
1259
 *| 12bit      |12bit|24bit      |16bit          |
1260
 *+------------+-----+-----------+---------------+
1261
 * @return
1262
 */
1263
uint64_t generateRequestId() {
770,337,005✔
1264
  static uint32_t hashId = 0;
1265
  static int32_t  requestSerialId = 0;
1266

1267
  if (hashId == 0) {
770,337,005✔
1268
    int32_t code = taosGetSystemUUIDU32(&hashId);
1,122,026✔
1269
    if (code != TSDB_CODE_SUCCESS) {
1,122,026✔
1270
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1271
               tstrerror(code));
1272
    }
1273
  }
1274

1275
  uint64_t id = 0;
770,336,446✔
1276

1277
  while (true) {
×
1278
    int64_t  ts = taosGetTimestampMs();
770,341,133✔
1279
    uint64_t pid = taosGetPId();
770,341,133✔
1280
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
770,337,073✔
1281
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
770,339,004✔
1282

1283
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
770,338,960✔
1284
    if (id) {
770,338,960✔
1285
      break;
770,338,960✔
1286
    }
1287
  }
1288
  return id;
770,338,960✔
1289
}
1290

1291
#if 0
1292
#include "cJSON.h"
1293
static setConfRet taos_set_config_imp(const char *config){
1294
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
1295
  static bool setConfFlag = false;
1296
  if (setConfFlag) {
1297
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
1298
    tstrncpy(ret.retMsg, "configuration can only set once", RET_MSG_LENGTH);
1299
    return ret;
1300
  }
1301
  taosInitGlobalCfg();
1302
  cJSON *root = cJSON_Parse(config);
1303
  if (root == NULL){
1304
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
1305
    tstrncpy(ret.retMsg, "parse json error", RET_MSG_LENGTH);
1306
    return ret;
1307
  }
1308

1309
  int size = cJSON_GetArraySize(root);
1310
  if(!cJSON_IsObject(root) || size == 0) {
1311
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
1312
    tstrncpy(ret.retMsg, "json content is invalid, must be not empty object", RET_MSG_LENGTH);
1313
    return ret;
1314
  }
1315

1316
  if(size >= 1000) {
1317
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
1318
    tstrncpy(ret.retMsg, "json object size is too long", RET_MSG_LENGTH);
1319
    return ret;
1320
  }
1321

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

1348
setConfRet taos_set_config(const char *config){
1349
  taosThreadMutexLock(&setConfMutex);
1350
  setConfRet ret = taos_set_config_imp(config);
1351
  taosThreadMutexUnlock(&setConfMutex);
1352
  return ret;
1353
}
1354
#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