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

taosdata / TDengine / #4674

18 Aug 2025 07:58AM UTC coverage: 59.821% (+0.1%) from 59.715%
#4674

push

travis-ci

web-flow
test: update case desc (#32551)

136937 of 292075 branches covered (46.88%)

Branch coverage included in aggregate %.

207916 of 284395 relevant lines covered (73.11%)

4553289.94 hits per line

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

50.0
/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

43
#define TSC_VAR_NOT_RELEASE 1
44
#define TSC_VAR_RELEASED    0
45

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

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

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

74
int32_t timestampDeltaLimit = 900;  // s
75

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

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

89
  int32_t num = atomic_add_fetch_32(&pTscObj->numOfReqs, 1);
409,143✔
90

91
  if (pTscObj->pAppInfo) {
409,140!
92
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
409,144✔
93

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

101
  return code;
409,146✔
102
}
103

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

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

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

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

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

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

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

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

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

244
static void deregisterRequest(SRequestObj *pRequest) {
408,543✔
245
  if (pRequest == NULL) {
408,543!
246
    tscError("pRequest == NULL");
×
247
    return;
×
248
  }
249

250
  STscObj            *pTscObj = pRequest->pTscObj;
408,543✔
251
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
408,543✔
252

253
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
408,543✔
254
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
408,626✔
255
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
408,609✔
256

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

262
  if (TSDB_CODE_SUCCESS == nodesSimAcquireAllocator(pRequest->allocatorRefId)) {
408,616!
263
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
408,595!
264
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
343,435✔
265
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
97,262✔
266
      tscDebug("req:0x%" PRIx64 ", insert duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
354,525✔
267
               "us, analyseCost:%" PRId64 "us, planCost:%" PRId64 "us, exec:%" PRId64 "us, QID:0x%" PRIx64,
268
               pRequest->self, duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs,
269
               pRequest->metric.analyseCostUs, pRequest->metric.planCostUs, pRequest->metric.execCostUs,
270
               pRequest->requestId);
271
      (void)atomic_add_fetch_64((int64_t *)&pActivity->insertElapsedTime, duration);
354,525✔
272
      reqType = SLOW_LOG_TYPE_INSERT;
354,568✔
273
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
54,070✔
274
      tscDebug("req:0x%" PRIx64 ", query duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
29,582✔
275
               "us, analyseCost:%" PRId64 "us, planCost:%" PRId64 "us, exec:%" PRId64 "us, QID:0x%" PRIx64,
276
               pRequest->self, duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs,
277
               pRequest->metric.analyseCostUs, pRequest->metric.planCostUs, pRequest->metric.execCostUs,
278
               pRequest->requestId);
279

280
      (void)atomic_add_fetch_64((int64_t *)&pActivity->queryElapsedTime, duration);
29,582✔
281
      reqType = SLOW_LOG_TYPE_QUERY;
29,579✔
282
    }
283

284
    if (TSDB_CODE_SUCCESS != nodesSimReleaseAllocator(pRequest->allocatorRefId)) {
408,635!
285
      tscError("failed to release allocator");
×
286
    }
287
  }
288

289
#ifdef USE_REPORT
290
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
408,603✔
291
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
266,367✔
292
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
246,782✔
293
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
19,585✔
294
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
12,941✔
295
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
6,644✔
296
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
5✔
297
    }
298
  }
299

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

317
  releaseTscObj(pTscObj->id);
408,603✔
318
}
319

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

326
  tscDebug("free transporter:%p in app inst %p", pAppInfo->pTransporter, pAppInfo);
2,272✔
327
  rpcClose(pAppInfo->pTransporter);
2,272✔
328
}
329

330
static bool clientRpcRfp(int32_t code, tmsg_t msgType) {
27,010✔
331
  if (NEED_REDIRECT_ERROR(code)) {
27,010!
332
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
22,162!
333
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_QUERY_HEARTBEAT || msgType == TDMT_SCH_DROP_TASK ||
22,162!
334
        msgType == TDMT_SCH_TASK_NOTIFY) {
335
      return false;
×
336
    }
337
    return true;
22,162✔
338
  } else if (code == TSDB_CODE_UTIL_QUEUE_OUT_OF_MEMORY || code == TSDB_CODE_OUT_OF_RPC_MEMORY_QUEUE ||
4,848!
339
             code == TSDB_CODE_SYN_WRITE_STALL) {
340
    tscDebug("client msg type %s should retry since %s", TMSG_INFO(msgType), tstrerror(code));
×
341
    return true;
×
342
  } else {
343
    return false;
4,848✔
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) {
2,272✔
357
  SRpcInit rpcInit;
358
  (void)memset(&rpcInit, 0, sizeof(rpcInit));
2,272✔
359
  rpcInit.localPort = 0;
2,272✔
360
  rpcInit.label = "TSC";
2,272✔
361
  rpcInit.numOfThreads = tsNumOfRpcThreads;
2,272✔
362
  rpcInit.cfp = processMsgFromServer;
2,272✔
363
  rpcInit.rfp = clientRpcRfp;
2,272✔
364
  rpcInit.sessions = 1024;
2,272✔
365
  rpcInit.connType = TAOS_CONN_CLIENT;
2,272✔
366
  rpcInit.user = (char *)user;
2,272✔
367
  rpcInit.idleTime = tsShellActivityTimer * 1000;
2,272✔
368
  rpcInit.compressSize = tsCompressMsgSize;
2,272✔
369
  rpcInit.dfp = destroyAhandle;
2,272✔
370

371
  rpcInit.retryMinInterval = tsRedirectPeriod;
2,272✔
372
  rpcInit.retryStepFactor = tsRedirectFactor;
2,272✔
373
  rpcInit.retryMaxInterval = tsRedirectMaxPeriod;
2,272✔
374
  rpcInit.retryMaxTimeout = tsMaxRetryWaitTime;
2,272✔
375

376
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
2,272✔
377
  connLimitNum = TMAX(connLimitNum, 10);
2,272✔
378
  connLimitNum = TMIN(connLimitNum, 1000);
2,272✔
379
  rpcInit.connLimitNum = connLimitNum;
2,272✔
380
  rpcInit.shareConnLimit = tsShareConnLimit;
2,272✔
381
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
2,272✔
382
  rpcInit.startReadTimer = 1;
2,272✔
383
  rpcInit.readTimeout = tsReadTimeout;
2,272✔
384
  rpcInit.ipv6 = tsEnableIpv6;
2,272✔
385

386
  int32_t code = taosVersionStrToInt(td_version, &rpcInit.compatibilityVer);
2,272✔
387
  if (TSDB_CODE_SUCCESS != code) {
2,272!
388
    tscError("invalid version string.");
×
389
    return code;
×
390
  }
391

392
  tscInfo("rpc max retry timeout %" PRId64 "", rpcInit.retryMaxTimeout);
2,272!
393
  *pDnodeConn = rpcOpen(&rpcInit);
2,272✔
394
  if (*pDnodeConn == NULL) {
2,272!
395
    tscError("failed to init connection to server since %s", tstrerror(terrno));
×
396
    code = terrno;
×
397
  }
398

399
  return code;
2,272✔
400
}
401

