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

taosdata / TDengine / #4897

25 Dec 2025 10:17AM UTC coverage: 65.717% (-0.2%) from 65.929%
#4897

push

travis-ci

web-flow
fix: [6622889291] Fix invalid rowSize. (#34043)

186011 of 283047 relevant lines covered (65.72%)

113853896.64 hits per line

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

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

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

41
#include "cus_name.h"
42
#include "clientSession.h"
43

44
#define TSC_VAR_NOT_RELEASE 1
45
#define TSC_VAR_RELEASED    0
46

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

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

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

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

78
static int32_t registerRequest(SRequestObj *pRequest, STscObj *pTscObj) {
729,456,257✔
79
  int32_t code = TSDB_CODE_SUCCESS;
729,456,257✔
80
  // connection has been released already, abort creating request.
81
  pRequest->self = taosAddRef(clientReqRefPool, pRequest);
729,456,257✔
82
  if (pRequest->self < 0) {
729,465,795✔
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);
729,455,389✔
89

90
  if (pTscObj->pAppInfo) {
729,465,628✔
91
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
729,465,816✔
92

93
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
729,458,213✔
94
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
729,465,151✔
95
    tscDebug("req:0x%" PRIx64 ", create request from conn:0x%" PRIx64
729,463,305✔
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;
729,455,594✔
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) {
332,400✔
222
  if (pRequest->pDb != NULL) {
332,400✔
223
    return strcmp(pRequest->pDb, exceptDb) != 0;
196,087✔
224
  }
225

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

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

249
  STscObj            *pTscObj = pRequest->pTscObj;
729,332,471✔
250
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
729,335,289✔
251

252
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
729,331,793✔
253
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
729,338,997✔
254
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
729,339,377✔
255

256
  int64_t duration = taosGetTimestampUs() - pRequest->metric.start;
729,337,611✔
257
  tscDebug("req:0x%" PRIx64 ", free from conn:0x%" PRIx64 ", QID:0x%" PRIx64
729,332,073✔
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)) {
729,333,484✔
262
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
729,339,368✔
263
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
523,274,817✔
264
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
274,554,092✔
265
      tscDebug("req:0x%" PRIx64 ", insert duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
523,918,124✔
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);
523,918,124✔
271
      reqType = SLOW_LOG_TYPE_INSERT;
523,919,996✔
272
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
205,415,486✔
273
      tscDebug("req:0x%" PRIx64 ", query duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
157,776,008✔
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);
157,776,008✔
280
      reqType = SLOW_LOG_TYPE_QUERY;
157,776,873✔
281
    }
282

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

288
#ifdef USE_REPORT
289
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
729,332,023✔
290
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
357,133✔
291
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
335,063✔
292
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
22,070✔
293
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
6,424✔
294
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
15,646✔
295
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
×
296
    }
297
  }
298

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

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

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

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

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

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

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

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

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

408
  return code;
1,252,262✔
409
}
410

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

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

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

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

450
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
1,252,224✔
451

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

457
  taosMemoryFreeClear(pAppInfo->instKey);
1,252,224✔
458
  closeTransporter(pAppInfo);
1,252,224✔
459

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

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

471
  taosMemoryFree(pAppInfo);
1,252,224✔
472
}
1,252,224✔
473

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

478
void destroyTscObj(void *pObj) {
2,558,702✔
479
  if (NULL == pObj) {
2,558,702✔
480
    return;
×
481
  }
482

483
  STscObj *pTscObj = pObj;
2,558,702✔
484
  int64_t  tscId = pTscObj->id;
2,558,702✔
485
  tscTrace("conn:%" PRIx64 ", begin destroy, p:%p", tscId, pTscObj);
2,559,502✔
486

487
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
2,559,502✔
488
  hbDeregisterConn(pTscObj, connKey);
2,559,502✔
489

490
  destroyAllRequests(pTscObj->pRequests);
2,559,902✔
491
  taosHashCleanup(pTscObj->pRequests);
2,559,902✔
492

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

500
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
2,559,902✔
501
  taosMemoryFree(pTscObj);
2,559,902✔
502

503
  tscTrace("conn:0x%" PRIx64 ", end destroy, p:%p", tscId, pTscObj);
2,559,902✔
504
}
505

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

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

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

