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

taosdata / TDengine / #3647

13 Mar 2025 05:26AM UTC coverage: 25.9% (-2.5%) from 28.375%
#3647

push

travis-ci

web-flow
Merge pull request #30158 from taosdata/docs/anchor-caps-30

docs: lowercase anchors for 3.0

53974 of 285572 branches covered (18.9%)

Branch coverage included in aggregate %.

92870 of 281392 relevant lines covered (33.0%)

617448.64 hits per line

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

40.23
/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
      errno = _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) {
1,553✔
80
  int32_t code = TSDB_CODE_SUCCESS;
1,553✔
81
  // connection has been released already, abort creating request.
82
  pRequest->self = taosAddRef(clientReqRefPool, pRequest);
1,553✔
83
  if (pRequest->self < 0) {
1,553!
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);
1,553✔
90

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

94
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
1,553✔
95
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
1,553✔
96
    tscDebug("req:0x%" PRIx64 ", new from connObj:0x%" PRIx64 ", current:%d, app current:%d, total:%d, QID:0x%" PRIx64,
1,553!
97
             pRequest->self, pRequest->pTscObj->id, num, currentInst, total, pRequest->requestId);
98
  }
99

100
  return code;
1,553✔
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

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

221
static bool checkSlowLogExceptDb(SRequestObj *pRequest, char *exceptDb) {
1✔
222
  if (pRequest->pDb != NULL) {
1!
223
    return strcmp(pRequest->pDb, exceptDb) != 0;
×
224
  }
225

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

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

249
  STscObj            *pTscObj = pRequest->pTscObj;
1,545✔
250
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
1,545✔
251

252
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
1,545✔
253
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);
1,545✔
254
  int32_t reqType = SLOW_LOG_TYPE_OTHERS;
1,545✔
255

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

261
  if (TSDB_CODE_SUCCESS == nodesSimAcquireAllocator(pRequest->allocatorRefId)) {
1,545!
262
    if ((pRequest->pQuery && pRequest->pQuery->pRoot && QUERY_NODE_VNODE_MODIFY_STMT == pRequest->pQuery->pRoot->type &&
1,545!
263
         (0 == ((SVnodeModifyOpStmt *)pRequest->pQuery->pRoot)->sqlNodeType)) ||
948✔
264
        QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType) {
908✔
265
      tscDebug("req:0x%" PRIx64 ", insert duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
1,005!
266
               "us, analyseCost:%" PRId64 "us, planCost:%" PRId64 "us, exec:%" PRId64 "us",
267
               pRequest->self, duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs,
268
               pRequest->metric.analyseCostUs, pRequest->metric.planCostUs, pRequest->metric.execCostUs);
269
      (void)atomic_add_fetch_64((int64_t *)&pActivity->insertElapsedTime, duration);
1,005✔
270
      reqType = SLOW_LOG_TYPE_INSERT;
1,005✔
271
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
540✔
272
      tscDebug("req:0x%" PRIx64 ", query duration:%" PRId64 "us, parseCost:%" PRId64 "us, ctgCost:%" PRId64
165!
273
               "us, analyseCost:%" PRId64 "us, planCost:%" PRId64 "us, exec:%" PRId64 "us",
274
               pRequest->self, duration, pRequest->metric.parseCostUs, pRequest->metric.ctgCostUs,
275
               pRequest->metric.analyseCostUs, pRequest->metric.planCostUs, pRequest->metric.execCostUs);
276

277
      (void)atomic_add_fetch_64((int64_t *)&pActivity->queryElapsedTime, duration);
165✔
278
      reqType = SLOW_LOG_TYPE_QUERY;
165✔
279
    }
280

281
    if (TSDB_CODE_SUCCESS != nodesSimReleaseAllocator(pRequest->allocatorRefId)) {
1,545!
282
      tscError("failed to release allocator");
×
283
    }
284
  }
285

286
  if (pTscObj->pAppInfo->serverCfg.monitorParas.tsEnableMonitor) {
1,545✔
287
    if (QUERY_NODE_VNODE_MODIFY_STMT == pRequest->stmtType || QUERY_NODE_INSERT_STMT == pRequest->stmtType) {
1,544!
288
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEINSERT);
1,005✔
289
    } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
539✔
290
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPESELECT);
165✔
291
    } else if (QUERY_NODE_DELETE_STMT == pRequest->stmtType) {
374!
292
      sqlReqLog(pTscObj->id, pRequest->killed, pRequest->code, MONITORSQLTYPEDELETE);
×
293
    }
294
  }
295

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

312
  releaseTscObj(pTscObj->id);
1,545✔
313
}
314

315
// todo close the transporter properly
316
void closeTransporter(SAppInstInfo *pAppInfo) {
7✔
317
  if (pAppInfo == NULL || pAppInfo->pTransporter == NULL) {
7!
318
    return;
×
319
  }
320

321
  tscDebug("free transporter:%p in app inst %p", pAppInfo->pTransporter, pAppInfo);
7!
322
  rpcClose(pAppInfo->pTransporter);
7✔
323
}
324

325
static bool clientRpcRfp(int32_t code, tmsg_t msgType) {
18✔
326
  if (NEED_REDIRECT_ERROR(code)) {
18!
327
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
5!
328
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_QUERY_HEARTBEAT || msgType == TDMT_SCH_DROP_TASK ||
5!
329
        msgType == TDMT_SCH_TASK_NOTIFY) {
330
      return false;
×
331
    }
332
    return true;
5✔
333
  } else {
334
    return false;
13✔
335
  }