402
void destroyAllRequests(SHashObj *pRequests) {
6,722✔
403
  void *pIter = taosHashIterate(pRequests, NULL);
6,722✔
404
  while (pIter != NULL) {
6,722!
405
    int64_t *rid = pIter;
×
406

407
    SRequestObj *pRequest = acquireRequest(*rid);
×
408
    if (pRequest) {
×
409
      destroyRequest(pRequest);
×
410
      (void)releaseRequest(*rid);  // ignore error
×
411
    }
412

413
    pIter = taosHashIterate(pRequests, pIter);
×
414
  }
415
}
6,722✔
416

417
void stopAllRequests(SHashObj *pRequests) {
5✔
418
  void *pIter = taosHashIterate(pRequests, NULL);
5✔
419
  while (pIter != NULL) {
5!
420
    int64_t *rid = pIter;
×
421

422
    SRequestObj *pRequest = acquireRequest(*rid);
×
423
    if (pRequest) {
×
424
      taos_stop_query(pRequest);
×
425
      (void)releaseRequest(*rid);  // ignore error
×
426
    }
427

428
    pIter = taosHashIterate(pRequests, pIter);
×
429
  }
430
}
5✔
431

432
void destroyAppInst(void *info) {
2,272✔
433
  SAppInstInfo *pAppInfo = *(SAppInstInfo **)info;
2,272✔
434
  tscInfo("destroy app inst mgr %p", pAppInfo);
2,272!
435

436
  int32_t code = taosThreadMutexLock(&appInfo.mutex);
2,272✔
437
  if (TSDB_CODE_SUCCESS != code) {
2,272!
438
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
439
  }
440

441
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
2,272✔
442

443
  code = taosThreadMutexUnlock(&appInfo.mutex);
2,272✔
444
  if (TSDB_CODE_SUCCESS != code) {
2,272!
445
    tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
446
  }
447

448
  taosMemoryFreeClear(pAppInfo->instKey);
2,272!
449
  closeTransporter(pAppInfo);
2,272✔
450

451
  code = taosThreadMutexLock(&pAppInfo->qnodeMutex);
2,272✔
452
  if (TSDB_CODE_SUCCESS != code) {
2,272!
453
    tscError("failed to lock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
454
  }
455

456
  taosArrayDestroy(pAppInfo->pQnodeList);
2,272✔
457
  code = taosThreadMutexUnlock(&pAppInfo->qnodeMutex);
2,272✔
458
  if (TSDB_CODE_SUCCESS != code) {
2,272!
459
    tscError("failed to unlock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
460
  }
461

462
  taosMemoryFree(pAppInfo);
2,272!
463
}
2,272✔
464

465
void destroyTscObj(void *pObj) {
6,719✔
466
  if (NULL == pObj) {
6,719!
467
    return;
×
468
  }
469

470
  STscObj *pTscObj = pObj;
6,719✔
471
  int64_t  tscId = pTscObj->id;
6,719✔
472
  tscTrace("conn:%" PRIx64 ", begin destroy, p:%p", tscId, pTscObj);
6,719!
473

474
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
6,719✔
475
  hbDeregisterConn(pTscObj, connKey);
6,719✔
476

477
  destroyAllRequests(pTscObj->pRequests);
6,722✔
478
  taosHashCleanup(pTscObj->pRequests);
6,722✔
479

480
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
6,722✔
481
  tscDebug("conn:0x%" PRIx64 ", p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
6,722✔
482
           pTscObj->pAppInfo->numOfConns);
483

484
  // In any cases, we should not free app inst here. Or an race condition rises.
485
  /*int64_t connNum = */ (void)atomic_sub_fetch_64(&pTscObj->pAppInfo->numOfConns, 1);
6,722✔
486

487
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
6,722✔
488
  taosMemoryFree(pTscObj);
6,721!
489

490
  tscTrace("conn:0x%" PRIx64 ", end destroy, p:%p", tscId, pTscObj);
6,722!
491
}
492

493
int32_t createTscObj(const char *user, const char *auth, const char *db, int32_t connType, SAppInstInfo *pAppInfo,
7,548✔
494
                     STscObj **pObj) {
495
  *pObj = (STscObj *)taosMemoryCalloc(1, sizeof(STscObj));
7,548!
496
  if (NULL == *pObj) {
7,548!
497
    return terrno;
×
498
  }
499

500
  (*pObj)->pRequests = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
7,548✔
501
  if (NULL == (*pObj)->pRequests) {
7,548!
502
    taosMemoryFree(*pObj);
×
503
    return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
504
  }
505

506
  (*pObj)->connType = connType;
7,548✔
507
  (*pObj)->pAppInfo = pAppInfo;
7,548✔
508
  (*pObj)->appHbMgrIdx = pAppInfo->pAppHbMgr->idx;
7,548✔
509
  tstrncpy((*pObj)->user, user, sizeof((*pObj)->user));
7,548✔
510
  (void)memcpy((*pObj)->pass, auth, TSDB_PASSWORD_LEN);
7,548✔
511

512
  if (db != NULL) {
7,548!
513
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
7,548✔
514
  }
515

516
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
7,548!
517

518
  int32_t code = TSDB_CODE_SUCCESS;
7,548✔
519

520
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
7,548✔
521
  if ((*pObj)->id < 0) {
7,547!
522
    tscError("failed to add object to clientConnRefPool");
×
523
    code = terrno;
×
524
    taosMemoryFree(*pObj);
×
525
    return code;
×
526
  }
527

528
  (void)atomic_add_fetch_64(&(*pObj)->pAppInfo->numOfConns, 1);
7,547✔
529

530
  tscInfo("conn:0x%" PRIx64 ", created, p:%p", (*pObj)->id, *pObj);
7,548!
531
  return code;
7,548✔
532
}
533

534
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
733,690✔
535

536
void releaseTscObj(int64_t rid) {
729,984✔
537
  int32_t code = taosReleaseRef(clientConnRefPool, rid);
729,984✔
538
  if (TSDB_CODE_SUCCESS != code) {
730,094!
539
    tscWarn("failed to release TscObj, code:%s", tstrerror(code));
×
540
  }
541
}
730,094✔
542

543
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
409,062✔
544
  int32_t code = TSDB_CODE_SUCCESS;
409,062✔
545
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
409,062!
546
  if (NULL == *pRequest) {
409,031!
547
    return terrno;
×
548
  }
549

550
  STscObj *pTscObj = acquireTscObj(connId);
409,031✔
551
  if (pTscObj == NULL) {
409,143!
552
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
553
  }
554
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
409,143!
555
  if (interParam == NULL) {
409,134!
556
    releaseTscObj(connId);
×
557
    TSC_ERR_JRET(terrno);
×
558
  }
559
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
409,134!
560
  interParam->pRequest = *pRequest;
409,130✔
561
  (*pRequest)->body.interParam = interParam;
409,130✔
562

563
  (*pRequest)->resType = RES_TYPE__QUERY;
409,130✔
564
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
409,130!
565
  (*pRequest)->metric.start = taosGetTimestampUs();
409,137✔
566

567
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
409,141✔
568
  (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt;
409,141✔
569
  (*pRequest)->type = type;
409,141✔
570
  (*pRequest)->allocatorRefId = -1;
409,141✔
571

572
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
409,141✔
573
  if (NULL == (*pRequest)->pDb) {
409,111✔
574
    TSC_ERR_JRET(terrno);
15,230!
575
  }
576
  (*pRequest)->pTscObj = pTscObj;
409,111✔
577
  (*pRequest)->inCallback = false;
409,111✔
578
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
409,111!
579
  if (NULL == (*pRequest)->msgBuf) {
409,037!
580
    code = terrno;
×
581
    goto _return;
×
582
  }
583
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
409,037✔
584
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
409,037!
585
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
409,053!
586

587
  return TSDB_CODE_SUCCESS;
409,150✔
588
_return:
×
589
  if ((*pRequest)->pTscObj) {
×
590
    doDestroyRequest(*pRequest);
×
591
  } else {
592
    taosMemoryFree(*pRequest);
×
593
  }
594
  return code;
×
595
}
596

597
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
412,118✔
598
  taosMemoryFreeClear(pResInfo->pRspMsg);
412,118!
599
  taosMemoryFreeClear(pResInfo->length);
412,062!
600
  taosMemoryFreeClear(pResInfo->row);
412,079!
601
  taosMemoryFreeClear(pResInfo->pCol);
412,063!
602
  taosMemoryFreeClear(pResInfo->fields);
412,066!
603
  taosMemoryFreeClear(pResInfo->userFields);
412,063!
604
  taosMemoryFreeClear(pResInfo->convertJson);
412,065!
605
  taosMemoryFreeClear(pResInfo->decompBuf);
412,065!
606

607
  if (pResInfo->convertBuf != NULL) {
412,065✔
608
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
136,475✔
609
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
105,527!
610
    }
611
    taosMemoryFreeClear(pResInfo->convertBuf);
30,948!
612
  }
613
}
412,028✔
614