532
  if (db != NULL) {
2,706,204✔
533
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
2,706,204✔
534
  }
535

536
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
2,706,204✔
537

538
  int32_t code = TSDB_CODE_SUCCESS;
2,706,191✔
539

540
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
2,706,191✔
541
  if ((*pObj)->id < 0) {
2,706,204✔
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);
2,706,204✔
549

550
  updateConnAccessInfo(&(*pObj)->sessInfo);
2,706,191✔
551
  tscInfo("conn:0x%" PRIx64 ", created, p:%p", (*pObj)->id, *pObj);
2,706,191✔
552
  return code;
2,706,204✔
553
}
554

555
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
811,259,618✔
556

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

564
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
729,455,054✔
565
  int32_t code = TSDB_CODE_SUCCESS;
729,455,054✔
566
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
729,455,054✔
567
  if (NULL == *pRequest) {
729,448,464✔
568
    return terrno;
×
569
  }
570

571
  STscObj *pTscObj = acquireTscObj(connId);
729,453,202✔
572
  if (pTscObj == NULL) {
729,467,822✔
573
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
574
  }
575
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
729,467,822✔
576
  if (interParam == NULL) {
729,464,616✔
577
    releaseTscObj(connId);
×
578
    TSC_ERR_JRET(terrno);
×
579
  }
580
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
729,464,616✔
581
  interParam->pRequest = *pRequest;
729,464,095✔
582
  (*pRequest)->body.interParam = interParam;
729,461,130✔
583

584
  (*pRequest)->resType = RES_TYPE__QUERY;
729,459,777✔
585
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
729,457,854✔
586
  (*pRequest)->metric.start = taosGetTimestampUs();
1,455,653,724✔
587

588
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
729,462,490✔
589
  (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt;
729,460,372✔
590
  (*pRequest)->type = type;
729,462,017✔
591
  (*pRequest)->allocatorRefId = -1;
729,463,949✔
592

593
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
729,464,371✔
594
  if (NULL == (*pRequest)->pDb) {
729,463,078✔
595
    TSC_ERR_JRET(terrno);
66,720,303✔
596
  }
597
  (*pRequest)->pTscObj = pTscObj;
729,455,064✔
598
  (*pRequest)->inCallback = false;
729,460,859✔
599
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
729,458,485✔
600
  if (NULL == (*pRequest)->msgBuf) {
729,452,527✔
601
    code = terrno;
×
602
    goto _return;
×
603
  }
604
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
729,456,954✔
605
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
729,458,927✔
606
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
729,459,913✔
607

608
  return TSDB_CODE_SUCCESS;
729,453,594✔
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) {
761,714,279✔
619
  taosMemoryFreeClear(pResInfo->pRspMsg);
761,714,279✔
620
  taosMemoryFreeClear(pResInfo->length);
761,714,768✔
621
  taosMemoryFreeClear(pResInfo->row);
761,713,135✔
622
  taosMemoryFreeClear(pResInfo->pCol);
761,713,353✔
623
  taosMemoryFreeClear(pResInfo->fields);
761,714,345✔
624
  taosMemoryFreeClear(pResInfo->userFields);
761,714,069✔
625
  taosMemoryFreeClear(pResInfo->convertJson);
761,711,070✔
626
  taosMemoryFreeClear(pResInfo->decompBuf);
761,712,674✔
627

628
  if (pResInfo->convertBuf != NULL) {
761,715,265✔
629
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
601,040,856✔
630
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
489,732,083✔
631
    }
632
    taosMemoryFreeClear(pResInfo->convertBuf);
111,311,164✔
633
  }
634
}
761,715,142✔
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); }
729,335,795✔
641

642
/// return the most previous req ref id
643
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
729,336,612✔
644
  int64_t      mostPrevReqRefId = pRequest->self;
729,336,612✔
645
  SRequestObj *pTmp = pRequest;
729,339,006✔
646
  while (pTmp->relation.prevRefId) {
729,339,006✔
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
729,338,930✔
656
  return mostPrevReqRefId;
729,335,334✔
657
}
658