336
}
337

338
// start timer for particular msgType
339
static bool clientRpcTfp(int32_t code, tmsg_t msgType) {
×
340
  if (msgType == TDMT_VND_SUBMIT || msgType == TDMT_VND_CREATE_TABLE) {
×
341
    return true;
×
342
  }
343
  return false;
×
344
}
345

346
// TODO refactor
347
int32_t openTransporter(const char *user, const char *auth, int32_t numOfThread, void **pDnodeConn) {
7✔
348
  SRpcInit rpcInit;
349
  (void)memset(&rpcInit, 0, sizeof(rpcInit));
7✔
350
  rpcInit.localPort = 0;
7✔
351
  rpcInit.label = "TSC";
7✔
352
  rpcInit.numOfThreads = tsNumOfRpcThreads;
7✔
353
  rpcInit.cfp = processMsgFromServer;
7✔
354
  rpcInit.rfp = clientRpcRfp;
7✔
355
  rpcInit.sessions = 1024;
7✔
356
  rpcInit.connType = TAOS_CONN_CLIENT;
7✔
357
  rpcInit.user = (char *)user;
7✔
358
  rpcInit.idleTime = tsShellActivityTimer * 1000;
7✔
359
  rpcInit.compressSize = tsCompressMsgSize;
7✔
360
  rpcInit.dfp = destroyAhandle;
7✔
361

362
  rpcInit.retryMinInterval = tsRedirectPeriod;
7✔
363
  rpcInit.retryStepFactor = tsRedirectFactor;
7✔
364
  rpcInit.retryMaxInterval = tsRedirectMaxPeriod;
7✔
365
  rpcInit.retryMaxTimeout = tsMaxRetryWaitTime;
7✔
366

367
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
7✔
368
  connLimitNum = TMAX(connLimitNum, 10);
7✔
369
  connLimitNum = TMIN(connLimitNum, 1000);
7✔
370
  rpcInit.connLimitNum = connLimitNum;
7✔
371
  rpcInit.shareConnLimit = tsShareConnLimit;
7✔
372
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
7✔
373
  rpcInit.startReadTimer = 1;
7✔
374
  rpcInit.readTimeout = tsReadTimeout;
7✔
375

376
  int32_t code = taosVersionStrToInt(td_version, &rpcInit.compatibilityVer);
7✔
377
  if (TSDB_CODE_SUCCESS != code) {
7!
378
    tscError("invalid version string.");
×
379
    return code;
×
380
  }
381

382
  *pDnodeConn = rpcOpen(&rpcInit);
7✔
383
  if (*pDnodeConn == NULL) {
7!
384
    tscError("failed to init connection to server since %s", tstrerror(terrno));
×
385
    code = terrno;
×
386
  }
387

388
  return code;
7✔
389
}
390

391
void destroyAllRequests(SHashObj *pRequests) {
81✔
392
  void *pIter = taosHashIterate(pRequests, NULL);
81✔
393
  while (pIter != NULL) {
81!
394
    int64_t *rid = pIter;
×
395

396
    SRequestObj *pRequest = acquireRequest(*rid);
×
397
    if (pRequest) {
×
398
      destroyRequest(pRequest);
×
399
      (void)releaseRequest(*rid);  // ignore error
×
400
    }
401

402
    pIter = taosHashIterate(pRequests, pIter);
×
403
  }
404
}
81✔
405

406
void stopAllRequests(SHashObj *pRequests) {
×
407
  void *pIter = taosHashIterate(pRequests, NULL);
×
408
  while (pIter != NULL) {
×
409
    int64_t *rid = pIter;
×
410

411
    SRequestObj *pRequest = acquireRequest(*rid);
×
412
    if (pRequest) {
×
413
      taos_stop_query(pRequest);
×
414
      (void)releaseRequest(*rid);  // ignore error
×
415
    }
416

417
    pIter = taosHashIterate(pRequests, pIter);
×
418
  }
419
}
×
420