615
SRequestObj *acquireRequest(int64_t rid) { return (SRequestObj *)taosAcquireRef(clientReqRefPool, rid); }
1,843,780✔
616

617
int32_t releaseRequest(int64_t rid) { return taosReleaseRef(clientReqRefPool, rid); }
1,844,313✔
618

619
int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }
408,552✔
620

621
/// return the most previous req ref id
622
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
408,600✔
623
  int64_t      mostPrevReqRefId = pRequest->self;
408,600✔
624
  SRequestObj *pTmp = pRequest;
408,600✔
625
  while (pTmp->relation.prevRefId) {
408,600!
626
    pTmp = acquireRequest(pTmp->relation.prevRefId);
×
627
    if (pTmp) {
×
628
      mostPrevReqRefId = pTmp->self;
×
629
      (void)releaseRequest(mostPrevReqRefId);  // ignore error
×
630
    } else {
631
      break;
×
632
    }
633
  }
634
  (void)removeRequest(mostPrevReqRefId);  // ignore error
408,600✔
635
  return mostPrevReqRefId;
408,617✔
636
}
637

638
void destroyNextReq(int64_t nextRefId) {
408,539✔
639
  if (nextRefId) {
408,539!
640
    SRequestObj *pObj = acquireRequest(nextRefId);
×
641
    if (pObj) {
×
642
      (void)releaseRequest(nextRefId);  // ignore error
×
643
      (void)releaseRequest(nextRefId);  // ignore error
×
644
    }
645
  }
646
}
408,539✔
647

