clientImpl.c 15.0 KB
Newer Older
1

2
#include "clientInt.h"
3
#include "clientLog.h"
4 5
#include "tdef.h"
#include "tep.h"
6
#include "tglobal.h"
7
#include "tmsgtype.h"
8 9
#include "tnote.h"
#include "tpagedfile.h"
10
#include "tref.h"
11
#include "parser.h"
12

13
static int32_t initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet);
14 15
static SMsgSendInfo* buildConnectMsg(SRequestObj *pRequest);
static void destroySendMsgInfo(SMsgSendInfo* pMsgBody);
H
Haojun Liao 已提交
16

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

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

  return true;
}

static bool validateUserName(const char* user) {
  return stringLengthCheck(user, TSDB_USER_LEN - 1);
}

static bool validatePassword(const char* passwd) {
35
  return stringLengthCheck(passwd, TSDB_PASSWORD_LEN - 1);
36 37 38 39 40 41
}

static bool validateDbName(const char* db) {
  return stringLengthCheck(db, TSDB_DB_NAME_LEN - 1);
}

42 43 44 45 46 47 48
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);
}

static STscObj* taosConnectImpl(const char *ip, const char *user, const char *auth, const char *db, uint16_t port, __taos_async_fn_t fp, void *param, SAppInstInfo* pAppInfo);
49 50