421
void destroyAppInst(void *info) {
7✔
422
  SAppInstInfo *pAppInfo = *(SAppInstInfo **)info;
7✔
423
  tscDebug("destroy app inst mgr %p", pAppInfo);
7!
424

425
  int32_t code = taosThreadMutexLock(&appInfo.mutex);
7✔
426
  if (TSDB_CODE_SUCCESS != code) {
7!
427
    tscError("failed to lock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
428
  }
429

430
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
7✔
431

432
  code = taosThreadMutexUnlock(&appInfo.mutex);
7✔
433
  if (TSDB_CODE_SUCCESS != code) {
7!
434
    tscError("failed to unlock app info, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
435
  }
436

437
  taosMemoryFreeClear(pAppInfo->instKey);
7!
438
  closeTransporter(pAppInfo);
7✔
439

440
  code = taosThreadMutexLock(&pAppInfo->qnodeMutex);
7✔
441
  if (TSDB_CODE_SUCCESS != code) {
7!
442
    tscError("failed to lock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
443
  }
444

445
  taosArrayDestroy(pAppInfo->pQnodeList);
7✔
446
  code = taosThreadMutexUnlock(&pAppInfo->qnodeMutex);
7✔
447
  if (TSDB_CODE_SUCCESS != code) {
7!
448
    tscError("failed to unlock qnode mutex, code:%s", tstrerror(TAOS_SYSTEM_ERROR(code)));
×
449
  }
450

451
  taosMemoryFree(pAppInfo);
7!
452
}
7✔
453

454
void destroyTscObj(void *pObj) {
81✔
455
  if (NULL == pObj) {
81!
456
    return;
×
457
  }
458

459
  STscObj *pTscObj = pObj;
81✔
460
  int64_t  tscId = pTscObj->id;
81✔
461
  tscTrace("connObj:%" PRIx64 ", begin destroy, p:%p", tscId, pTscObj);
81!
462

463
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
81✔
464
  hbDeregisterConn(pTscObj, connKey);
81✔
465

466
  destroyAllRequests(pTscObj->pRequests);
81✔
467
  taosHashCleanup(pTscObj->pRequests);
81✔
468

469
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
81✔
470
  tscDebug("connObj:0x%" PRIx64 ", p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
81!
471
           pTscObj->pAppInfo->numOfConns);
472

473
  // In any cases, we should not free app inst here. Or an race condition rises.
474
  /*int64_t connNum = */ (void)atomic_sub_fetch_64(&pTscObj->pAppInfo->numOfConns, 1);
81✔
475

476
  (void)taosThreadMutexDestroy(&pTscObj->mutex);
81✔
477
  taosMemoryFree(pTscObj);
81!
478

479
  tscTrace("connObj:0x%" PRIx64 ", end destroy, p:%p", tscId, pTscObj);
81!
480
}
481

482
int32_t createTscObj(const char *user, const char *auth, const char *db, int32_t connType, SAppInstInfo *pAppInfo,
92✔
483
                     STscObj **pObj) {
484
  *pObj = (STscObj *)taosMemoryCalloc(1, sizeof(STscObj));
92!
485
  if (NULL == *pObj) {
92!
486
    return terrno;
×
487
  }
488

489
  (*pObj)->pRequests = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
92✔
490
  if (NULL == (*pObj)->pRequests) {
92!
491
    taosMemoryFree(*pObj);
×
492
    return terrno ? terrno : TSDB_CODE_OUT_OF_MEMORY;
×
493
  }
494

495
  (*pObj)->connType = connType;
92✔
496
  (*pObj)->pAppInfo = pAppInfo;
92✔
497
  (*pObj)->appHbMgrIdx = pAppInfo->pAppHbMgr->idx;
92✔
498
  tstrncpy((*pObj)->user, user, sizeof((*pObj)->user));
92✔
499
  (void)memcpy((*pObj)->pass, auth, TSDB_PASSWORD_LEN);
92✔
500

501
  if (db != NULL) {
92!
502
    tstrncpy((*pObj)->db, db, tListLen((*pObj)->db));
92✔
503
  }
504

505
  TSC_ERR_RET(taosThreadMutexInit(&(*pObj)->mutex, NULL));
92!
506

507
  int32_t code = TSDB_CODE_SUCCESS;
92✔
508

509
  (*pObj)->id = taosAddRef(clientConnRefPool, *pObj);
92✔
510
  if ((*pObj)->id < 0) {
92!
511
    tscError("failed to add object to clientConnRefPool");
×
512
    code = terrno;
×
513
    taosMemoryFree(*pObj);
×
514
    return code;
×
515
  }
516

517
  (void)atomic_add_fetch_64(&(*pObj)->pAppInfo->numOfConns, 1);
92✔
518

519
  tscInfo("connObj:0x%" PRIx64 ", created, p:%p", (*pObj)->id, *pObj);
92!
520
  return code;
92✔
521
}
522

523
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
3,380✔
524

525
void releaseTscObj(int64_t rid) {
3,206✔
526
  int32_t code = taosReleaseRef(clientConnRefPool, rid);
3,206✔
527
  if (TSDB_CODE_SUCCESS != code) {
3,206!
528
    tscWarn("failed to release TscObj, code:%s", tstrerror(code));
×
529
  }
530
}
3,206✔
531

532
int32_t createRequest(uint64_t connId, int32_t type, int64_t reqid, SRequestObj **pRequest) {
1,553✔
533
  int32_t code = TSDB_CODE_SUCCESS;
1,553✔
534
  *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
1,553!
535
  if (NULL == *pRequest) {
1,553!
536
    return terrno;
×
537
  }
538

539
  STscObj *pTscObj = acquireTscObj(connId);
1,553✔
540
  if (pTscObj == NULL) {
1,553!
541
    TSC_ERR_JRET(TSDB_CODE_TSC_DISCONNECTED);
×
542
  }
543
  SSyncQueryParam *interParam = taosMemoryCalloc(1, sizeof(SSyncQueryParam));
1,553!
544
  if (interParam == NULL) {
1,553!
545
    releaseTscObj(connId);
×
546
    TSC_ERR_JRET(terrno);
×
547
  }
548
  TSC_ERR_JRET(tsem_init(&interParam->sem, 0, 0));
1,553!
549
  interParam->pRequest = *pRequest;
1,553✔
550
  (*pRequest)->body.interParam = interParam;
1,553✔
551

552
  (*pRequest)->resType = RES_TYPE__QUERY;
1,553✔
553
  (*pRequest)->requestId = reqid == 0 ? generateRequestId() : reqid;
1,553!
554
  (*pRequest)->metric.start = taosGetTimestampUs();
1,553✔
555

556
  (*pRequest)->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
1,553✔
557
  (*pRequest)->body.resInfo.charsetCxt = pTscObj->optionInfo.charsetCxt;
1,553✔
558
  (*pRequest)->type = type;
1,553✔
559
  (*pRequest)->allocatorRefId = -1;
1,553✔
560

561
  (*pRequest)->pDb = getDbOfConnection(pTscObj);
1,553✔
562
  if (NULL == (*pRequest)->pDb) {
1,553✔
563
    TSC_ERR_JRET(terrno);
617!
564
  }
565
  (*pRequest)->pTscObj = pTscObj;
1,553✔
566
  (*pRequest)->inCallback = false;
1,553✔
567
  (*pRequest)->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
1,553!
568
  if (NULL == (*pRequest)->msgBuf) {
1,553!
569
    code = terrno;
×
570
    goto _return;
×
571
  }
572
  (*pRequest)->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
1,553✔
573
  TSC_ERR_JRET(tsem_init(&(*pRequest)->body.rspSem, 0, 0));
1,553!
574
  TSC_ERR_JRET(registerRequest(*pRequest, pTscObj));
1,553!
575

576
  return TSDB_CODE_SUCCESS;
1,553✔
577
_return:
×
578
  if ((*pRequest)->pTscObj) {
×
579
    doDestroyRequest(*pRequest);
×
580
  } else {
581
    taosMemoryFree(*pRequest);
×
582
  }
583
  return code;
×
584
}
585

586
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
1,545✔
587
  taosMemoryFreeClear(pResInfo->pRspMsg);
1,545!
588
  taosMemoryFreeClear(pResInfo->length);
1,545!
589
  taosMemoryFreeClear(pResInfo->row);
1,545!
590
  taosMemoryFreeClear(pResInfo->pCol);
1,545!
591
  taosMemoryFreeClear(pResInfo->fields);
1,545!
592
  taosMemoryFreeClear(pResInfo->userFields);
1,545!
593
  taosMemoryFreeClear(pResInfo->convertJson);
1,545!
594
  taosMemoryFreeClear(pResInfo->decompBuf);
1,545!
595

596
  if (pResInfo->convertBuf != NULL) {
1,545✔
597
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
459✔
598
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
292!
599
    }
600
    taosMemoryFreeClear(pResInfo->convertBuf);
167!
601
  }
602
}
1,545✔
603

604
SRequestObj *acquireRequest(int64_t rid) { return (SRequestObj *)taosAcquireRef(clientReqRefPool, rid); }
5,548✔
605

606
int32_t releaseRequest(int64_t rid) { return taosReleaseRef(clientReqRefPool, rid); }
5,539✔
607

608
int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }
1,545✔
609