648
void destroySubRequests(SRequestObj *pRequest) {
×
649
  int32_t      reqIdx = -1;
×
650
  SRequestObj *pReqList[16] = {NULL};
×
651
  uint64_t     tmpRefId = 0;
×
652

653
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
×
654
    return;
×
655
  }
656

657
  SRequestObj *pTmp = pRequest;
×
658
  while (pTmp->relation.prevRefId) {
×
659
    tmpRefId = pTmp->relation.prevRefId;
×
660
    pTmp = acquireRequest(tmpRefId);
×
661
    if (pTmp) {
×
662
      pReqList[++reqIdx] = pTmp;
×
663
      (void)releaseRequest(tmpRefId);  // ignore error
×
664
    } else {
665
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
666
      break;
×
667
    }
668
  }
669

670
  for (int32_t i = reqIdx; i >= 0; i--) {
×
671
    (void)removeRequest(pReqList[i]->self);  // ignore error
×
672
  }
673

674
  tmpRefId = pRequest->relation.nextRefId;
×
675
  while (tmpRefId) {
×
676
    pTmp = acquireRequest(tmpRefId);
×
677
    if (pTmp) {
×
678
      tmpRefId = pTmp->relation.nextRefId;
×
679
      (void)removeRequest(pTmp->self);   // ignore error
×
680
      (void)releaseRequest(pTmp->self);  // ignore error
×
681
    } else {
682
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
683
      break;
×
684
    }
685
  }
686
}
687

688
void doDestroyRequest(void *p) {
408,569✔
689
  if (NULL == p) {
408,569!
690
    return;
×
691
  }
692

693
  SRequestObj *pRequest = (SRequestObj *)p;
408,569✔
694

695
  uint64_t reqId = pRequest->requestId;
408,569✔
696
  tscTrace("QID:0x%" PRIx64 ", begin destroy request, res:%p", reqId, pRequest);
408,569!
697

698
  int64_t nextReqRefId = pRequest->relation.nextRefId;
408,569✔
699

700
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
408,569✔
701
  if (TSDB_CODE_SUCCESS != code) {
408,627✔
702
    tscDebug("failed to remove request from hash since %s", tstrerror(code));
7,548✔
703
  }
704
  schedulerFreeJob(&pRequest->body.queryJob, 0);
408,627✔
705

706
  destorySqlCallbackWrapper(pRequest->pWrapper);
408,598✔
707

708
  taosMemoryFreeClear(pRequest->msgBuf);
408,590!
709

710
  doFreeReqResultInfo(&pRequest->body.resInfo);
408,529✔
711
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
408,526!
712
    tscError("failed to destroy semaphore");
×
713
  }
714

715
  taosArrayDestroy(pRequest->tableList);
408,600✔
716
  taosArrayDestroy(pRequest->targetTableList);
408,540✔
717
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
408,572✔
718

719
  if (pRequest->self) {
408,582✔
720
    deregisterRequest(pRequest);
408,580✔
721
  }
722

723
  taosMemoryFreeClear(pRequest->pDb);
408,602!
724
  taosArrayDestroy(pRequest->dbList);
408,487✔
725
  if (pRequest->body.interParam) {
408,552!
726
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
408,562!
727
      tscError("failed to destroy semaphore in pRequest");
×
728
    }
729
  }
730
  taosMemoryFree(pRequest->body.interParam);
408,572!
731

732
  qDestroyQuery(pRequest->pQuery);
408,518✔
733
  nodesDestroyAllocator(pRequest->allocatorRefId);
408,551✔
734

735
  taosMemoryFreeClear(pRequest->effectiveUser);
408,584!
736
  taosMemoryFreeClear(pRequest->sqlstr);
408,584!
737
  taosMemoryFree(pRequest);
408,567!
738
  tscTrace("QID:0x%" PRIx64 ", end destroy request, res:%p", reqId, pRequest);
408,547!
739
  destroyNextReq(nextReqRefId);
408,547✔
740
}
741

742
void destroyRequest(SRequestObj *pRequest) {
408,609✔
743
  if (pRequest == NULL) return;
408,609!
744

745
  taos_stop_query(pRequest);
408,609✔
746
  (void)removeFromMostPrevReq(pRequest);
408,614✔
747
}
748

749
void taosStopQueryImpl(SRequestObj *pRequest) {
408,601✔
750
  pRequest->killed = true;
408,601✔
751

752
  // It is not a query, no need to stop.
753
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
408,601✔
754
    tscDebug("QID:0x%" PRIx64 ", no need to be killed since not query", pRequest->requestId);
36,381✔
755
    return;
36,403✔
756
  }
757

758
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
372,220✔
759
  tscDebug("QID:0x%" PRIx64 ", killed", pRequest->requestId);
