clientImpl.c 25.5 KB
Newer Older
1

2
#include "clientInt.h"
3
#include "clientLog.h"
4
#include "command.h"
5
#include "scheduler.h"
H
Haojun Liao 已提交
6
#include "tdatablock.h"
7
#include "tdef.h"
8
#include "tglobal.h"
9
#include "tmsgtype.h"
H
Haojun Liao 已提交
10
#include "tpagedbuf.h"
11
#include "tref.h"
X
Xiaoyu Wang 已提交
12

S
Shengliang Guan 已提交
13
static int32_t       initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet);
dengyihao's avatar
dengyihao 已提交
14 15
static SMsgSendInfo* buildConnectMsg(SRequestObj* pRequest);
static void          destroySendMsgInfo(SMsgSendInfo* pMsgBody);
16
static int32_t       setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp);
H
Haojun Liao 已提交
17

18
static bool stringLengthCheck(const char* str, size_t maxsize) {
19 20 21 22 23 24 25 26 27 28 29 30
  if (str == NULL) {
    return false;
  }

  size_t len = strlen(str);
  if (len <= 0 || len > maxsize) {
    return false;
  }

  return true;
}

dengyihao's avatar
dengyihao 已提交
31
static bool validateUserName(const char* user) { return stringLengthCheck(user, TSDB_USER_LEN - 1); }
32

dengyihao's avatar
dengyihao 已提交
33
static bool validatePassword(const char* passwd) { return stringLengthCheck(passwd, TSDB_PASSWORD_LEN - 1); }
34

dengyihao's avatar
dengyihao 已提交
35
static bool validateDbName(const char* db) { return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1); }
36

37 38 39 40 41 42
static char* getClusterKey(const char* user, const char* auth, const char* ip, int32_t port) {
  char key[512] = {0};
  snprintf(key, sizeof(key), "%s:%s:%s:%d", user, auth, ip, port);
  return strdup(key);
}

dengyihao's avatar
dengyihao 已提交
43 44 45
static STscObj* taosConnectImpl(const char* user, const char* auth, const char* db, __taos_async_fn_t fp, void* param,
                                SAppInstInfo* pAppInfo);
static void     setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols);
46

dengyihao's avatar
dengyihao 已提交
47 48
TAOS* taos_connect_internal(const char* ip, const char* user, const char* pass, const char* auth, const char* db,
                            uint16_t port) {
49 50 51 52
  if (taos_init() != TSDB_CODE_SUCCESS) {
    return NULL;
  }

53 54 55 56 57
  if (!validateUserName(user)) {
    terrno = TSDB_CODE_TSC_INVALID_USER_LENGTH;
    return NULL;
  }

58
  char localDb[TSDB_DB_NAME_LEN] = {0};
59
  if (db != NULL) {
dengyihao's avatar
dengyihao 已提交
60
    if (!validateDbName(db)) {
61 62 63 64
      terrno = TSDB_CODE_TSC_INVALID_DB_LENGTH;
      return NULL;
    }

65 66
    tstrncpy(localDb, db, sizeof(localDb));
    strdequote(localDb);
67 68
  }

69
  char secretEncrypt[TSDB_PASSWORD_LEN + 1] = {0};
70 71 72 73 74 75
  if (auth == NULL) {
    if (!validatePassword(pass)) {
      terrno = TSDB_CODE_TSC_INVALID_PASS_LENGTH;
      return NULL;
    }

dengyihao's avatar
dengyihao 已提交
76
    taosEncryptPass_c((uint8_t*)pass, strlen(pass), secretEncrypt);
77 78 79 80
  } else {
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
  }

81
  SCorEpSet epSet = {0};
S
Shengliang Guan 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94
  if (ip) {
    if (initEpSetFromCfg(ip, NULL, &epSet) < 0) {
      return NULL;
    }

    if (port) {
      epSet.epSet.eps[0].port = port;
    }
  } else {
    if (initEpSetFromCfg(tsFirst, tsSecond, &epSet) < 0) {
      return NULL;
    }
  }
95

dengyihao's avatar
dengyihao 已提交
96
  char*          key = getClusterKey(user, secretEncrypt, ip, port);
H
Haojun Liao 已提交
97
  SAppInstInfo** pInst = NULL;
98

wafwerar's avatar
wafwerar 已提交
99
  taosThreadMutexLock(&appInfo.mutex);
H
Haojun Liao 已提交
100 101

  pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
L
Liu Jicong 已提交
102
  SAppInstInfo* p = NULL;
103
  if (pInst == NULL) {
wafwerar's avatar
wafwerar 已提交
104
    p = taosMemoryCalloc(1, sizeof(struct SAppInstInfo));
dengyihao's avatar
dengyihao 已提交
105
    p->mgmtEp = epSet;
H
Haojun Liao 已提交
106
    p->pTransporter = openTransporter(user, secretEncrypt, tsNumOfCores);
D
dapan 已提交
107
    p->pAppHbMgr = appHbMgrInit(p, key);
H
Haojun Liao 已提交
108
    taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
109

H
Haojun Liao 已提交
110
    pInst = &p;
111 112
  }

wafwerar's avatar
wafwerar 已提交
113
  taosThreadMutexUnlock(&appInfo.mutex);
H
Haojun Liao 已提交
114

wafwerar's avatar
wafwerar 已提交
115
  taosMemoryFreeClear(key);
H
Haojun Liao 已提交
116
  return taosConnectImpl(user, &secretEncrypt[0], localDb, NULL, NULL, *pInst);
117 118
}