610
/// return the most previous req ref id
611
int64_t removeFromMostPrevReq(SRequestObj *pRequest) {
1,545✔
612
  int64_t      mostPrevReqRefId = pRequest->self;
1,545✔
613
  SRequestObj *pTmp = pRequest;
1,545✔
614
  while (pTmp->relation.prevRefId) {
1,545!
615
    pTmp = acquireRequest(pTmp->relation.prevRefId);
×
616
    if (pTmp) {
×
617
      mostPrevReqRefId = pTmp->self;
×
618
      (void)releaseRequest(mostPrevReqRefId);  // ignore error
×
619
    } else {
620
      break;
×
621
    }
622
  }
623
  (void)removeRequest(mostPrevReqRefId);  // ignore error
1,545✔
624
  return mostPrevReqRefId;
1,545✔
625
}
626

627
void destroyNextReq(int64_t nextRefId) {
1,545✔
628
  if (nextRefId) {
1,545!
629
    SRequestObj *pObj = acquireRequest(nextRefId);
×
630
    if (pObj) {
×
631
      (void)releaseRequest(nextRefId);  // ignore error
×
632
      (void)releaseRequest(nextRefId);  // ignore error
×
633
    }
634
  }
635
}
1,545✔
636

637
void destroySubRequests(SRequestObj *pRequest) {
×
638
  int32_t      reqIdx = -1;
×
639
  SRequestObj *pReqList[16] = {NULL};
×
640
  uint64_t     tmpRefId = 0;
×
641

642
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
×
643
    return;
×
644
  }
645

646
  SRequestObj *pTmp = pRequest;
×
647
  while (pTmp->relation.prevRefId) {
×
648
    tmpRefId = pTmp->relation.prevRefId;
×
649
    pTmp = acquireRequest(tmpRefId);
×
650
    if (pTmp) {
×
651
      pReqList[++reqIdx] = pTmp;
×
652
      (void)releaseRequest(tmpRefId);  // ignore error
×
653
    } else {
654
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
655
      break;
×
656
    }
657
  }
658

659
  for (int32_t i = reqIdx; i >= 0; i--) {
×
660
    (void)removeRequest(pReqList[i]->self);  // ignore error
×
661
  }
662

663
  tmpRefId = pRequest->relation.nextRefId;
×
664
  while (tmpRefId) {
×
665
    pTmp = acquireRequest(tmpRefId);
×
666
    if (pTmp) {
×
667
      tmpRefId = pTmp->relation.nextRefId;
×
668
      (void)removeRequest(pTmp->self);   // ignore error
×
669
      (void)releaseRequest(pTmp->self);  // ignore error
×
670
    } else {
671
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
672
      break;
×
673
    }
674
  }
675
}
676