372,209✔
760
}
761

762
void stopAllQueries(SRequestObj *pRequest) {
408,607✔
763
  int32_t      reqIdx = -1;
408,607✔
764
  SRequestObj *pReqList[16] = {NULL};
408,607✔
765
  uint64_t     tmpRefId = 0;
408,607✔
766

767
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
408,607!
768
    return;
×
769
  }
770

771
  SRequestObj *pTmp = pRequest;
408,607✔
772
  while (pTmp->relation.prevRefId) {
408,607!
773
    tmpRefId = pTmp->relation.prevRefId;
×
774
    pTmp = acquireRequest(tmpRefId);
×
775
    if (pTmp) {
×
776
      pReqList[++reqIdx] = pTmp;
×
777
    } else {
778
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
779
      break;
×
780
    }
781
  }
782

783
  for (int32_t i = reqIdx; i >= 0; i--) {
408,612!
784
    taosStopQueryImpl(pReqList[i]);
×
785
    (void)releaseRequest(pReqList[i]->self);  // ignore error
×
786
  }
787

788
  taosStopQueryImpl(pRequest);
408,612✔
789

790
  tmpRefId = pRequest->relation.nextRefId;
408,614✔
791
  while (tmpRefId) {
408,613!
792
    pTmp = acquireRequest(tmpRefId);
×
793
    if (pTmp) {
×
794
      tmpRefId = pTmp->relation.nextRefId;
×
795
      taosStopQueryImpl(pTmp);
×
796
      (void)releaseRequest(pTmp->self);  // ignore error
×
797
    } else {
798
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
799
      break;
×
800
    }
801
  }
802
}
803
#ifdef USE_REPORT
804
void crashReportThreadFuncUnexpectedStopped(void) { atomic_store_32(&clientStop, -1); }
×
805

806
static void *tscCrashReportThreadFp(void *param) {
×
807
  int32_t code = 0;
×
808
  setThreadName("client-crashReport");
×
809
  char filepath[PATH_MAX] = {0};
×
810
  (void)snprintf(filepath, sizeof(filepath), "%s%s.taosCrashLog", tsLogDir, TD_DIRSEP);
×
811
  char     *pMsg = NULL;
×
812
  int64_t   msgLen = 0;
×
813
  TdFilePtr pFile = NULL;
×
814
  bool      truncateFile = false;
×
815
  int32_t   sleepTime = 200;
×
816
  int32_t   reportPeriodNum = 3600 * 1000 / sleepTime;
×
817
  int32_t   loopTimes = reportPeriodNum;
×
818

819
#ifdef WINDOWS
820
  if (taosCheckCurrentInDll()) {
821
    atexit(crashReportThreadFuncUnexpectedStopped);
822
  }
823
#endif
824

825
  if (-1 != atomic_val_compare_exchange_32(&clientStop, -1, 0)) {
×
826
    return NULL;
×
827
  }
828
  STelemAddrMgmt mgt;
829
  code = taosTelemetryMgtInit(&mgt, tsTelemServer);
×
830
  if (code) {
×
831
    tscError("failed to init telemetry management, code:%s", tstrerror(code));
×
832
    return NULL;
×
833
  }
834

835
  code = initCrashLogWriter();
×
836
  if (code) {
×
837
    tscError("failed to init crash log writer, code:%s", tstrerror(code));
×
838
    return NULL;
×
839
  }
840

841
  while (1) {
842
    checkAndPrepareCrashInfo();
×
843
    if (clientStop > 0 && reportThreadSetQuit()) break;
×
844
    if (loopTimes++ < reportPeriodNum) {
×
845
      if (loopTimes < 0) loopTimes = reportPeriodNum;
×
846
      taosMsleep(sleepTime);
×
847
      continue;
×
848
    }
849

850
    taosReadCrashInfo(filepath, &pMsg, &msgLen, &pFile);
×
851
    if (pMsg && msgLen > 0) {
×
852
      if (taosSendTelemReport(&mgt, tsClientCrashReportUri, tsTelemPort, pMsg, msgLen, HTTP_FLAT) != 0) {
×
853
        tscError("failed to send crash report");
×
854
        if (pFile) {
×
855
          taosReleaseCrashLogFile(pFile, false);
×
856
          pFile = NULL;
×
857

858
          taosMsleep(sleepTime);
×
859
          loopTimes = 0;
×
860
          continue;
×
861
        }
862
      } else {
863
        tscInfo("succeed to send crash report");
×
864
        truncateFile = true;
×
865
      }
866
    } else {
867
      tscInfo("no crash info was found");
×
868
    }
869

870
    taosMemoryFree(pMsg);
×
871

872
    if (pMsg && msgLen > 0) {
×
873
      pMsg = NULL;
×
874
      continue;
×
875
    }
876

877
    if (pFile) {
×
878
      taosReleaseCrashLogFile(pFile, truncateFile);
×
879
      pFile = NULL;
×
880
      truncateFile = false;
×
881
    }
882

883
    taosMsleep(sleepTime);
×
884
    loopTimes = 0;
×
885
  }
886
  taosTelemetryDestroy(&mgt);
×
887

888
  clientStop = -2;
×
889
  return NULL;
×
890
}
891

892
int32_t tscCrashReportInit() {
2,546✔
893
  if (!tsEnableCrashReport) {
2,546!
894
    return TSDB_CODE_SUCCESS;
2,546✔
895
  }
896
  int32_t      code = TSDB_CODE_SUCCESS;
×
897
  TdThreadAttr thAttr;
898
  TSC_ERR_JRET(taosThreadAttrInit(&thAttr));
×
899
  TSC_ERR_JRET(taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE));
