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

16
#include "catalog.h"
H
Haojun Liao 已提交
17 18
#include "clientInt.h"
#include "clientLog.h"
dengyihao's avatar
dengyihao 已提交
19 20
#include "functionMgt.h"
#include "os.h"
21
#include "query.h"
X
Xiaoyu Wang 已提交
22
#include "qworker.h"
X
Xiaoyu Wang 已提交
23
#include "scheduler.h"
H
Haojun Liao 已提交
24 25
#include "tcache.h"
#include "tglobal.h"
dengyihao's avatar
dengyihao 已提交
26
#include "tmsg.h"
H
Haojun Liao 已提交
27 28
#include "tref.h"
#include "trpc.h"
dengyihao's avatar
dengyihao 已提交
29
#include "tsched.h"
H
Haojun Liao 已提交
30 31 32
#include "ttime.h"

#define TSC_VAR_NOT_RELEASE 1
33
#define TSC_VAR_RELEASED    0
H
Haojun Liao 已提交
34

dengyihao's avatar
dengyihao 已提交
35
SAppInfo appInfo;
L
Liu Jicong 已提交
36
int32_t  clientReqRefPool = -1;
dengyihao's avatar
dengyihao 已提交
37
int32_t  clientConnRefPool = -1;
H
Haojun Liao 已提交
38

dengyihao's avatar
dengyihao 已提交
39 40
int32_t timestampDeltaLimit = 900;  // s

L
Liu Jicong 已提交
41 42
static TdThreadOnce tscinit = PTHREAD_ONCE_INIT;
volatile int32_t    tscInitRes = 0;
H
Haojun Liao 已提交
43

dengyihao's avatar
dengyihao 已提交
44
static int32_t registerRequest(SRequestObj *pRequest, STscObj *pTscObj) {
H
Haojun Liao 已提交
45
  // connection has been released already, abort creating request.
H
Haojun Liao 已提交
46
  pRequest->self = taosAddRef(clientReqRefPool, pRequest);
H
Haojun Liao 已提交
47 48 49 50

  int32_t num = atomic_add_fetch_32(&pTscObj->numOfReqs, 1);

  if (pTscObj->pAppInfo) {
D
dapan1121 已提交
51
    SAppClusterSummary *pSummary = &pTscObj->pAppInfo->summary;
H
Haojun Liao 已提交
52

L
Liu Jicong 已提交
53 54
    int32_t total = atomic_add_fetch_64((int64_t *)&pSummary->totalRequests, 1);
    int32_t currentInst = atomic_add_fetch_64((int64_t *)&pSummary->currentRequests, 1);
dengyihao's avatar
dengyihao 已提交
55 56
    tscDebug("0x%" PRIx64 " new Request from connObj:0x%" PRIx64
             ", current:%d, app current:%d, total:%d, reqId:0x%" PRIx64,
D
dapan1121 已提交
57
             pRequest->self, pRequest->pTscObj->id, num, currentInst, total, pRequest->requestId);
H
Haojun Liao 已提交
58
  }
D
dapan1121 已提交
59 60

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
61 62
}

dengyihao's avatar
dengyihao 已提交
63
static void deregisterRequest(SRequestObj *pRequest) {
dengyihao's avatar
dengyihao 已提交
64
  const static int64_t SLOW_QUERY_INTERVAL = 3000000L;  // todo configurable
H
Haojun Liao 已提交
65 66
  assert(pRequest != NULL);

dengyihao's avatar
dengyihao 已提交
67
  STscObj            *pTscObj = pRequest->pTscObj;
D
dapan1121 已提交
68
  SAppClusterSummary *pActivity = &pTscObj->pAppInfo->summary;
H
Haojun Liao 已提交
69

L
Liu Jicong 已提交
70
  int32_t currentInst = atomic_sub_fetch_64((int64_t *)&pActivity->currentRequests, 1);
H
Haojun Liao 已提交
71 72
  int32_t num = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);

73
  int64_t duration = taosGetTimestampUs() - pRequest->metric.start;
dengyihao's avatar
dengyihao 已提交
74 75
  tscDebug("0x%" PRIx64 " free Request from connObj: 0x%" PRIx64 ", reqId:0x%" PRIx64
           " elapsed:%.2f ms, "
76 77
           "current:%d, app current:%d",
           pRequest->self, pTscObj->id, pRequest->requestId, duration / 1000.0, num, currentInst);