659
void destroyNextReq(int64_t nextRefId) {
729,330,346✔
660
  if (nextRefId) {
729,330,346✔
661
    SRequestObj *pObj = acquireRequest(nextRefId);
×
662
    if (pObj) {
×
663
      (void)releaseRequest(nextRefId);  // ignore error
×
664
      (void)releaseRequest(nextRefId);  // ignore error
×
665
    }
666
  }
667
}
729,330,346✔
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) {
729,336,445✔
710
  if (NULL == p) {
729,336,445✔
711
    return;
×
712
  }
713

714
  SRequestObj *pRequest = (SRequestObj *)p;
729,336,445✔
715

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

719
  int64_t nextReqRefId = pRequest->relation.nextRefId;
729,336,447✔
720

721
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
729,334,637✔
722
  if (TSDB_CODE_SUCCESS != code) {
729,337,107✔
723
    tscDebug("failed to remove request from hash since %s", tstrerror(code));
2,706,171✔
724
  }
725
  schedulerFreeJob(&pRequest->body.queryJob, 0);
729,337,107✔
726

727
  destorySqlCallbackWrapper(pRequest->pWrapper);
729,338,205✔
728

729
  taosMemoryFreeClear(pRequest->msgBuf);
729,332,549✔
730

731
  doFreeReqResultInfo(&pRequest->body.resInfo);
729,326,580✔
732
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
729,330,276✔
733
    tscError("failed to destroy semaphore");
×
734
  }
735

736
  SSessParam para = {.type = SESSION_MAX_CONCURRENCY, .value = -1};
729,334,034✔
737
  code = tscUpdateSessMgtMetric(pRequest->pTscObj, &para);
729,328,966✔
738

739
  taosArrayDestroy(pRequest->tableList);
729,332,703✔
740
  taosArrayDestroy(pRequest->targetTableList);
729,329,057✔
741
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
729,329,660✔
742

743
  if (pRequest->self) {
729,329,571✔
744
    deregisterRequest(pRequest);
729,331,838✔
745
  }
746

747
  taosMemoryFreeClear(pRequest->pDb);
729,333,805✔
748
  taosArrayDestroy(pRequest->dbList);
729,319,671✔
749
  if (pRequest->body.interParam) {
729,328,176✔
750
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
729,332,515✔
751
      tscError("failed to destroy semaphore in pRequest");
×
752
    }
753
  }
754
  taosMemoryFree(pRequest->body.interParam);
729,329,365✔
755

756
  qDestroyQuery(pRequest->pQuery);
729,322,607✔
757
  nodesDestroyAllocator(pRequest->allocatorRefId);
729,324,594✔
758

759
  taosMemoryFreeClear(pRequest->effectiveUser);
729,333,233✔
760
  taosMemoryFreeClear(pRequest->sqlstr);
729,334,220✔
761
  taosMemoryFree(pRequest);
729,318,496✔
762
  tscTrace("QID:0x%" PRIx64 ", end destroy request, res:%p", reqId, pRequest);
729,326,894✔
763
  destroyNextReq(nextReqRefId);
729,326,894✔
764
}
765

766
void destroyRequest(SRequestObj *pRequest) {
729,335,745✔
767
  if (pRequest == NULL) return;
729,335,745✔
768

769
  taos_stop_query(pRequest);
729,335,745✔
770
  (void)removeFromMostPrevReq(pRequest);
729,338,765✔
771
}
772

773
void taosStopQueryImpl(SRequestObj *pRequest) {
729,336,904✔
774
  pRequest->killed = true;
729,336,904✔
775

776
  // It is not a query, no need to stop.
777
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
729,338,162✔
778
    tscDebug("QID:0x%" PRIx64 ", no need to be killed since not query", pRequest->requestId);
95,307,873✔
779
    return;
95,312,621✔
780
  }
781

782
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
634,024,513✔
783
  tscDebug("QID:0x%" PRIx64 ", killed", pRequest->requestId);
634,025,872✔
784
}
785

786
void stopAllQueries(SRequestObj *pRequest) {
729,332,929✔
787
  int32_t      reqIdx = -1;
729,332,929✔
788
  SRequestObj *pReqList[16] = {NULL};
729,332,929✔
789
  uint64_t     tmpRefId = 0;
729,332,840✔
790

791
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
729,332,840✔
792
    return;
×
793
  }