dengyihao's avatar
dengyihao 已提交
119
int32_t buildRequest(STscObj* pTscObj, const char* sql, int sqlLen, SRequestObj** pRequest) {
X
Xiaoyu Wang 已提交
120 121
  *pRequest = createRequest(pTscObj, NULL, NULL, TSDB_SQL_SELECT);
  if (*pRequest == NULL) {
122
    tscError("failed to malloc sqlObj");
X
Xiaoyu Wang 已提交
123
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
124 125
  }

wafwerar's avatar
wafwerar 已提交
126
  (*pRequest)->sqlstr = taosMemoryMalloc(sqlLen + 1);
X
Xiaoyu Wang 已提交
127
  if ((*pRequest)->sqlstr == NULL) {
dengyihao's avatar
dengyihao 已提交
128
    tscError("0x%" PRIx64 " failed to prepare sql string buffer", (*pRequest)->self);
X
Xiaoyu Wang 已提交
129 130
    (*pRequest)->msgBuf = strdup("failed to prepare sql string buffer");
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
131 132
  }

X
Xiaoyu Wang 已提交
133 134 135
  strntolower((*pRequest)->sqlstr, sql, (int32_t)sqlLen);
  (*pRequest)->sqlstr[sqlLen] = 0;
  (*pRequest)->sqlLen = sqlLen;
136

dengyihao's avatar
dengyihao 已提交
137
  tscDebugL("0x%" PRIx64 " SQL: %s, reqId:0x%" PRIx64, (*pRequest)->self, (*pRequest)->sqlstr, (*pRequest)->requestId);
X
Xiaoyu Wang 已提交
138 139
  return TSDB_CODE_SUCCESS;
}
140

X
Xiaoyu Wang 已提交
141
int32_t parseSql(SRequestObj* pRequest, bool topicQuery, SQuery** pQuery) {
H
Haojun Liao 已提交
142 143
  STscObj* pTscObj = pRequest->pTscObj;

X
Xiaoyu Wang 已提交
144
  SParseContext cxt = {
dengyihao's avatar
dengyihao 已提交
145 146
      .requestId = pRequest->requestId,
      .acctId = pTscObj->acctId,
X
Xiaoyu Wang 已提交
147
      .db = pRequest->pDb,
X
Xiaoyu Wang 已提交
148
      .topicQuery = topicQuery,
dengyihao's avatar
dengyihao 已提交
149 150 151 152 153
      .pSql = pRequest->sqlstr,
      .sqlLen = pRequest->sqlLen,
      .pMsg = pRequest->msgBuf,
      .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE,
      .pTransporter = pTscObj->pAppInfo->pTransporter,
X
Xiaoyu Wang 已提交
154
  };
H
Haojun Liao 已提交
155

H
Haojun Liao 已提交
156 157
  cxt.mgmtEpSet = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);
  int32_t code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &cxt.pCatalog);
H
Haojun Liao 已提交
158 159 160 161 162
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  code = qParseQuerySql(&cxt, pQuery);
X
Xiaoyu Wang 已提交
163 164 165 166 167 168
  if (TSDB_CODE_SUCCESS == code) {
    if ((*pQuery)->haveResultSet) {
      setResSchemaInfo(&pRequest->body.resInfo, (*pQuery)->pResSchema, (*pQuery)->numOfResCols);
    }
    TSWAP(pRequest->dbList, (*pQuery)->pDbList, SArray*);
    TSWAP(pRequest->tableList, (*pQuery)->pTableList, SArray*);
X
Xiaoyu Wang 已提交
169
  }
170

X
Xiaoyu Wang 已提交
171 172
  return code;
}
H
Haojun Liao 已提交
173

174 175 176 177 178 179 180 181 182
int32_t execLocalCmd(SRequestObj* pRequest, SQuery* pQuery) {
  SRetrieveTableRsp* pRsp = NULL;
  int32_t code = qExecCommand(pQuery->pRoot, &pRsp);
  if (TSDB_CODE_SUCCESS == code && NULL != pRsp) {
    code = setQueryResultFromRsp(&pRequest->body.resInfo, pRsp);
  }
  return code;
}

X
Xiaoyu Wang 已提交
183
int32_t execDdlQuery(SRequestObj* pRequest, SQuery* pQuery) {
X
Xiaoyu Wang 已提交
184 185 186 187 188
  // drop table if exists not_exists_table
  if (NULL == pQuery->pCmdMsg) {
    return TSDB_CODE_SUCCESS;
  }

189 190 191
  SCmdMsgInfo* pMsgInfo = pQuery->pCmdMsg;
  pRequest->type = pMsgInfo->msgType;
  pRequest->body.requestMsg = (SDataBuf){.pData = pMsgInfo->pMsg, .len = pMsgInfo->msgLen, .handle = NULL};
X
Xiaoyu Wang 已提交
192
  pMsgInfo->pMsg = NULL; // pMsg transferred to SMsgSendInfo management
193 194 195

  STscObj*      pTscObj = pRequest->pTscObj;
  SMsgSendInfo* pSendMsg = buildMsgInfoImpl(pRequest);
196 197 198 199 200 201 202 203

  if (pMsgInfo->msgType == TDMT_VND_SHOW_TABLES) {
    SShowReqInfo* pShowReqInfo = &pRequest->body.showInfo;
    if (pShowReqInfo->pArray == NULL) {
      pShowReqInfo->currentIndex = 0;  // set the first vnode/ then iterate the next vnode
      pShowReqInfo->pArray = pMsgInfo->pExtension;
    }
  }
204 205
  int64_t transporterId = 0;
  asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pMsgInfo->epSet, &transporterId, pSendMsg);