D
dapan1121 已提交
78

wmmhello's avatar
wmmhello 已提交
79 80 81 82 83 84 85
  tscPerf("insert duration %" PRId64 "us: syntax:%" PRId64 "us, ctg:%" PRId64 "us, semantic:%" PRId64
              "us, exec:%" PRId64 "us, stmtType:%d",
          duration, pRequest->metric.syntaxEnd - pRequest->metric.syntaxStart,
          pRequest->metric.ctgEnd - pRequest->metric.ctgStart, pRequest->metric.semanticEnd -
                                                               pRequest->metric.ctgEnd, pRequest->metric.execEnd - pRequest->metric.semanticEnd,
          pRequest->stmtType);

D
dapan1121 已提交
86
  if (QUERY_NODE_VNODE_MODIF_STMT == pRequest->stmtType) {
wmmhello's avatar
wmmhello 已提交
87 88 89 90 91 92
//        tscPerf("insert duration %" PRId64 "us: syntax:%" PRId64 "us, ctg:%" PRId64 "us, semantic:%" PRId64
//                "us, exec:%" PRId64 "us",
//                duration, pRequest->metric.syntaxEnd - pRequest->metric.syntaxStart,
//                pRequest->metric.ctgEnd - pRequest->metric.ctgStart, pRequest->metric.semanticEnd -
//                pRequest->metric.ctgEnd, pRequest->metric.execEnd - pRequest->metric.semanticEnd);
//    atomic_add_fetch_64((int64_t *)&pActivity->insertElapsedTime, duration);
D
dapan1121 已提交
93
  } else if (QUERY_NODE_SELECT_STMT == pRequest->stmtType) {
dengyihao's avatar
dengyihao 已提交
94 95 96 97 98 99
    //    tscPerf("select duration %" PRId64 "us: syntax:%" PRId64 "us, ctg:%" PRId64 "us, semantic:%" PRId64
    //            "us, planner:%" PRId64 "us, exec:%" PRId64 "us, reqId:0x%" PRIx64,
    //            duration, pRequest->metric.syntaxEnd - pRequest->metric.syntaxStart,
    //            pRequest->metric.ctgEnd - pRequest->metric.ctgStart, pRequest->metric.semanticEnd -
    //            pRequest->metric.ctgEnd, pRequest->metric.planEnd - pRequest->metric.semanticEnd,
    //            pRequest->metric.resultReady - pRequest->metric.planEnd, pRequest->requestId);
100

dengyihao's avatar
dengyihao 已提交
101
    atomic_add_fetch_64((int64_t *)&pActivity->queryElapsedTime, duration);
D
dapan1121 已提交
102
  }
dengyihao's avatar
dengyihao 已提交
103

D
dapan1121 已提交
104 105 106
  if (duration >= SLOW_QUERY_INTERVAL) {
    atomic_add_fetch_64((int64_t *)&pActivity->numOfSlowQueries, 1);
  }
dengyihao's avatar
dengyihao 已提交
107

D
dapan1121 已提交
108
  releaseTscObj(pTscObj->id);
H
Haojun Liao 已提交
109 110
}

111
// todo close the transporter properly
D
dapan1121 已提交
112 113
void closeTransporter(SAppInstInfo *pAppInfo) {
  if (pAppInfo == NULL || pAppInfo->pTransporter == NULL) {
H
Haojun Liao 已提交
114 115 116
    return;
  }

D
dapan1121 已提交
117 118
  tscDebug("free transporter:%p in app inst %p", pAppInfo->pTransporter, pAppInfo);
  rpcClose(pAppInfo->pTransporter);
H
Haojun Liao 已提交
119 120
}

dengyihao's avatar
dengyihao 已提交
121
static bool clientRpcRfp(int32_t code, tmsg_t msgType) {
D
dapan1121 已提交
122
  if (NEED_REDIRECT_ERROR(code)) {
dengyihao's avatar
dengyihao 已提交
123
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
D
dapan1121 已提交
124
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_QUERY_HEARTBEAT || msgType == TDMT_SCH_DROP_TASK) {
dengyihao's avatar
dengyihao 已提交
125 126
      return false;
    }
D
dapan1121 已提交
127 128 129 130 131 132
    return true;
  } else {
    return false;
  }
}