677
void doDestroyRequest(void *p) {
1,545✔
678
  if (NULL == p) {
1,545!
679
    return;
×
680
  }
681

682
  SRequestObj *pRequest = (SRequestObj *)p;
1,545✔
683

684
  uint64_t reqId = pRequest->requestId;
1,545✔
685
  tscDebug("QID:0x%" PRIx64 ", begin destroy request, res:%p", reqId, pRequest);
1,545!
686

687
  int64_t nextReqRefId = pRequest->relation.nextRefId;
1,545✔
688

689
  int32_t code = taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
1,545✔
690
  if (TSDB_CODE_SUCCESS != code) {
1,545✔
691
    tscDebug("failed to remove request from hash since %s", tstrerror(code));
92!
692
  }
693
  schedulerFreeJob(&pRequest->body.queryJob, 0);
1,545✔
694

695
  destorySqlCallbackWrapper(pRequest->pWrapper);
1,545✔
696

697
  taosMemoryFreeClear(pRequest->msgBuf);
1,545!
698

699
  doFreeReqResultInfo(&pRequest->body.resInfo);
1,545✔
700
  if (TSDB_CODE_SUCCESS != tsem_destroy(&pRequest->body.rspSem)) {
1,545!
701
    tscError("failed to destroy semaphore");
×
702
  }
703

704
  taosArrayDestroy(pRequest->tableList);
1,545✔
705
  taosArrayDestroy(pRequest->targetTableList);
1,545✔
706
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
1,545✔
707

708
  if (pRequest->self) {
1,545!
709
    deregisterRequest(pRequest);
1,545✔
710
  }
711

712
  taosMemoryFreeClear(pRequest->pDb);
1,545!
713
  taosArrayDestroy(pRequest->dbList);
1,545✔
714
  if (pRequest->body.interParam) {
1,545!
715
    if (TSDB_CODE_SUCCESS != tsem_destroy(&((SSyncQueryParam *)pRequest->body.interParam)->sem)) {
1,545!
716
      tscError("failed to destroy semaphore in pRequest");
×
717
    }
718
  }
719
  taosMemoryFree(pRequest->body.interParam);
1,545!
720

721
  qDestroyQuery(pRequest->pQuery);
1,545✔
722
  nodesDestroyAllocator(pRequest->allocatorRefId);
1,545✔
723

724
  taosMemoryFreeClear(pRequest->effectiveUser);
1,545!
725
  taosMemoryFreeClear(pRequest->sqlstr);
1,545!
726
  taosMemoryFree(pRequest);
1,545!
727
  tscDebug("QID:0x%" PRIx64 ", end destroy request, res:%p", reqId, pRequest);
1,545!
728
  destroyNextReq(nextReqRefId);
1,545✔
729
}
730

731
void destroyRequest(SRequestObj *pRequest) {
1,545✔
732
  if (pRequest == NULL) return;
1,545!
733

734
  taos_stop_query(pRequest);
1,545✔
735
  (void)removeFromMostPrevReq(pRequest);
1,545✔
736
}
737

738
void taosStopQueryImpl(SRequestObj *pRequest) {
1,545✔
739
  pRequest->killed = true;
1,545✔
740

741
  // It is not a query, no need to stop.
742
  if (NULL == pRequest->pQuery || QUERY_EXEC_MODE_SCHEDULE != pRequest->pQuery->execMode) {
1,545✔
743
    tscDebug("QID:0x%" PRIx64 ", no need to be killed since not query", pRequest->requestId);
511!
744
    return;
511✔
745
  }
746

747
  schedulerFreeJob(&pRequest->body.queryJob, TSDB_CODE_TSC_QUERY_KILLED);
1,034✔
748
  tscDebug("QID:0x%" PRIx64 ", killed", pRequest->requestId);
1,034!
749
}
750

751
void stopAllQueries(SRequestObj *pRequest) {
1,545✔
752
  int32_t      reqIdx = -1;
1,545✔
753
  SRequestObj *pReqList[16] = {NULL};
1,545✔
754
  uint64_t     tmpRefId = 0;
1,545✔
755

756
  if (pRequest->relation.userRefId && pRequest->relation.userRefId != pRequest->self) {
1,545!
757
    return;
×
758
  }
759

760
  SRequestObj *pTmp = pRequest;
1,545✔
761
  while (pTmp->relation.prevRefId) {
1,545!
762
    tmpRefId = pTmp->relation.prevRefId;
×
763
    pTmp = acquireRequest(tmpRefId);
×
764
    if (pTmp) {
×
765
      pReqList[++reqIdx] = pTmp;
×
766
    } else {
767
      tscError("prev req ref 0x%" PRIx64 " is not there", tmpRefId);
×
768
      break;
×
769
    }
770
  }
771

772
  for (int32_t i = reqIdx; i >= 0; i--) {
1,545!
773
    taosStopQueryImpl(pReqList[i]);
×
774
    (void)releaseRequest(pReqList[i]->self);  // ignore error
×
775
  }
776

777
  taosStopQueryImpl(pRequest);
1,545✔
778

779
  tmpRefId = pRequest->relation.nextRefId;
1,545✔
780
  while (tmpRefId) {
1,545!
781
    pTmp = acquireRequest(tmpRefId);
×
782
    if (pTmp) {
×
783
      tmpRefId = pTmp->relation.nextRefId;
×
784
      taosStopQueryImpl(pTmp);
×
785
      (void)releaseRequest(pTmp->self);  // ignore error
×
786
    } else {
787
      tscError("next req ref 0x%" PRIx64 " is not there", tmpRefId);
×
788
      break;
×
789
    }
790
  }
791
}
792

793
void crashReportThreadFuncUnexpectedStopped(void) { atomic_store_32(&clientStop, -1); }
×
794