X
Xiaoyu Wang 已提交
206

207
  tsem_wait(&pRequest->body.rspSem);
X
Xiaoyu Wang 已提交
208 209
  return TSDB_CODE_SUCCESS;
}
X
Xiaoyu Wang 已提交
210

211 212
int32_t getPlan(SRequestObj* pRequest, SQuery* pQuery, SQueryPlan** pPlan, SArray* pNodeList) {
  pRequest->type = pQuery->msgType;
X
Xiaoyu Wang 已提交
213 214 215 216
  SPlanContext cxt = {
    .queryId = pRequest->requestId,
    .acctId = pRequest->pTscObj->acctId,
    .mgmtEpSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp),
D
dapan1121 已提交
217 218
    .pAstRoot = pQuery->pRoot,
    .showRewrite = pQuery->showRewrite
X
Xiaoyu Wang 已提交
219
  };
220
  int32_t  code = qCreateQueryPlan(&cxt, pPlan, pNodeList);
X
Xiaoyu Wang 已提交
221 222 223 224
  if (code != 0) {
    return code;
  }
  return code;
X
Xiaoyu Wang 已提交
225 226
}

227 228
void setResSchemaInfo(SReqResultInfo* pResInfo, const SSchema* pSchema, int32_t numOfCols) {
  assert(pSchema != NULL && numOfCols > 0);
229

230
  pResInfo->numOfCols = numOfCols;
wafwerar's avatar
wafwerar 已提交
231
  pResInfo->fields = taosMemoryCalloc(numOfCols, sizeof(pSchema[0]));
232 233

  for (int32_t i = 0; i < pResInfo->numOfCols; ++i) {
234
    pResInfo->fields[i].bytes = pSchema[i].bytes;
dengyihao's avatar
dengyihao 已提交
235
    pResInfo->fields[i].type = pSchema[i].type;
236
    tstrncpy(pResInfo->fields[i].name, pSchema[i].name, tListLen(pResInfo->fields[i].name));
237
  }
X
Xiaoyu Wang 已提交
238 239
}

X
Xiaoyu Wang 已提交
240
int32_t scheduleQuery(SRequestObj* pRequest, SQueryPlan* pDag, SArray* pNodeList) {
241
  void* pTransporter = pRequest->pTscObj->pAppInfo->pTransporter;
242

D
dapan1121 已提交
243
  SQueryResult res = {.code = 0, .numOfRows = 0, .msgSize = ERROR_MSG_BUF_DEFAULT_SIZE, .msg = pRequest->msgBuf};
D
dapan1121 已提交
244
  int32_t      code = schedulerExecJob(pTransporter, pNodeList, pDag, &pRequest->body.queryJob, pRequest->sqlstr, &res);
D
dapan1121 已提交
245
  if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
246 247
    if (pRequest->body.queryJob != 0) {
      schedulerFreeJob(pRequest->body.queryJob);
248 249
    }

D
dapan1121 已提交
250
    pRequest->code = code;
D
dapan1121 已提交
251
    terrno = code;
H
Haojun Liao 已提交
252
    return pRequest->code;
X
Xiaoyu Wang 已提交
253
  }
254

255
  if (TDMT_VND_SUBMIT == pRequest->type || TDMT_VND_CREATE_TABLE == pRequest->type) {
D
dapan1121 已提交
256
    pRequest->body.resInfo.numOfRows = res.numOfRows;
dengyihao's avatar
test  
dengyihao 已提交
257

D
dapan1121 已提交
258 259
    if (pRequest->body.queryJob != 0) {
      schedulerFreeJob(pRequest->body.queryJob);
D
dapan1121 已提交
260 261
    }
  }
D
dapan1121 已提交
262

D
dapan1121 已提交
263
  pRequest->code = res.code;
D
dapan1121 已提交
264
  terrno = res.code;  
D
dapan1121 已提交
265
  return pRequest->code;
X
Xiaoyu Wang 已提交
266
}
X
Xiaoyu Wang 已提交
267