dengyihao's avatar
dengyihao 已提交
133 134
// start timer for particular msgType
static bool clientRpcTfp(int32_t code, tmsg_t msgType) {
dengyihao's avatar
dengyihao 已提交
135 136 137
  if (msgType == TDMT_VND_SUBMIT || msgType == TDMT_VND_CREATE_TABLE) {
    return true;
  }
dengyihao's avatar
dengyihao 已提交
138 139 140
  return false;
}

H
Haojun Liao 已提交
141
// TODO refactor
dengyihao's avatar
dengyihao 已提交
142
void *openTransporter(const char *user, const char *auth, int32_t numOfThread) {
H
Haojun Liao 已提交
143 144 145 146 147 148
  SRpcInit rpcInit;
  memset(&rpcInit, 0, sizeof(rpcInit));
  rpcInit.localPort = 0;
  rpcInit.label = "TSC";
  rpcInit.numOfThreads = numOfThread;
  rpcInit.cfp = processMsgFromServer;
D
dapan1121 已提交
149
  rpcInit.rfp = clientRpcRfp;
S
Shengliang Guan 已提交
150
  rpcInit.sessions = 1024;
H
Haojun Liao 已提交
151 152
  rpcInit.connType = TAOS_CONN_CLIENT;
  rpcInit.user = (char *)user;
S
Shengliang Guan 已提交
153
  rpcInit.idleTime = tsShellActivityTimer * 1000;
dengyihao's avatar
dengyihao 已提交
154
  rpcInit.compressSize = tsCompressMsgSize;
dengyihao's avatar
dengyihao 已提交
155
  rpcInit.dfp = destroyAhandle;
dengyihao's avatar
dengyihao 已提交
156

dengyihao's avatar
dengyihao 已提交
157 158 159 160
  rpcInit.retryMinInterval = tsRedirectPeriod;
  rpcInit.retryStepFactor = tsRedirectFactor;
  rpcInit.retryMaxInterval = tsRedirectMaxPeriod;
  rpcInit.retryMaxTimouet = tsMaxRetryWaitTime;
dengyihao's avatar
dengyihao 已提交
161

dengyihao's avatar
dengyihao 已提交
162
  void *pDnodeConn = rpcOpen(&rpcInit);
H
Haojun Liao 已提交
163 164 165 166 167 168 169 170
  if (pDnodeConn == NULL) {
    tscError("failed to init connection to server");
    return NULL;
  }

  return pDnodeConn;
}

D
dapan1121 已提交
171
void destroyAllRequests(SHashObj *pRequests) {
L
Liu Jicong 已提交
172
  void *pIter = taosHashIterate(pRequests, NULL);
D
dapan1121 已提交
173 174 175
  while (pIter != NULL) {
    int64_t *rid = pIter;

D
dapan1121 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    SRequestObj *pRequest = acquireRequest(*rid);
    if (pRequest) {
      destroyRequest(pRequest);
      releaseRequest(*rid);
    }

    pIter = taosHashIterate(pRequests, pIter);
  }
}

void stopAllRequests(SHashObj *pRequests) {
  void *pIter = taosHashIterate(pRequests, NULL);
  while (pIter != NULL) {
    int64_t *rid = pIter;

    SRequestObj *pRequest = acquireRequest(*rid);
    if (pRequest) {
      taos_stop_query(pRequest);
      releaseRequest(*rid);
    }
L
Liu Jicong 已提交
196

D
dapan1121 已提交
197 198 199 200
    pIter = taosHashIterate(pRequests, pIter);
  }
}

dengyihao's avatar
dengyihao 已提交
201
void destroyAppInst(SAppInstInfo *pAppInfo) {
D
dapan1121 已提交
202
  tscDebug("destroy app inst mgr %p", pAppInfo);
D
dapan1121 已提交
203 204

  taosThreadMutexLock(&appInfo.mutex);
dengyihao's avatar
dengyihao 已提交
205

D
dapan1121 已提交
206 207
  hbRemoveAppHbMrg(&pAppInfo->pAppHbMgr);
  taosHashRemove(appInfo.pInstMap, pAppInfo->instKey, strlen(pAppInfo->instKey));
D
dapan1121 已提交
208 209 210

  taosThreadMutexUnlock(&appInfo.mutex);

D
dapan1121 已提交
211 212
  taosMemoryFreeClear(pAppInfo->instKey);
  closeTransporter(pAppInfo);
dengyihao's avatar
dengyihao 已提交
213

D
dapan1121 已提交
214 215
  taosThreadMutexLock(&pAppInfo->qnodeMutex);
  taosArrayDestroy(pAppInfo->pQnodeList);
dengyihao's avatar
dengyihao 已提交
216
  taosThreadMutexUnlock(&pAppInfo->qnodeMutex);
D
dapan1121 已提交
217 218 219 220

  taosMemoryFree(pAppInfo);
}