795
static void *tscCrashReportThreadFp(void *param) {
×
796
  int32_t code = 0;
×
797
  setThreadName("client-crashReport");
×
798
  char filepath[PATH_MAX] = {0};
×
799
  (void)snprintf(filepath, sizeof(filepath), "%s%s.taosCrashLog", tsLogDir, TD_DIRSEP);
×
800
  char     *pMsg = NULL;
×
801
  int64_t   msgLen = 0;
×
802
  TdFilePtr pFile = NULL;
×
803
  bool      truncateFile = false;
×
804
  int32_t   sleepTime = 200;
×
805
  int32_t   reportPeriodNum = 3600 * 1000 / sleepTime;
×
806
  int32_t   loopTimes = reportPeriodNum;
×
807

808
#ifdef WINDOWS
809
  if (taosCheckCurrentInDll()) {
810
    atexit(crashReportThreadFuncUnexpectedStopped);
811
  }
812
#endif
813

814
  if (-1 != atomic_val_compare_exchange_32(&clientStop, -1, 0)) {
×
815
    return NULL;
×
816
  }
817
  STelemAddrMgmt mgt;
818
  code = taosTelemetryMgtInit(&mgt, tsTelemServer);
×
819
  if (code) {
×
820
    tscError("failed to init telemetry management, code:%s", tstrerror(code));
×
821
    return NULL;
×
822
  }
823

824
  code = initCrashLogWriter();
×
825
  if (code) {
×
826
    tscError("failed to init crash log writer, code:%s", tstrerror(code));
×
827
    return NULL;
×
828
  }
829

830
  while (1) {
831
    checkAndPrepareCrashInfo();
×
832
    if (clientStop > 0 && reportThreadSetQuit()) break;
×
833
    if (loopTimes++ < reportPeriodNum) {
×
834
      if (loopTimes < 0) loopTimes = reportPeriodNum;
×
835
      taosMsleep(sleepTime);
×
836
      continue;
×
837
    }
838

839
    taosReadCrashInfo(filepath, &pMsg, &msgLen, &pFile);
×
840
    if (pMsg && msgLen > 0) {
×
841
      if (taosSendTelemReport(&mgt, tsClientCrashReportUri, tsTelemPort, pMsg, msgLen, HTTP_FLAT) != 0) {
×
842
        tscError("failed to send crash report");
×
843
        if (pFile) {
×
844
          taosReleaseCrashLogFile(pFile, false);
×
845
          pFile = NULL;
×
846

847
          taosMsleep(sleepTime);
×
848
          loopTimes = 0;
×
849
          continue;
×
850
        }
851
      } else {
852
        tscInfo("succeed to send crash report");
×
853
        truncateFile = true;
×
854
      }
855
    } else {
856
      tscInfo("no crash info was found");
×
857
    }
858

859
    taosMemoryFree(pMsg);
×
860

861
    if (pMsg && msgLen > 0) {
×
862
      pMsg = NULL;
×
863
      continue;
×
864
    }
865

866
    if (pFile) {
×
867
      taosReleaseCrashLogFile(pFile, truncateFile);
×
868
      pFile = NULL;
×
869
      truncateFile = false;
×
870
    }
871

872
    taosMsleep(sleepTime);
×
873
    loopTimes = 0;
×
874
  }
875
  taosTelemetryDestroy(&mgt);
×
876

877
  clientStop = -2;
×
878
  return NULL;
×
879
}
880

881
int32_t tscCrashReportInit() {
5✔
882
  if (!tsEnableCrashReport) {
5!
883
    return TSDB_CODE_SUCCESS;
5✔
884
  }
885
  int32_t      code = TSDB_CODE_SUCCESS;
×
886
  TdThreadAttr thAttr;
887
  TSC_ERR_JRET(taosThreadAttrInit(&thAttr));
×
888
  TSC_ERR_JRET(taosThreadAttrSetDetachState(&thAttr, PTHREAD_CREATE_JOINABLE));
×
889
  TdThread crashReportThread;
890
  if (taosThreadCreate(&crashReportThread, &thAttr, tscCrashReportThreadFp, NULL) != 0) {
×
891
    tscError("failed to create crashReport thread since %s", strerror(errno));
×
892
    terrno = TAOS_SYSTEM_ERROR(errno);
×
893
    TSC_ERR_RET(errno);
×
894
  }
895

896
  (void)taosThreadAttrDestroy(&thAttr);
×
897
_return:
×
898
  if (code) {
×
899
    terrno = TAOS_SYSTEM_ERROR(errno);
×
900
    TSC_ERR_RET(terrno);
×
901
  }
902

903
  return code;
×
904
}
905

906
void tscStopCrashReport() {
5✔
907
  if (!tsEnableCrashReport) {
5!
908
    return;
5✔
909
  }
910

911
  if (atomic_val_compare_exchange_32(&clientStop, 0, 1)) {
×
912
    tscDebug("crash report thread already stopped");
×
913
    return;
×
914
  }
915

916
  while (atomic_load_32(&clientStop) > 0) {
×
917
    taosMsleep(100);
×
918
  }
919
}
920

921
void tscWriteCrashInfo(int signum, void *sigInfo, void *context) {
×
922
  writeCrashLogToFile(signum, sigInfo, CUS_PROMPT, lastClusterId, appInfo.startTime);
×
923
}
×
924