D
dapan1121 已提交
268
SRequestObj* execQueryImpl(STscObj* pTscObj, const char* sql, int sqlLen) {
S
Shengliang Guan 已提交
269
  SRequestObj* pRequest = NULL;
X
Xiaoyu Wang 已提交
270
  SQuery* pQuery = NULL;
D
dapan1121 已提交
271
  int32_t code = 0;
X
Xiaoyu Wang 已提交
272
  SArray* pNodeList = taosArrayInit(4, sizeof(struct SQueryNodeAddr));
X
Xiaoyu Wang 已提交
273 274

  CHECK_CODE_GOTO(buildRequest(pTscObj, sql, sqlLen, &pRequest), _return);
X
Xiaoyu Wang 已提交
275
  CHECK_CODE_GOTO(parseSql(pRequest, false, &pQuery), _return);
H
Haojun Liao 已提交
276

277 278 279
  if (pQuery->localCmd) {
    CHECK_CODE_GOTO(execLocalCmd(pRequest, pQuery), _return);
  } else if (pQuery->directRpc) {
X
Xiaoyu Wang 已提交
280
    CHECK_CODE_GOTO(execDdlQuery(pRequest, pQuery), _return);
H
Haojun Liao 已提交
281
  } else {
X
Xiaoyu Wang 已提交
282
    CHECK_CODE_GOTO(getPlan(pRequest, pQuery, &pRequest->body.pDag, pNodeList), _return);
283
    CHECK_CODE_GOTO(scheduleQuery(pRequest, pRequest->body.pDag, pNodeList), _return);
X
Xiaoyu Wang 已提交
284 285 286
  }

_return:
287
  taosArrayDestroy(pNodeList);
X
Xiaoyu Wang 已提交
288
  qDestroyQuery(pQuery);
D
dapan1121 已提交
289
  if (NULL != pRequest && TSDB_CODE_SUCCESS != code) {
X
Xiaoyu Wang 已提交
290 291
    pRequest->code = terrno;
  }
292

293 294 295
  return pRequest;
}

D
dapan1121 已提交
296 297 298 299 300 301 302 303 304
int32_t refreshMeta(STscObj* pTscObj, SRequestObj* pRequest) {
  SCatalog *pCatalog = NULL;
  int32_t code = 0;
  int32_t dbNum = taosArrayGetSize(pRequest->dbList);
  int32_t tblNum = taosArrayGetSize(pRequest->tableList);

  if (dbNum <= 0 && tblNum <= 0) {
    return TSDB_CODE_QRY_APP_ERROR;
  }
D
dapan1121 已提交
305
  
D
dapan1121 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318
  code = catalogGetHandle(pTscObj->pAppInfo->clusterId, &pCatalog);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  SEpSet epset = getEpSet_s(&pTscObj->pAppInfo->mgmtEp);

  for (int32_t i = 0; i < dbNum; ++i) {
    char *dbFName = taosArrayGet(pRequest->dbList, i);
    
    code = catalogRefreshDBVgInfo(pCatalog, pTscObj->pAppInfo->pTransporter, &epset, dbFName);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
D
dapan1121 已提交
319 320 321
    }
  }

D
dapan1121 已提交
322 323 324 325 326 327 328
  for (int32_t i = 0; i < tblNum; ++i) {
    SName *tableName = taosArrayGet(pRequest->tableList, i);

    code = catalogRefreshTableMeta(pCatalog, pTscObj->pAppInfo->pTransporter, &epset, tableName, -1);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
D
dapan1121 已提交
329 330
  }

D
dapan1121 已提交
331
  return code;
D
dapan1121 已提交
332 333 334 335 336
}


SRequestObj* execQuery(STscObj* pTscObj, const char* sql, int sqlLen) {
  SRequestObj* pRequest = NULL;
D
dapan1121 已提交
337
  int32_t retryNum = 0;
D
dapan1121 已提交
338 339
  int32_t code = 0;

D
dapan1121 已提交
340
  while (retryNum++ < REQUEST_MAX_TRY_TIMES) {
D
dapan1121 已提交
341
    pRequest = execQueryImpl(pTscObj, sql, sqlLen);
D
dapan1121 已提交
342
    if (TSDB_CODE_SUCCESS == pRequest->code || !NEED_CLIENT_HANDLE_ERROR(pRequest->code)) {
D
dapan1121 已提交
343 344 345
      break;
    }

D
dapan1121 已提交
346 347 348
    code = refreshMeta(pTscObj, pRequest);
    if (code) {
      pRequest->code = code;
D
dapan1121 已提交
349 350
      break;
    }
D
dapan1121 已提交
351 352

    destroyRequest(pRequest);
D
dapan1121 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  }
  
  return pRequest;
}

TAOS_RES* taos_query_l(TAOS* taos, const char* sql, int sqlLen) {
  STscObj* pTscObj = (STscObj*)taos;
  if (sqlLen > (size_t)TSDB_MAX_ALLOWED_SQL_LEN) {
    tscError("sql string exceeds max length:%d", TSDB_MAX_ALLOWED_SQL_LEN);
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
    return NULL;
  }

  return execQuery(pTscObj, sql, sqlLen);
}

S
Shengliang Guan 已提交
369 370
int initEpSetFromCfg(const char* firstEp, const char* secondEp, SCorEpSet* pEpSet) {
  pEpSet->version = 0;
371

H
Haojun Liao 已提交
372
  // init mnode ip set
dengyihao's avatar
dengyihao 已提交
373
  SEpSet* mgmtEpSet = &(pEpSet->epSet);
374
  mgmtEpSet->numOfEps = 0;
dengyihao's avatar
dengyihao 已提交
375
  mgmtEpSet->inUse = 0;
376

S
Shengliang Guan 已提交
377 378 379 380
  if (firstEp && firstEp[0] != 0) {
    if (strlen(firstEp) >= TSDB_EP_LEN) {
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
      return -1;
S
Shengliang Guan 已提交
381
    }
S
Shengliang Guan 已提交
382 383 384 385 386 387 388 389 390

    taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[0]);
    mgmtEpSet->numOfEps++;
  }

  if (secondEp && secondEp[0] != 0) {
    if (strlen(secondEp) >= TSDB_EP_LEN) {
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
      return -1;
391
    }
S
Shengliang Guan 已提交
392 393 394

    taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
    mgmtEpSet->numOfEps++;
395 396 397 398 399 400 401 402 403 404
  }

  if (mgmtEpSet->numOfEps == 0) {
    terrno = TSDB_CODE_TSC_INVALID_FQDN;
    return -1;
  }

  return 0;
}