TAOS *taos_connect_internal(const char *ip, const char *user, const char *pass, const char *auth, const char *db, uint16_t port) {
51 52 53 54
  if (taos_init() != TSDB_CODE_SUCCESS) {
    return NULL;
  }

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  if (!validateUserName(user)) {
    terrno = TSDB_CODE_TSC_INVALID_USER_LENGTH;
    return NULL;
  }

  char tmp[TSDB_DB_NAME_LEN] = {0};
  if (db != NULL) {
    if(!validateDbName(db)) {
      terrno = TSDB_CODE_TSC_INVALID_DB_LENGTH;
      return NULL;
    }

    tstrncpy(tmp, db, sizeof(tmp));
    strdequote(tmp);
  }

71
  char secretEncrypt[32] = {0};
72 73 74 75 76 77
  if (auth == NULL) {
    if (!validatePassword(pass)) {
      terrno = TSDB_CODE_TSC_INVALID_PASS_LENGTH;
      return NULL;
    }

78
    taosEncryptPass_c((uint8_t *)pass, strlen(pass), secretEncrypt);
79 80 81 82
  } else {
    tstrncpy(secretEncrypt, auth, tListLen(secretEncrypt));
  }

83
  SCorEpSet epSet = {0};
84 85 86 87 88 89 90 91 92 93 94 95 96 97
  if (ip) {
    if (initEpSetFromCfg(ip, NULL, &epSet) < 0) {
      return NULL;
    }

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

98 99
  char* key = getClusterKey(user, secretEncrypt, ip, port);

H
Haojun Liao 已提交
100
  SAppInstInfo** pInst = taosHashGet(appInfo.pInstMap, key, strlen(key));
101
  if (pInst == NULL) {
H
Haojun Liao 已提交
102 103
    SAppInstInfo* p = calloc(1, sizeof(struct SAppInstInfo));
    p->mgmtEp       = epSet;
H
Haojun Liao 已提交
104
    p->pTransporter = openTransporter(user, secretEncrypt, tsNumOfCores);
H
Haojun Liao 已提交
105
    taosHashPut(appInfo.pInstMap, key, strlen(key), &p, POINTER_BYTES);
106

H
Haojun Liao 已提交
107
    pInst = &p;
108 109
  }

H
Haojun Liao 已提交
110 111
  tfree(key);
  return taosConnectImpl(ip, user, &secretEncrypt[0], db, port, NULL, NULL, *pInst);
112 113
}

H
Haojun Liao 已提交
114 115 116 117 118 119 120
static bool supportedQueryType(int32_t type) {
  return (type == TSDB_MSG_TYPE_CREATE_USER || type == TSDB_MSG_TYPE_SHOW || type == TSDB_MSG_TYPE_DROP_USER ||
          type == TSDB_MSG_TYPE_DROP_ACCT || type == TSDB_MSG_TYPE_CREATE_DB || type == TSDB_MSG_TYPE_CREATE_ACCT ||
          type == TSDB_MSG_TYPE_CREATE_TABLE || type == TSDB_MSG_TYPE_CREATE_STB || type == TSDB_MSG_TYPE_USE_DB ||
          type == TSDB_MSG_TYPE_DROP_DB || type == TSDB_MSG_TYPE_DROP_STB);
}

H
Haojun Liao 已提交
121
TAOS_RES *taos_query_l(TAOS *taos, const char *sql, int sqlLen) {
122
  STscObj *pTscObj = (STscObj *)taos;
123 124 125 126 127 128 129 130
  if (sqlLen > (size_t) tsMaxSQLStringLen) {
    tscError("sql string exceeds max length:%d", tsMaxSQLStringLen);
    terrno = TSDB_CODE_TSC_EXCEED_SQL_LIMIT;
    return NULL;
  }

  nPrintTsc("%s", sql)

131
  SRequestObj* pRequest = createRequest(pTscObj, NULL, NULL, TSDB_SQL_SELECT);
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  if (pRequest == NULL) {
    tscError("failed to malloc sqlObj");
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }

  pRequest->sqlstr = malloc(sqlLen + 1);
  if (pRequest->sqlstr == NULL) {
    tscError("0x%"PRIx64" failed to prepare sql string buffer", pRequest->self);

    pRequest->msgBuf = strdup("failed to prepare sql string buffer");
    terrno = pRequest->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return pRequest;
  }

  strntolower(pRequest->sqlstr, sql, (int32_t)sqlLen);
  pRequest->sqlstr[sqlLen] = 0;

  tscDebugL("0x%"PRIx64" SQL: %s", pRequest->requestId, pRequest->sqlstr);

X
Xiaoyu Wang 已提交
152
  SParseContext cxt = {
H
Haojun Liao 已提交
153 154
    .ctx    = {.requestId = pRequest->requestId, .acctId = pTscObj->acctId, .db = getConnectionDB(pTscObj)},
    .pSql   = pRequest->sqlstr,
X
Xiaoyu Wang 已提交
155
    .sqlLen = sqlLen,
H
Haojun Liao 已提交
156
    .pMsg   = pRequest->msgBuf,
X
Xiaoyu Wang 已提交
157 158
    .msgLen = ERROR_MSG_BUF_DEFAULT_SIZE
  };
H
Haojun Liao 已提交
159

X
Xiaoyu Wang 已提交
160 161 162
  SQueryNode* pQuery = NULL;
  int32_t code = qParseQuerySql(&cxt, &pQuery);
  if (qIsDclQuery(pQuery)) {
H
Haojun Liao 已提交
163
    SDclStmtInfo* pDcl = (SDclStmtInfo*) pQuery;
164

X
Xiaoyu Wang 已提交
165
    pRequest->type = pDcl->msgType;
166
    pRequest->body.requestMsg = (SDataBuf){.pData = pDcl->pMsg, .len = pDcl->msgLen};
X
Xiaoyu Wang 已提交
167

168
    SMsgSendInfo* body = buildSendMsgInfoImpl(pRequest);
X
Xiaoyu Wang 已提交
169 170
    SEpSet* pEpSet = &pTscObj->pAppInfo->mgmtEp.epSet;

X
Xiaoyu Wang 已提交
171
    if (pDcl->msgType == TSDB_MSG_TYPE_CREATE_TABLE) {
X
Xiaoyu Wang 已提交
172 173 174 175 176 177 178 179 180
      struct SCatalog* pCatalog = NULL;

      char buf[12] = {0};
      sprintf(buf, "%d", pTscObj->pAppInfo->clusterId);
      code = catalogGetHandle(buf, &pCatalog);
      if (code != 0) {
        pRequest->code = code;
        return pRequest;
      }
X
Xiaoyu Wang 已提交
181

182
      SCreateTableMsg* pMsg = body->msgInfo.pData;
X
Xiaoyu Wang 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

      SName t = {0};
      tNameFromString(&t, pMsg->name, T_NAME_ACCT|T_NAME_DB|T_NAME_TABLE);

      char db[TSDB_DB_NAME_LEN + TS_PATH_DELIMITER_LEN + TSDB_ACCT_ID_LEN] = {0};
      tNameGetFullDbName(&t, db);

      SVgroupInfo info = {0};
      catalogGetTableHashVgroup(pCatalog, pTscObj->pTransporter, pEpSet, db, tNameGetTableName(&t), &info);

      int64_t transporterId = 0;
      SEpSet ep = {0};
      ep.inUse = info.inUse;
      ep.numOfEps = info.numOfEps;
      for(int32_t i = 0; i < ep.numOfEps; ++i) {
        ep.port[i] = info.epAddr[i].port;
        tstrncpy(ep.fqdn[i], info.epAddr[i].fqdn, tListLen(ep.fqdn[i]));
200
      }
201

H
Haojun Liao 已提交
202
      asyncSendMsgToServer(pTscObj->pTransporter, &ep, &transporterId, body);
203
    } else {
X
Xiaoyu Wang 已提交
204
      int64_t transporterId = 0;
H
Haojun Liao 已提交
205
      asyncSendMsgToServer(pTscObj->pTransporter, pEpSet, &transporterId, body);
206
    }
X
Xiaoyu Wang 已提交
207 208

    tsem_wait(&pRequest->body.rspSem);
209
    destroySendMsgInfo(body);
210 211
  }

X
Xiaoyu Wang 已提交
212 213
  tfree(cxt.ctx.db);

214 215
  if (code != TSDB_CODE_SUCCESS) {
    pRequest->code = code;
216
    return pRequest;
217 218 219 220 221
  }

  return pRequest;
}

222
int initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet) {
223 224
  pEpSet->version = 0;

H
Haojun Liao 已提交
225
  // init mnode ip set
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  SEpSet *mgmtEpSet   = &(pEpSet->epSet);
  mgmtEpSet->numOfEps = 0;
  mgmtEpSet->inUse    = 0;

  if (firstEp && firstEp[0] != 0) {
    if (strlen(firstEp) >= TSDB_EP_LEN) {
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
      return -1;
    }

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

  if (secondEp && secondEp[0] != 0) {
    if (strlen(secondEp) >= TSDB_EP_LEN) {
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
      return -1;
    }

    taosGetFqdnPortFromEp(secondEp, mgmtEpSet->fqdn[mgmtEpSet->numOfEps], &(mgmtEpSet->port[mgmtEpSet->numOfEps]));
    mgmtEpSet->numOfEps++;
  }

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

  return 0;
}

258
STscObj* taosConnectImpl(const char *ip, const char *user, const char *auth, const char *db, uint16_t port, __taos_async_fn_t fp, void *param, SAppInstInfo* pAppInfo) {
259
  STscObj *pTscObj = createTscObj(user, auth, db, pAppInfo);
260 261 262 263 264
  if (NULL == pTscObj) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return pTscObj;
  }

265
  SRequestObj *pRequest = createRequest(pTscObj, fp, param, TSDB_MSG_TYPE_CONNECT);
266 267 268
  if (pRequest == NULL) {
    destroyTscObj(pTscObj);
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
269 270 271
    return NULL;
  }

272
  SMsgSendInfo* body = buildConnectMsg(pRequest);
273 274

  int64_t transporterId = 0;
H
Haojun Liao 已提交
275
  asyncSendMsgToServer(pTscObj->pTransporter, &pTscObj->pAppInfo->mgmtEp.epSet, &transporterId, body);
276 277

  tsem_wait(&pRequest->body.rspSem);
278
  destroySendMsgInfo(body);
H
Haojun Liao 已提交
279

280 281 282 283 284 285 286 287
  if (pRequest->code != TSDB_CODE_SUCCESS) {
    const char *errorMsg = (pRequest->code == TSDB_CODE_RPC_FQDN_ERROR) ? taos_errstr(pRequest) : tstrerror(terrno);
    printf("failed to connect to server, reason: %s\n\n", errorMsg);

    destroyRequest(pRequest);
    taos_close(pTscObj);
    pTscObj = NULL;
  } else {
H
Haojun Liao 已提交
288
    tscDebug("0x%"PRIx64" connection is opening, connId:%d, dnodeConn:%p", pTscObj->id, pTscObj->connId, pTscObj->pTransporter);
289 290 291 292 293 294
    destroyRequest(pRequest);
  }

  return pTscObj;
}