925
void taos_init_imp(void) {
5✔
926
#if defined(LINUX)
927
  if (tscDbg.memEnable) {
5!
928
    int32_t code = taosMemoryDbgInit();
×
929
    if (code) {
×
930
      (void)printf("failed to init memory dbg, error:%s\n", tstrerror(code));
×
931
    } else {
932
      tsAsyncLog = false;
×
933
      (void)printf("memory dbg enabled\n");
×
934
    }
935
  }
936
#endif
937

938
  // In the APIs of other program language, taos_cleanup is not available yet.
939
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
940
  (void)atexit(taos_cleanup);
5✔
941
  errno = TSDB_CODE_SUCCESS;
5✔
942
  taosSeedRand(taosGetTimestampSec());
5✔
943

944
  appInfo.pid = taosGetPId();
5✔
945
  appInfo.startTime = taosGetTimestampMs();
5✔
946
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
5✔
947
  appInfo.pInstMapByClusterId =
5✔
948
      taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_ENTRY_LOCK);
5✔
949
  if (NULL == appInfo.pInstMap || NULL == appInfo.pInstMapByClusterId) {
5!
950
    (void)printf("failed to allocate memory when init appInfo\n");
×
951
    tscInitRes = terrno;
×
952
    return;
×
953
  }
954
  taosHashSetFreeFp(appInfo.pInstMap, destroyAppInst);
5✔
955

956
  const char *logName = CUS_PROMPT "log";
5✔
957
  ENV_ERR_RET(taosInitLogOutput(&logName), "failed to init log output");
5!
958
  if (taosCreateLog(logName, 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
5!
959
    (void)printf(" WARING: Create %s failed:%s. configDir=%s\n", logName, strerror(errno), configDir);
×
960
    tscInitRes = terrno;
×
961
    return;
×
962
  }
963

964
  ENV_ERR_RET(taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1), "failed to init cfg");
5!
965

966
  initQueryModuleMsgHandle();
5✔
967
  if ((tsCharsetCxt = taosConvInit(tsCharset)) == NULL) {
5!
968
    tscInitRes = terrno;
×
969
    tscError("failed to init conv");
×
970
    return;
×
971
  }
972
#ifndef WINDOWS
973
  ENV_ERR_RET(tzInit(), "failed to init timezone");
5!
974
#endif
975
  ENV_ERR_RET(monitorInit(), "failed to init monitor");
5!
976
  ENV_ERR_RET(rpcInit(), "failed to init rpc");
5!
977

978
  if (InitRegexCache() != 0) {
5!
979
    tscInitRes = terrno;
×
980
    (void)printf("failed to init regex cache\n");
×
981
    return;
×
982
  }
983

984
  tscInfo("starting to initialize TAOS driver");
5!
985

986
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
5✔
987
  ENV_ERR_RET(catalogInit(&cfg), "failed to init catalog");
5!
988
  ENV_ERR_RET(schedulerInit(), "failed to init scheduler");
5!
989
  ENV_ERR_RET(initClientId(), "failed to init clientId");
5!
990

991
  ENV_ERR_RET(initTaskQueue(), "failed to init task queue");
5!
992
  ENV_ERR_RET(fmFuncMgtInit(), "failed to init funcMgt");
5!
993
  ENV_ERR_RET(nodesInitAllocatorSet(), "failed to init allocator set");
5!
994

995
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
5✔
996
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
5✔
997

998
  ENV_ERR_RET(taosGetAppName(appInfo.appName, NULL), "failed to get app name");
5!
999
  ENV_ERR_RET(taosThreadMutexInit(&appInfo.mutex, NULL), "failed to init thread mutex");
5!
1000
  ENV_ERR_RET(tscCrashReportInit(), "failed to init crash report");
5!
1001
  ENV_ERR_RET(qInitKeywordsTable(), "failed to init parser keywords table");
5!
1002

1003
  tscInfo("TAOS driver is initialized successfully");
5!
1004
}
1005

1006
int taos_init() {
137✔
1007
  (void)taosThreadOnce(&tscinit, taos_init_imp);
137✔
1008
  return tscInitRes;
137✔
1009
}
1010

1011
const char *getCfgName(TSDB_OPTION option) {
9✔
1012
  const char *name = NULL;
9✔
1013

1014
  switch (option) {
9!
1015
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
×
1016
      name = "shellActivityTimer";
×
1017
      break;
×
1018
    case TSDB_OPTION_LOCALE:
×
1019
      name = "locale";
×
1020
      break;
×
1021
    case TSDB_OPTION_CHARSET:
×
1022
      name = "charset";
×
1023
      break;
×
1024
    case TSDB_OPTION_TIMEZONE:
9✔
1025
      name = "timezone";
9✔
1026
      break;
9✔
1027
    case TSDB_OPTION_USE_ADAPTER:
×
1028
      name = "useAdapter";
×
1029
      break;
×
1030
    default:
×
1031
      break;
×
1032
  }
1033

1034
  return name;
9✔
1035
}
1036

