transCli.c 48.0 KB
Newer Older
dengyihao's avatar
dengyihao 已提交
1
/** Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
dengyihao's avatar
dengyihao 已提交
2

dengyihao's avatar
dengyihao 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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/>.
 */

#ifdef USE_UV
#include "transComm.h"

typedef struct SCliConn {
dengyihao's avatar
dengyihao 已提交
20
  T_REF_DECLARE()
dengyihao's avatar
dengyihao 已提交
21 22
  uv_connect_t connReq;
  uv_stream_t* stream;
dengyihao's avatar
dengyihao 已提交
23
  queue        wreqQueue;
dengyihao's avatar
dengyihao 已提交
24

dengyihao's avatar
dengyihao 已提交
25 26 27 28
  void* hostThrd;

  SConnBuffer readBuf;
  STransQueue cliMsgs;
dengyihao's avatar
dengyihao 已提交
29
  queue       q;
dengyihao's avatar
dengyihao 已提交
30 31

  STransCtx  ctx;
dengyihao's avatar
dengyihao 已提交
32 33
  bool       broken;  // link broken or not
  ConnStatus status;  //
dengyihao's avatar
dengyihao 已提交
34

dengyihao's avatar
dengyihao 已提交
35
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
36 37 38
  char*    ip;
  uint32_t port;

dengyihao's avatar
dengyihao 已提交
39
  SDelayTask* task;
dengyihao's avatar
dengyihao 已提交
40

dengyihao's avatar
dengyihao 已提交
41
  // debug and log info
dengyihao's avatar
dengyihao 已提交
42 43 44
  char src[32];
  char dst[32];

dengyihao's avatar
dengyihao 已提交
45
} SCliConn;
dengyihao's avatar
dengyihao 已提交
46

dengyihao's avatar
dengyihao 已提交
47
typedef struct SCliMsg {
dengyihao's avatar
dengyihao 已提交
48
  STransConnCtx* ctx;
dengyihao's avatar
formate  
dengyihao 已提交
49
  STransMsg      msg;
dengyihao's avatar
dengyihao 已提交
50
  queue          q;
dengyihao's avatar
dengyihao 已提交
51
  STransMsgType  type;
dengyihao's avatar
dengyihao 已提交
52

dengyihao's avatar
dengyihao 已提交
53
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
54 55
  uint64_t st;
  int      sent;  //(0: no send, 1: alread sent)
dengyihao's avatar
dengyihao 已提交
56 57
} SCliMsg;

dengyihao's avatar
dengyihao 已提交
58
typedef struct SCliThrd {
dengyihao's avatar
dengyihao 已提交
59 60
  TdThread    thread;  // tid
  int64_t     pid;     // pid
dengyihao's avatar
dengyihao 已提交
61
  uv_loop_t*  loop;
dengyihao's avatar
dengyihao 已提交
62
  SAsyncPool* asyncPool;
dengyihao's avatar
dengyihao 已提交
63
  uv_timer_t  timer;
dengyihao's avatar
dengyihao 已提交
64 65 66
  void*       pool;  // conn pool

  // msg queue
dengyihao's avatar
dengyihao 已提交
67
  queue         msg;
wafwerar's avatar
wafwerar 已提交
68
  TdThreadMutex msgMtx;
dengyihao's avatar
dengyihao 已提交
69
  SDelayQueue*  delayQueue;
dengyihao's avatar
dengyihao 已提交
70
  SDelayQueue*  timeoutQueue;
dengyihao's avatar
dengyihao 已提交
71 72
  uint64_t      nextTimeout;  // next timeout
  void*         pTransInst;   //
dengyihao's avatar
dengyihao 已提交
73

dengyihao's avatar
dengyihao 已提交
74
  SCvtAddr cvtAddr;
dengyihao's avatar
dengyihao 已提交
75

dengyihao's avatar
dengyihao 已提交
76 77
  SCliMsg* stopMsg;

dengyihao's avatar
dengyihao 已提交
78
  bool quit;
dengyihao's avatar
dengyihao 已提交
79
} SCliThrd;
dengyihao's avatar
dengyihao 已提交
80

U
ubuntu 已提交
81
typedef struct SCliObj {
dengyihao's avatar
dengyihao 已提交
82 83 84 85
  char       label[TSDB_LABEL_LEN];
  int32_t    index;
  int        numOfThreads;
  SCliThrd** pThreadObj;
U
ubuntu 已提交
86
} SCliObj;
dengyihao's avatar
dengyihao 已提交
87

dengyihao's avatar
dengyihao 已提交
88 89 90 91
typedef struct SConnList {
  queue conn;
} SConnList;

dengyihao's avatar
dengyihao 已提交
92
// conn pool
dengyihao's avatar
dengyihao 已提交
93
// add expire timeout and capacity limit
dengyihao's avatar
dengyihao 已提交
94
static void*     createConnPool(int size);
95
static void*     destroyConnPool(void* pool);
dengyihao's avatar
dengyihao 已提交
96
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port);
dengyihao's avatar
dengyihao 已提交
97
static void      addConnToPool(void* pool, SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
98
static void      doCloseIdleConn(void* param);
dengyihao's avatar
dengyihao 已提交
99

dengyihao's avatar
dengyihao 已提交
100 101 102 103 104 105 106 107
static int sockDebugInfo(struct sockaddr* sockname, char* dst) {
  struct sockaddr_in addr = *(struct sockaddr_in*)sockname;

  char buf[20] = {0};
  int  r = uv_ip4_name(&addr, (char*)buf, sizeof(buf));
  sprintf(dst, "%s:%d", buf, ntohs(addr.sin_port));
  return r;
}
dengyihao's avatar
dengyihao 已提交
108
// register timer in each thread to clear expire conn
dengyihao's avatar
dengyihao 已提交
109
// static void cliTimeoutCb(uv_timer_t* handle);
U
ubuntu 已提交
110
// alloc buf for recv
dengyihao's avatar
dengyihao 已提交
111
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
U
ubuntu 已提交
112 113
// callback after  read nbytes from socket
static void cliRecvCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
114
// callback after write data to socket
U
ubuntu 已提交
115
static void cliSendCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
116
// callback after conn  to server
U
ubuntu 已提交
117 118
static void cliConnCb(uv_connect_t* req, int status);
static void cliAsyncCb(uv_async_t* handle);
dengyihao's avatar
dengyihao 已提交
119

dengyihao's avatar
dengyihao 已提交
120
static int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg);
dengyihao's avatar
dengyihao 已提交
121

dengyihao's avatar
dengyihao 已提交
122
static SCliConn* cliCreateConn(SCliThrd* thrd);
U
ubuntu 已提交
123 124
static void      cliDestroyConn(SCliConn* pConn, bool clear /*clear tcp handle or not*/);
static void      cliDestroy(uv_handle_t* handle);
dengyihao's avatar
dengyihao 已提交
125
static void      cliSend(SCliConn* pConn);
dengyihao's avatar
dengyihao 已提交
126

dengyihao's avatar
dengyihao 已提交
127 128 129 130 131 132 133
static bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx) {
  if (code != 0) return false;
  if (pCtx->retryCnt == 0) return false;
  if (transEpSetIsEqual(&pCtx->epSet, &pCtx->origEpSet)) return false;
  return true;
}

dengyihao's avatar
dengyihao 已提交
134
void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr);
dengyihao's avatar
dengyihao 已提交
135 136 137 138
/*
 * set TCP connection timeout per-socket level
 */
static int cliCreateSocket();
dengyihao's avatar
dengyihao 已提交
139
// process data read from server, add decompress etc later
U
ubuntu 已提交
140
static void cliHandleResp(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
141
// handle except about conn
U
ubuntu 已提交
142
static void cliHandleExcept(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
143

144
// handle req from app
dengyihao's avatar
dengyihao 已提交
145 146 147 148 149 150 151 152
static void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd);
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd);
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd);
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd);
static void (*cliAsyncHandle[])(SCliMsg* pMsg, SCliThrd* pThrd) = {cliHandleReq, cliHandleQuit, cliHandleRelease, NULL,
                                                                   cliHandleUpdate};

static void cliSendQuit(SCliThrd* thrd);
U
ubuntu 已提交
153
static void destroyUserdata(STransMsg* userdata);
dengyihao's avatar
dengyihao 已提交
154

U
ubuntu 已提交
155
static int cliRBChoseIdx(STrans* pTransInst);
dengyihao's avatar
dengyihao 已提交
156

dengyihao's avatar
dengyihao 已提交
157
static void destroyCmsg(void* cmsg);
dengyihao's avatar
dengyihao 已提交
158
static void transDestroyConnCtx(STransConnCtx* ctx);
dengyihao's avatar
dengyihao 已提交
159
// thread obj
dengyihao's avatar
dengyihao 已提交
160 161
static SCliThrd* createThrdObj();
static void      destroyThrdObj(SCliThrd* pThrd);
dengyihao's avatar
dengyihao 已提交
162

dengyihao's avatar
dengyihao 已提交
163 164
static void cliWalkCb(uv_handle_t* handle, void* arg);

dengyihao's avatar
dengyihao 已提交
165 166 167 168 169 170 171 172 173 174 175 176
static void cliReleaseUnfinishedMsg(SCliConn* conn) {
  SCliMsg* pMsg = NULL;
  for (int i = 0; i < transQueueSize(&conn->cliMsgs); i++) {
    pMsg = transQueueGet(&conn->cliMsgs, i);
    if (pMsg != NULL && pMsg->ctx != NULL) {
      if (conn->ctx.freeFunc != NULL) {
        conn->ctx.freeFunc(pMsg->ctx->ahandle);
      }
    }
    destroyCmsg(pMsg);
  }
}
dengyihao's avatar
dengyihao 已提交
177 178 179 180 181 182 183
#define CLI_RELEASE_UV(loop)        \
  do {                              \
    uv_walk(loop, cliWalkCb, NULL); \
    uv_run(loop, UV_RUN_DEFAULT);   \
    uv_loop_close(loop);            \
  } while (0);

dengyihao's avatar
dengyihao 已提交
184 185 186 187 188 189
// snprintf may cause performance problem
#define CONN_CONSTRUCT_HASH_KEY(key, ip, port)          \
  do {                                                  \
    snprintf(key, sizeof(key), "%s:%d", ip, (int)port); \
  } while (0)