dengyihao's avatar
dengyihao 已提交
405 406 407
STscObj* taosConnectImpl(const char* user, const char* auth, const char* db, __taos_async_fn_t fp, void* param,
                         SAppInstInfo* pAppInfo) {
  STscObj* pTscObj = createTscObj(user, auth, db, pAppInfo);
408 409 410 411 412
  if (NULL == pTscObj) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return pTscObj;
  }

dengyihao's avatar
dengyihao 已提交
413
  SRequestObj* pRequest = createRequest(pTscObj, fp, param, TDMT_MND_CONNECT);
414 415 416
  if (pRequest == NULL) {
    destroyTscObj(pTscObj);
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
417 418 419
    return NULL;
  }

420
  SMsgSendInfo* body = buildConnectMsg(pRequest);
421 422

  int64_t transporterId = 0;
H
Haojun Liao 已提交
423
  asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &pTscObj->pAppInfo->mgmtEp.epSet, &transporterId, body);
424 425 426

  tsem_wait(&pRequest->body.rspSem);
  if (pRequest->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
427 428
    const char* errorMsg =
        (pRequest->code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(pRequest->code);
429 430 431 432 433 434
    printf("failed to connect to server, reason: %s\n\n", errorMsg);

    destroyRequest(pRequest);
    taos_close(pTscObj);
    pTscObj = NULL;
  } else {
dengyihao's avatar
dengyihao 已提交
435 436
    tscDebug("0x%" PRIx64 " connection is opening, connId:%d, dnodeConn:%p, reqId:0x%" PRIx64, pTscObj->id,
             pTscObj->connId, pTscObj->pAppInfo->pTransporter, pRequest->requestId);
437 438 439 440 441 442
    destroyRequest(pRequest);
  }

  return pTscObj;
}

dengyihao's avatar
dengyihao 已提交
443
static SMsgSendInfo* buildConnectMsg(SRequestObj* pRequest) {
wafwerar's avatar
wafwerar 已提交
444
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
445 446 447 448 449
  if (pMsgSendInfo == NULL) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
450
  pMsgSendInfo->msgType = TDMT_MND_CONNECT;
451

452
  pMsgSendInfo->requestObjRefId = pRequest->self;
dengyihao's avatar
dengyihao 已提交
453 454 455
  pMsgSendInfo->requestId = pRequest->requestId;
  pMsgSendInfo->fp = handleRequestRspFp[TMSG_INDEX(pMsgSendInfo->msgType)];
  pMsgSendInfo->param = pRequest;
456

S
Shengliang Guan 已提交
457 458
  SConnectReq connectReq = {0};
  STscObj*    pObj = pRequest->pTscObj;
459

H
Haojun Liao 已提交
460
  char* db = getDbOfConnection(pObj);
461
  if (db != NULL) {
S
Shengliang Guan 已提交
462
    tstrncpy(connectReq.db, db, sizeof(connectReq.db));
463
  }
wafwerar's avatar
wafwerar 已提交
464
  taosMemoryFreeClear(db);
465

S
Shengliang Guan 已提交
466 467 468 469 470
  connectReq.pid = htonl(appInfo.pid);
  connectReq.startTime = htobe64(appInfo.startTime);
  tstrncpy(connectReq.app, appInfo.appName, sizeof(connectReq.app));

  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connectReq);
wafwerar's avatar
wafwerar 已提交
471
  void*   pReq = taosMemoryMalloc(contLen);
S
Shengliang Guan 已提交
472
  tSerializeSConnectReq(pReq, contLen, &connectReq);
473

S
Shengliang Guan 已提交
474 475
  pMsgSendInfo->msgInfo.len = contLen;
  pMsgSendInfo->msgInfo.pData = pReq;
476
  return pMsgSendInfo;
477 478
}

479
static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
H
Haojun Liao 已提交
480
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
481 482
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
483
}
484

dengyihao's avatar
dengyihao 已提交
485
bool persistConnForSpecificMsg(void* parenct, tmsg_t msgType) {
D
dapan1121 已提交
486
  return msgType == TDMT_VND_QUERY_RSP || msgType == TDMT_VND_FETCH_RSP || msgType == TDMT_VND_RES_READY_RSP || msgType == TDMT_VND_QUERY_HEARTBEAT_RSP;
dengyihao's avatar
dengyihao 已提交
487
}
488

489
void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
dengyihao's avatar
dengyihao 已提交
490
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->ahandle;
491
  assert(pMsg->ahandle != NULL);
492