×
900
  TdThread crashReportThread;
901
  if (taosThreadCreate(&crashReportThread, &thAttr, tscCrashReportThreadFp, NULL) != 0) {
×
902
    tscError("failed to create crashReport thread since %s", strerror(ERRNO));
×
903
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
904
    TSC_ERR_RET(terrno);
×
905
  }
906

907
  (void)taosThreadAttrDestroy(&thAttr);
×
908
_return:
×
909
  if (code) {
×
910
    terrno = TAOS_SYSTEM_ERROR(ERRNO);
×
911
    TSC_ERR_RET(terrno);
×
912
  }
913

914
  return code;
×
915
}
916

917
void tscStopCrashReport() {
2,547✔
918
  if (!tsEnableCrashReport) {
2,547!
919
    return;
2,547✔
920
  }
921

922
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
923
    tscDebug("crash report thread already stopped");
×
924
    return;
×
925
  }
926

927
  while (atomic_load_32(&clientStop) > 0) {
×
928
    taosMsleep(100);
×
929
  }
930
}
931

932
void taos_write_crashinfo(int signum, void *sigInfo, void *context) {
×
933
  writeCrashLogToFile(signum, sigInfo, CUS_PROMPT, lastClusterId, appInfo.startTime);
×
934
}
×
935
#endif
936

937
#ifdef TAOSD_INTEGRATED
938
typedef struct {
939
  TdThread pid;
940
  int32_t  stat;  // < 0: start failed, 0: init(not start), 1: start successfully
941
} SDaemonObj;
942

943
extern int  dmStartDaemon(int argc, char const *argv[]);
944
extern void dmStopDaemon();
945

946
SDaemonObj daemonObj = {0};
947

948
typedef struct {
949
  int32_t argc;
950
  char  **argv;
951
} SExecArgs;
952

953
static void *dmStartDaemonFunc(void *param) {
954
  int32_t    code = 0;
955
  SExecArgs *pArgs = (SExecArgs *)param;
956
  int32_t    argc = pArgs->argc;
957
  char     **argv = pArgs->argv;
958

959
  code = dmStartDaemon(argc, (const char **)argv);
960
  if (code != 0) {
961
    printf("failed to start taosd since %s\r\n", tstrerror(code));
962
    goto _exit;
963
  }
964

965
_exit:
966
  if (code != 0) {
967
    atomic_store_32(&daemonObj.stat, code);
968
  }
969
  return NULL;
970
}
971

972
static int32_t shellStartDaemon(int argc, char *argv[]) {
973
  int32_t    code = 0, lino = 0;
974
  SExecArgs *pArgs = NULL;
975
  int64_t    startMs = taosGetTimestampMs(), endMs = startMs;
976

977
  TdThreadAttr thAttr;
978
  (void)taosThreadAttrInit(&thAttr);
979
  (void)taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE);
980
#ifdef TD_COMPACT_OS
981
  (void)taosThreadAttrSetStackSize(&thAttr, STACK_SIZE_SMALL);
982
#endif
983
  pArgs = (SExecArgs *)taosMemoryCalloc(1, sizeof(SExecArgs));
984
  if (pArgs == NULL) {
985
    code = terrno;
986
    TAOS_CHECK_EXIT(code);
987
  }
988
  pArgs->argc = argc;
989
  pArgs->argv = argv;
990

991
#ifndef TD_AS_LIB
992
  tsLogEmbedded = 1;
993
#endif
994

995
  TAOS_CHECK_EXIT(taosThreadCreate(&daemonObj.pid, &thAttr, dmStartDaemonFunc, pArgs));
996

997
  while (true) {
998
    if (atomic_load_64(&tsDndStart)) {
999
      atomic_store_32(&daemonObj.stat, 1);
1000
      break;
1001
    }
1002
    int32_t daemonstat = atomic_load_32(&daemonObj.stat);
1003
    if (daemonstat < 0) {
1004
      code = daemonstat;
1005
      TAOS_CHECK_EXIT(code);
1006
    }
1007

1008
    if (daemonstat > 1) {
1009
      code = TSDB_CODE_APP_ERROR;
1010
      TAOS_CHECK_EXIT(code);
1011
    }
1012
    taosMsleep(1000);
1013
  }
1014

1015
_exit:
1016
  endMs = taosGetTimestampMs();
1017
  (void)taosThreadAttrDestroy(&thAttr);
1018
  taosMemoryFreeClear(pArgs);
1019
  if (code) {
1020
    printf("\r\n The daemon start failed at line %d since %s, cost %" PRIi64 " ms\r\n", lino, tstrerror(code),
1021
           endMs - startMs);
1022
  } else {
1023
    printf("\r\n The daemon started successfully, cost %" PRIi64 " ms\r\n", endMs - startMs);
1024
  }
1025
#ifndef TD_AS_LIB
1026
  tsLogEmbedded = 0;
1027
#endif
1028
  return code;
1029
}
1030

1031
void shellStopDaemon() {
1032
#ifndef TD_AS_LIB
1033
  tsLogEmbedded = 1;
1034
#endif
1035
  dmStopDaemon();
1036
  if (taosCheckPthreadValid(daemonObj.pid)) {
1037
    (void)taosThreadJoin(daemonObj.pid, NULL);
1038
    taosThreadClear(&daemonObj.pid);
1039
  }
1040
}
1041
#endif
1042