794

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

807
  for (int32_t i = reqIdx; i >= 0; i--) {
729,337,842✔
808
    taosStopQueryImpl(pReqList[i]);
×
809
    (void)releaseRequest(pReqList[i]->self);  // ignore error
×
810
  }
811

812
  taosStopQueryImpl(pRequest);
729,337,842✔
813

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

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

843
#ifdef WINDOWS
844
  if (taosCheckCurrentInDll()) {
845
    atexit(crashReportThreadFuncUnexpectedStopped);
846
  }
847
#endif
848

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

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

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

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

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

894
    taosMemoryFree(pMsg);
×
895

896
    if (pMsg && msgLen > 0) {
×
897
      pMsg = NULL;
×
898
      continue;
×
899
    }
900

901
    if (pFile) {
×
902
      taosReleaseCrashLogFile(pFile, truncateFile);
×
903
      pFile = NULL;
×
904
      truncateFile = false;
×
905
    }
906

907
    taosMsleep(sleepTime);
×
908
    loopTimes = 0;
×
909
  }
910
  taosTelemetryDestroy(&mgt);
×
911

912
  clientStop = -2;
×
913
  return NULL;
×
914
}
915

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

931
  (void)taosThreadAttrDestroy(&thAttr);
×
932
_return:
×
933
  if (code) {
×
934
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
935
    TSC_ERR_RET(terrno);
×
936
  }
937

938
  return code;
×
939
}
940

941
void tscStopCrashReport() {
1,195,063✔
942
  if (!tsEnableCrashReport) {
1,195,063✔
943
    return;
1,195,063✔
944
  }
945

946
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
947
    tscDebug("crash report thread already stopped");
×
948
    return;
×
949
  }
950

951
  while (atomic_load_32(&clientStop) > 0) {
×
952
    taosMsleep(100);
×
953
  }
954
}
955

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

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

967
extern int  dmStartDaemon(int argc, char const *argv[]);
968
extern void dmStopDaemon();
969

970
SDaemonObj daemonObj = {0};
971

972
typedef struct {
973
  int32_t argc;
974
  char  **argv;
975
} SExecArgs;
976

977
static void *dmStartDaemonFunc(void *param) {
978
  int32_t    code = 0;
979
  SExecArgs *pArgs = (SExecArgs *)param;
980
  int32_t    argc = pArgs->argc;
981
  char     **argv = pArgs->argv;
982

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

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

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

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

1015
#ifndef TD_AS_LIB
1016
  tsLogEmbedded = 1;
1017
#endif
1018

1019
  TAOS_CHECK_EXIT(taosThreadCreate(&daemonObj.pid, &thAttr, dmStartDaemonFunc, pArgs));
1020

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

1032
    if (daemonstat > 1) {
1033
      code = TSDB_CODE_APP_ERROR;
1034
      TAOS_CHECK_EXIT(code);
1035
    }
1036
    taosMsleep(1000);
1037
  }
1038

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

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

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

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

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

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

1108
#ifdef TAOSD_INTEGRATED
1109
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0), "failed to init cfg");
1110
#else
1111
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
1,195,028✔
1112
#endif
1113

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

1128
  if (InitRegexCache() != 0) {
1,195,028✔
1129
    tscInitRes = terrno;
×
1130
    (void)printf("failed to init regex cache\n");
×
1131
    return;
×
1132
  }
1133

1134
  tscInfo("starting to initialize TAOS driver");
1,195,028✔
1135

1136
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
1,195,028✔
1137
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
1,195,028✔
1138
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
1,195,028✔
1139
  ENV_ERR_RET(initClientId(), "failed to init clientId");
1,195,028✔
1140

1141
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
1,195,028✔
1142
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
1,195,028✔
1143
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
1,195,028✔
1144

1145
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
1,195,028✔
1146
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
1,195,028✔
1147

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

1158
  if (tsSessionControl) {
1,195,028✔
1159
    ENV_ERR_RET(sessMgtInit(), "failed to init session management");
×
1160
  }
1161

1162
  tscInfo("TAOS driver is initialized successfully");
1,195,028✔
1163
}
1164