493
  if (pSendInfo->requestObjRefId != 0) {
dengyihao's avatar
dengyihao 已提交
494
    SRequestObj* pRequest = (SRequestObj*)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
495
    assert(pRequest->self == pSendInfo->requestObjRefId);
496

497
    pRequest->metric.rsp = taosGetTimestampMs();
498

dengyihao's avatar
dengyihao 已提交
499
    STscObj* pTscObj = pRequest->pTscObj;
500 501 502 503
    if (pEpSet) {
      if (!isEpsetEqual(&pTscObj->pAppInfo->mgmtEp.epSet, pEpSet)) {
        updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
      }
504 505
    }

506
    /*
dengyihao's avatar
dengyihao 已提交
507 508
     * There is not response callback function for submit response.
     * The actual inserted number of points is the first number.
509
     */
510
    int32_t elapsed = pRequest->metric.rsp - pRequest->metric.start;
511
    if (pMsg->code == TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
512 513
      tscDebug("0x%" PRIx64 " message:%s, code:%s rspLen:%d, elapsed:%d ms, reqId:0x%" PRIx64, pRequest->self,
               TMSG_INFO(pMsg->msgType), tstrerror(pMsg->code), pMsg->contLen, elapsed, pRequest->requestId);
514
    } else {
dengyihao's avatar
dengyihao 已提交
515 516
      tscError("0x%" PRIx64 " SQL cmd:%s, code:%s rspLen:%d, elapsed time:%d ms, reqId:0x%" PRIx64, pRequest->self,
               TMSG_INFO(pMsg->msgType), tstrerror(pMsg->code), pMsg->contLen, elapsed, pRequest->requestId);
517
    }
518

H
Haojun Liao 已提交
519
    taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
520 521
  }

dengyihao's avatar
dengyihao 已提交
522
  SDataBuf buf = {.len = pMsg->contLen, .pData = NULL, .handle = pMsg->handle};
523 524

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
525
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
526 527 528 529 530 531
    if (buf.pData == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      pMsg->code = TSDB_CODE_OUT_OF_MEMORY;
    } else {
      memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
    }
532 533
  }

534
  pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
535
  rpcFreeCont(pMsg->pCont);
536
  destroySendMsgInfo(pSendInfo);
537
}
538

dengyihao's avatar
dengyihao 已提交
539
TAOS* taos_connect_auth(const char* ip, const char* user, const char* auth, const char* db, uint16_t port) {
540 541 542 543 544 545 546 547 548 549 550 551 552
  tscDebug("try to connect to %s:%u by auth, user:%s db:%s", ip, port, user, db);
  if (user == NULL) {
    user = TSDB_DEFAULT_USER;
  }

  if (auth == NULL) {
    tscError("No auth info is given, failed to connect to server");
    return NULL;
  }

  return taos_connect_internal(ip, user, NULL, auth, db, port);
}