H
Haojun Liao 已提交
221
void destroyTscObj(void *pObj) {
D
dapan1121 已提交
222 223 224
  if (NULL == pObj) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
225

H
Haojun Liao 已提交
226
  STscObj *pTscObj = pObj;
dengyihao's avatar
dengyihao 已提交
227
  int64_t  tscId = pTscObj->id;
D
dapan1121 已提交
228
  tscTrace("begin to destroy tscObj %" PRIx64 " p:%p", tscId, pTscObj);
H
Haojun Liao 已提交
229

D
dapan1121 已提交
230
  SClientHbKey connKey = {.tscRid = pTscObj->id, .connType = pTscObj->connType};
231
  hbDeregisterConn(pTscObj->pAppInfo->pAppHbMgr, connKey);
232

D
dapan1121 已提交
233
  destroyAllRequests(pTscObj->pRequests);
234
  taosHashCleanup(pTscObj->pRequests);
dengyihao's avatar
dengyihao 已提交
235

D
dapan1121 已提交
236
  schedulerStopQueryHb(pTscObj->pAppInfo->pTransporter);
dengyihao's avatar
dengyihao 已提交
237
  tscDebug("connObj 0x%" PRIx64 " p:%p destroyed, remain inst totalConn:%" PRId64, pTscObj->id, pTscObj,
D
dapan1121 已提交
238 239
           pTscObj->pAppInfo->numOfConns);

H
Haojun Liao 已提交
240
  // In any cases, we should not free app inst here. Or an race condition rises.
dengyihao's avatar
dengyihao 已提交
241
  /*int64_t connNum = */ atomic_sub_fetch_64(&pTscObj->pAppInfo->numOfConns, 1);
242

wafwerar's avatar
wafwerar 已提交
243
  taosThreadMutexDestroy(&pTscObj->mutex);
D
dapan1121 已提交
244
  taosMemoryFree(pTscObj);
D
dapan1121 已提交
245

D
dapan1121 已提交
246
  tscTrace("end to destroy tscObj %" PRIx64 " p:%p", tscId, pTscObj);
H
Haojun Liao 已提交
247 248
}

249
void *createTscObj(const char *user, const char *auth, const char *db, int32_t connType, SAppInstInfo *pAppInfo) {
wafwerar's avatar
wafwerar 已提交
250
  STscObj *pObj = (STscObj *)taosMemoryCalloc(1, sizeof(STscObj));
H
Haojun Liao 已提交
251
  if (NULL == pObj) {
S
Shengliang Guan 已提交
252
    terrno = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
253 254 255
    return NULL;
  }

D
dapan1121 已提交
256 257 258
  pObj->pRequests = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
  if (NULL == pObj->pRequests) {
    taosMemoryFree(pObj);
S
Shengliang Guan 已提交
259
    terrno = TSDB_CODE_OUT_OF_MEMORY;
D
dapan1121 已提交
260 261
    return NULL;
  }
L
Liu Jicong 已提交
262

263
  pObj->connType = connType;
H
Haojun Liao 已提交
264 265 266 267
  pObj->pAppInfo = pAppInfo;
  tstrncpy(pObj->user, user, sizeof(pObj->user));
  memcpy(pObj->pass, auth, TSDB_PASSWORD_LEN);

268 269 270 271
  if (db != NULL) {
    tstrncpy(pObj->db, db, tListLen(pObj->db));
  }

wafwerar's avatar
wafwerar 已提交
272
  taosThreadMutexInit(&pObj->mutex, NULL);
D
dapan1121 已提交
273
  pObj->id = taosAddRef(clientConnRefPool, pObj);
H
Haojun Liao 已提交
274

D
dapan1121 已提交
275 276
  atomic_add_fetch_64(&pObj->pAppInfo->numOfConns, 1);

D
dapan1121 已提交
277
  tscDebug("connObj created, 0x%" PRIx64 ",p:%p", pObj->id, pObj);
H
Haojun Liao 已提交
278 279 280
  return pObj;
}

