tscEnv.c 14.4 KB
Newer Older
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 17
#include "clientInt.h"
#include "clientLog.h"
18 19 20 21 22 23 24
#include "os.h"
#include "taosmsg.h"
#include "tcache.h"
#include "tconfig.h"
#include "tglobal.h"
#include "tnote.h"
#include "tref.h"
25
#include "trpc.h"
26 27 28 29 30 31 32 33
#include "tsched.h"
#include "ttime.h"
#include "ttimezone.h"

#define TSC_VAR_NOT_RELEASE 1
#define TSC_VAR_RELEASED    0

SAppInfo   appInfo;
34
int32_t    tscReqRef  = -1;
35
int32_t    tscConnRef = -1;
36
void      *tscQhandle = NULL;
37

38
int32_t tsNumOfThreads = 1;
39
volatile int32_t tscInitRes = 0;
40

41
static void registerRequest(SRequestObj* pRequest) {
42
  STscObj *pTscObj = (STscObj *)taosAcquireRef(tscConnRef, pRequest->pTscObj->id);
43 44 45 46 47
  assert(pTscObj != NULL);

  // connection has been released already, abort creating request.
  pRequest->self = taosAddRef(tscReqRef, pRequest);

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

50 51
  if (pTscObj->pAppInfo) {
    SInstanceActivity *pActivity = &pTscObj->pAppInfo->summary;
52

53 54
    int32_t total = atomic_add_fetch_32(&pActivity->totalRequests, 1);
    int32_t currentInst = atomic_add_fetch_32(&pActivity->currentRequests, 1);
55
    tscDebug("0x%" PRIx64 " new Request from connObj:0x%" PRIx64 ", current:%d, app current:%d, total:%d", pRequest->self,
56 57
             pRequest->pTscObj->id, num, currentInst, total);
  }
58 59 60 61 62 63 64 65 66 67 68
}

static void deregisterRequest(SRequestObj* pRequest) {
  assert(pRequest != NULL);

  STscObj* pTscObj = pRequest->pTscObj;
  SInstanceActivity* pActivity = &pTscObj->pAppInfo->summary;

  int32_t currentInst = atomic_sub_fetch_32(&pActivity->currentRequests, 1);
  int32_t num   = atomic_sub_fetch_32(&pTscObj->numOfReqs, 1);

H
Haojun Liao 已提交
69
  tscDebug("0x%"PRIx64" free Request from connObj: 0x%"PRIx64", current:%d, app current:%d", pRequest->self, pTscObj->id, num, currentInst);
70 71
  taosReleaseRef(tscConnRef, pTscObj->id);
}
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
static void tscInitLogFile() {
  taosReadGlobalLogCfg();
  if (mkdir(tsLogDir, 0755) != 0 && errno != EEXIST) {
    printf("failed to create log dir:%s\n", tsLogDir);
  }

  const char    *defaultLogFileNamePrefix = "taoslog";
  const int32_t  maxLogFileNum = 10;

  char temp[128] = {0};
  sprintf(temp, "%s/%s", tsLogDir, defaultLogFileNamePrefix);
  if (taosInitLog(temp, tsNumOfLogLines, maxLogFileNum) < 0) {
    printf("failed to open log file in directory:%s\n", tsLogDir);
  }
}

89 90
void closeTransporter(STscObj* pTscObj)  {
  if (pTscObj == NULL || pTscObj->pTransporter == NULL) {
91 92 93
    return;
  }

94 95 96
  tscDebug("free transporter:%p in connObj: 0x%"PRIx64, pTscObj->pTransporter, pTscObj->id);
  rpcClose(pTscObj->pTransporter);
  pTscObj->pTransporter = NULL;
97 98
}