dengyihao's avatar
dengyihao 已提交
553 554 555
TAOS* taos_connect_l(const char* ip, int ipLen, const char* user, int userLen, const char* pass, int passLen,
                     const char* db, int dbLen, uint16_t port) {
  char ipStr[TSDB_EP_LEN] = {0};
556
  char dbStr[TSDB_DB_NAME_LEN] = {0};
dengyihao's avatar
dengyihao 已提交
557 558
  char userStr[TSDB_USER_LEN] = {0};
  char passStr[TSDB_PASSWORD_LEN] = {0};
559

dengyihao's avatar
dengyihao 已提交
560
  strncpy(ipStr, ip, TMIN(TSDB_EP_LEN - 1, ipLen));
dengyihao's avatar
dengyihao 已提交
561 562
  strncpy(userStr, user, TMIN(TSDB_USER_LEN - 1, userLen));
  strncpy(passStr, pass, TMIN(TSDB_PASSWORD_LEN - 1, passLen));
dengyihao's avatar
dengyihao 已提交
563
  strncpy(dbStr, db, TMIN(TSDB_DB_NAME_LEN - 1, dbLen));
564
  return taos_connect(ipStr, userStr, passStr, dbStr, port);
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
static void doSetOneRowPtr(SReqResultInfo* pResultInfo) {
  for (int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
    SResultColumn* pCol = &pResultInfo->pCol[i];

    int32_t type = pResultInfo->fields[i].type;
    int32_t bytes = pResultInfo->fields[i].bytes;

    if (IS_VAR_DATA_TYPE(type)) {
      if (pCol->offset[pResultInfo->current] != -1) {
        char* pStart = pResultInfo->pCol[i].offset[pResultInfo->current] + pResultInfo->pCol[i].pData;

        pResultInfo->length[i] = varDataLen(pStart);
        pResultInfo->row[i] = varDataVal(pStart);
      } else {
        pResultInfo->row[i] = NULL;
      }
    } else {
      if (!colDataIsNull_f(pCol->nullbitmap, pResultInfo->current)) {
        pResultInfo->row[i] = pResultInfo->pCol[i].pData + bytes * pResultInfo->current;
      } else {
        pResultInfo->row[i] = NULL;
      }
    }
  }
}

void* doFetchRow(SRequestObj* pRequest, bool setupOneRowPtr) {
594
  assert(pRequest != NULL);
595
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
596

H
Haojun Liao 已提交
597 598
  SEpSet epSet = {0};

H
Haojun Liao 已提交
599
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
600
    if (pRequest->type == TDMT_VND_QUERY) {
601 602
      // All data has returned to App already, no need to try again
      if (pResultInfo->completed) {
603
        pResultInfo->numOfRows = 0;
604 605 606
        return NULL;
      }

607
      SReqResultInfo* pResInfo = &pRequest->body.resInfo;
608 609
      pRequest->code = schedulerFetchRows(pRequest->body.queryJob, (void**)&pResInfo->pData);
      if (pRequest->code != TSDB_CODE_SUCCESS) {
610
        pResultInfo->numOfRows = 0;
611 612 613 614 615
        return NULL;
      }

      pRequest->code = setQueryResultFromRsp(&pRequest->body.resInfo, (SRetrieveTableRsp*)pResInfo->pData);
      if (pRequest->code != TSDB_CODE_SUCCESS) {
616
        pResultInfo->numOfRows = 0;
617 618
        return NULL;
      }
H
Haojun Liao 已提交
619

dengyihao's avatar
dengyihao 已提交
620 621
      tscDebug("0x%" PRIx64 " fetch results, numOfRows:%d total Rows:%" PRId64 ", complete:%d, reqId:0x%" PRIx64,
               pRequest->self, pResInfo->numOfRows, pResInfo->totalRows, pResInfo->completed, pRequest->requestId);
622

623
      if (pResultInfo->numOfRows == 0) {
D
dapan1121 已提交
624 625 626 627
        return NULL;
      }

      goto _return;
628
    } else if (pRequest->type == TDMT_MND_SHOW) {
H
Haojun Liao 已提交
629
      pRequest->type = TDMT_MND_SHOW_RETRIEVE;
H
Haojun Liao 已提交
630
      epSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp);
H
Haojun Liao 已提交
631 632
    } else if (pRequest->type == TDMT_VND_SHOW_TABLES) {
      pRequest->type = TDMT_VND_SHOW_TABLES_FETCH;
H
Haojun Liao 已提交
633
      SShowReqInfo* pShowReqInfo = &pRequest->body.showInfo;
dengyihao's avatar
dengyihao 已提交
634
      SVgroupInfo*  pVgroupInfo = taosArrayGet(pShowReqInfo->pArray, pShowReqInfo->currentIndex);
H
Haojun Liao 已提交
635

L
Liu Jicong 已提交
636
      epSet = pVgroupInfo->epSet;
H
Haojun Liao 已提交
637 638 639 640 641 642 643 644
    } else if (pRequest->type == TDMT_VND_SHOW_TABLES_FETCH) {
      pRequest->type = TDMT_VND_SHOW_TABLES;
      SShowReqInfo* pShowReqInfo = &pRequest->body.showInfo;
      pShowReqInfo->currentIndex += 1;
      if (pShowReqInfo->currentIndex >= taosArrayGetSize(pShowReqInfo->pArray)) {
        return NULL;
      }

dengyihao's avatar
dengyihao 已提交
645
      SVgroupInfo*     pVgroupInfo = taosArrayGet(pShowReqInfo->pArray, pShowReqInfo->currentIndex);
wafwerar's avatar
wafwerar 已提交
646
      SVShowTablesReq* pShowReq = taosMemoryCalloc(1, sizeof(SVShowTablesReq));
H
Haojun Liao 已提交
647 648 649 650 651 652
      pShowReq->head.vgId = htonl(pVgroupInfo->vgId);

      pRequest->body.requestMsg.len = sizeof(SVShowTablesReq);
      pRequest->body.requestMsg.pData = pShowReq;

      SMsgSendInfo* body = buildMsgInfoImpl(pRequest);
L
Liu Jicong 已提交
653
      epSet = pVgroupInfo->epSet;
H
Haojun Liao 已提交
654

H
Haojun Liao 已提交
655
      int64_t  transporterId = 0;
dengyihao's avatar
dengyihao 已提交
656
      STscObj* pTscObj = pRequest->pTscObj;
H
Haojun Liao 已提交
657
      asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &epSet, &transporterId, body);
H
Haojun Liao 已提交
658 659 660
      tsem_wait(&pRequest->body.rspSem);

      pRequest->type = TDMT_VND_SHOW_TABLES_FETCH;
dengyihao's avatar
dengyihao 已提交
661
    } else if (pRequest->type == TDMT_MND_SHOW_RETRIEVE) {
D
dapan1121 已提交
662
      epSet = getEpSet_s(&pRequest->pTscObj->pAppInfo->mgmtEp);
dengyihao's avatar
dengyihao 已提交
663

D
dapan1121 已提交
664 665 666
      if (pResultInfo->completed) {
        return NULL;
      }
H
Haojun Liao 已提交
667
    }
H
Haojun Liao 已提交
668

669 670 671 672 673
    if (pResultInfo->completed) {
      pResultInfo->numOfRows = 0;
      return NULL;
    }

674
    SMsgSendInfo* body = buildMsgInfoImpl(pRequest);
H
Haojun Liao 已提交
675

676
    int64_t  transporterId = 0;
dengyihao's avatar
dengyihao 已提交
677
    STscObj* pTscObj = pRequest->pTscObj;
H
Haojun Liao 已提交
678
    asyncSendMsgToServer(pTscObj->pAppInfo->pTransporter, &epSet, &transporterId, body);
H
Haojun Liao 已提交
679 680 681 682 683 684 685 686 687

    tsem_wait(&pRequest->body.rspSem);

    pResultInfo->current = 0;
    if (pResultInfo->numOfRows <= pResultInfo->current) {
      return NULL;
    }
  }

D
dapan1121 已提交
688
_return:
689 690 691
  if (setupOneRowPtr) {
    doSetOneRowPtr(pResultInfo);
    pResultInfo->current += 1;
H
Haojun Liao 已提交
692 693 694 695 696
  }

  return pResultInfo->row;
}