295 296 297 298 299 300 301 302 303 304 305 306 307
static SMsgSendInfo* buildConnectMsg(SRequestObj *pRequest) {
  SMsgSendInfo *pMsgSendInfo = calloc(1, sizeof(SMsgSendInfo));
  if (pMsgSendInfo == NULL) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }

  pMsgSendInfo->msgType         = TSDB_MSG_TYPE_CONNECT;
  pMsgSendInfo->msgInfo.len     = sizeof(SConnectMsg);
  pMsgSendInfo->requestObjRefId = pRequest->self;
  pMsgSendInfo->requestId       = pRequest->requestId;
  pMsgSendInfo->fp              = handleRequestRspFp[pMsgSendInfo->msgType];
  pMsgSendInfo->param           = pRequest;
308 309 310

  SConnectMsg *pConnect = calloc(1, sizeof(SConnectMsg));
  if (pConnect == NULL) {
311
    tfree(pMsgSendInfo);
312
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
313
    return NULL;
314 315
  }

316 317
  STscObj *pObj = pRequest->pTscObj;

318
  char* db = getConnectionDB(pObj);
319
  tstrncpy(pConnect->db, db, sizeof(pConnect->db));
320
  tfree(db);
321

322 323 324
  pConnect->pid = htonl(appInfo.pid);
  pConnect->startTime = htobe64(appInfo.startTime);
  tstrncpy(pConnect->app, appInfo.appName, tListLen(pConnect->app));