1165
int taos_init() {
1,848,457✔
1166
  (void)taosThreadOnce(&tscinit, taos_init_imp);
1,848,457✔
1167
  return tscInitRes;
1,848,394✔
1168
}
1169

1170
const char *getCfgName(TSDB_OPTION option) {
1,665✔
1171
  const char *name = NULL;
1,665✔
1172

1173
  switch (option) {
1,665✔
1174
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
571✔
1175
      name = "shellActivityTimer";
571✔
1176
      break;
571✔
1177
    case TSDB_OPTION_LOCALE:
×
1178
      name = "locale";
×
1179
      break;
×
1180
    case TSDB_OPTION_CHARSET:
×
1181
      name = "charset";
×
1182
      break;
×
1183
    case TSDB_OPTION_TIMEZONE:
1,094✔
1184
      name = "timezone";
1,094✔
1185
      break;
1,094✔
1186
    case TSDB_OPTION_USE_ADAPTER:
×
1187
      name = "useAdapter";
×
1188
      break;
×
1189
    default:
×
1190
      break;
×
1191
  }
1192

1193
  return name;
1,665✔
1194
}
1195

1196
int taos_options_imp(TSDB_OPTION option, const char *str) {
556,245✔
1197
  if (option == TSDB_OPTION_CONFIGDIR) {
556,245✔
1198
#ifndef WINDOWS
1199
    char newstr[PATH_MAX];
548,616✔
1200
    int  len = strlen(str);
554,580✔
1201
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
554,580✔
1202
      if (len + 2 >= PATH_MAX) {
554,342✔
1203
        tscError("Too long path %s", str);
×
1204
        return -1;
×
1205
      }
1206
      newstr[0] = '"';
554,342✔
1207
      (void)memcpy(newstr + 1, str, len);
554,342✔
1208
      newstr[len + 1] = '"';
554,342✔
1209
      newstr[len + 2] = '\0';
554,342✔
1210
      str = newstr;
554,342✔
1211
    }
1212
#endif
1213
    tstrncpy(configDir, str, PATH_MAX);
554,580✔
1214
    tscInfo("set cfg:%s to %s", configDir, str);
554,580✔
1215
    return 0;
554,580✔
1216
  }
1217

1218
  // initialize global config
1219
  if (taos_init() != 0) {
1,665✔
1220
    return -1;
×
1221
  }
1222

1223
  SConfig     *pCfg = taosGetCfg();
1,665✔
1224
  SConfigItem *pItem = NULL;
1,665✔
1225
  const char  *name = getCfgName(option);
1,665✔
1226

1227
  if (name == NULL) {
1,665✔
1228
    tscError("Invalid option %d", option);
×
1229
    return -1;
×
1230
  }
1231

1232
  pItem = cfgGetItem(pCfg, name);
1,665✔
1233
  if (pItem == NULL) {
1,665✔
1234
    tscError("Invalid option %d", option);
×
1235
    return -1;
×
1236
  }
1237

1238
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
1,665✔
1239
  if (code != 0) {
1,665✔
1240
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
571✔
1241
  } else {
1242
    tscInfo("set cfg:%s to %s", name, str);
1,094✔
1243
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
1,094✔
1244
      code = taosCfgDynamicOptions(pCfg, name, false);
×
1245
    }
1246
  }
1247

1248
  return code;
1,665✔
1249
}
1250

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

1264
  if (hashId == 0) {
755,322,572✔
1265
    int32_t code = taosGetSystemUUIDU32(&hashId);
1,193,990✔
1266
    if (code != TSDB_CODE_SUCCESS) {
1,193,990✔
1267
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1268
               tstrerror(code));
1269
    }
1270
  }
1271

1272
  uint64_t id = 0;
755,324,108✔
1273

1274
  while (true) {
×
1275
    int64_t  ts = taosGetTimestampMs();
755,327,891✔
1276
    uint64_t pid = taosGetPId();
755,327,891✔
1277
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
755,319,110✔
1278
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
755,322,399✔
1279

1280
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
755,323,362✔
1281
    if (id) {
755,323,362✔
1282
      break;
755,323,362✔
1283
    }
1284
  }
1285
  return id;
755,323,362✔
1286
}
1287

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

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

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

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

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