1037
int taos_options_imp(TSDB_OPTION option, const char *str) {
13✔
1038
  if (option == TSDB_OPTION_CONFIGDIR) {
13✔
1039
#ifndef WINDOWS
1040
    char newstr[PATH_MAX];
1041
    int  len = strlen(str);
4✔
1042
    if (len > 1 && str[0] != '"' && str[0] != '\'') {
4!
1043
      if (len + 2 >= PATH_MAX) {
4!
1044
        tscError("Too long path %s", str);
×
1045
        return -1;
×
1046
      }
1047
      newstr[0] = '"';
4✔
1048
      (void)memcpy(newstr + 1, str, len);
4✔
1049
      newstr[len + 1] = '"';
4✔
1050
      newstr[len + 2] = '\0';
4✔
1051
      str = newstr;
4✔
1052
    }
1053
#endif
1054
    tstrncpy(configDir, str, PATH_MAX);
4✔
1055
    tscInfo("set cfg:%s to %s", configDir, str);
4!
1056
    return 0;
4✔
1057
  }
1058

1059
  // initialize global config
1060
  if (taos_init() != 0) {
9!
1061
    return -1;
×
1062
  }
1063

1064
  SConfig     *pCfg = taosGetCfg();
9✔
1065
  SConfigItem *pItem = NULL;
9✔
1066
  const char  *name = getCfgName(option);
9✔
1067

1068
  if (name == NULL) {
9!
1069
    tscError("Invalid option %d", option);
×
1070
    return -1;
×
1071
  }
1072

1073
  pItem = cfgGetItem(pCfg, name);
9✔
1074
  if (pItem == NULL) {
9!
1075
    tscError("Invalid option %d", option);
×
1076
    return -1;
×
1077
  }
1078

1079
  int code = cfgSetItem(pCfg, name, str, CFG_STYPE_TAOS_OPTIONS, true);
9✔
1080
  if (code != 0) {
9!
1081
    tscError("failed to set cfg:%s to %s since %s", name, str, terrstr());
×
1082
  } else {
1083
    tscInfo("set cfg:%s to %s", name, str);
9!
1084
    if (TSDB_OPTION_SHELL_ACTIVITY_TIMER == option || TSDB_OPTION_USE_ADAPTER == option) {
9!
1085
      code = taosCfgDynamicOptions(pCfg, name, false);
×
1086
    }
1087
  }
1088

1089
  return code;
9✔
1090
}
1091

1092
/**
1093
 * The request id is an unsigned integer format of 64bit.
1094
 *+------------+-----+-----------+---------------+
1095
 *| uid|localIp| PId | timestamp | serial number |
1096
 *+------------+-----+-----------+---------------+
1097
 *| 12bit      |12bit|24bit      |16bit          |
1098
 *+------------+-----+-----------+---------------+
1099
 * @return
1100
 */
1101
uint64_t generateRequestId() {
51,635✔
1102
  static uint32_t hashId = 0;
1103
  static int32_t  requestSerialId = 0;
1104

1105
  if (hashId == 0) {
51,635✔
1106
    int32_t code = taosGetSystemUUIDU32(&hashId);
5✔
1107
    if (code != TSDB_CODE_SUCCESS) {
5!
1108
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
×
1109
               tstrerror(code));
1110
    }
1111
  }
1112

1113
  uint64_t id = 0;
51,635✔
1114

1115
  while (true) {
×
1116
    int64_t  ts = taosGetTimestampMs();
51,635✔
1117
    uint64_t pid = taosGetPId();
51,635✔
1118
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
51,635✔
1119
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
51,635!
1120

1121
    id = (((uint64_t)(hashId & 0x0FFF)) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
51,635✔
1122
    if (id) {
51,635!
1123
      break;
51,635✔
1124
    }
1125
  }
1126
  return id;
51,635✔
1127
}
1128

1129
#if 0
1130
#include "cJSON.h"
1131
static setConfRet taos_set_config_imp(const char *config){
1132
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
1133
  static bool setConfFlag = false;
1134
  if (setConfFlag) {
1135
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
1136
    tstrncpy(ret.retMsg, "configuration can only set once", RET_MSG_LENGTH);
1137
    return ret;
1138
  }
1139
  taosInitGlobalCfg();
1140
  cJSON *root = cJSON_Parse(config);
1141
  if (root == NULL){
1142
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
1143
    tstrncpy(ret.retMsg, "parse json error", RET_MSG_LENGTH);
1144
    return ret;
1145
  }
1146

1147
  int size = cJSON_GetArraySize(root);
1148
  if(!cJSON_IsObject(root) || size == 0) {
1149
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
1150
    tstrncpy(ret.retMsg, "json content is invalid, must be not empty object", RET_MSG_LENGTH);
1151
    return ret;
1152
  }
1153

1154
  if(size >= 1000) {
1155
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
1156
    tstrncpy(ret.retMsg, "json object size is too long", RET_MSG_LENGTH);
1157
    return ret;
1158
  }
1159

1160
  for(int i = 0; i < size; i++){
1161
    cJSON *item = cJSON_GetArrayItem(root, i);
1162
    if(!item) {
1163
      ret.retCode = SET_CONF_RET_ERR_INNER;
1164
      tstrncpy(ret.retMsg, "inner error", RET_MSG_LENGTH);
1165
      return ret;
1166
    }
1167
    if(!taosReadConfigOption(item->string, item->valuestring, NULL, NULL, TAOS_CFG_CSTATUS_OPTION, TSDB_CFG_CTYPE_B_CLIENT)){
1168
      ret.retCode = SET_CONF_RET_ERR_PART;
1169
      if (strlen(ret.retMsg) == 0){
1170
        snprintf(ret.retMsg, RET_MSG_LENGTH, "part error|%s", item->string);
1171
      }else{
1172
        int tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1173
        size_t leftSize = tmp >= 0 ? tmp : 0;
1174
        strncat(ret.retMsg, "|",  leftSize);
1175
        tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
1176
        leftSize = tmp >= 0 ? tmp : 0;
1177
        strncat(ret.retMsg, item->string, leftSize);
1178
      }
1179
    }
1180
  }
1181
  cJSON_Delete(root);
1182
  setConfFlag = true;
1183
  return ret;
1184
}
1185

1186
setConfRet taos_set_config(const char *config){
1187
  taosThreadMutexLock(&setConfMutex);
1188
  setConfRet ret = taos_set_config_imp(config);
1189
  taosThreadMutexUnlock(&setConfMutex);
1190
  return ret;
1191
}
1192
#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