697
static int32_t doPrepareResPtr(SReqResultInfo* pResInfo) {
H
Haojun Liao 已提交
698
  if (pResInfo->row == NULL) {
wafwerar's avatar
wafwerar 已提交
699 700 701 702
    pResInfo->row    = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
    pResInfo->pCol   = taosMemoryCalloc(pResInfo->numOfCols, sizeof(SResultColumn));
    pResInfo->length = taosMemoryCalloc(pResInfo->numOfCols, sizeof(int32_t));
    pResInfo->convertBuf = taosMemoryCalloc(pResInfo->numOfCols, POINTER_BYTES);
703

704 705 706
    if (pResInfo->row == NULL || pResInfo->pCol == NULL || pResInfo->length == NULL || pResInfo->convertBuf == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
707
  }
708 709

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
710 711
}

712
int32_t setResultDataPtr(SReqResultInfo* pResultInfo, TAOS_FIELD* pFields, int32_t numOfCols, int32_t numOfRows) {
H
Haojun Liao 已提交
713 714
  assert(numOfCols > 0 && pFields != NULL && pResultInfo != NULL);
  if (numOfRows == 0) {
715
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
716 717
  }

718 719 720 721
  int32_t code = doPrepareResPtr(pResultInfo);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
722

723 724
  int32_t* colLength = (int32_t*)pResultInfo->pData;
  char*    pStart = ((char*)pResultInfo->pData) + sizeof(int32_t) * numOfCols;
H
Haojun Liao 已提交
725
  for (int32_t i = 0; i < numOfCols; ++i) {
726 727 728 729 730 731 732 733 734 735 736
    colLength[i] = htonl(colLength[i]);

    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
      pResultInfo->pCol[i].offset = (int32_t*)pStart;
      pStart += numOfRows * sizeof(int32_t);
    } else {
      pResultInfo->pCol[i].nullbitmap = pStart;
      pStart += BitmapLen(pResultInfo->numOfRows);
    }

    pResultInfo->pCol[i].pData = pStart;
H
Haojun Liao 已提交
737
    pResultInfo->length[i] = pResultInfo->fields[i].bytes;
738 739 740
    pResultInfo->row[i] = pResultInfo->pCol[i].pData;

    pStart += colLength[i];
741
  }
742

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
  for (int32_t i = 0; i < numOfCols; ++i) {
    int32_t type = pResultInfo->fields[i].type;
    int32_t bytes = pResultInfo->fields[i].bytes;

    if (type == TSDB_DATA_TYPE_NCHAR) {
      char* p = taosMemoryRealloc(pResultInfo->convertBuf[i], colLength[i]);
      if (p == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      pResultInfo->convertBuf[i] = p;

      SResultColumn* pCol = &pResultInfo->pCol[i];
      for (int32_t j = 0; j < numOfRows; ++j) {
        if (pCol->offset[j] != -1) {
          pStart = pCol->offset[j] + pCol->pData;

          int32_t len = taosUcs4ToMbs((TdUcs4*)varDataVal(pStart), varDataLen(pStart), varDataVal(p));
          ASSERT(len <= bytes);

          varDataSetLen(p, len);
          pCol->offset[j] = (p - pResultInfo->convertBuf[i]);
          p += (len + VARSTR_HEADER_SIZE);
        }
      }

      pResultInfo->pCol[i].pData = pResultInfo->convertBuf[i];
    }
  }

772
  return TSDB_CODE_SUCCESS;
S
Shengliang Guan 已提交
773 774
}

H
Haojun Liao 已提交
775
char* getDbOfConnection(STscObj* pObj) {
dengyihao's avatar
dengyihao 已提交
776
  char* p = NULL;
wafwerar's avatar
wafwerar 已提交
777
  taosThreadMutexLock(&pObj->mutex);
778 779 780 781
  size_t len = strlen(pObj->db);
  if (len > 0) {
    p = strndup(pObj->db, tListLen(pObj->db));
  }
S
Shengliang Guan 已提交
782

wafwerar's avatar
wafwerar 已提交
783
  taosThreadMutexUnlock(&pObj->mutex);
784 785 786 787 788
  return p;
}

void setConnectionDB(STscObj* pTscObj, const char* db) {
  assert(db != NULL && pTscObj != NULL);
wafwerar's avatar
wafwerar 已提交
789
  taosThreadMutexLock(&pTscObj->mutex);
790
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
wafwerar's avatar
wafwerar 已提交
791
  taosThreadMutexUnlock(&pTscObj->mutex);
792
}
S
Shengliang Guan 已提交
793

794
int32_t setQueryResultFromRsp(SReqResultInfo* pResultInfo, const SRetrieveTableRsp* pRsp) {
795 796
  assert(pResultInfo != NULL && pRsp != NULL);

797 798 799 800 801 802
  pResultInfo->pRspMsg    = (const char*)pRsp;
  pResultInfo->pData      = (void*)pRsp->data;
  pResultInfo->numOfRows  = htonl(pRsp->numOfRows);
  pResultInfo->current    = 0;
  pResultInfo->completed  = (pRsp->completed == 1);
  pResultInfo->payloadLen = htonl(pRsp->compLen);
H
Haojun Liao 已提交
803

804
  // TODO handle the compressed case
805
  pResultInfo->totalRows += pResultInfo->numOfRows;
806
  return setResultDataPtr(pResultInfo, pResultInfo->fields, pResultInfo->numOfCols, pResultInfo->numOfRows);
L
fix  
Liu Jicong 已提交
807
}