325

326 327
  pMsgSendInfo->msgInfo.pData = pConnect;
  return pMsgSendInfo;
328 329
}

330
static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
H
Haojun Liao 已提交
331
  assert(pMsgBody != NULL);
332 333
  tfree(pMsgBody->msgInfo.pData);
  tfree(pMsgBody);
H
Haojun Liao 已提交
334 335
}

H
Haojun Liao 已提交
336
int32_t asyncSendMsgToServer(void *pTransporter, SEpSet* epSet, int64_t* pTransporterId, const SMsgSendInfo* pInfo) {
337
  char *pMsg = rpcMallocCont(pInfo->msgInfo.len);
338
  if (NULL == pMsg) {
339
    tscError("0x%"PRIx64" msg:%s malloc failed", pInfo->requestId, taosMsg[pInfo->msgType]);
340
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
341
    return -1;
342 343
  }

344
  memcpy(pMsg, pInfo->msgInfo.pData, pInfo->msgInfo.len);
345
  SRpcMsg rpcMsg = {
346
      .msgType = pInfo->msgType,
347
      .pCont   = pMsg,
348 349
      .contLen = pInfo->msgInfo.len,
      .ahandle = (void*) pInfo,
350 351 352 353
      .handle  = NULL,
      .code    = 0
  };

354 355
  assert(pInfo->fp != NULL);

356 357 358 359 360
  rpcSendRequest(pTransporter, epSet, &rpcMsg, pTransporterId);
  return TSDB_CODE_SUCCESS;
}

void processMsgFromServer(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
361 362
  SMsgSendInfo *pSendInfo = (SMsgSendInfo *) pMsg->ahandle;
  assert(pMsg->ahandle != NULL);
363

364
  if (pSendInfo->requestObjRefId != 0) {
H
Haojun Liao 已提交
365
    SRequestObj *pRequest = (SRequestObj *)taosAcquireRef(clientReqRefPool, pSendInfo->requestObjRefId);
366
    assert(pRequest->self == pSendInfo->requestObjRefId);
367

368 369
    pRequest->metric.rsp = taosGetTimestampMs();
    pRequest->code = pMsg->code;
370

371 372 373 374 375
    STscObj *pTscObj = pRequest->pTscObj;
    if (pEpSet) {
      if (!isEpsetEqual(&pTscObj->pAppInfo->mgmtEp.epSet, pEpSet)) {
        updateEpSet_s(&pTscObj->pAppInfo->mgmtEp, pEpSet);
      }
376 377
    }

378
    /*
379 380
   * There is not response callback function for submit response.
   * The actual inserted number of points is the first number.
381 382 383 384 385 386 387 388 389
     */
    if (pMsg->code == TSDB_CODE_SUCCESS) {
      tscDebug("0x%" PRIx64 " message:%s, code:%s rspLen:%d, elapsed:%" PRId64 " ms", pRequest->requestId,
               taosMsg[pMsg->msgType], tstrerror(pMsg->code), pMsg->contLen,
               pRequest->metric.rsp - pRequest->metric.start);
    } else {
      tscError("0x%" PRIx64 " SQL cmd:%s, code:%s rspLen:%d, elapsed time:%" PRId64 " ms", pRequest->requestId,
               taosMsg[pMsg->msgType], tstrerror(pMsg->code), pMsg->contLen,
               pRequest->metric.rsp - pRequest->metric.start);
390
    }
391

H
Haojun Liao 已提交
392
    taosReleaseRef(clientReqRefPool, pSendInfo->requestObjRefId);
393 394
  }

395 396
  SDataBuf buf = {.pData = pMsg->pCont, .len = pMsg->contLen};
  pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
397 398
  rpcFreeCont(pMsg->pCont);
}
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