L
Liu Jicong 已提交
281
STscObj *acquireTscObj(int64_t rid) { return (STscObj *)taosAcquireRef(clientConnRefPool, rid); }
D
dapan1121 已提交
282

L
Liu Jicong 已提交
283
int32_t releaseTscObj(int64_t rid) { return taosReleaseRef(clientConnRefPool, rid); }
D
dapan1121 已提交
284

dengyihao's avatar
dengyihao 已提交
285
void *createRequest(uint64_t connId, int32_t type, int64_t reqid) {
wafwerar's avatar
wafwerar 已提交
286
  SRequestObj *pRequest = (SRequestObj *)taosMemoryCalloc(1, sizeof(SRequestObj));
H
Haojun Liao 已提交
287
  if (NULL == pRequest) {
S
Shengliang Guan 已提交
288
    terrno = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
289 290 291
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
292
  STscObj *pTscObj = acquireTscObj(connId);
293
  if (pTscObj == NULL) {
294
    taosMemoryFree(pRequest);
295 296 297 298
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return NULL;
  }

L
Liu Jicong 已提交
299
  pRequest->resType = RES_TYPE__QUERY;
dengyihao's avatar
dengyihao 已提交
300
  pRequest->requestId = reqid == 0 ? generateRequestId() : reqid;
D
dapan1121 已提交
301
  pRequest->metric.start = taosGetTimestampUs();
H
Haojun Liao 已提交
302

303
  pRequest->body.resInfo.convertUcs4 = true;  // convert ucs4 by default
dengyihao's avatar
dengyihao 已提交
304
  pRequest->type = type;
305
  pRequest->allocatorRefId = -1;
306 307 308 309

  pRequest->pDb = getDbOfConnection(pTscObj);
  pRequest->pTscObj = pTscObj;

wafwerar's avatar
wafwerar 已提交
310
  pRequest->msgBuf = taosMemoryCalloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
D
stmt  
dapan1121 已提交
311
  pRequest->msgBufLen = ERROR_MSG_BUF_DEFAULT_SIZE;
H
Haojun Liao 已提交
312 313
  tsem_init(&pRequest->body.rspSem, 0, 0);

314
  if (registerRequest(pRequest, pTscObj)) {
D
dapan1121 已提交
315 316 317
    doDestroyRequest(pRequest);
    return NULL;
  }
L
Liu Jicong 已提交
318

H
Haojun Liao 已提交
319 320 321
  return pRequest;
}

L
Liu Jicong 已提交
322
void doFreeReqResultInfo(SReqResultInfo *pResInfo) {
wafwerar's avatar
wafwerar 已提交
323 324 325 326 327
  taosMemoryFreeClear(pResInfo->pRspMsg);
  taosMemoryFreeClear(pResInfo->length);
  taosMemoryFreeClear(pResInfo->row);
  taosMemoryFreeClear(pResInfo->pCol);
  taosMemoryFreeClear(pResInfo->fields);
328
  taosMemoryFreeClear(pResInfo->userFields);
wmmhello's avatar
wmmhello 已提交
329
  taosMemoryFreeClear(pResInfo->convertJson);
330 331 332

  if (pResInfo->convertBuf != NULL) {
    for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
wafwerar's avatar
wafwerar 已提交
333
      taosMemoryFreeClear(pResInfo->convertBuf[i]);
334
    }
wafwerar's avatar
wafwerar 已提交
335
    taosMemoryFreeClear(pResInfo->convertBuf);
336
  }
H
Haojun Liao 已提交
337 338
}

D
dapan1121 已提交
339 340 341 342 343 344
SRequestObj *acquireRequest(int64_t rid) { return (SRequestObj *)taosAcquireRef(clientReqRefPool, rid); }

int32_t releaseRequest(int64_t rid) { return taosReleaseRef(clientReqRefPool, rid); }

int32_t removeRequest(int64_t rid) { return taosRemoveRef(clientReqRefPool, rid); }