dengyihao's avatar
dengyihao 已提交
190 191 192 193 194
#define CONN_HOST_THREAD_IDX1(idx, exh, refId, pThrd) \
  do {                                                \
    if (exh == NULL) {                                \
      idx = -1;                                       \
    } else {                                          \
dengyihao's avatar
dengyihao 已提交
195
      ASYNC_CHECK_HANDLE((exh), refId);               \
dengyihao's avatar
dengyihao 已提交
196
      pThrd = (SCliThrd*)(exh)->pThrd;                \
dengyihao's avatar
dengyihao 已提交
197 198
    }                                                 \
  } while (0)
dengyihao's avatar
dengyihao 已提交
199
#define CONN_PERSIST_TIME(para)    ((para) == 0 ? 3 * 1000 : (para))
dengyihao's avatar
dengyihao 已提交
200
#define CONN_GET_HOST_THREAD(conn) (conn ? ((SCliConn*)conn)->hostThrd : NULL)
dengyihao's avatar
dengyihao 已提交
201
#define CONN_GET_INST_LABEL(conn)  (((STrans*)(((SCliThrd*)(conn)->hostThrd)->pTransInst))->label)
S
Shengliang Guan 已提交
202 203 204 205 206 207 208
#define CONN_SHOULD_RELEASE(conn, head)                                                                           \
  do {                                                                                                            \
    if ((head)->release == 1 && (head->msgLen) == sizeof(*head)) {                                                \
      uint64_t ahandle = head->ahandle;                                                                           \
      CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);                                                                  \
      transClearBuffer(&conn->readBuf);                                                                           \
      transFreeMsg(transContFromHead((char*)head));                                                               \
dengyihao's avatar
dengyihao 已提交
209 210 211 212
      if (transQueueSize(&conn->cliMsgs) > 0 && ahandle == 0) {                                                   \
        SCliMsg* cliMsg = transQueueGet(&conn->cliMsgs, 0);                                                       \
        if (cliMsg->type == Release) return;                                                                      \
      }                                                                                                           \
S
Shengliang Guan 已提交
213 214 215 216 217 218
      tDebug("%s conn %p receive release request, ref:%d", CONN_GET_INST_LABEL(conn), conn, T_REF_VAL_GET(conn)); \
      if (T_REF_VAL_GET(conn) > 1) {                                                                              \
        transUnrefCliHandle(conn);                                                                                \
      }                                                                                                           \
      destroyCmsg(pMsg);                                                                                          \
      cliReleaseUnfinishedMsg(conn);                                                                              \
dengyihao's avatar
dengyihao 已提交
219
      transQueueClear(&conn->cliMsgs);                                                                            \
S
Shengliang Guan 已提交
220 221 222
      addConnToPool(((SCliThrd*)conn->hostThrd)->pool, conn);                                                     \
      return;                                                                                                     \
    }                                                                                                             \
dengyihao's avatar
dengyihao 已提交
223 224
  } while (0)

dengyihao's avatar
dengyihao 已提交
225 226 227 228 229
#define CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle)                                         \
  do {                                                                                    \
    int i = 0, sz = transQueueSize(&conn->cliMsgs);                                       \
    for (; i < sz; i++) {                                                                 \
      pMsg = transQueueGet(&conn->cliMsgs, i);                                            \
S
Shengliang 已提交
230
      if (pMsg != NULL && pMsg->ctx != NULL && (uint64_t)pMsg->ctx->ahandle == ahandle) { \
dengyihao's avatar
dengyihao 已提交
231 232 233 234 235 236 237 238
        break;                                                                            \
      }                                                                                   \
    }                                                                                     \
    if (i == sz) {                                                                        \
      pMsg = NULL;                                                                        \
    } else {                                                                              \
      pMsg = transQueueRm(&conn->cliMsgs, i);                                             \
    }                                                                                     \
dengyihao's avatar
dengyihao 已提交
239
  } while (0)
U
ubuntu 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252
#define CONN_GET_NEXT_SENDMSG(conn)                 \
  do {                                              \
    int i = 0;                                      \
    do {                                            \
      pCliMsg = transQueueGet(&conn->cliMsgs, i++); \
      if (pCliMsg && 0 == pCliMsg->sent) {          \
        break;                                      \
      }                                             \
    } while (pCliMsg != NULL);                      \
    if (pCliMsg == NULL) {                          \
      goto _RETURN;                                 \
    }                                               \
  } while (0)
dengyihao's avatar
dengyihao 已提交
253

dengyihao's avatar
dengyihao 已提交
254 255 256 257 258
#define CONN_HANDLE_THREAD_QUIT(thrd) \
  do {                                \
    if (thrd->quit) {                 \
      return;                         \
    }                                 \
dengyihao's avatar
dengyihao 已提交
259 260 261 262 263
  } while (0)

#define CONN_HANDLE_BROKEN(conn) \
  do {                           \
    if (conn->broken) {          \
dengyihao's avatar
formate  
dengyihao 已提交
264
      cliHandleExcept(conn);     \
dengyihao's avatar
dengyihao 已提交
265
      return;                    \
dengyihao's avatar
dengyihao 已提交
266
    }                            \
dengyihao's avatar
dengyihao 已提交
267
  } while (0)
dengyihao's avatar
dengyihao 已提交
268

dengyihao's avatar
formate  
dengyihao 已提交
269 270
#define CONN_SET_PERSIST_BY_APP(conn) \
  do {                                \
dengyihao's avatar
dengyihao 已提交
271 272
    if (conn->status == ConnNormal) { \
      conn->status = ConnAcquire;     \
dengyihao's avatar
formate  
dengyihao 已提交
273 274 275
      transRefCliHandle(conn);        \
    }                                 \
  } while (0)
276

dengyihao's avatar
dengyihao 已提交
277 278 279 280
#define CONN_NO_PERSIST_BY_APP(conn) \
  (((conn)->status == ConnNormal || (conn)->status == ConnInPool) && T_REF_VAL_GET(conn) == 1)
#define CONN_RELEASE_BY_SERVER(conn) \
  (((conn)->status == ConnRelease || (conn)->status == ConnInPool) && T_REF_VAL_GET(conn) == 1)
281

S
Shengliang Guan 已提交
282 283
#define REQUEST_NO_RESP(msg)         ((msg)->info.noResp == 1)
#define REQUEST_PERSIS_HANDLE(msg)   ((msg)->info.persistHandle == 1)
dengyihao's avatar
dengyihao 已提交
284
#define REQUEST_RELEASE_HANDLE(cmsg) ((cmsg)->type == Release)
dengyihao's avatar
dengyihao 已提交
285

dengyihao's avatar
dengyihao 已提交
286
#define EPSET_IS_VALID(epSet)       ((epSet) != NULL && (epSet)->numOfEps != 0)
dengyihao's avatar
dengyihao 已提交
287
#define EPSET_GET_SIZE(epSet)       (epSet)->numOfEps
dengyihao's avatar
dengyihao 已提交
288
#define EPSET_GET_INUSE_IP(epSet)   ((epSet)->eps[(epSet)->inUse].fqdn)
dengyihao's avatar
dengyihao 已提交
289
#define EPSET_GET_INUSE_PORT(epSet) ((epSet)->eps[(epSet)->inUse].port)
dengyihao's avatar
dengyihao 已提交
290 291 292 293 294
#define EPSET_FORWARD_INUSE(epSet)                                 \
  do {                                                             \
    if ((epSet)->numOfEps != 0) {                                  \
      (epSet)->inUse = (++((epSet)->inUse)) % ((epSet)->numOfEps); \
    }                                                              \
dengyihao's avatar
dengyihao 已提交
295
  } while (0)
dengyihao's avatar
dengyihao 已提交
296

dengyihao's avatar
dengyihao 已提交
297 298 299 300 301 302 303 304 305 306 307
#define EPSET_DEBUG_STR(epSet, tbuf)                                                                                   \
  do {                                                                                                                 \
    int len = snprintf(tbuf, sizeof(tbuf), "epset:{");                                                                 \
    for (int i = 0; i < (epSet)->numOfEps; i++) {                                                                      \
      if (i == (epSet)->numOfEps - 1) {                                                                                \
        len += snprintf(tbuf + len, sizeof(tbuf) - len, "%d. %s:%d", i, (epSet)->eps[i].fqdn, (epSet)->eps[i].port);   \
      } else {                                                                                                         \
        len += snprintf(tbuf + len, sizeof(tbuf) - len, "%d. %s:%d, ", i, (epSet)->eps[i].fqdn, (epSet)->eps[i].port); \
      }                                                                                                                \
    }                                                                                                                  \
    len += snprintf(tbuf + len, sizeof(tbuf) - len, "}, inUse:%d", (epSet)->inUse);                                    \
dengyihao's avatar
dengyihao 已提交
308
  } while (0);
dengyihao's avatar
dengyihao 已提交
309

U
ubuntu 已提交
310
static void* cliWorkThread(void* arg);
dengyihao's avatar
dengyihao 已提交
311

dengyihao's avatar
dengyihao 已提交
312
bool cliMaySendCachedMsg(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
313
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
314
    SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
315
    CONN_GET_NEXT_SENDMSG(conn);
dengyihao's avatar
dengyihao 已提交
316 317
    cliSend(conn);
  }
dengyihao's avatar
dengyihao 已提交
318
  return false;
U
ubuntu 已提交
319 320
_RETURN:
  return false;
dengyihao's avatar
dengyihao 已提交
321
}
dengyihao's avatar
formate  
dengyihao 已提交
322
void cliHandleResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
323 324
  SCliThrd* pThrd = conn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
325

dengyihao's avatar
opt rpc  
dengyihao 已提交
326 327
  STransMsgHead* pHead = NULL;
  transDumpFromBuffer(&conn->readBuf, (char**)&pHead);