TAOS *taos_connect_auth(const char *ip, const char *user, const char *auth, const char *db, uint16_t port) {
  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);
}

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};
  char dbStr[TSDB_DB_NAME_LEN] = {0};
  char userStr[TSDB_USER_LEN]  = {0};
  char passStr[TSDB_PASSWORD_LEN]   = {0};

  strncpy(ipStr,   ip,   MIN(TSDB_EP_LEN - 1, ipLen));
  strncpy(userStr, user, MIN(TSDB_USER_LEN - 1, userLen));
  strncpy(passStr, pass, MIN(TSDB_PASSWORD_LEN - 1, passLen));
  strncpy(dbStr,   db,   MIN(TSDB_DB_NAME_LEN - 1, dbLen));
  return taos_connect(ipStr, userStr, passStr, dbStr, port);
425 426 427 428
}

void* doFetchRow(SRequestObj* pRequest) {
  assert(pRequest != NULL);
429
  SReqResultInfo* pResultInfo = &pRequest->body.resInfo;
430

H
Haojun Liao 已提交
431
  if (pResultInfo->pData == NULL || pResultInfo->current >= pResultInfo->numOfRows) {
432
    pRequest->type = TSDB_MSG_TYPE_SHOW_RETRIEVE;
H
Haojun Liao 已提交
433

434
    SMsgSendInfo* body = buildSendMsgInfoImpl(pRequest);
H
Haojun Liao 已提交
435

436 437
    int64_t  transporterId = 0;
    STscObj *pTscObj = pRequest->pTscObj;
H
Haojun Liao 已提交
438
    asyncSendMsgToServer(pTscObj->pTransporter, &pTscObj->pAppInfo->mgmtEp.epSet, &transporterId, body);
H
Haojun Liao 已提交
439 440

    tsem_wait(&pRequest->body.rspSem);
441
    destroySendMsgInfo(body);
H
Haojun Liao 已提交
442 443 444 445 446 447 448 449 450 451 452 453

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

  for(int32_t i = 0; i < pResultInfo->numOfCols; ++i) {
    pResultInfo->row[i] = pResultInfo->pCol[i] + pResultInfo->fields[i].bytes * pResultInfo->current;
    if (IS_VAR_DATA_TYPE(pResultInfo->fields[i].type)) {
      pResultInfo->length[i] = varDataLen(pResultInfo->row[i]);
      pResultInfo->row[i] = varDataVal(pResultInfo->row[i]);
454
    }
H
Haojun Liao 已提交
455 456 457 458 459 460
  }

  pResultInfo->current += 1;
  return pResultInfo->row;
}

461
void setResultDataPtr(SReqResultInfo* pResultInfo, TAOS_FIELD* pFields, int32_t numOfCols, int32_t numOfRows) {
H
Haojun Liao 已提交
462 463 464 465 466 467 468 469
  assert(numOfCols > 0 && pFields != NULL && pResultInfo != NULL);
  if (numOfRows == 0) {
    return;
  }

  int32_t offset = 0;
  for (int32_t i = 0; i < numOfCols; ++i) {
    pResultInfo->length[i] = pResultInfo->fields[i].bytes;
H
Haojun Liao 已提交
470
    pResultInfo->row[i]    = (char*) (pResultInfo->pData + offset * pResultInfo->numOfRows);
H
Haojun Liao 已提交
471 472
    pResultInfo->pCol[i]   = pResultInfo->row[i];
    offset += pResultInfo->fields[i].bytes;
473
  }
S
Shengliang Guan 已提交
474 475
}

476 477 478 479 480
char* getConnectionDB(STscObj* pObj) {
  char *p = NULL;
  pthread_mutex_lock(&pObj->mutex);
  p = strndup(pObj->db, tListLen(pObj->db));
  pthread_mutex_unlock(&pObj->mutex);
S
Shengliang Guan 已提交
481

482 483 484 485 486 487 488 489 490
  return p;
}

void setConnectionDB(STscObj* pTscObj, const char* db) {
  assert(db != NULL && pTscObj != NULL);
  pthread_mutex_lock(&pTscObj->mutex);
  tstrncpy(pTscObj->db, db, tListLen(pTscObj->db));
  pthread_mutex_unlock(&pTscObj->mutex);
}
S
Shengliang Guan 已提交
491