1043
void taos_init_imp(void) {
2,547✔
1044
#if defined(LINUX)
1045
  if (tscDbg.memEnable) {
2,547!
1046
    int32_t code = taosMemoryDbgInit();
×
1047
    if (code) {
×
1048
      (void)printf("failed to init memory dbg, error:%s\n", tstrerror(code));
×
1049
    } else {
1050
      tsAsyncLog = false;
×
1051
      (void)printf("memory dbg enabled\n");
×
1052
    }
1053
  }
1054
#endif
1055

1056
  // In the APIs of other program language, taos_cleanup is not available yet.
1057
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
1058
  (void)atexit(taos_cleanup);
2,547✔
1059
  SET_ERRNO(TSDB_CODE_SUCCESS);
2,547✔
1060
  terrno = TSDB_CODE_SUCCESS;
2,547✔
1061
  taosSeedRand(taosGetTimestampSec());
2,547✔
1062

1063
  appInfo.pid = taosGetPId();
2,547✔
1064
  appInfo.startTime = taosGetTimestampMs();
2,547✔
1065
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
2,547✔
1066
  appInfo.pInstMapByClusterId =
2,547✔
1067
      taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);
2,547✔
1068
  if (NULL == appInfo.pInstMap || NULL == appInfo.pInstMapByClusterId) {
2,547!
1069
    (void)printf("failed to allocate memory when init appInfo\n");
×
1070
    tscInitRes = terrno;
×
1071
    return;
1✔
1072
  }
1073
  taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst);
2,547✔
1074

1075
  const char *logName = CUS_PROMPT "log";
2,547✔
1076
  ENV_ERR_RET(taosInitLogOutput(&logName), "failed to init log output");
2,547!
1077
  if (taosCreateLog(logName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
2,547✔
1078
    (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logName, strerror(ERRNO), configDir);
1✔
1079
    tscInitRes = terrno;
1✔
1080
    return;
1✔
1081
  }
1082

1083
#ifdef TAOSD_INTEGRATED
1084
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0), "failed to init cfg");
1085
#else
1086
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
2,546!
1087
#endif
1088

1089
  initQueryModuleMsgHandle();
2,546✔
1090
#ifndef DISALLOW_NCHAR_WITHOUT_ICONV
1091
  if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL) {
2,546!
1092
    tscInitRes = terrno;
×
1093
    tscError("failed to init conv");
×
1094
    return;
×
1095
  }
1096
#endif
1097
#if !defined(WINDOWS) && !defined(TD_ASTRA)
1098
  ENV_ERR_RET(tzInit(), "failed to init timezone");
2,546!
1099
#endif
1100
  ENV_ERR_RET(monitorInit(), "failed to init monitor");
2,546!
1101
  ENV_ERR_RET(rpcInit(), "failed to init rpc");
2,546!
1102

1103
  if (InitRegexCache() != 0) {
2,546!
1104
    tscInitRes = terrno;
×
1105
    (void)printf("failed to init regex cache\n");
×
1106
    return;
×
1107
  }
1108

1109
  tscInfo("starting to initialize TAOS driver");
2,546!
1110

1111
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
2,546✔
1112
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
2,546!
1113
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
2,546!
1114
  ENV_ERR_RET(initClientId(), "failed to init clientId");
2,546!
1115

1116
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
2,546!
1117
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
2,546!
1118
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
2,546!
1119

1120
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
2,546✔
1121
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
2,546✔
1122

1123
  ENV_ERR_RET(taosGetAppName(appInfo.appName, NULL), "failed to get app name");
2,546!
1124
  ENV_ERR_RET(taosThreadMutexInit(&appInfo.mutex, NULL), "failed to init thread mutex");
2,546!
1125
#ifdef USE_REPORT
1126
  ENV_ERR_RET(tscCrashReportInit(), "failed to init crash report");
2,546!
1127
#endif
1128
  ENV_ERR_RET(qInitKeywordsTable(), "failed to init parser keywords table");
2,546!
1129
#ifdef TAOSD_INTEGRATED
1130
  ENV_ERR_RET(shellStartDaemon(0, NULL), "failed to start taosd daemon");
1131
#endif
1132
  tscInfo("TAOS driver is initialized successfully");
2,546!
1133
}
1134

1135
int taos_init() {
3,900✔
1136
  (void)taosThreadOnce(&tscinit, taos_init_imp);
3,900✔
1137
  return tscInitRes;
3,900✔
1138
}
1139

1140
const char *getCfgName(TSDB_OPTION option) {
532✔
1141
  const char *name = NULL;
532✔
1142

1143
  switch (option) {
532!
1144
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
×
1145
      name = "shellActivityTimer";
×
1146
      break;
×
1147
    case TSDB_OPTION_LOCALE:
×
1148
      name = "locale";
×
1149
      break;
×
1150
    case TSDB_OPTION_CHARSET:
×
1151
      name = "charset";
×
1152
      break;
×
1153
    case TSDB_OPTION_TIMEZONE:
9✔
1154
      name = "timezone";
9✔
1155
      break;
9✔
1156
    case TSDB_OPTION_USE_ADAPTER:
×
1157
      name = "useAdapter";
×
1158
      break;
×
1159
    default:
523✔
1160
      break;
523✔
1161
  }
1162

1163
  return name;
532✔
1164
}
1165

1166
int taos_options_imp(TSDB_OPTION option, const char *str) {
927✔
1167
  if (option == TSDB_OPTION_CONFIGDIR) {
927✔
1168
#ifndef WINDOWS
1169
    char newstr[PATH_MAX];
1170
    int  len = strlen(str);
395✔
1171
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
395!
1172
      if (len + 2 >= PATH_MAX) {
395!
1173
        tscError("Too long path %s", str);
×
1174
        return -1;
×
1175
      }
1176
      newstr[0] = '"';
395✔
1177
      (void)memcpy(newstr + 1, str, len);
395✔
1178
      newstr[len + 1] = '"';
395✔
1179
      newstr[len + 2] = '\0';
395✔
1180
      str = newstr;
395✔
1181
    }
1182
#endif
1183
    tstrncpy(configDir, str, PATH_MAX);
395✔
1184
    tscInfo("set cfg:%s to %s", configDir, str);
395!
1185
    return 0;
395✔
1186
  }