99 100
// TODO refactor
void* openTransporter(const char *user, const char *auth) {
101 102 103 104
  SRpcInit rpcInit;
  memset(&rpcInit, 0, sizeof(rpcInit));
  rpcInit.localPort = 0;
  rpcInit.label = "TSC";
105 106
  rpcInit.numOfThreads = tsNumOfThreads;
  rpcInit.cfp = processMsgFromServer;
107 108 109 110 111
  rpcInit.sessions = tsMaxConnections;
  rpcInit.connType = TAOS_CONN_CLIENT;
  rpcInit.user = (char *)user;
  rpcInit.idleTime = tsShellActivityTimer * 1000;
  rpcInit.ckey = "key";
112 113
//  rpcInit.spi = 1;
  rpcInit.secret = (char *)auth;
114

115 116 117
  void* pDnodeConn = rpcOpen(&rpcInit);
  if (pDnodeConn == NULL) {
    tscError("failed to init connection to server");
118 119 120
    return NULL;
  }

121
  return pDnodeConn;
122 123
}

124 125
void destroyTscObj(void *pObj) {
  STscObj *pTscObj = pObj;
H
Haojun Liao 已提交
126 127 128

  atomic_sub_fetch_64(&pTscObj->pAppInfo->numOfConns, 1);
  tscDebug("connObj 0x%"PRIx64" destroyed, totalConn:%"PRId64, pTscObj->id, pTscObj->pAppInfo->numOfConns);
129 130 131 132

  closeTransporter(pTscObj);
  pthread_mutex_destroy(&pTscObj->mutex);
  tfree(pTscObj);
133 134
}

135
void* createTscObj(const char* user, const char* auth, const char *ip, uint32_t port, SAppInstInfo* pAppInfo) {
136 137 138 139 140 141
  STscObj *pObj = (STscObj *)calloc(1, sizeof(STscObj));
  if (NULL == pObj) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }

142 143 144 145
  pObj->pAppInfo = pAppInfo;
  if (pAppInfo != NULL) {
    pObj->pTransporter = pAppInfo->pTransporter;
  }
146 147

  tstrncpy(pObj->user, user, sizeof(pObj->user));
148
  memcpy(pObj->pass, auth, TSDB_PASSWORD_LEN);
149 150

  pthread_mutex_init(&pObj->mutex, NULL);
151
  pObj->id = taosAddRef(tscConnRef, pObj);
152

H
Haojun Liao 已提交
153
  tscDebug("connObj created, 0x%"PRIx64, pObj->id);
154
  return pObj;
155 156 157 158 159 160 161 162 163 164 165 166 167 168
}

void* createRequest(STscObj* pObj, __taos_async_fn_t fp, void* param, int32_t type) {
  assert(pObj != NULL);

  SRequestObj *pRequest = (SRequestObj *)calloc(1, sizeof(SRequestObj));
  if (NULL == pRequest) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }

  // TODO generated request uuid
  pRequest->requestId  = 0;

169 170
  pRequest->metric.start = taosGetTimestampMs();

171 172 173 174
  pRequest->type       = type;
  pRequest->pTscObj    = pObj;
  pRequest->body.fp    = fp;
  pRequest->body.param = param;
175
  pRequest->msgBuf     = calloc(1, ERROR_MSG_BUF_DEFAULT_SIZE);
176 177 178
  tsem_init(&pRequest->body.rspSem, 0, 0);

  registerRequest(pRequest);
179
  return pRequest;
180 181
}

H
Haojun Liao 已提交
182
static void doDestroyRequest(void* p) {
183
  assert(p != NULL);
H
Haojun Liao 已提交
184
  SRequestObj* pRequest = (SRequestObj*)p;
185 186 187 188 189 190 191 192

  assert(RID_VALID(pRequest->self));

  tfree(pRequest->msgBuf);
  tfree(pRequest->sqlstr);
  tfree(pRequest->pInfo);

  deregisterRequest(pRequest);
H
Haojun Liao 已提交
193
  tfree(pRequest);
194 195
}

H
Haojun Liao 已提交
196 197 198 199 200 201 202 203
void destroyRequest(SRequestObj* pRequest) {
  if (pRequest == NULL) {
    return;
  }

  taosReleaseRef(tscReqRef, pRequest->self);
}

204 205 206 207 208 209 210 211 212 213
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;
  srand(taosGetTimestampSec());

  deltaToUtcInitOnce();
  taosInitGlobalCfg();
214
  taosReadCfgFromFile();
215 216

  tscInitLogFile();
217
  if (taosCheckAndPrintCfg()) {
218 219 220 221 222
    tscInitRes = -1;
    return;
  }

  taosInitNotes();