D
dapan1121 已提交
345
void doDestroyRequest(void *p) {
D
dapan1121 已提交
346 347 348
  if (NULL == p) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
349

dengyihao's avatar
dengyihao 已提交
350
  SRequestObj *pRequest = (SRequestObj *)p;
dengyihao's avatar
dengyihao 已提交
351

D
dapan1121 已提交
352
  uint64_t reqId = pRequest->requestId;
D
dapan1121 已提交
353
  tscTrace("begin to destroy request %" PRIx64 " p:%p", reqId, pRequest);
dengyihao's avatar
dengyihao 已提交
354

D
dapan1121 已提交
355
  taosHashRemove(pRequest->pTscObj->pRequests, &pRequest->self, sizeof(pRequest->self));
L
Liu Jicong 已提交
356

D
dapan1121 已提交
357
  schedulerFreeJob(&pRequest->body.queryJob, 0);
D
dapan1121 已提交
358

wafwerar's avatar
wafwerar 已提交
359 360
  taosMemoryFreeClear(pRequest->msgBuf);
  taosMemoryFreeClear(pRequest->pDb);
H
Haojun Liao 已提交
361

H
Haojun Liao 已提交
362
  doFreeReqResultInfo(&pRequest->body.resInfo);
H
Haojun Liao 已提交
363

X
Xiaoyu Wang 已提交
364 365
  taosArrayDestroy(pRequest->tableList);
  taosArrayDestroy(pRequest->dbList);
D
dapan1121 已提交
366
  taosArrayDestroy(pRequest->targetTableList);
X
Xiaoyu Wang 已提交
367
  qDestroyQuery(pRequest->pQuery);
368
  nodesDestroyAllocator(pRequest->allocatorRefId);
X
Xiaoyu Wang 已提交
369

D
dapan1121 已提交
370
  destroyQueryExecRes(&pRequest->body.resInfo.execRes);
D
dapan1121 已提交
371

D
dapan1121 已提交
372 373 374
  if (pRequest->self) {
    deregisterRequest(pRequest);
  }
D
dapan1121 已提交
375

H
Haojun Liao 已提交
376 377 378 379
  if (pRequest->syncQuery) {
    taosMemoryFree(pRequest->body.param);
  }

D
dapan1121 已提交
380
  taosMemoryFreeClear(pRequest->sqlstr);
381
  taosMemoryFree(pRequest);
D
dapan1121 已提交
382
  tscTrace("end to destroy request %" PRIx64 " p:%p", reqId, pRequest);
H
Haojun Liao 已提交
383 384
}

dengyihao's avatar
dengyihao 已提交
385
void destroyRequest(SRequestObj *pRequest) {
H
Haojun Liao 已提交
386 387 388 389
  if (pRequest == NULL) {
    return;
  }

D
dapan1121 已提交
390
  taos_stop_query(pRequest);
D
dapan1121 已提交
391
  removeRequest(pRequest->self);
H
Haojun Liao 已提交
392 393 394 395 396 397 398
}

void taos_init_imp(void) {
  // In the APIs of other program language, taos_cleanup is not available yet.
  // So, to make sure taos_cleanup will be invoked to clean up the allocated resource to suppress the valgrind warning.
  atexit(taos_cleanup);
  errno = TSDB_CODE_SUCCESS;
wafwerar's avatar
wafwerar 已提交
399
  taosSeedRand(taosGetTimestampSec());
H
Haojun Liao 已提交
400 401

  deltaToUtcInitOnce();
S
Shengliang Guan 已提交
402

wafwerar's avatar
wafwerar 已提交
403
  if (taosCreateLog("taoslog", 10, configDir, NULL, NULL, NULL, NULL, 1) != 0) {
A
Alex Duan 已提交
404 405
    // ignore create log failed, only print
    printf(" WARING: Create taoslog failed. configDir=%s\n", configDir);
S
Shengliang Guan 已提交
406 407
  }

wafwerar's avatar
wafwerar 已提交
408
  if (taosInitCfg(configDir, NULL, NULL, NULL, NULL, 1) != 0) {
S
Shengliang Guan 已提交
409 410 411 412
    tscInitRes = -1;
    return;
  }

413
  initQueryModuleMsgHandle();
H
Haojun Liao 已提交
414

S
Shengliang Guan 已提交
415 416 417
  if (taosConvInit() != 0) {
    ASSERTS(0, "failed to init conv");
  }
dengyihao's avatar
dengyihao 已提交
418

S
Shengliang Guan 已提交
419
  rpcInit();
H
Haojun Liao 已提交
420

D
dapan1121 已提交
421
  SCatalogCfg cfg = {.maxDBCacheNum = 100, .maxTblCacheNum = 100};
422 423
  catalogInit(&cfg);

D
dapan1121 已提交
424
  schedulerInit();
S
Shengliang Guan 已提交
425
  tscDebug("starting to initialize TAOS driver");
H
Haojun Liao 已提交
426

wafwerar's avatar
wafwerar 已提交
427
#ifndef WINDOWS
H
Haojun Liao 已提交
428
  taosSetCoreDump(true);
wafwerar's avatar
wafwerar 已提交
429
#endif
H
Haojun Liao 已提交
430 431

  initTaskQueue();
432
  fmFuncMgtInit();
433
  nodesInitAllocatorSet();
H
Haojun Liao 已提交
434

435
  clientConnRefPool = taosOpenRef(200, destroyTscObj);
dengyihao's avatar
dengyihao 已提交
436
  clientReqRefPool = taosOpenRef(40960, doDestroyRequest);
H
Haojun Liao 已提交
437

dengyihao's avatar
dengyihao 已提交
438
  // transDestroyBuffer(&conn->readBuf);
H
Haojun Liao 已提交
439
  taosGetAppName(appInfo.appName, NULL);
wafwerar's avatar
wafwerar 已提交
440
  taosThreadMutexInit(&appInfo.mutex, NULL);
H
Haojun Liao 已提交
441

dengyihao's avatar
dengyihao 已提交
442
  appInfo.pid = taosGetPId();
H
Haojun Liao 已提交
443
  appInfo.startTime = taosGetTimestampMs();
dengyihao's avatar
dengyihao 已提交
444
  appInfo.pInstMap = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
H
Haojun Liao 已提交
445 446 447 448
  tscDebug("client is initialized successfully");
}