1187

1188
  // initialize global config
1189
  if (taos_init() != 0) {
532!
1190
    return -1;
×
1191
  }
1192

1193
  SConfig     *pCfg = taosGetCfg();
532✔
1194
  SConfigItem *pItem = NULL;
532✔
1195
  const char  *name = getCfgName(option);
532✔
1196

1197
  if (name == NULL) {
532✔
1198
    tscError("Invalid option %d", option);
523!
1199
    return -1;
523✔
1200
  }
1201

1202
  pItem = cfgGetItem(pCfg, name);
9✔
1203
  if (pItem == NULL) {
9!
1204
    tscError("Invalid option %d", option);
×
1205
    return -1;
×
1206
  }
1207

1208
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
9✔
1209
  if (code != 0) {
9!
1210
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
×
1211
  } else {
1212
    tscInfo("set cfg:%s to %s", name, str);
9!
1213
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
9!
1214
      code = taosCfgDynamicOptions(pCfg, name, false);
×
1215
    }
1216
  }
1217

1218
  return code;
9✔
1219
}
1220

1221
/**
1222
 * The request id is an unsigned integer format of 64bit.
1223
 *+------------+-----+-----------+---------------+
1224
 *| uid|localIp| PId | timestamp | serial number |
1225
 *+------------+-----+-----------+---------------+
1226
 *| 12bit      |12bit|24bit      |16bit          |
1227
 *+------------+-----+-----------+---------------+
1228
 * @return
1229
 */
1230
uint64_t generateRequestId() {
468,472✔
1231
  static uint32_t hashId = 0;
1232
  static int32_t  requestSerialId = 0;
1233

1234
  if (hashId == 0) {
468,472✔
1235
    int32_t code = taosGetSystemUUIDU32(&hashId);
2,212✔
1236
    if (code != TSDB_CODE_SUCCESS) {
2,212!
1237
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1238
               tstrerror(code));
1239
    }
1240
  }
1241

1242
  uint64_t id = 0;
468,471✔
1243

1244
  while (true) {
×
1245
    int64_t  ts = taosGetTimestampMs();
468,504✔
1246
    uint64_t pid = taosGetPId();
468,504✔
1247
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
468,472✔
1248
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
468,503!
1249

1250
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
468,511✔
1251
    if (id) {
468,511!
1252
      break;
468,511✔
1253
    }
1254
  }
1255
  return id;
468,511✔
1256
}
1257

1258
#if 0
1259
#include "cJSON.h"
1260
static setConfRet taos_set_config_imp(const char *config){
1261
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
1262
  static bool setConfFlag = false;
1263
  if (setConfFlag) {
1264
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
1265
    tstrncpy(ret.retMsg, "configuration can only set once", RET_MSG_LENGTH);
1266
    return ret;
1267
  }
1268
  taosInitGlobalCfg();
1269
  cJSON *root = cJSON_Parse(config);
1270
  if (root == NULL){
1271
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
1272
    tstrncpy(ret.retMsg, "parse json error", RET_MSG_LENGTH);
1273
    return ret;
1274
  }
1275

1276
  int size = cJSON_GetArraySize(root);
1277
  if(!cJSON_IsObject(root) || size == 0) {
1278
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
1279
    tstrncpy(ret.retMsg, "json content is invalid, must be not empty object", RET_MSG_LENGTH);
1280
    return ret;
1281
  }
1282

1283
  if(size >= 1000) {
1284
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
1285
    tstrncpy(ret.retMsg, "json object size is too long", RET_MSG_LENGTH);
1286
    return ret;
1287
  }
1288

1289
  for(int i = 0; i < size; i++){
1290
    cJSON *item = cJSON_GetArrayItem(root, i);
1291
    if(!item) {
1292
      ret.retCode = SET_CONF_RET_ERR_INNER;
1293
      tstrncpy(ret.retMsg, "inner error", RET_MSG_LENGTH);
1294
      return ret;
1295
    }
1296
    if(!taosReadConfigOption(item->string, item->valuestring, NULL, NULL, TAOS_CFG_CSTATUS_OPTION, TSDB_CFG_CTYPE_B_CLIENT)){
1297
      ret.retCode = SET_CONF_RET_ERR_PART;
1298
      if (strlen(ret.retMsg) == 0){
1299
        snprintf(ret.retMsg, RET_MSG_LENGTH, "part error|%s", item->string);
1300
      }else{
1301
        int tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1302
        size_t leftSize = tmp >= 0 ? tmp : 0;
1303
        strncat(ret.retMsg, "|",  leftSize);
1304
        tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1305
        leftSize = tmp >= 0 ? tmp : 0;
1306
        strncat(ret.retMsg, item->string, leftSize);
1307
      }
1308
    }
1309
  }
1310
  cJSON_Delete(root);
1311
  setConfFlag = true;
1312
  return ret;
1313
}
1314

1315
setConfRet taos_set_config(const char *config){
1316
  taosThreadMutexLock(&setConfMutex);
1317
  setConfRet ret = taos_set_config_imp(config);
1318
  taosThreadMutexUnlock(&setConfMutex);
1319
  return ret;
1320
}
1321
#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