dengyihao's avatar
dengyihao 已提交
328 329
  pHead->code = htonl(pHead->code);
  pHead->msgLen = htonl(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
330

dengyihao's avatar
dengyihao 已提交
331 332 333 334 335
  STransMsg transMsg = {0};
  transMsg.contLen = transContLenFromMsg(pHead->msgLen);
  transMsg.pCont = transContFromHead((char*)pHead);
  transMsg.code = pHead->code;
  transMsg.msgType = pHead->msgType;
S
Shengliang Guan 已提交
336
  transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
337
  transMsg.info.traceId = pHead->traceId;
dengyihao's avatar
dengyihao 已提交
338
  transMsg.info.hasEpSet = pHead->hasEpSet;
dengyihao's avatar
dengyihao 已提交
339

dengyihao's avatar
dengyihao 已提交
340 341
  SCliMsg*       pMsg = NULL;
  STransConnCtx* pCtx = NULL;
dengyihao's avatar
dengyihao 已提交
342
  CONN_SHOULD_RELEASE(conn, pHead);
dengyihao's avatar
dengyihao 已提交
343

dengyihao's avatar
dengyihao 已提交
344 345
  if (CONN_NO_PERSIST_BY_APP(conn)) {
    pMsg = transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
346 347 348

    pCtx = pMsg ? pMsg->ctx : NULL;
    transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
349
    tDebug("%s conn %p get ahandle %p, persist: 0", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
U
ubuntu 已提交
350
  } else {
dengyihao's avatar
dengyihao 已提交
351 352 353
    uint64_t ahandle = (uint64_t)pHead->ahandle;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
    if (pMsg == NULL) {
S
Shengliang Guan 已提交
354
      transMsg.info.ahandle = transCtxDumpVal(&conn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
355 356
      tDebug("%s conn %p construct ahandle %p by %s, persist: 1", CONN_GET_INST_LABEL(conn), conn,
             transMsg.info.ahandle, TMSG_INFO(transMsg.msgType));
S
Shengliang Guan 已提交
357
      if (!CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
D
dapan1121 已提交
358
        transMsg.code = TSDB_CODE_RPC_BROKEN_LINK;
S
Shengliang Guan 已提交
359
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&conn->ctx, (int32_t*)&(transMsg.msgType));
dengyihao's avatar
dengyihao 已提交
360 361
        tDebug("%s conn %p construct ahandle %p due brokenlink, persist: 1", CONN_GET_INST_LABEL(conn), conn,
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
362 363 364
      }
    } else {
      pCtx = pMsg ? pMsg->ctx : NULL;
S
Shengliang Guan 已提交
365
      transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
366
      tDebug("%s conn %p get ahandle %p, persist: 1", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
367
    }
U
ubuntu 已提交
368
  }
dengyihao's avatar
dengyihao 已提交
369
  // buf's mem alread translated to transMsg.pCont
dengyihao's avatar
dengyihao 已提交
370
  if (!CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
371
    transMsg.info.handle = (void*)conn->refId;
dengyihao's avatar
dengyihao 已提交
372
    tDebug("%s conn %p ref by app", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
373
  }
dengyihao's avatar
dengyihao 已提交
374

dengyihao's avatar
dengyihao 已提交
375
  STraceId* trace = &transMsg.info.traceId;
dengyihao's avatar
dengyihao 已提交
376

dengyihao's avatar
dengyihao 已提交
377 378
  tGTrace("%s conn %p %s received from %s, local info:%s, msg size:%d, code:0x%x", CONN_GET_INST_LABEL(conn), conn,
          TMSG_INFO(pHead->msgType), conn->dst, conn->src, transMsg.contLen, transMsg.code);
dengyihao's avatar
dengyihao 已提交
379

dengyihao's avatar
dengyihao 已提交
380
  if (pCtx == NULL && CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
381
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
382 383
    return;
  }
S
Shengliang Guan 已提交
384
  if (CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
385
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
386 387
    return;
  }
dengyihao's avatar
dengyihao 已提交
388

dengyihao's avatar
dengyihao 已提交
389
  if (cliAppCb(conn, &transMsg, pMsg) != 0) {
dengyihao's avatar
dengyihao 已提交
390
    return;
dengyihao's avatar
dengyihao 已提交
391
  }
dengyihao's avatar
dengyihao 已提交
392 393
  destroyCmsg(pMsg);

dengyihao's avatar
dengyihao 已提交
394
  if (cliMaySendCachedMsg(conn) == true) {
dengyihao's avatar
dengyihao 已提交
395 396
    return;
  }
dengyihao's avatar
dengyihao 已提交
397

U
ubuntu 已提交
398
  if (CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
399
    addConnToPool(pThrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
400
  }
dengyihao's avatar
test  
dengyihao 已提交
401

dengyihao's avatar
dengyihao 已提交
402
  uv_read_start((uv_stream_t*)conn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
403
}
U
ubuntu 已提交
404 405

void cliHandleExcept(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
406
  if (transQueueEmpty(&pConn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
407
    if (pConn->broken == true && CONN_NO_PERSIST_BY_APP(pConn)) {
dengyihao's avatar
dengyihao 已提交
408
      tTrace("%s conn %p handle except, persist:0", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
formate  
dengyihao 已提交
409 410 411
      transUnrefCliHandle(pConn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
412
  }
dengyihao's avatar
dengyihao 已提交
413 414 415
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
  bool      once = false;
D
dapan1121 已提交
416
  do {
dengyihao's avatar
dengyihao 已提交
417
    SCliMsg* pMsg = transQueuePop(&pConn->cliMsgs);
D
dapan1121 已提交
418 419
    if (pMsg == NULL && once) {
      break;
dengyihao's avatar
dengyihao 已提交
420
    }
dengyihao's avatar
dengyihao 已提交
421
    STransConnCtx* pCtx = pMsg ? pMsg->ctx : NULL;
U
ubuntu 已提交
422

dengyihao's avatar
dengyihao 已提交
423
    STransMsg transMsg = {0};
dengyihao's avatar
dengyihao 已提交
424
    transMsg.code = pConn->broken ? TSDB_CODE_RPC_BROKEN_LINK : TSDB_CODE_RPC_NETWORK_UNAVAIL;
dengyihao's avatar
dengyihao 已提交
425
    transMsg.msgType = pMsg ? pMsg->msg.msgType + 1 : 0;
S
Shengliang Guan 已提交
426
    transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
427

dengyihao's avatar
dengyihao 已提交
428
    if (pMsg == NULL && !CONN_NO_PERSIST_BY_APP(pConn)) {
S
Shengliang Guan 已提交
429
      transMsg.info.ahandle = transCtxDumpVal(&pConn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
430
      tDebug("%s conn %p construct ahandle %p by %s", CONN_GET_INST_LABEL(pConn), pConn, transMsg.info.ahandle,
dengyihao's avatar
dengyihao 已提交
431
             TMSG_INFO(transMsg.msgType));
S
Shengliang Guan 已提交
432 433
      if (transMsg.info.ahandle == NULL) {
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&pConn->ctx, (int32_t*)&(transMsg.msgType));
dengyihao's avatar
dengyihao 已提交
434
        tDebug("%s conn %p construct ahandle %p due to brokenlink", CONN_GET_INST_LABEL(pConn), pConn,
S
Shengliang Guan 已提交
435
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
436
      }
dengyihao's avatar
dengyihao 已提交
437
    } else {
S
Shengliang Guan 已提交
438
      transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
439 440 441
    }

    if (pCtx == NULL || pCtx->pSem == NULL) {
S
Shengliang Guan 已提交
442
      if (transMsg.info.ahandle == NULL) {
D
dapan1121 已提交
443
        once = true;
U
ubuntu 已提交
444 445
        continue;
      }
dengyihao's avatar
dengyihao 已提交
446
    }
dengyihao's avatar
dengyihao 已提交
447
    if (cliAppCb(pConn, &transMsg, pMsg) != 0) {
dengyihao's avatar
dengyihao 已提交
448
      return;
dengyihao's avatar
dengyihao 已提交
449 450
    }
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
451
    tTrace("%s conn %p start to destroy, ref:%d", CONN_GET_INST_LABEL(pConn), pConn, T_REF_VAL_GET(pConn));
D
dapan1121 已提交
452
  } while (!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
453
  transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
454
}
dengyihao's avatar
dengyihao 已提交
455

dengyihao's avatar
dengyihao 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
// void cliTimeoutCb(uv_timer_t* handle) {
//   SCliThrd* pThrd = handle->data;
//   STrans*   pTransInst = pThrd->pTransInst;
//   int64_t   currentTime = pThrd->nextTimeout;
//   tTrace("%s conn timeout, try to remove expire conn from conn pool", pTransInst->label);
//
//   SConnList* p = taosHashIterate((SHashObj*)pThrd->pool, NULL);
//   while (p != NULL) {
//     while (!QUEUE_IS_EMPTY(&p->conn)) {
//       queue*    h = QUEUE_HEAD(&p->conn);
//       SCliConn* c = QUEUE_DATA(h, SCliConn, q);
//       if (c->expireTime < currentTime) {
//         QUEUE_REMOVE(h);
//         transUnrefCliHandle(c);
//       } else {
//         break;
//       }
//     }
//     p = taosHashIterate((SHashObj*)pThrd->pool, p);
//   }
//
//   pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
//   uv_timer_start(handle, cliTimeoutCb, CONN_PERSIST_TIME(pTransInst->idleTime) / 2, 0);
// }
U
ubuntu 已提交
480 481

void* createConnPool(int size) {
482 483
  // thread local, no lock
  return taosHashInit(size, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
484
}
U
ubuntu 已提交
485
void* destroyConnPool(void* pool) {
dengyihao's avatar
dengyihao 已提交
486
  SConnList* connList = taosHashIterate((SHashObj*)pool, NULL);
dengyihao's avatar
dengyihao 已提交
487 488
  while (connList != NULL) {
    while (!QUEUE_IS_EMPTY(&connList->conn)) {
dengyihao's avatar
dengyihao 已提交
489
      queue*    h = QUEUE_HEAD(&connList->conn);
dengyihao's avatar
dengyihao 已提交
490
      SCliConn* c = QUEUE_DATA(h, SCliConn, q);
U
ubuntu 已提交
491
      cliDestroyConn(c, true);
dengyihao's avatar
dengyihao 已提交
492
    }
dengyihao's avatar
dengyihao 已提交
493
    connList = taosHashIterate((SHashObj*)pool, connList);
dengyihao's avatar
dengyihao 已提交
494
  }
dengyihao's avatar
dengyihao 已提交
495
  taosHashCleanup(pool);
496
  return NULL;
dengyihao's avatar
dengyihao 已提交
497 498
}

dengyihao's avatar
dengyihao 已提交
499
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port) {
dengyihao's avatar
dengyihao 已提交
500
  char key[128] = {0};
dengyihao's avatar
dengyihao 已提交
501
  CONN_CONSTRUCT_HASH_KEY(key, ip, port);
dengyihao's avatar
dengyihao 已提交
502

dengyihao's avatar
dengyihao 已提交
503 504
  SHashObj*  pPool = pool;
  SConnList* plist = taosHashGet(pPool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
505 506
  if (plist == NULL) {
    SConnList list;
dengyihao's avatar
dengyihao 已提交
507 508
    taosHashPut(pPool, key, strlen(key), (void*)&list, sizeof(list));
    plist = taosHashGet(pPool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
509
    QUEUE_INIT(&plist->conn);
dengyihao's avatar
dengyihao 已提交
510 511 512 513 514
  }

  if (QUEUE_IS_EMPTY(&plist->conn)) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
515
  queue*    h = QUEUE_HEAD(&plist->conn);
dengyihao's avatar
dengyihao 已提交
516
  SCliConn* conn = QUEUE_DATA(h, SCliConn, q);
dengyihao's avatar
dengyihao 已提交
517
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
518 519 520
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
  assert(h == &conn->q);
dengyihao's avatar
dengyihao 已提交
521 522 523 524

  transDQCancel(((SCliThrd*)conn->hostThrd)->timeoutQueue, conn->task);
  conn->task = NULL;

dengyihao's avatar
dengyihao 已提交
525
  return conn;
dengyihao's avatar
dengyihao 已提交
526
}
dengyihao's avatar
dengyihao 已提交
527
static int32_t allocConnRef(SCliConn* conn, bool update) {
dengyihao's avatar
dengyihao 已提交
528
  if (update) {
dengyihao's avatar
dengyihao 已提交
529
    transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
530
    conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
531 532 533 534
  }
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
535
  exh->refId = transAddExHandle(transGetRefMgt(), exh);
dengyihao's avatar
dengyihao 已提交
536
  conn->refId = exh->refId;
dengyihao's avatar
dengyihao 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  return 0;
}

static int32_t specifyConnRef(SCliConn* conn, bool update, int64_t handle) {
  if (update) {
    transRemoveExHandle(transGetRefMgt(), conn->refId);
    conn->refId = -1;
  }
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), handle);
  if (exh == NULL) {
    return -1;
  }
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
  conn->refId = exh->refId;

  transReleaseExHandle(transGetRefMgt(), handle);
  return 0;
dengyihao's avatar
dengyihao 已提交
555
}
dengyihao's avatar
dengyihao 已提交
556

dengyihao's avatar
dengyihao 已提交
557
static void addConnToPool(void* pool, SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
558 559 560
  if (conn->status == ConnInPool) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
561
  SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
562 563
  CONN_HANDLE_THREAD_QUIT(thrd);

dengyihao's avatar
dengyihao 已提交
564 565
  allocConnRef(conn, true);

dengyihao's avatar
dengyihao 已提交
566
  STrans* pTransInst = thrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
567
  cliReleaseUnfinishedMsg(conn);
dengyihao's avatar
dengyihao 已提交
568
  transQueueClear(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
569
  transCtxCleanup(&conn->ctx);
dengyihao's avatar
dengyihao 已提交
570
  conn->status = ConnInPool;
dengyihao's avatar
dengyihao 已提交
571

dengyihao's avatar
dengyihao 已提交
572
  char key[128] = {0};
dengyihao's avatar
dengyihao 已提交
573
  CONN_CONSTRUCT_HASH_KEY(key, conn->ip, conn->port);
dengyihao's avatar
dengyihao 已提交
574
  tTrace("%s conn %p added to conn pool, read buf cap:%d", CONN_GET_INST_LABEL(conn), conn, conn->readBuf.cap);
dengyihao's avatar
dengyihao 已提交
575

dengyihao's avatar
dengyihao 已提交
576
  SConnList* plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
577 578
  // list already create before
  assert(plist != NULL);
dengyihao's avatar
dengyihao 已提交
579 580
  QUEUE_INIT(&conn->q);
  QUEUE_PUSH(&plist->conn, &conn->q);
dengyihao's avatar
dengyihao 已提交
581

dengyihao's avatar
dengyihao 已提交
582
  assert(!QUEUE_IS_EMPTY(&plist->conn));
dengyihao's avatar
dengyihao 已提交
583 584 585 586 587

  STaskArg* arg = taosMemoryCalloc(1, sizeof(STaskArg));
  arg->param1 = conn;
  arg->param2 = thrd;
  conn->task = transDQSched(thrd->timeoutQueue, doCloseIdleConn, arg, CONN_PERSIST_TIME(pTransInst->idleTime));
dengyihao's avatar
dengyihao 已提交
588
}
dengyihao's avatar
dengyihao 已提交
589
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
590
  SCliConn*    conn = handle->data;
dengyihao's avatar
dengyihao 已提交
591
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
592
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
593
}
U
ubuntu 已提交
594
static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
595
  // impl later
dengyihao's avatar
dengyihao 已提交
596 597 598
  if (handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
599 600
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
601
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
602
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
603
    if (transReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
604
      tTrace("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn);
U
ubuntu 已提交
605
      cliHandleResp(conn);
dengyihao's avatar
dengyihao 已提交
606
    } else {
dengyihao's avatar
dengyihao 已提交
607
      tTrace("%s conn %p read partial packet, continue to read", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
608
    }
dengyihao's avatar
dengyihao 已提交
609 610
    return;
  }
dengyihao's avatar
dengyihao 已提交
611

612 613
  assert(nread <= 0);
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
614 615 616
    // ref http://docs.libuv.org/en/v1.x/stream.html?highlight=uv_read_start#c.uv_read_cb
    // nread might be 0, which does not indicate an error or EOF. This is equivalent to EAGAIN or EWOULDBLOCK under
    // read(2).
dengyihao's avatar
dengyihao 已提交
617
    tTrace("%s conn %p read empty", CONN_GET_INST_LABEL(conn), conn);
618 619
    return;
  }
dengyihao's avatar
fix bug  
dengyihao 已提交
620
  if (nread < 0) {
dengyihao's avatar
dengyihao 已提交
621
    tWarn("%s conn %p read error:%s, ref:%d", CONN_GET_INST_LABEL(conn), conn, uv_err_name(nread), T_REF_VAL_GET(conn));
dengyihao's avatar
dengyihao 已提交
622
    conn->broken = true;
U
ubuntu 已提交
623
    cliHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
624
  }
dengyihao's avatar
dengyihao 已提交
625
}
dengyihao's avatar
dengyihao 已提交
626

dengyihao's avatar
dengyihao 已提交
627
static SCliConn* cliCreateConn(SCliThrd* pThrd) {
wafwerar's avatar
wafwerar 已提交
628
  SCliConn* conn = taosMemoryCalloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
629
  // read/write stream handle
wafwerar's avatar
wafwerar 已提交
630
  conn->stream = (uv_stream_t*)taosMemoryMalloc(sizeof(uv_tcp_t));
dengyihao's avatar
dengyihao 已提交
631 632 633 634
  uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
  conn->stream->data = conn;

  conn->connReq.data = conn;
dengyihao's avatar
dengyihao 已提交
635

dengyihao's avatar
dengyihao 已提交
636 637
  transReqQueueInit(&conn->wreqQueue);

dengyihao's avatar
dengyihao 已提交
638
  transQueueInit(&conn->cliMsgs, NULL);
dengyihao's avatar
opt rpc  
dengyihao 已提交
639 640

  transInitBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
641
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
642
  conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
643 644
  conn->status = ConnNormal;
  conn->broken = 0;
dengyihao's avatar
dengyihao 已提交
645
  transRefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
646

dengyihao's avatar
dengyihao 已提交
647
  allocConnRef(conn, false);
dengyihao's avatar
dengyihao 已提交
648

dengyihao's avatar
dengyihao 已提交
649 650
  return conn;
}
U
ubuntu 已提交
651
static void cliDestroyConn(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
652
  tTrace("%s conn %p remove from conn pool", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
653 654
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
655
  transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
opt rpc  
dengyihao 已提交
656
  transDestroyBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
657

dengyihao's avatar
opt rpc  
dengyihao 已提交
658
  conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
659 660
  if (conn->task != NULL) transDQCancel(((SCliThrd*)conn->hostThrd)->timeoutQueue, conn->task);

dengyihao's avatar
dengyihao 已提交
661
  if (clear) {
dengyihao's avatar
dengyihao 已提交
662
    if (!uv_is_closing((uv_handle_t*)conn->stream)) {
dengyihao's avatar
dengyihao 已提交
663
      uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
664 665
      uv_close((uv_handle_t*)conn->stream, cliDestroy);
    }
666
  }
dengyihao's avatar
dengyihao 已提交
667
}
U
ubuntu 已提交
668
static void cliDestroy(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
669 670 671 672
  if (uv_handle_get_type(handle) != UV_TCP || handle->data == NULL) {
    return;
  }

dengyihao's avatar
dengyihao 已提交
673
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
674
  transRemoveExHandle(transGetRefMgt(), conn->refId);
wafwerar's avatar
wafwerar 已提交
675
  taosMemoryFree(conn->ip);
dengyihao's avatar
dengyihao 已提交
676
  conn->stream->data = NULL;
wafwerar's avatar
wafwerar 已提交
677
  taosMemoryFree(conn->stream);
dengyihao's avatar
dengyihao 已提交
678
  transCtxCleanup(&conn->ctx);
dengyihao's avatar
dengyihao 已提交
679
  cliReleaseUnfinishedMsg(conn);
dengyihao's avatar
dengyihao 已提交
680
  transQueueDestroy(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
681
  tTrace("%s conn %p destroy successfully", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
682 683
  transReqQueueClear(&conn->wreqQueue);

wafwerar's avatar
wafwerar 已提交
684
  taosMemoryFree(conn);
dengyihao's avatar
dengyihao 已提交
685
}
dengyihao's avatar
dengyihao 已提交
686
static bool cliHandleNoResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
687 688
  bool res = false;
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
689
    SCliMsg* pMsg = transQueueGet(&conn->cliMsgs, 0);
dengyihao's avatar
dengyihao 已提交
690
    if (REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
691
      transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
692 693 694 695 696
      destroyCmsg(pMsg);
      res = true;
    }
    if (res == true) {
      if (cliMaySendCachedMsg(conn) == false) {
dengyihao's avatar
dengyihao 已提交
697
        SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
698
        addConnToPool(thrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
699 700 701 702 703
      }
    }
  }
  return res;
}
U
ubuntu 已提交
704
static void cliSendCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
705 706
  SCliConn* pConn = transReqQueueRemove(req);
  if (pConn == NULL) return;
dengyihao's avatar
dengyihao 已提交
707

dengyihao's avatar
dengyihao 已提交
708
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
709
    tTrace("%s conn %p data already was written out", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
710
  } else {
S
Shengliang Guan 已提交
711
    tError("%s conn %p failed to write:%s", CONN_GET_INST_LABEL(pConn), pConn, uv_err_name(status));
U
ubuntu 已提交
712
    cliHandleExcept(pConn);
dengyihao's avatar
dengyihao 已提交
713 714
    return;
  }
dengyihao's avatar
dengyihao 已提交
715
  if (cliHandleNoResp(pConn) == true) {
dengyihao's avatar
dengyihao 已提交
716
    tTrace("%s conn %p no resp required", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
717 718
    return;
  }
dengyihao's avatar
dengyihao 已提交
719
  uv_read_start((uv_stream_t*)pConn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
720
}
dengyihao's avatar
dengyihao 已提交
721

U
ubuntu 已提交
722
void cliSend(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
723 724
  CONN_HANDLE_BROKEN(pConn);

dengyihao's avatar
dengyihao 已提交
725
  assert(!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
726 727

  SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
728
  CONN_GET_NEXT_SENDMSG(pConn);
dengyihao's avatar
dengyihao 已提交
729 730
  pCliMsg->sent = 1;

dengyihao's avatar
dengyihao 已提交
731
  STransConnCtx* pCtx = pCliMsg->ctx;
dengyihao's avatar
dengyihao 已提交
732

dengyihao's avatar
dengyihao 已提交
733 734
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
735

U
ubuntu 已提交
736
  STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
dengyihao's avatar
dengyihao 已提交
737 738 739 740
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
dengyihao's avatar
dengyihao 已提交
741
  int msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
742

dengyihao's avatar
dengyihao 已提交
743 744
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
  pHead->ahandle = pCtx != NULL ? (uint64_t)pCtx->ahandle : 0;
dengyihao's avatar
dengyihao 已提交
745 746
  pHead->noResp = REQUEST_NO_RESP(pMsg) ? 1 : 0;
  pHead->persist = REQUEST_PERSIS_HANDLE(pMsg) ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
747 748
  pHead->msgType = pMsg->msgType;
  pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);
dengyihao's avatar
dengyihao 已提交
749
  pHead->release = REQUEST_RELEASE_HANDLE(pCliMsg) ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
750
  memcpy(pHead->user, pTransInst->user, strlen(pTransInst->user));
dengyihao's avatar
dengyihao 已提交
751
  pHead->traceId = pMsg->info.traceId;
dengyihao's avatar
dengyihao 已提交
752 753

  uv_buf_t wb = uv_buf_init((char*)pHead, msgLen);
dengyihao's avatar
dengyihao 已提交
754 755

  STraceId* trace = &pMsg->info.traceId;
dengyihao's avatar
dengyihao 已提交
756 757
  tGTrace("%s conn %p %s is sent to %s, local info %s", CONN_GET_INST_LABEL(pConn), pConn, TMSG_INFO(pHead->msgType),
          pConn->dst, pConn->src);
dengyihao's avatar
dengyihao 已提交
758

dengyihao's avatar
dengyihao 已提交
759 760 761
  if (pHead->persist == 1) {
    CONN_SET_PERSIST_BY_APP(pConn);
  }
dengyihao's avatar
dengyihao 已提交
762

dengyihao's avatar
dengyihao 已提交
763
  uv_write_t* req = transReqQueuePush(&pConn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
764
  uv_write(req, (uv_stream_t*)pConn->stream, &wb, 1, cliSendCb);
U
ubuntu 已提交
765 766
  return;
_RETURN:
dengyihao's avatar
dengyihao 已提交
767
  return;
dengyihao's avatar
dengyihao 已提交
768
}
U
ubuntu 已提交
769 770

void cliConnCb(uv_connect_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
771
  // impl later
dengyihao's avatar
dengyihao 已提交
772 773
  SCliConn* pConn = req->data;
  if (status != 0) {
S
Shengliang Guan 已提交
774
    tError("%s conn %p failed to connect server:%s", CONN_GET_INST_LABEL(pConn), pConn, uv_strerror(status));
U
ubuntu 已提交
775
    cliHandleExcept(pConn);
776
    return;
dengyihao's avatar
dengyihao 已提交
777
  }
dengyihao's avatar
dengyihao 已提交
778 779 780 781 782
  // int addrlen = sizeof(pConn->addr);
  struct sockaddr peername, sockname;
  int             addrlen = sizeof(peername);

  uv_tcp_getpeername((uv_tcp_t*)pConn->stream, &peername, &addrlen);
dengyihao's avatar
dengyihao 已提交
783
  transGetSockDebugInfo(&peername, pConn->dst);
dengyihao's avatar
dengyihao 已提交
784

dengyihao's avatar
dengyihao 已提交
785 786
  addrlen = sizeof(sockname);
  uv_tcp_getsockname((uv_tcp_t*)pConn->stream, &sockname, &addrlen);
dengyihao's avatar
dengyihao 已提交
787
  transGetSockDebugInfo(&sockname, pConn->src);
dengyihao's avatar
dengyihao 已提交
788

dengyihao's avatar
dengyihao 已提交
789
  tTrace("%s conn %p connect to server successfully", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
790
  assert(pConn->stream == req->handle);
dengyihao's avatar
dengyihao 已提交
791

U
ubuntu 已提交
792
  cliSend(pConn);
dengyihao's avatar
dengyihao 已提交
793 794
}

dengyihao's avatar
dengyihao 已提交
795
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
796 797 798 799 800
  if (!transAsyncPoolIsEmpty(pThrd->asyncPool)) {
    pThrd->stopMsg = pMsg;
    return;
  }
  pThrd->stopMsg = NULL;
dengyihao's avatar
dengyihao 已提交
801
  pThrd->quit = true;
U
ubuntu 已提交
802
  tDebug("cli work thread %p start to quit", pThrd);
dengyihao's avatar
dengyihao 已提交
803
  destroyCmsg(pMsg);
dengyihao's avatar
fix bug  
dengyihao 已提交
804
  destroyConnPool(pThrd->pool);
dengyihao's avatar
dengyihao 已提交
805
  uv_timer_stop(&pThrd->timer);
dengyihao's avatar
dengyihao 已提交
806
  uv_walk(pThrd->loop, cliWalkCb, NULL);
dengyihao's avatar
dengyihao 已提交
807
}
dengyihao's avatar
dengyihao 已提交
808
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
809
  int64_t    refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
810
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
811
  if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
812
    tDebug("%" PRId64 " already release", refId);
dengyihao's avatar
dengyihao 已提交
813 814
    destroyCmsg(pMsg);
    return;
dengyihao's avatar
dengyihao 已提交
815 816 817
  }

  SCliConn* conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
818 819
  transReleaseExHandle(transGetRefMgt(), refId);

dengyihao's avatar
dengyihao 已提交
820
  tDebug("%s conn %p start to release to inst", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
821

dengyihao's avatar
dengyihao 已提交
822 823
  if (T_REF_VAL_GET(conn) == 2) {
    transUnrefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
824 825
    if (!transQueuePush(&conn->cliMsgs, pMsg)) {
      return;
dengyihao's avatar
dengyihao 已提交
826 827
    }
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
828 829
  }
}
dengyihao's avatar
dengyihao 已提交
830
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
831
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
832
  pThrd->cvtAddr = pCtx->cvtAddr;
dengyihao's avatar
dengyihao 已提交
833 834
  destroyCmsg(pMsg);
}
U
ubuntu 已提交
835

dengyihao's avatar
dengyihao 已提交
836
SCliConn* cliGetConn(SCliMsg* pMsg, SCliThrd* pThrd, bool* ignore) {
dengyihao's avatar
dengyihao 已提交
837 838 839 840
  STransConnCtx* pCtx = pMsg->ctx;
  SCliConn*      conn = NULL;

  int64_t refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
841
  if (refId != 0) {
dengyihao's avatar
dengyihao 已提交
842
    SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
843
    if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
844 845 846
      *ignore = true;
      destroyCmsg(pMsg);
      return NULL;
dengyihao's avatar
dengyihao 已提交
847 848
    } else {
      conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
849 850
      if (conn == NULL) {
        conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
dengyihao's avatar
dengyihao 已提交
851
        if (conn != NULL) specifyConnRef(conn, true, refId);
dengyihao's avatar
dengyihao 已提交
852
      }
dengyihao's avatar
dengyihao 已提交
853
      transReleaseExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
854 855 856
    }
    return conn;
  };
dengyihao's avatar
dengyihao 已提交
857 858 859

  conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
860
    tTrace("%s conn %p get from conn pool:%p", CONN_GET_INST_LABEL(conn), conn, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
861
  } else {
dengyihao's avatar
dengyihao 已提交
862
    tTrace("%s not found conn in conn pool:%p", ((STrans*)pThrd->pTransInst)->label, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
863
  }
dengyihao's avatar
dengyihao 已提交
864 865
  return conn;
}
dengyihao's avatar
dengyihao 已提交
866 867 868 869 870 871 872 873 874 875 876
void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr) {
  if (pCvtAddr->cvt == false) {
    return;
  }
  for (int i = 0; i < pEpSet->numOfEps && pEpSet->numOfEps == 1; i++) {
    if (strncmp(pEpSet->eps[i].fqdn, pCvtAddr->fqdn, TSDB_FQDN_LEN) == 0) {
      memset(pEpSet->eps[i].fqdn, 0, TSDB_FQDN_LEN);
      memcpy(pEpSet->eps[i].fqdn, pCvtAddr->ip, TSDB_FQDN_LEN);
    }
  }
}
dengyihao's avatar
dengyihao 已提交
877
void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
878
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
formate  
dengyihao 已提交
879
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
880

dengyihao's avatar
dengyihao 已提交
881
  cliMayCvtFqdnToIp(&pCtx->epSet, &pThrd->cvtAddr);
dengyihao's avatar
dengyihao 已提交
882 883 884 885 886
  if (!EPSET_IS_VALID(&pCtx->epSet)) {
    destroyCmsg(pMsg);
    tError("invalid epset");
    return;
  }
dengyihao's avatar
dengyihao 已提交
887

dengyihao's avatar
dengyihao 已提交
888 889 890
  bool      ignore = false;
  SCliConn* conn = cliGetConn(pMsg, pThrd, &ignore);
  if (ignore == true) {
dengyihao's avatar
dengyihao 已提交
891
    tError("ignore msg");
dengyihao's avatar
dengyihao 已提交
892 893
    return;
  }
dengyihao's avatar
dengyihao 已提交
894

dengyihao's avatar
dengyihao 已提交
895
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
896
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
897
    transQueuePush(&conn->cliMsgs, pMsg);
U
ubuntu 已提交
898
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
899
  } else {
U
ubuntu 已提交
900
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
901 902 903 904

    int64_t refId = (int64_t)pMsg->msg.info.handle;
    if (refId != 0) specifyConnRef(conn, true, refId);

dengyihao's avatar
dengyihao 已提交
905
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
906
    transQueuePush(&conn->cliMsgs, pMsg);
dengyihao's avatar
dengyihao 已提交
907

dengyihao's avatar
dengyihao 已提交
908 909
    conn->ip = strdup(EPSET_GET_INUSE_IP(&pCtx->epSet));
    conn->port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
910

dengyihao's avatar
dengyihao 已提交
911 912
    int ret = transSetConnOption((uv_tcp_t*)conn->stream);
    if (ret) {
dengyihao's avatar
dengyihao 已提交
913
      tError("%s conn %p failed to set conn option, errmsg %s", transLabel(pTransInst), conn, uv_err_name(ret));
dengyihao's avatar
dengyihao 已提交
914
    }
dengyihao's avatar
dengyihao 已提交
915
    int32_t fd = taosCreateSocketWithTimeout(TRANS_CONN_TIMEOUT);
dengyihao's avatar
dengyihao 已提交
916
    if (fd == -1) {
dengyihao's avatar
dengyihao 已提交
917
      tTrace("%s conn %p failed to create socket", transLabel(pTransInst), conn);
dengyihao's avatar
dengyihao 已提交
918 919 920 921
      cliHandleExcept(conn);
      return;
    }
    uv_tcp_open((uv_tcp_t*)conn->stream, fd);
922

dengyihao's avatar
dengyihao 已提交
923
    struct sockaddr_in addr;
924 925 926
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = taosGetIpv4FromFqdn(conn->ip);
    addr.sin_port = (uint16_t)htons((uint16_t)conn->port);
dengyihao's avatar
dengyihao 已提交
927
    tTrace("%s conn %p try to connect to %s:%d", pTransInst->label, conn, conn->ip, conn->port);
dengyihao's avatar
dengyihao 已提交
928 929
    ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
    if (ret != 0) {
S
Shengliang Guan 已提交
930
      tTrace("%s conn %p failed to connect to %s:%d, reason:%s", pTransInst->label, conn, conn->ip, conn->port,
dengyihao's avatar
dengyihao 已提交
931 932 933 934
             uv_err_name(ret));
      cliHandleExcept(conn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
935 936
  }
}
U
ubuntu 已提交
937
static void cliAsyncCb(uv_async_t* handle) {
dengyihao's avatar
dengyihao 已提交
938 939 940
  SAsyncItem* item = handle->data;
  SCliThrd*   pThrd = item->pThrd;
  SCliMsg*    pMsg = NULL;
dengyihao's avatar
dengyihao 已提交
941

dengyihao's avatar
dengyihao 已提交
942
  // batch process to avoid to lock/unlock frequently
dengyihao's avatar
formate  
dengyihao 已提交
943
  queue wq;
wafwerar's avatar
wafwerar 已提交
944
  taosThreadMutexLock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
945
  QUEUE_MOVE(&item->qmsg, &wq);
wafwerar's avatar
wafwerar 已提交
946
  taosThreadMutexUnlock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
947

dengyihao's avatar
dengyihao 已提交
948 949 950 951
  int count = 0;
  while (!QUEUE_IS_EMPTY(&wq)) {
    queue* h = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
952 953

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
954 955
    if (pMsg == NULL) {
      continue;
dengyihao's avatar
dengyihao 已提交
956
    }
dengyihao's avatar
dengyihao 已提交
957
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
958
    count++;
dengyihao's avatar
dengyihao 已提交
959 960
  }
  if (count >= 2) {
S
Shengliang Guan 已提交
961
    tTrace("cli process batch size:%d", count);
dengyihao's avatar
dengyihao 已提交
962
  }
dengyihao's avatar
dengyihao 已提交
963
  if (pThrd->stopMsg != NULL) cliHandleQuit(pThrd->stopMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
964 965
}

U
ubuntu 已提交
966
static void* cliWorkThread(void* arg) {
dengyihao's avatar
dengyihao 已提交
967
  SCliThrd* pThrd = (SCliThrd*)arg;
dengyihao's avatar
dengyihao 已提交
968
  pThrd->pid = taosGetSelfPthreadId();
U
ubuntu 已提交
969
  setThreadName("trans-cli-work");
dengyihao's avatar
dengyihao 已提交
970
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
971
  return NULL;
dengyihao's avatar
dengyihao 已提交
972 973
}

U
ubuntu 已提交
974
void* transInitClient(uint32_t ip, uint32_t port, char* label, int numOfThreads, void* fp, void* shandle) {
wafwerar's avatar
wafwerar 已提交
975
  SCliObj* cli = taosMemoryCalloc(1, sizeof(SCliObj));
dengyihao's avatar
dengyihao 已提交
976

dengyihao's avatar
dengyihao 已提交
977
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
978 979
  memcpy(cli->label, label, strlen(label));
  cli->numOfThreads = numOfThreads;
dengyihao's avatar
dengyihao 已提交
980
  cli->pThreadObj = (SCliThrd**)taosMemoryCalloc(cli->numOfThreads, sizeof(SCliThrd*));
dengyihao's avatar
dengyihao 已提交
981 982

  for (int i = 0; i < cli->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
983
    SCliThrd* pThrd = createThrdObj();
dengyihao's avatar
dengyihao 已提交
984
    pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
dengyihao's avatar
dengyihao 已提交
985
    pThrd->pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
986

wafwerar's avatar
wafwerar 已提交
987
    int err = taosThreadCreate(&pThrd->thread, NULL, cliWorkThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
988
    if (err == 0) {
S
Shengliang Guan 已提交
989
      tDebug("success to create tranport-cli thread:%d", i);
dengyihao's avatar
dengyihao 已提交
990
    }
dengyihao's avatar
dengyihao 已提交
991
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
992
  }
dengyihao's avatar
dengyihao 已提交
993

dengyihao's avatar
dengyihao 已提交
994 995
  return cli;
}
dengyihao's avatar
dengyihao 已提交
996

U
ubuntu 已提交
997
static void destroyUserdata(STransMsg* userdata) {
dengyihao's avatar
dengyihao 已提交
998 999 1000 1001 1002 1003
  if (userdata->pCont == NULL) {
    return;
  }
  transFreeMsg(userdata->pCont);
  userdata->pCont = NULL;
}
dengyihao's avatar
dengyihao 已提交
1004 1005
static void destroyCmsg(void* arg) {
  SCliMsg* pMsg = arg;
dengyihao's avatar
dengyihao 已提交
1006 1007 1008 1009 1010
  if (pMsg == NULL) {
    return;
  }
  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
wafwerar's avatar
wafwerar 已提交
1011
  taosMemoryFree(pMsg);
dengyihao's avatar
dengyihao 已提交
1012
}
dengyihao's avatar
dengyihao 已提交
1013

dengyihao's avatar
dengyihao 已提交
1014 1015
static SCliThrd* createThrdObj() {
  SCliThrd* pThrd = (SCliThrd*)taosMemoryCalloc(1, sizeof(SCliThrd));
U
ubuntu 已提交
1016

dengyihao's avatar
dengyihao 已提交
1017
  QUEUE_INIT(&pThrd->msg);
wafwerar's avatar
wafwerar 已提交
1018
  taosThreadMutexInit(&pThrd->msgMtx, NULL);
dengyihao's avatar
dengyihao 已提交
1019

wafwerar's avatar
wafwerar 已提交
1020
  pThrd->loop = (uv_loop_t*)taosMemoryMalloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
1021 1022
  uv_loop_init(pThrd->loop);

dengyihao's avatar
dengyihao 已提交
1023
  pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 5, pThrd, cliAsyncCb);
dengyihao's avatar
dengyihao 已提交
1024 1025
  uv_timer_init(pThrd->loop, &pThrd->timer);
  pThrd->timer.data = pThrd;
dengyihao's avatar
dengyihao 已提交
1026

dengyihao's avatar
dengyihao 已提交
1027
  pThrd->pool = createConnPool(4);
dengyihao's avatar
dengyihao 已提交
1028
  transDQCreate(pThrd->loop, &pThrd->delayQueue);
dengyihao's avatar
dengyihao 已提交
1029

dengyihao's avatar
dengyihao 已提交
1030 1031
  transDQCreate(pThrd->loop, &pThrd->timeoutQueue);

dengyihao's avatar
dengyihao 已提交
1032
  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
1033 1034
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1035
static void destroyThrdObj(SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1036 1037 1038
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1039

wafwerar's avatar
wafwerar 已提交
1040
  taosThreadJoin(pThrd->thread, NULL);
dengyihao's avatar
dengyihao 已提交
1041
  CLI_RELEASE_UV(pThrd->loop);
wafwerar's avatar
wafwerar 已提交
1042
  taosThreadMutexDestroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
1043
  TRANS_DESTROY_ASYNC_POOL_MSG(pThrd->asyncPool, SCliMsg, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1044
  transAsyncPoolDestroy(pThrd->asyncPool);
dengyihao's avatar
dengyihao 已提交
1045

dengyihao's avatar
dengyihao 已提交
1046
  transDQDestroy(pThrd->delayQueue, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1047
  transDQDestroy(pThrd->timeoutQueue, NULL);
wafwerar's avatar
wafwerar 已提交
1048 1049
  taosMemoryFree(pThrd->loop);
  taosMemoryFree(pThrd);
dengyihao's avatar
dengyihao 已提交
1050
}
dengyihao's avatar
dengyihao 已提交
1051

dengyihao's avatar
dengyihao 已提交
1052
static void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1053
  //
wafwerar's avatar
wafwerar 已提交
1054
  taosMemoryFree(ctx);
dengyihao's avatar
dengyihao 已提交
1055
}
dengyihao's avatar
dengyihao 已提交
1056

dengyihao's avatar
dengyihao 已提交
1057
void cliSendQuit(SCliThrd* thrd) {
dengyihao's avatar
dengyihao 已提交
1058
  // cli can stop gracefully
wafwerar's avatar
wafwerar 已提交
1059
  SCliMsg* msg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1060
  msg->type = Quit;
dengyihao's avatar
dengyihao 已提交
1061
  transAsyncSend(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
1062
  atomic_store_8(&thrd->asyncPool->stop, 1);
dengyihao's avatar
dengyihao 已提交
1063
}
dengyihao's avatar
dengyihao 已提交
1064 1065
void cliWalkCb(uv_handle_t* handle, void* arg) {
  if (!uv_is_closing(handle)) {
dengyihao's avatar
dengyihao 已提交
1066
    uv_read_stop((uv_stream_t*)handle);
dengyihao's avatar
dengyihao 已提交
1067
    uv_close(handle, cliDestroy);
dengyihao's avatar
dengyihao 已提交
1068 1069
  }
}
dengyihao's avatar
dengyihao 已提交
1070

U
ubuntu 已提交
1071
int cliRBChoseIdx(STrans* pTransInst) {
dengyihao's avatar
dengyihao 已提交
1072 1073 1074 1075
  int8_t index = pTransInst->index;
  if (pTransInst->numOfThreads == 0) {
    return -1;
  }
U
ubuntu 已提交
1076 1077 1078 1079 1080
  if (pTransInst->index++ >= pTransInst->numOfThreads) {
    pTransInst->index = 0;
  }
  return index % pTransInst->numOfThreads;
}
dengyihao's avatar
dengyihao 已提交
1081 1082
static void doDelayTask(void* param) {
  STaskArg* arg = param;
dengyihao's avatar
dengyihao 已提交
1083 1084
  SCliMsg*  pMsg = arg->param1;
  SCliThrd* pThrd = arg->param2;
dengyihao's avatar
dengyihao 已提交
1085 1086
  taosMemoryFree(arg);

dengyihao's avatar
dengyihao 已提交
1087
  cliHandleReq(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1088
}
dengyihao's avatar
dengyihao 已提交
1089

dengyihao's avatar
dengyihao 已提交
1090 1091 1092 1093
static void doCloseIdleConn(void* param) {
  STaskArg* arg = param;
  SCliConn* conn = arg->param1;
  SCliThrd* pThrd = arg->param2;
dengyihao's avatar
dengyihao 已提交
1094 1095
  tTrace("%s conn %p idle, close it", CONN_GET_INST_LABEL(conn), conn);
  conn->task = NULL;
dengyihao's avatar
dengyihao 已提交
1096 1097
  cliDestroyConn(conn, true);
  taosMemoryFree(arg);
dengyihao's avatar
dengyihao 已提交
1098 1099
}

dengyihao's avatar
dengyihao 已提交
1100 1101 1102
static void cliSchedMsgToNextNode(SCliMsg* pMsg, SCliThrd* pThrd) {
  STransConnCtx* pCtx = pMsg->ctx;

dengyihao's avatar
dengyihao 已提交
1103 1104
  STraceId* trace = &pMsg->msg.info.traceId;
  char      tbuf[256] = {0};
dengyihao's avatar
dengyihao 已提交
1105
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1106
  tGDebug("%s retry on next node, use %s, retryCnt:%d, limit:%d", transLabel(pThrd->pTransInst), tbuf,
dengyihao's avatar
dengyihao 已提交
1107
          pCtx->retryCnt + 1, pCtx->retryLimit);
dengyihao's avatar
dengyihao 已提交
1108 1109 1110 1111 1112

  STaskArg* arg = taosMemoryMalloc(sizeof(STaskArg));
  arg->param1 = pMsg;
  arg->param2 = pThrd;
  transDQSched(pThrd->delayQueue, doDelayTask, arg, TRANS_RETRY_INTERVAL);
dengyihao's avatar
dengyihao 已提交
1113
}
dengyihao's avatar
dengyihao 已提交
1114

dengyihao's avatar
dengyihao 已提交
1115
void cliCompareAndSwap(int8_t* val, int8_t exp, int8_t newVal) {
dengyihao's avatar
dengyihao 已提交
1116 1117 1118 1119
  if (*val != exp) {
    *val = newVal;
  }
}
dengyihao's avatar
dengyihao 已提交
1120

dengyihao's avatar
dengyihao 已提交
1121
bool cliTryExtractEpSet(STransMsg* pResp, SEpSet* dst) {
dengyihao's avatar
dengyihao 已提交
1122 1123 1124 1125 1126 1127
  if ((pResp == NULL || pResp->info.hasEpSet == 0)) {
    return false;
  }
  // rebuild resp msg
  SEpSet epset;
  if (tDeserializeSEpSet(pResp->pCont, pResp->contLen, &epset) < 0) {
dengyihao's avatar
dengyihao 已提交
1128 1129 1130 1131
    return false;
  }
  int32_t tlen = tSerializeSEpSet(NULL, 0, dst);

dengyihao's avatar
dengyihao 已提交
1132 1133 1134 1135 1136 1137 1138
  char*   buf = NULL;
  int32_t len = pResp->contLen - tlen;
  if (len != 0) {
    buf = rpcMallocCont(len);
    memcpy(buf, (char*)pResp->pCont + tlen, len);
  }
  rpcFreeCont(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
1139 1140

  pResp->pCont = buf;
dengyihao's avatar
dengyihao 已提交
1141 1142 1143
  pResp->contLen = len;

  *dst = epset;
dengyihao's avatar
dengyihao 已提交
1144 1145
  return true;
}
dengyihao's avatar
dengyihao 已提交
1146
int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
1147 1148
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1149

dengyihao's avatar
dengyihao 已提交
1150
  if (pMsg == NULL || pMsg->ctx == NULL) {
dengyihao's avatar
dengyihao 已提交
1151
    tTrace("%s conn %p handle resp", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
1152 1153 1154
    pTransInst->cfp(pTransInst->parent, pResp, NULL);
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
1155
  /*
dengyihao's avatar
dengyihao 已提交
1156 1157 1158
   *  no retry
   *  1. query conn
   *  2. rpc thread already receive quit msg
dengyihao's avatar
dengyihao 已提交
1159
   */
dengyihao's avatar
dengyihao 已提交
1160 1161
  STransConnCtx* pCtx = pMsg->ctx;
  int32_t        code = pResp->code;
dengyihao's avatar
dengyihao 已提交
1162 1163

  bool retry = (pTransInst->retry != NULL && pTransInst->retry(code, pResp->msgType - 1)) ? true : false;
dengyihao's avatar
dengyihao 已提交
1164
  if (retry) {
dengyihao's avatar
dengyihao 已提交
1165 1166
    pMsg->sent = 0;
    pCtx->retryCnt += 1;
dengyihao's avatar
dengyihao 已提交
1167
    if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK) {
dengyihao's avatar
dengyihao 已提交
1168
      cliCompareAndSwap(&pCtx->retryLimit, TRANS_RETRY_COUNT_LIMIT, EPSET_GET_SIZE(&pCtx->epSet) * 3);
dengyihao's avatar
dengyihao 已提交
1169 1170 1171
      if (pCtx->retryCnt < pCtx->retryLimit) {
        transUnrefCliHandle(pConn);
        EPSET_FORWARD_INUSE(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1172
        transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
1173 1174 1175 1176
        cliSchedMsgToNextNode(pMsg, pThrd);
        return -1;
      }
    } else {
dengyihao's avatar
dengyihao 已提交
1177
      cliCompareAndSwap(&pCtx->retryLimit, TRANS_RETRY_COUNT_LIMIT, TRANS_RETRY_COUNT_LIMIT);
dengyihao's avatar
dengyihao 已提交
1178 1179
      if (pCtx->retryCnt < pCtx->retryLimit) {
        if (pResp->contLen == 0) {
dengyihao's avatar
dengyihao 已提交
1180
          EPSET_FORWARD_INUSE(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1181
        } else {
dengyihao's avatar
dengyihao 已提交
1182 1183 1184
          if (tDeserializeSEpSet(pResp->pCont, pResp->contLen, &pCtx->epSet) < 0) {
            tError("%s conn %p failed to deserialize epset", CONN_GET_INST_LABEL(pConn));
          }
dengyihao's avatar
dengyihao 已提交
1185
        }
dengyihao's avatar
dengyihao 已提交
1186
        addConnToPool(pThrd->pool, pConn);
dengyihao's avatar
dengyihao 已提交
1187 1188 1189
        transFreeMsg(pResp->pCont);
        cliSchedMsgToNextNode(pMsg, pThrd);
        return -1;
dengyihao's avatar
dengyihao 已提交
1190
      }
dengyihao's avatar
dengyihao 已提交
1191 1192
    }
  }
dengyihao's avatar
dengyihao 已提交
1193

dengyihao's avatar
dengyihao 已提交
1194
  STraceId* trace = &pResp->info.traceId;
dengyihao's avatar
dengyihao 已提交
1195

dengyihao's avatar
dengyihao 已提交
1196
  bool hasEpSet = cliTryExtractEpSet(pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1197
  if (hasEpSet) {
dengyihao's avatar
dengyihao 已提交
1198 1199
    char tbuf[256] = {0};
    EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1200
    tGDebug("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1201
  }
dengyihao's avatar
dengyihao 已提交
1202

dengyihao's avatar
dengyihao 已提交
1203
  if (pCtx->pSem != NULL) {
dengyihao's avatar
dengyihao 已提交
1204
    tGDebug("%s conn %p(sync) handle resp", CONN_GET_INST_LABEL(pConn), pConn);
1205
    if (pCtx->pRsp == NULL) {
dengyihao's avatar
dengyihao 已提交
1206
      tGTrace("%s conn %p(sync) failed to resp, ignore", CONN_GET_INST_LABEL(pConn), pConn);
1207 1208 1209
    } else {
      memcpy((char*)pCtx->pRsp, (char*)pResp, sizeof(*pResp));
    }
dengyihao's avatar
dengyihao 已提交
1210
    tsem_post(pCtx->pSem);
1211
    pCtx->pRsp = NULL;
dengyihao's avatar
dengyihao 已提交
1212
  } else {
dengyihao's avatar
dengyihao 已提交
1213
    tGDebug("%s conn %p handle resp", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1214
    if (retry == false && hasEpSet == true) {
dengyihao's avatar
dengyihao 已提交
1215
      pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1216 1217 1218 1219 1220 1221
    } else {
      if (!cliIsEpsetUpdated(code, pCtx)) {
        pTransInst->cfp(pTransInst->parent, pResp, NULL);
      } else {
        pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1222
    }
dengyihao's avatar
dengyihao 已提交
1223
  }
dengyihao's avatar
dengyihao 已提交
1224
  return 0;
dengyihao's avatar
dengyihao 已提交
1225
}
U
ubuntu 已提交
1226 1227

void transCloseClient(void* arg) {
U
ubuntu 已提交
1228
  SCliObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
1229
  for (int i = 0; i < cli->numOfThreads; i++) {
U
ubuntu 已提交
1230
    cliSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1231
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1232
  }
wafwerar's avatar
wafwerar 已提交
1233 1234
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
dengyihao's avatar
dengyihao 已提交
1235
}
dengyihao's avatar
dengyihao 已提交
1236 1237 1238 1239 1240
void transRefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_INC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1241
  tTrace("%s conn %p ref %d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1242 1243 1244 1245 1246 1247 1248
  UNUSED(ref);
}
void transUnrefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_DEC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1249
  tTrace("%s conn %p ref:%d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1250
  if (ref == 0) {
U
ubuntu 已提交
1251
    cliDestroyConn((SCliConn*)handle, true);
dengyihao's avatar
dengyihao 已提交
1252 1253
  }
}
dengyihao's avatar
dengyihao 已提交
1254
SCliThrd* transGetWorkThrdFromHandle(int64_t handle, bool* validHandle) {
dengyihao's avatar
dengyihao 已提交
1255
  SCliThrd*  pThrd = NULL;
dengyihao's avatar
dengyihao 已提交
1256
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
1257 1258 1259
  if (exh == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1260 1261

  *validHandle = true;
dengyihao's avatar
dengyihao 已提交
1262
  pThrd = exh->pThrd;
dengyihao's avatar
dengyihao 已提交
1263
  transReleaseExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
1264 1265
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1266
SCliThrd* transGetWorkThrd(STrans* trans, int64_t handle, bool* validHandle) {
dengyihao's avatar
dengyihao 已提交
1267
  if (handle == 0) {
dengyihao's avatar
dengyihao 已提交
1268
    int idx = cliRBChoseIdx(trans);
dengyihao's avatar
dengyihao 已提交
1269
    if (idx < 0) return NULL;
dengyihao's avatar
dengyihao 已提交
1270 1271
    return ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
D
dapan1121 已提交
1272 1273 1274 1275 1276 1277 1278
  SCliThrd* pThrd = transGetWorkThrdFromHandle(handle, validHandle);
  if (*validHandle == true && pThrd == NULL) {
    int idx = cliRBChoseIdx(trans);
    if (idx < 0) return NULL;
    pThrd = ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
  return pThrd;
dengyihao's avatar
dengyihao 已提交
1279
}
dengyihao's avatar
dengyihao 已提交
1280
int transReleaseCliHandle(void* handle) {
dengyihao's avatar
dengyihao 已提交
1281 1282 1283 1284
  int  idx = -1;
  bool valid = false;

  SCliThrd* pThrd = transGetWorkThrdFromHandle((int64_t)handle, &valid);
dengyihao's avatar
dengyihao 已提交
1285
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
1286
    return -1;
dengyihao's avatar
dengyihao 已提交
1287
  }
dengyihao's avatar
dengyihao 已提交
1288

S
Shengliang Guan 已提交
1289
  STransMsg tmsg = {.info.handle = handle};
dengyihao's avatar
dengyihao 已提交
1290 1291 1292
  TRACE_SET_MSGID(&tmsg.info.traceId, tGenIdPI64());

  SCliMsg* cmsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1293
  cmsg->msg = tmsg;
dengyihao's avatar
dengyihao 已提交
1294
  cmsg->type = Release;
dengyihao's avatar
dengyihao 已提交
1295

dengyihao's avatar
dengyihao 已提交
1296 1297 1298
  STraceId* trace = &tmsg.info.traceId;
  tGDebug("send release request at thread:%08" PRId64 "", pThrd->pid);

dengyihao's avatar
dengyihao 已提交
1299 1300 1301
  if (0 != transAsyncSend(pThrd->asyncPool, &cmsg->q)) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1302
  return 0;
dengyihao's avatar
dengyihao 已提交
1303
}
dengyihao's avatar
dengyihao 已提交
1304

dengyihao's avatar
dengyihao 已提交
1305
int transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1306
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1307 1308
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1309
    return -1;
dengyihao's avatar
dengyihao 已提交
1310
  }
dengyihao's avatar
dengyihao 已提交
1311

dengyihao's avatar
dengyihao 已提交
1312 1313 1314
  bool      valid = false;
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle, &valid);
  if (pThrd == NULL && valid == false) {
dengyihao's avatar
dengyihao 已提交
1315
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1316
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1317
    return -1;
dengyihao's avatar
dengyihao 已提交
1318 1319
  }

dengyihao's avatar
dengyihao 已提交
1320
  TRACE_SET_MSGID(&pReq->info.traceId, tGenIdPI64());
dengyihao's avatar
dengyihao 已提交
1321

wafwerar's avatar
wafwerar 已提交
1322
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1323
  pCtx->epSet = *pEpSet;
S
Shengliang Guan 已提交
1324
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1325
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1326 1327 1328 1329

  if (ctx != NULL) {
    pCtx->appCtx = *ctx;
  }
dengyihao's avatar
dengyihao 已提交
1330
  assert(pTransInst->connType == TAOS_CONN_CLIENT);
dengyihao's avatar
dengyihao 已提交
1331

wafwerar's avatar
wafwerar 已提交
1332
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1333
  cliMsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
1334
  cliMsg->msg = *pReq;
dengyihao's avatar
dengyihao 已提交
1335
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1336
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1337
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
1338

dengyihao's avatar
dengyihao 已提交
1339
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
1340
  tGDebug("%s send request at thread:%08" PRId64 ", dst:%s:%d, app:%p", transLabel(pTransInst), pThrd->pid,
dengyihao's avatar
dengyihao 已提交
1341
          EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet), pReq->info.ahandle);
dengyihao's avatar
dengyihao 已提交
1342 1343
  if (0 != transAsyncSend(pThrd->asyncPool, &(cliMsg->q))) {
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1344
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1345 1346
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1347
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1348
  return 0;
dengyihao's avatar
dengyihao 已提交
1349
}
dengyihao's avatar
dengyihao 已提交
1350

dengyihao's avatar
dengyihao 已提交
1351
int transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMsg* pRsp) {
dengyihao's avatar
dengyihao 已提交
1352
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1353 1354
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1355
    return -1;
dengyihao's avatar
dengyihao 已提交
1356
  }
dengyihao's avatar
dengyihao 已提交
1357

dengyihao's avatar
dengyihao 已提交
1358 1359 1360
  bool      valid = false;
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle, &valid);
  if (pThrd == NULL && valid == false) {
dengyihao's avatar
dengyihao 已提交
1361
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1362
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1363
    return -1;
dengyihao's avatar
dengyihao 已提交
1364
  }
dengyihao's avatar
dengyihao 已提交
1365

dengyihao's avatar
dengyihao 已提交
1366 1367
  tsem_t* sem = taosMemoryCalloc(1, sizeof(tsem_t));
  tsem_init(sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
1368

dengyihao's avatar
dengyihao 已提交
1369 1370
  TRACE_SET_MSGID(&pReq->info.traceId, tGenIdPI64());

wafwerar's avatar
wafwerar 已提交
1371
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1372
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
1373
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
1374
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1375
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1376
  pCtx->pSem = sem;
dengyihao's avatar
dengyihao 已提交
1377 1378
  pCtx->pRsp = pRsp;

wafwerar's avatar
wafwerar 已提交
1379
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1380 1381 1382
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pReq;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1383
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1384
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
1385

dengyihao's avatar
dengyihao 已提交
1386
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
1387
  tGDebug("%s send request at thread:%08" PRId64 ", dst:%s:%d, app:%p", transLabel(pTransInst), pThrd->pid,
dengyihao's avatar
dengyihao 已提交
1388
          EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet), pReq->info.ahandle);
dengyihao's avatar
dengyihao 已提交
1389

dengyihao's avatar
dengyihao 已提交
1390 1391
  int ret = transAsyncSend(pThrd->asyncPool, &cliMsg->q);
  if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1392
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1393
    goto _RETURN;
dengyihao's avatar
dengyihao 已提交
1394
  }
dengyihao's avatar
dengyihao 已提交
1395
  tsem_wait(sem);
dengyihao's avatar
dengyihao 已提交
1396 1397

_RETURN:
dengyihao's avatar
dengyihao 已提交
1398 1399
  tsem_destroy(sem);
  taosMemoryFree(sem);
dengyihao's avatar
dengyihao 已提交
1400
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1401
  return ret;
dengyihao's avatar
dengyihao 已提交
1402
}
dengyihao's avatar
dengyihao 已提交
1403 1404 1405
/*
 *
 **/
dengyihao's avatar
dengyihao 已提交
1406
int transSetDefaultAddr(void* shandle, const char* ip, const char* fqdn) {
dengyihao's avatar
dengyihao 已提交
1407
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1408 1409 1410
  if (pTransInst == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1411 1412 1413 1414 1415 1416 1417

  SCvtAddr cvtAddr = {0};
  if (ip != NULL && fqdn != NULL) {
    memcpy(cvtAddr.ip, ip, strlen(ip));
    memcpy(cvtAddr.fqdn, fqdn, strlen(fqdn));
    cvtAddr.cvt = true;
  }
dengyihao's avatar
dengyihao 已提交
1418 1419
  for (int i = 0; i < pTransInst->numOfThreads; i++) {
    STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1420
    pCtx->cvtAddr = cvtAddr;
dengyihao's avatar
dengyihao 已提交
1421 1422 1423 1424

    SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
    cliMsg->ctx = pCtx;
    cliMsg->type = Update;
dengyihao's avatar
dengyihao 已提交
1425
    cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
1426

dengyihao's avatar
dengyihao 已提交
1427
    SCliThrd* thrd = ((SCliObj*)pTransInst->tcphandle)->pThreadObj[i];
S
Shengliang Guan 已提交
1428
    tDebug("%s update epset at thread:%08" PRId64, pTransInst->label, thrd->pid);
dengyihao's avatar
dengyihao 已提交
1429

dengyihao's avatar
dengyihao 已提交
1430 1431
    if (transAsyncSend(thrd->asyncPool, &(cliMsg->q)) != 0) {
      destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1432
      transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1433 1434
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
1435
  }
dengyihao's avatar
dengyihao 已提交
1436
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1437
  return 0;
dengyihao's avatar
dengyihao 已提交
1438
}
dengyihao's avatar
dengyihao 已提交
1439 1440 1441 1442 1443 1444 1445

int64_t transAllocHandle() {
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->refId = transAddExHandle(transGetRefMgt(), exh);
  tDebug("pre alloc refId %" PRId64 "", exh->refId);
  return exh->refId;
}
dengyihao's avatar
dengyihao 已提交
1446
#endif