223 224
  initMsgHandleFp();

225 226
  rpcInit();

227
  tscDebug("starting to initialize TAOS driver, local ep: %s", tsLocalEp);
228 229 230 231 232 233 234 235 236 237 238 239 240 241

  taosSetCoreDump(true);

  double factor = 4.0;
  int32_t numOfThreads = MAX((int)(tsNumOfCores * tsNumOfThreadsPerCore / factor), 2);

  int32_t queueSize = tsMaxConnections * 2;
  tscQhandle = taosInitScheduler(queueSize, numOfThreads, "tsc");
  if (NULL == tscQhandle) {
    tscError("failed to init task queue");
    tscInitRes = -1;
    return;
  }

242
  tscDebug("client task queue is initialized, numOfThreads: %d", numOfThreads);
243
  tscConnRef = taosOpenRef(200, destroyTscObj);
H
Haojun Liao 已提交
244
  tscReqRef  = taosOpenRef(40960, doDestroyRequest);
245

246
  taosGetAppName(appInfo.appName, NULL);
247
  appInfo.pid       = taosGetPId();
248
  appInfo.startTime = taosGetTimestampMs();
249
  appInfo.pInstMap  = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
250 251 252 253

  tscDebug("client is initialized successfully");
}

254
int taos_options_imp(TSDB_OPTION option, const char *str) {
255 256 257 258 259 260 261 262
  SGlobalCfg *cfg = NULL;

  switch (option) {
    case TSDB_OPTION_CONFIGDIR:
      cfg = taosGetConfigOption("configDir");
      assert(cfg != NULL);

      if (cfg->cfgStatus <= TAOS_CFG_CSTATUS_OPTION) {
263
        tstrncpy(configDir, str, TSDB_FILENAME_LEN);
264
        cfg->cfgStatus = TAOS_CFG_CSTATUS_OPTION;
265
        tscInfo("set config file directory:%s", str);
266
      } else {
267
        tscWarn("config option:%s, input value:%s, is configured by %s, use %s", cfg->option, str, tsCfgStatusStr[cfg->cfgStatus], (char *)cfg->ptr);
268 269 270 271 272 273 274 275
      }
      break;

    case TSDB_OPTION_SHELL_ACTIVITY_TIMER:
      cfg = taosGetConfigOption("shellActivityTimer");
      assert(cfg != NULL);

      if (cfg->cfgStatus <= TAOS_CFG_CSTATUS_OPTION) {
276
        tsShellActivityTimer = atoi(str);
277 278 279 280 281
        if (tsShellActivityTimer < 1) tsShellActivityTimer = 1;
        if (tsShellActivityTimer > 3600) tsShellActivityTimer = 3600;
        cfg->cfgStatus = TAOS_CFG_CSTATUS_OPTION;
        tscInfo("set shellActivityTimer:%d", tsShellActivityTimer);
      } else {
282
        tscWarn("config option:%s, input value:%s, is configured by %s, use %d", cfg->option, str, tsCfgStatusStr[cfg->cfgStatus], *(int32_t *)cfg->ptr);
283 284 285 286 287 288 289
      }
      break;

    case TSDB_OPTION_LOCALE: {  // set locale
      cfg = taosGetConfigOption("locale");
      assert(cfg != NULL);

290
      size_t len = strlen(str);
291
      if (len == 0 || len > TSDB_LOCALE_LEN) {
292
        tscInfo("Invalid locale:%s, use default", str);
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        return -1;
      }

      if (cfg->cfgStatus <= TAOS_CFG_CSTATUS_OPTION) {
        char sep = '.';

        if (strlen(tsLocale) == 0) { // locale does not set yet
          char* defaultLocale = setlocale(LC_CTYPE, "");

          // The locale of the current OS does not be set correctly, so the default locale cannot be acquired.
          // The launch of current system will abort soon.
          if (defaultLocale == NULL) {
            tscError("failed to get default locale, please set the correct locale in current OS");
            return -1;
          }

          tstrncpy(tsLocale, defaultLocale, TSDB_LOCALE_LEN);
        }

        // set the user specified locale
313
        char *locale = setlocale(LC_CTYPE, str);
314 315 316 317 318 319

        if (locale != NULL) { // failed to set the user specified locale
          tscInfo("locale set, prev locale:%s, new locale:%s", tsLocale, locale);
          cfg->cfgStatus = TAOS_CFG_CSTATUS_OPTION;
        } else { // set the user specified locale failed, use default LC_CTYPE as current locale
          locale = setlocale(LC_CTYPE, tsLocale);
320
          tscInfo("failed to set locale:%s, current locale:%s", str, tsLocale);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        }

        tstrncpy(tsLocale, locale, TSDB_LOCALE_LEN);

        char *charset = strrchr(tsLocale, sep);
        if (charset != NULL) {
          charset += 1;

          charset = taosCharsetReplace(charset);

          if (taosValidateEncodec(charset)) {
            if (strlen(tsCharset) == 0) {
              tscInfo("charset set:%s", charset);
            } else {
              tscInfo("charset changed from %s to %s", tsCharset, charset);
            }

            tstrncpy(tsCharset, charset, TSDB_LOCALE_LEN);
            cfg->cfgStatus = TAOS_CFG_CSTATUS_OPTION;

          } else {
            tscInfo("charset:%s is not valid in locale, charset remains:%s", charset, tsCharset);
          }

          free(charset);
        } else { // it may be windows system
          tscInfo("charset remains:%s", tsCharset);
        }
      } else {
350
        tscWarn("config option:%s, input value:%s, is configured by %s, use %s", cfg->option, str, tsCfgStatusStr[cfg->cfgStatus], (char *)cfg->ptr);
351 352 353 354 355 356 357 358 359
      }
      break;
    }

    case TSDB_OPTION_CHARSET: {
      /* set charset will override the value of charset, assigned during system locale changed */
      cfg = taosGetConfigOption("charset");
      assert(cfg != NULL);

360
      size_t len = strlen(str);
361
      if (len == 0 || len > TSDB_LOCALE_LEN) {
362
        tscInfo("failed to set charset:%s", str);
363 364 365 366
        return -1;
      }

      if (cfg->cfgStatus <= TAOS_CFG_CSTATUS_OPTION) {
367
        if (taosValidateEncodec(str)) {
368
          if (strlen(tsCharset) == 0) {
369
            tscInfo("charset is set:%s", str);
370
          } else {
371
            tscInfo("charset changed from %s to %s", tsCharset, str);
372 373
          }

374
          tstrncpy(tsCharset, str, TSDB_LOCALE_LEN);
375 376
          cfg->cfgStatus = TAOS_CFG_CSTATUS_OPTION;
        } else {
377
          tscInfo("charset:%s not valid", str);
378 379
        }
      } else {
380
        tscWarn("config option:%s, input value:%s, is configured by %s, use %s", cfg->option, str, tsCfgStatusStr[cfg->cfgStatus], (char *)cfg->ptr);
381 382 383 384 385 386 387 388 389 390
      }

      break;
    }

    case TSDB_OPTION_TIMEZONE:
      cfg = taosGetConfigOption("timezone");
      assert(cfg != NULL);

      if (cfg->cfgStatus <= TAOS_CFG_CSTATUS_OPTION) {
391
        tstrncpy(tsTimezone, str, TSDB_TIMEZONE_LEN);
392 393
        tsSetTimeZone();
        cfg->cfgStatus = TAOS_CFG_CSTATUS_OPTION;
394
        tscDebug("timezone set:%s, input:%s by taos_options", tsTimezone, str);
395
      } else {
396
        tscWarn("config option:%s, input value:%s, is configured by %s, use %s", cfg->option, str, tsCfgStatusStr[cfg->cfgStatus], (char *)cfg->ptr);
397 398 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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
      }
      break;

    default:
      // TODO return the correct error code to client in the format for taos_errstr()
      tscError("Invalid option %d", option);
      return -1;
  }

  return 0;
}

#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){
  pthread_mutex_lock(&setConfMutex);
  setConfRet ret = taos_set_config_imp(config);
  pthread_mutex_unlock(&setConfMutex);
  return ret;
}
#endif