int taos_init() {
wafwerar's avatar
wafwerar 已提交
449
  taosThreadOnce(&tscinit, taos_init_imp);
H
Haojun Liao 已提交
450 451 452 453
  return tscInitRes;
}

int taos_options_imp(TSDB_OPTION option, const char *str) {
H
Haojun Liao 已提交
454
  if (option == TSDB_OPTION_CONFIGDIR) {
S
Shengliang Guan 已提交
455 456 457
    tstrncpy(configDir, str, PATH_MAX);
    tscInfo("set cfg:%s to %s", configDir, str);
    return 0;
H
Haojun Liao 已提交
458 459
  } else {
    taos_init();  // initialize global config
S
Shengliang Guan 已提交
460 461
  }

dengyihao's avatar
dengyihao 已提交
462
  SConfig     *pCfg = taosGetCfg();
S
Shengliang Guan 已提交
463
  SConfigItem *pItem = NULL;
H
Haojun Liao 已提交
464 465 466

  switch (option) {
    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
S
Shengliang Guan 已提交
467
      pItem = cfgGetItem(pCfg, "shellActivityTimer");
H
Haojun Liao 已提交
468
      break;
S
Shengliang Guan 已提交
469 470
    case TSDB_OPTION_LOCALE:
      pItem = cfgGetItem(pCfg, "locale");
H
Haojun Liao 已提交
471
      break;
S
Shengliang Guan 已提交
472 473
    case TSDB_OPTION_CHARSET:
      pItem = cfgGetItem(pCfg, "charset");
H
Haojun Liao 已提交
474 475
      break;
    case TSDB_OPTION_TIMEZONE:
S
Shengliang Guan 已提交
476
      pItem = cfgGetItem(pCfg, "timezone");
H
Haojun Liao 已提交
477 478
      break;
    default:
S
Shengliang Guan 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491
      break;
  }

  if (pItem == NULL) {
    tscError("Invalid option %d", option);
    return -1;
  }

  int code = cfgSetItem(pCfg, pItem->name, str, CFG_STYPE_TAOS_OPTIONS);
  if (code != 0) {
    tscError("failed to set cfg:%s to %s since %s", pItem->name, str, terrstr());
  } else {
    tscInfo("set cfg:%s to %s", pItem->name, str);
H
Haojun Liao 已提交
492
  }
S
Shengliang Guan 已提交
493 494

  return code;
H
Haojun Liao 已提交
495 496
}

497 498 499 500 501
/**
 * The request id is an unsigned integer format of 64bit.
 *+------------+-----+-----------+---------------+
 *| uid|localIp| PId | timestamp | serial number |
 *+------------+-----+-----------+---------------+
502
 *| 12bit      |12bit|24bit      |16bit          |
503 504 505 506
 *+------------+-----+-----------+---------------+
 * @return
 */
uint64_t generateRequestId() {
H
Haojun Liao 已提交
507
  static uint64_t hashId = 0;
dengyihao's avatar
dengyihao 已提交
508
  static uint32_t requestSerialId = 0;
H
Haojun Liao 已提交
509 510 511 512 513 514 515 516 517 518 519

  if (hashId == 0) {
    char    uid[64] = {0};
    int32_t code = taosGetSystemUUID(uid, tListLen(uid));
    if (code != TSDB_CODE_SUCCESS) {
      tscError("Failed to get the system uid to generated request id, reason:%s. use ip address instead",
               tstrerror(TAOS_SYSTEM_ERROR(errno)));

    } else {
      hashId = MurmurHash3_32(uid, strlen(uid));
    }
520 521
  }

D
dapan1121 已提交
522
  uint64_t id = 0;
L
Liu Jicong 已提交
523

D
dapan1121 已提交
524 525 526
  while (true) {
    int64_t  ts = taosGetTimestampMs();
    uint64_t pid = taosGetPId();
dengyihao's avatar
dengyihao 已提交
527 528
    uint32_t val = atomic_add_fetch_32(&requestSerialId, 1);
    if (val >= 0xFFFF) atomic_store_32(&requestSerialId, 0);
529

D
dapan1121 已提交
530 531 532 533 534
    id = ((hashId & 0x0FFF) << 52) | ((pid & 0x0FFF) << 40) | ((ts & 0xFFFFFF) << 16) | (val & 0xFFFF);
    if (id) {
      break;
    }
  }
535 536 537
  return id;
}

H
Haojun Liao 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
#if 0
#include "cJSON.h"
static setConfRet taos_set_config_imp(const char *config){
  setConfRet ret = {SET_CONF_RET_SUCC, {0}};
  static bool setConfFlag = false;
  if (setConfFlag) {
    ret.retCode = SET_CONF_RET_ERR_ONLY_ONCE;
    strcpy(ret.retMsg, "configuration can only set once");
    return ret;
  }
  taosInitGlobalCfg();
  cJSON *root = cJSON_Parse(config);
  if (root == NULL){
    ret.retCode = SET_CONF_RET_ERR_JSON_PARSE;
    strcpy(ret.retMsg, "parse json error");
    return ret;
  }

  int size = cJSON_GetArraySize(root);
  if(!cJSON_IsObject(root) || size == 0) {
    ret.retCode = SET_CONF_RET_ERR_JSON_INVALID;
    strcpy(ret.retMsg, "json content is invalid, must be not empty object");
    return ret;
  }

  if(size >= 1000) {
    ret.retCode = SET_CONF_RET_ERR_TOO_LONG;
    strcpy(ret.retMsg, "json object size is too long");
    return ret;
  }

  for(int i = 0; i < size; i++){
    cJSON *item = cJSON_GetArrayItem(root, i);
    if(!item) {
      ret.retCode = SET_CONF_RET_ERR_INNER;
      strcpy(ret.retMsg, "inner error");
      return ret;
    }
    if(!taosReadConfigOption(item->string, item->valuestring, NULL, NULL, TAOS_CFG_CSTATUS_OPTION, TSDB_CFG_CTYPE_B_CLIENT)){
      ret.retCode = SET_CONF_RET_ERR_PART;
      if (strlen(ret.retMsg) == 0){
        snprintf(ret.retMsg, RET_MSG_LENGTH, "part error|%s", item->string);
      }else{
        int tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
        size_t leftSize = tmp >= 0 ? tmp : 0;
        strncat(ret.retMsg, "|",  leftSize);
        tmp = RET_MSG_LENGTH - 1 - (int)strlen(ret.retMsg);
        leftSize = tmp >= 0 ? tmp : 0;
        strncat(ret.retMsg, item->string, leftSize);
      }
    }
  }
  cJSON_Delete(root);
  setConfFlag = true;
  return ret;
}

setConfRet taos_set_config(const char *config){
wafwerar's avatar
wafwerar 已提交
596
  taosThreadMutexLock(&setConfMutex);
H
Haojun Liao 已提交
597
  setConfRet ret = taos_set_config_imp(config);
wafwerar's avatar
wafwerar 已提交
598
  taosThreadMutexUnlock(&setConfMutex);
H
Haojun Liao 已提交
599 600
  return ret;
}
601
#endif