transCli.c 58.7 KB
Newer Older
dengyihao's avatar
dengyihao 已提交
1
/** Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
dengyihao's avatar
dengyihao 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * 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"

dengyihao's avatar
dengyihao 已提交
18
typedef struct SConnList {
dengyihao's avatar
dengyihao 已提交
19
  queue   conns;
dengyihao's avatar
dengyihao 已提交
20
  int32_t size;
dengyihao's avatar
dengyihao 已提交
21 22
} SConnList;

dengyihao's avatar
dengyihao 已提交
23
typedef struct SCliConn {
dengyihao's avatar
dengyihao 已提交
24
  T_REF_DECLARE()
dengyihao's avatar
dengyihao 已提交
25 26
  uv_connect_t connReq;
  uv_stream_t* stream;
dengyihao's avatar
dengyihao 已提交
27
  queue        wreqQueue;
dengyihao's avatar
dengyihao 已提交
28 29

  uv_timer_t* timer;  // read timer, forbidden
dengyihao's avatar
dengyihao 已提交
30

dengyihao's avatar
dengyihao 已提交
31 32 33 34
  void* hostThrd;

  SConnBuffer readBuf;
  STransQueue cliMsgs;
dengyihao's avatar
dengyihao 已提交
35 36 37

  queue      q;
  SConnList* list;
dengyihao's avatar
dengyihao 已提交
38 39

  STransCtx  ctx;
dengyihao's avatar
dengyihao 已提交
40 41
  bool       broken;  // link broken or not
  ConnStatus status;  //
dengyihao's avatar
dengyihao 已提交
42

dengyihao's avatar
dengyihao 已提交
43
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
44 45 46
  char*    ip;
  uint32_t port;

dengyihao's avatar
dengyihao 已提交
47
  SDelayTask* task;
dengyihao's avatar
dengyihao 已提交
48

dengyihao's avatar
dengyihao 已提交
49
  // debug and log info
dengyihao's avatar
dengyihao 已提交
50 51 52
  char src[32];
  char dst[32];

dengyihao's avatar
dengyihao 已提交
53
} SCliConn;
dengyihao's avatar
dengyihao 已提交
54

dengyihao's avatar
dengyihao 已提交
55
typedef struct SCliMsg {
dengyihao's avatar
dengyihao 已提交
56
  STransConnCtx* ctx;
dengyihao's avatar
formate  
dengyihao 已提交
57
  STransMsg      msg;
dengyihao's avatar
dengyihao 已提交
58
  queue          q;
dengyihao's avatar
dengyihao 已提交
59
  STransMsgType  type;
dengyihao's avatar
dengyihao 已提交
60

dengyihao's avatar
dengyihao 已提交
61
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
62 63
  uint64_t st;
  int      sent;  //(0: no send, 1: alread sent)
dengyihao's avatar
dengyihao 已提交
64 65
} SCliMsg;

dengyihao's avatar
dengyihao 已提交
66
typedef struct SCliThrd {
dengyihao's avatar
dengyihao 已提交
67 68 69 70 71 72
  TdThread      thread;  // tid
  int64_t       pid;     // pid
  uv_loop_t*    loop;
  SAsyncPool*   asyncPool;
  uv_prepare_t* prepare;
  void*         pool;  // conn pool
dengyihao's avatar
dengyihao 已提交
73
  // timer handles
dengyihao's avatar
dengyihao 已提交
74
  SArray* timerList;
dengyihao's avatar
dengyihao 已提交
75
  // msg queue
dengyihao's avatar
dengyihao 已提交
76
  queue         msg;
wafwerar's avatar
wafwerar 已提交
77
  TdThreadMutex msgMtx;
dengyihao's avatar
dengyihao 已提交
78
  SDelayQueue*  delayQueue;
dengyihao's avatar
dengyihao 已提交
79
  SDelayQueue*  timeoutQueue;
dengyihao's avatar
dengyihao 已提交
80 81
  uint64_t      nextTimeout;  // next timeout
  void*         pTransInst;   //
dengyihao's avatar
dengyihao 已提交
82

dengyihao's avatar
dengyihao 已提交
83
  void (*destroyAhandleFp)(void* ahandle);
dengyihao's avatar
dengyihao 已提交
84 85
  SHashObj* fqdn2ipCache;
  SCvtAddr  cvtAddr;
dengyihao's avatar
dengyihao 已提交
86

dengyihao's avatar
dengyihao 已提交
87 88
  SCliMsg* stopMsg;

dengyihao's avatar
dengyihao 已提交
89
  bool quit;
dengyihao's avatar
dengyihao 已提交
90
} SCliThrd;
dengyihao's avatar
dengyihao 已提交
91

U
ubuntu 已提交
92
typedef struct SCliObj {
dengyihao's avatar
dengyihao 已提交
93 94 95 96
  char       label[TSDB_LABEL_LEN];
  int32_t    index;
  int        numOfThreads;
  SCliThrd** pThreadObj;
U
ubuntu 已提交
97
} SCliObj;
dengyihao's avatar
dengyihao 已提交
98

dengyihao's avatar
dengyihao 已提交
99
// conn pool
dengyihao's avatar
dengyihao 已提交
100
// add expire timeout and capacity limit
dengyihao's avatar
dengyihao 已提交
101
static void*     createConnPool(int size);
102
static void*     destroyConnPool(void* pool);
dengyihao's avatar
dengyihao 已提交
103
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port);
dengyihao's avatar
dengyihao 已提交
104
static void      addConnToPool(void* pool, SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
105
static void      doCloseIdleConn(void* param);
dengyihao's avatar
dengyihao 已提交
106

dengyihao's avatar
dengyihao 已提交
107 108
// register conn timer
static void cliConnTimeout(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
109 110
// register timer for read
static void cliReadTimeoutCb(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
111
// register timer in each thread to clear expire conn
dengyihao's avatar
dengyihao 已提交
112
// static void cliTimeoutCb(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
113
// alloc buffer for recv
dengyihao's avatar
dengyihao 已提交
114
static FORCE_INLINE void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
115
// callback after recv nbytes from socket
U
ubuntu 已提交
116
static void cliRecvCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
117
// callback after send data to socket
U
ubuntu 已提交
118
static void cliSendCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
119
// callback after conn to server
U
ubuntu 已提交
120 121
static void cliConnCb(uv_connect_t* req, int status);
static void cliAsyncCb(uv_async_t* handle);
dengyihao's avatar
dengyihao 已提交
122
static void cliIdleCb(uv_idle_t* handle);
dengyihao's avatar
dengyihao 已提交
123
static void cliPrepareCb(uv_prepare_t* handle);
dengyihao's avatar
dengyihao 已提交
124

dengyihao's avatar
dengyihao 已提交
125 126
static bool cliRecvReleaseReq(SCliConn* conn, STransMsgHead* pHead);

dengyihao's avatar
dengyihao 已提交
127
static int32_t allocConnRef(SCliConn* conn, bool update);
dengyihao's avatar
dengyihao 已提交
128

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

dengyihao's avatar
dengyihao 已提交
131
static SCliConn* cliCreateConn(SCliThrd* thrd);
U
ubuntu 已提交
132 133
static void      cliDestroyConn(SCliConn* pConn, bool clear /*clear tcp handle or not*/);
static void      cliDestroy(uv_handle_t* handle);
dengyihao's avatar
dengyihao 已提交
134
static void      cliSend(SCliConn* pConn);
dengyihao's avatar
dengyihao 已提交
135
static void      cliDestroyConnMsgs(SCliConn* conn, bool destroy);
dengyihao's avatar
dengyihao 已提交
136

dengyihao's avatar
dengyihao 已提交
137
// cli util func
dengyihao's avatar
dengyihao 已提交
138 139
static FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx);
static FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr);
dengyihao's avatar
dengyihao 已提交
140

dengyihao's avatar
dengyihao 已提交
141
static FORCE_INLINE int32_t cliBuildExceptResp(SCliMsg* pMsg, STransMsg* resp);
dengyihao's avatar
dengyihao 已提交
142

dengyihao's avatar
dengyihao 已提交
143 144 145
static FORCE_INLINE uint32_t cliGetIpFromFqdnCache(SHashObj* cache, char* fqdn);
static FORCE_INLINE void     cliUpdateFqdnCache(SHashObj* cache, char* fqdn);

dengyihao's avatar
dengyihao 已提交
146
// process data read from server, add decompress etc later
U
ubuntu 已提交
147
static void cliHandleResp(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
148
// handle except about conn
U
ubuntu 已提交
149
static void cliHandleExcept(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
150
static void cliReleaseUnfinishedMsg(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
151

152
// handle req from app
dengyihao's avatar
dengyihao 已提交
153 154 155 156 157 158 159
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};

dengyihao's avatar
dengyihao 已提交
160 161
static FORCE_INLINE void destroyUserdata(STransMsg* userdata);
static FORCE_INLINE void destroyCmsg(void* cmsg);
dengyihao's avatar
dengyihao 已提交
162
static FORCE_INLINE void destroyCmsgAndAhandle(void* cmsg);
dengyihao's avatar
dengyihao 已提交
163
static FORCE_INLINE int  cliRBChoseIdx(STrans* pTransInst);
dengyihao's avatar
dengyihao 已提交
164
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx);
dengyihao's avatar
dengyihao 已提交
165

dengyihao's avatar
dengyihao 已提交
166
// thread obj
dengyihao's avatar
dengyihao 已提交
167
static SCliThrd* createThrdObj(void* trans);
dengyihao's avatar
dengyihao 已提交
168
static void      destroyThrdObj(SCliThrd* pThrd);
dengyihao's avatar
dengyihao 已提交
169

dengyihao's avatar
dengyihao 已提交
170 171 172 173 174 175 176 177 178
static void cliWalkCb(uv_handle_t* handle, void* arg);

#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 已提交
179 180 181 182 183 184
// 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 已提交
185 186
#define CONN_PERSIST_TIME(para)   ((para) <= 90000 ? 90000 : (para))
#define CONN_GET_INST_LABEL(conn) (((STrans*)(((SCliThrd*)(conn)->hostThrd)->pTransInst))->label)
dengyihao's avatar
dengyihao 已提交
187

dengyihao's avatar
dengyihao 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
#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);                            \
      if (pMsg->ctx != NULL && (uint64_t)pMsg->ctx->ahandle == ahandle) { \
        break;                                                            \
      }                                                                   \
    }                                                                     \
    if (i == sz) {                                                        \
      pMsg = NULL;                                                        \
      tDebug("msg not found, %" PRIu64 "", ahandle);                      \
    } else {                                                              \
      pMsg = transQueueRm(&conn->cliMsgs, i);                             \
      tDebug("msg found, %" PRIu64 "", ahandle);                          \
    }                                                                     \
dengyihao's avatar
dengyihao 已提交
204
  } while (0)
dengyihao's avatar
dengyihao 已提交
205

U
ubuntu 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218
#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 已提交
219

dengyihao's avatar
formate  
dengyihao 已提交
220 221
#define CONN_SET_PERSIST_BY_APP(conn) \
  do {                                \
dengyihao's avatar
dengyihao 已提交
222 223
    if (conn->status == ConnNormal) { \
      conn->status = ConnAcquire;     \
dengyihao's avatar
formate  
dengyihao 已提交
224 225 226
      transRefCliHandle(conn);        \
    }                                 \
  } while (0)
227

dengyihao's avatar
dengyihao 已提交
228 229 230 231
#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)
232

S
Shengliang Guan 已提交
233 234
#define REQUEST_NO_RESP(msg)         ((msg)->info.noResp == 1)
#define REQUEST_PERSIS_HANDLE(msg)   ((msg)->info.persistHandle == 1)
dengyihao's avatar
dengyihao 已提交
235
#define REQUEST_RELEASE_HANDLE(cmsg) ((cmsg)->type == Release)
dengyihao's avatar
dengyihao 已提交
236

dengyihao's avatar
dengyihao 已提交
237
#define EPSET_IS_VALID(epSet)       ((epSet) != NULL && (epSet)->numOfEps >= 0 && (epSet)->inUse >= 0)
dengyihao's avatar
dengyihao 已提交
238
#define EPSET_GET_SIZE(epSet)       (epSet)->numOfEps
dengyihao's avatar
dengyihao 已提交
239
#define EPSET_GET_INUSE_IP(epSet)   ((epSet)->eps[(epSet)->inUse].fqdn)
dengyihao's avatar
dengyihao 已提交
240
#define EPSET_GET_INUSE_PORT(epSet) ((epSet)->eps[(epSet)->inUse].port)
dengyihao's avatar
dengyihao 已提交
241 242 243 244 245 246
#define EPSET_FORWARD_INUSE(epSet)                             \
  do {                                                         \
    if ((epSet)->numOfEps != 0) {                              \
      ++((epSet)->inUse);                                      \
      (epSet)->inUse = ((epSet)->inUse) % ((epSet)->numOfEps); \
    }                                                          \
dengyihao's avatar
dengyihao 已提交
247
  } while (0)
dengyihao's avatar
dengyihao 已提交
248

dengyihao's avatar
dengyihao 已提交
249 250 251 252 253 254 255 256 257 258 259
#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 已提交
260
  } while (0);
dengyihao's avatar
dengyihao 已提交
261

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

dengyihao's avatar
dengyihao 已提交
264 265 266 267 268 269 270 271
static void cliReleaseUnfinishedMsg(SCliConn* conn) {
  SCliThrd* pThrd = conn->hostThrd;

  for (int i = 0; i < transQueueSize(&conn->cliMsgs); i++) {
    SCliMsg* msg = transQueueGet(&conn->cliMsgs, i);
    if (msg != NULL && msg->ctx != NULL && msg->ctx->ahandle != (void*)0x9527) {
      if (conn->ctx.freeFunc != NULL && msg->ctx->ahandle != NULL) {
        conn->ctx.freeFunc(msg->ctx->ahandle);
dengyihao's avatar
dengyihao 已提交
272
      } else if (msg->ctx->ahandle != NULL && pThrd->destroyAhandleFp != NULL) {
dengyihao's avatar
dengyihao 已提交
273
        tDebug("%s conn %p destroy unfinished ahandle %p", CONN_GET_INST_LABEL(conn), conn, msg->ctx->ahandle);
dengyihao's avatar
dengyihao 已提交
274
        pThrd->destroyAhandleFp(msg->ctx->ahandle);
dengyihao's avatar
dengyihao 已提交
275 276 277 278 279
      }
    }
    destroyCmsg(msg);
  }
}
dengyihao's avatar
dengyihao 已提交
280
bool cliMaySendCachedMsg(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
281
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
282
    SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
283
    CONN_GET_NEXT_SENDMSG(conn);
dengyihao's avatar
dengyihao 已提交
284 285 286 287 288 289
    if (pCliMsg == NULL)
      return false;
    else {
      cliSend(conn);
      return true;
    }
dengyihao's avatar
dengyihao 已提交
290
  }
dengyihao's avatar
dengyihao 已提交
291
  return false;
U
ubuntu 已提交
292 293
_RETURN:
  return false;
dengyihao's avatar
dengyihao 已提交
294
}
dengyihao's avatar
formate  
dengyihao 已提交
295
void cliHandleResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
296 297
  SCliThrd* pThrd = conn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
298

dengyihao's avatar
dengyihao 已提交
299 300 301 302 303 304
  if (conn->timer) {
    if (uv_is_active((uv_handle_t*)conn->timer)) {
      tDebug("%s conn %p stop timer", CONN_GET_INST_LABEL(conn), conn);
      uv_timer_stop(conn->timer);
    }
    taosArrayPush(pThrd->timerList, &conn->timer);
dengyihao's avatar
dengyihao 已提交
305
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
306
    conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
307 308
  }

dengyihao's avatar
opt rpc  
dengyihao 已提交
309
  STransMsgHead* pHead = NULL;
dengyihao's avatar
dengyihao 已提交
310 311 312

  int32_t msgLen = transDumpFromBuffer(&conn->readBuf, (char**)&pHead);
  if (msgLen <= 0) {
dengyihao's avatar
dengyihao 已提交
313 314 315
    tDebug("%s conn %p recv invalid packet ", CONN_GET_INST_LABEL(conn), conn);
    return;
  }
dengyihao's avatar
dengyihao 已提交
316 317 318 319

  if (transDecompressMsg((char**)&pHead, msgLen) < 0) {
    tDebug("%s conn %p recv invalid packet, failed to decompress", CONN_GET_INST_LABEL(conn), conn);
  }
dengyihao's avatar
dengyihao 已提交
320 321
  pHead->code = htonl(pHead->code);
  pHead->msgLen = htonl(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
322 323 324 325
  if (cliRecvReleaseReq(conn, pHead)) {
    return;
  }

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

dengyihao's avatar
dengyihao 已提交
335 336 337 338
  SCliMsg*       pMsg = NULL;
  STransConnCtx* pCtx = NULL;
  if (CONN_NO_PERSIST_BY_APP(conn)) {
    pMsg = transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
339 340 341

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

dengyihao's avatar
dengyihao 已提交
368
  STraceId* trace = &transMsg.info.traceId;
dengyihao's avatar
dengyihao 已提交
369
  tGDebug("%s conn %p %s received from %s, local info:%s, len:%d, code str:%s", CONN_GET_INST_LABEL(conn), conn,
dengyihao's avatar
dengyihao 已提交
370
          TMSG_INFO(pHead->msgType), conn->dst, conn->src, pHead->msgLen, tstrerror(transMsg.code));
dengyihao's avatar
dengyihao 已提交
371

dengyihao's avatar
dengyihao 已提交
372
  if (pCtx == NULL && CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
373
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
374
    transFreeMsg(transMsg.pCont);
dengyihao's avatar
dengyihao 已提交
375 376
    return;
  }
S
Shengliang Guan 已提交
377
  if (CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
378
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
379
    transFreeMsg(transMsg.pCont);
dengyihao's avatar
dengyihao 已提交
380 381
    return;
  }
dengyihao's avatar
dengyihao 已提交
382

dengyihao's avatar
dengyihao 已提交
383
  if (pMsg == NULL || (pMsg && pMsg->type != Release)) {
dengyihao's avatar
dengyihao 已提交
384 385 386
    if (cliAppCb(conn, &transMsg, pMsg) != 0) {
      return;
    }
dengyihao's avatar
dengyihao 已提交
387
  }
dengyihao's avatar
dengyihao 已提交
388 389
  destroyCmsg(pMsg);

dengyihao's avatar
dengyihao 已提交
390
  if (cliMaySendCachedMsg(conn) == true) {
dengyihao's avatar
dengyihao 已提交
391 392
    return;
  }
dengyihao's avatar
dengyihao 已提交
393

U
ubuntu 已提交
394
  if (CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
395
    return addConnToPool(pThrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
396
  }
dengyihao's avatar
test  
dengyihao 已提交
397

dengyihao's avatar
dengyihao 已提交
398
  uv_read_start((uv_stream_t*)conn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
399
}
U
ubuntu 已提交
400

dengyihao's avatar
dengyihao 已提交
401
void cliHandleExceptImpl(SCliConn* pConn, int32_t code) {
dengyihao's avatar
dengyihao 已提交
402
  if (transQueueEmpty(&pConn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
403
    if (pConn->broken == true && CONN_NO_PERSIST_BY_APP(pConn)) {
dengyihao's avatar
dengyihao 已提交
404
      tTrace("%s conn %p handle except, persist:0", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
formate  
dengyihao 已提交
405 406 407
      transUnrefCliHandle(pConn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
408
  }
dengyihao's avatar
dengyihao 已提交
409 410 411
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
  bool      once = false;
D
dapan1121 已提交
412
  do {
dengyihao's avatar
dengyihao 已提交
413
    SCliMsg* pMsg = transQueuePop(&pConn->cliMsgs);
dengyihao's avatar
enh log  
dengyihao 已提交
414

D
dapan1121 已提交
415 416
    if (pMsg == NULL && once) {
      break;
dengyihao's avatar
dengyihao 已提交
417
    }
dengyihao's avatar
enh log  
dengyihao 已提交
418 419 420 421 422 423

    if (pMsg != NULL && REQUEST_NO_RESP(&pMsg->msg)) {
      destroyCmsg(pMsg);
      break;
    }

dengyihao's avatar
dengyihao 已提交
424
    STransConnCtx* pCtx = pMsg ? pMsg->ctx : NULL;
U
ubuntu 已提交
425

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

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

    if (pCtx == NULL || pCtx->pSem == NULL) {
S
Shengliang Guan 已提交
447
      if (transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
448 449 450 451 452
        if (pMsg == NULL || REQUEST_NO_RESP(&pMsg->msg) || pMsg->type == Release) {
          destroyCmsg(pMsg);
          once = true;
          continue;
        }
U
ubuntu 已提交
453
      }
dengyihao's avatar
dengyihao 已提交
454
    }
dengyihao's avatar
enh log  
dengyihao 已提交
455

dengyihao's avatar
dengyihao 已提交
456
    if (pMsg == NULL || (pMsg && pMsg->type != Release)) {
dengyihao's avatar
dengyihao 已提交
457 458 459
      if (cliAppCb(pConn, &transMsg, pMsg) != 0) {
        return;
      }
dengyihao's avatar
dengyihao 已提交
460 461
    }
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
462
    tTrace("%s conn %p start to destroy, ref:%d", CONN_GET_INST_LABEL(pConn), pConn, T_REF_VAL_GET(pConn));
D
dapan1121 已提交
463
  } while (!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
464
  transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
465
}
dengyihao's avatar
dengyihao 已提交
466
void cliHandleExcept(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
467
  tTrace("%s conn %p except ref:%d", CONN_GET_INST_LABEL(conn), conn, T_REF_VAL_GET(conn));
dengyihao's avatar
dengyihao 已提交
468 469
  cliHandleExceptImpl(conn, -1);
}
dengyihao's avatar
dengyihao 已提交
470

dengyihao's avatar
dengyihao 已提交
471 472
void cliConnTimeout(uv_timer_t* handle) {
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
473 474
  SCliThrd* pThrd = conn->hostThrd;

dengyihao's avatar
dengyihao 已提交
475
  tTrace("%s conn %p conn timeout, ref:%d", CONN_GET_INST_LABEL(conn), conn, T_REF_VAL_GET(conn));
dengyihao's avatar
dengyihao 已提交
476

dengyihao's avatar
dengyihao 已提交
477
  uv_timer_stop(handle);
dengyihao's avatar
dengyihao 已提交
478 479 480 481
  handle->data = NULL;
  taosArrayPush(pThrd->timerList, &conn->timer);

  conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
482
  cliHandleExceptImpl(conn, -1);
dengyihao's avatar
dengyihao 已提交
483
}
dengyihao's avatar
dengyihao 已提交
484 485 486 487
void cliReadTimeoutCb(uv_timer_t* handle) {
  // set up timeout cb
  SCliConn* conn = handle->data;
  tTrace("%s conn %p timeout, ref:%d", CONN_GET_INST_LABEL(conn), conn, T_REF_VAL_GET(conn));
dengyihao's avatar
dengyihao 已提交
488
  uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
489 490
  cliHandleExceptImpl(conn, TSDB_CODE_RPC_TIMEOUT);
}
U
ubuntu 已提交
491 492

void* createConnPool(int size) {
493 494
  // thread local, no lock
  return taosHashInit(size, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
495
}
U
ubuntu 已提交
496
void* destroyConnPool(void* pool) {
dengyihao's avatar
dengyihao 已提交
497
  SConnList* connList = taosHashIterate((SHashObj*)pool, NULL);
dengyihao's avatar
dengyihao 已提交
498
  while (connList != NULL) {
dengyihao's avatar
dengyihao 已提交
499 500
    while (!QUEUE_IS_EMPTY(&connList->conns)) {
      queue*    h = QUEUE_HEAD(&connList->conns);
dengyihao's avatar
dengyihao 已提交
501
      SCliConn* c = QUEUE_DATA(h, SCliConn, q);
U
ubuntu 已提交
502
      cliDestroyConn(c, true);
dengyihao's avatar
dengyihao 已提交
503
    }
dengyihao's avatar
dengyihao 已提交
504
    connList = taosHashIterate((SHashObj*)pool, connList);
dengyihao's avatar
dengyihao 已提交
505
  }
dengyihao's avatar
dengyihao 已提交
506
  taosHashCleanup(pool);
507
  return NULL;
dengyihao's avatar
dengyihao 已提交
508 509
}

dengyihao's avatar
dengyihao 已提交
510
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port) {
dengyihao's avatar
TS-2015  
dengyihao 已提交
511
  char key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
512
  CONN_CONSTRUCT_HASH_KEY(key, ip, port);
dengyihao's avatar
dengyihao 已提交
513 514

  SConnList* plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
515
  if (plist == NULL) {
dengyihao's avatar
dengyihao 已提交
516
    SConnList list = {0};
dengyihao's avatar
dengyihao 已提交
517 518
    taosHashPut((SHashObj*)pool, key, strlen(key), (void*)&list, sizeof(list));
    plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
519
    if (plist == NULL) return NULL;
dengyihao's avatar
dengyihao 已提交
520
    QUEUE_INIT(&plist->conns);
dengyihao's avatar
dengyihao 已提交
521 522
  }

dengyihao's avatar
dengyihao 已提交
523
  if (QUEUE_IS_EMPTY(&plist->conns)) {
dengyihao's avatar
dengyihao 已提交
524 525
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
526 527

  plist->size -= 1;
dengyihao's avatar
dengyihao 已提交
528
  queue*    h = QUEUE_HEAD(&plist->conns);
dengyihao's avatar
dengyihao 已提交
529
  SCliConn* conn = QUEUE_DATA(h, SCliConn, q);
dengyihao's avatar
dengyihao 已提交
530
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
531 532
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
533

dengyihao's avatar
dengyihao 已提交
534 535 536 537
  if (conn->task != NULL) {
    transDQCancel(((SCliThrd*)conn->hostThrd)->timeoutQueue, conn->task);
    conn->task = NULL;
  }
dengyihao's avatar
dengyihao 已提交
538
  return conn;
dengyihao's avatar
dengyihao 已提交
539
}
dengyihao's avatar
dengyihao 已提交
540 541 542 543 544 545
static void addConnToPool(void* pool, SCliConn* conn) {
  if (conn->status == ConnInPool) {
    return;
  }
  allocConnRef(conn, true);

dengyihao's avatar
dengyihao 已提交
546
  SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
547 548 549 550 551 552
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
    taosArrayPush(thrd->timerList, &conn->timer);
    conn->timer->data = NULL;
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
553 554 555 556 557
  if (T_REF_VAL_GET(conn) > 1) {
    transUnrefCliHandle(conn);
  }

  cliDestroyConnMsgs(conn, false);
dengyihao's avatar
dengyihao 已提交
558

dengyihao's avatar
dengyihao 已提交
559 560 561
  conn->status = ConnInPool;

  if (conn->list == NULL) {
dengyihao's avatar
TS-2015  
dengyihao 已提交
562
    char key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
563 564 565
    CONN_CONSTRUCT_HASH_KEY(key, conn->ip, conn->port);
    tTrace("%s conn %p added to conn pool, read buf cap:%d", CONN_GET_INST_LABEL(conn), conn, conn->readBuf.cap);
    conn->list = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
566 567
  } else {
    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 已提交
568
  }
dengyihao's avatar
dengyihao 已提交
569
  QUEUE_PUSH(&conn->list->conns, &conn->q);
dengyihao's avatar
dengyihao 已提交
570
  conn->list->size += 1;
dengyihao's avatar
dengyihao 已提交
571

dengyihao's avatar
dengyihao 已提交
572
  if (conn->list->size >= 50) {
dengyihao's avatar
dengyihao 已提交
573 574
    STaskArg* arg = taosMemoryCalloc(1, sizeof(STaskArg));
    arg->param1 = conn;
dengyihao's avatar
dengyihao 已提交
575
    arg->param2 = thrd;
dengyihao's avatar
dengyihao 已提交
576 577

    STrans* pTransInst = thrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
578 579
    conn->task = transDQSched(thrd->timeoutQueue, doCloseIdleConn, arg, CONN_PERSIST_TIME(pTransInst->idleTime));
  }
dengyihao's avatar
dengyihao 已提交
580
}
dengyihao's avatar
dengyihao 已提交
581
static int32_t allocConnRef(SCliConn* conn, bool update) {
dengyihao's avatar
dengyihao 已提交
582
  if (update) {
dengyihao's avatar
dengyihao 已提交
583
    transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
584
    conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
585 586 587 588
  }
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
589
  exh->refId = transAddExHandle(transGetRefMgt(), exh);
dengyihao's avatar
dengyihao 已提交
590
  conn->refId = exh->refId;
dengyihao's avatar
dengyihao 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
  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 已提交
609
}
dengyihao's avatar
dengyihao 已提交
610

dengyihao's avatar
dengyihao 已提交
611
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
612
  SCliConn*    conn = handle->data;
dengyihao's avatar
dengyihao 已提交
613
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
614
  tDebug("%s conn %p alloc read buf", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
615
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
616
}
U
ubuntu 已提交
617
static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
618
  // impl later
dengyihao's avatar
dengyihao 已提交
619 620 621
  if (handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
622 623
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
624
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
625
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
626
    while (transReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
627
      tDebug("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
628 629 630 631 632 633
      if (pBuf->invalid) {
        cliHandleExcept(conn);
        break;
      } else {
        cliHandleResp(conn);
      }
dengyihao's avatar
dengyihao 已提交
634
    }
dengyihao's avatar
dengyihao 已提交
635 636
    return;
  }
dengyihao's avatar
dengyihao 已提交
637

638 639
  assert(nread <= 0);
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
640 641 642
    // 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 已提交
643
    tTrace("%s conn %p read empty", CONN_GET_INST_LABEL(conn), conn);
644 645
    return;
  }
dengyihao's avatar
fix bug  
dengyihao 已提交
646
  if (nread < 0) {
dengyihao's avatar
dengyihao 已提交
647
    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 已提交
648
    conn->broken = true;
U
ubuntu 已提交
649
    cliHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
650
  }
dengyihao's avatar
dengyihao 已提交
651
}
dengyihao's avatar
dengyihao 已提交
652

dengyihao's avatar
dengyihao 已提交
653
static SCliConn* cliCreateConn(SCliThrd* pThrd) {
wafwerar's avatar
wafwerar 已提交
654
  SCliConn* conn = taosMemoryCalloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
655
  // read/write stream handle
G
gccgdb1234 已提交
656
  conn->stream = (uv_stream_t*)taosMemoryMalloc(sizeof(uv_tcp_t));
dengyihao's avatar
dengyihao 已提交
657 658
  uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
  conn->stream->data = conn;
G
gccgdb1234 已提交
659
  transSetConnOption((uv_tcp_t*)conn->stream);
dengyihao's avatar
dengyihao 已提交
660

dengyihao's avatar
dengyihao 已提交
661 662 663 664 665 666 667 668
  uv_timer_t* timer = taosArrayGetSize(pThrd->timerList) > 0 ? *(uv_timer_t**)taosArrayPop(pThrd->timerList) : NULL;
  if (timer == NULL) {
    timer = taosMemoryCalloc(1, sizeof(uv_timer_t));
    tDebug("no available timer, create a timer %p", timer);
    uv_timer_init(pThrd->loop, timer);
  }
  timer->data = conn;
  conn->timer = timer;
dengyihao's avatar
dengyihao 已提交
669

dengyihao's avatar
dengyihao 已提交
670
  conn->connReq.data = conn;
dengyihao's avatar
dengyihao 已提交
671 672
  transReqQueueInit(&conn->wreqQueue);

dengyihao's avatar
dengyihao 已提交
673
  transQueueInit(&conn->cliMsgs, NULL);
dengyihao's avatar
opt rpc  
dengyihao 已提交
674 675

  transInitBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
676
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
677
  conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
678 679
  conn->status = ConnNormal;
  conn->broken = 0;
dengyihao's avatar
dengyihao 已提交
680
  transRefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
681

dengyihao's avatar
dengyihao 已提交
682
  allocConnRef(conn, false);
dengyihao's avatar
dengyihao 已提交
683

dengyihao's avatar
dengyihao 已提交
684 685
  return conn;
}
U
ubuntu 已提交
686
static void cliDestroyConn(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
687
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
688
  tTrace("%s conn %p remove from conn pool", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
689 690
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
691
  transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
opt rpc  
dengyihao 已提交
692
  conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
693

dengyihao's avatar
dengyihao 已提交
694 695 696 697 698 699 700
  if (conn->task != NULL) {
    transDQCancel(pThrd->timeoutQueue, conn->task);
    conn->task = NULL;
  }
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
701
    taosArrayPush(pThrd->timerList, &conn->timer);
dengyihao's avatar
dengyihao 已提交
702 703
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
704

dengyihao's avatar
dengyihao 已提交
705
  if (clear) {
dengyihao's avatar
dengyihao 已提交
706
    if (!uv_is_closing((uv_handle_t*)conn->stream)) {
dengyihao's avatar
dengyihao 已提交
707
      uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
708 709
      uv_close((uv_handle_t*)conn->stream, cliDestroy);
    }
710
  }
dengyihao's avatar
dengyihao 已提交
711
}
U
ubuntu 已提交
712
static void cliDestroy(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
713 714 715
  if (uv_handle_get_type(handle) != UV_TCP || handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
716
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
717
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
718 719
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
dengyihao's avatar
dengyihao 已提交
720 721
    taosArrayPush(pThrd->timerList, &conn->timer);
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
722 723
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
724

dengyihao's avatar
dengyihao 已提交
725
  transRemoveExHandle(transGetRefMgt(), conn->refId);
wafwerar's avatar
wafwerar 已提交
726 727
  taosMemoryFree(conn->ip);
  taosMemoryFree(conn->stream);
dengyihao's avatar
dengyihao 已提交
728 729 730

  cliDestroyConnMsgs(conn, true);

dengyihao's avatar
dengyihao 已提交
731
  tTrace("%s conn %p destroy successfully", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
732
  transReqQueueClear(&conn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
733
  transDestroyBuffer(&conn->readBuf);
wafwerar's avatar
wafwerar 已提交
734
  taosMemoryFree(conn);
dengyihao's avatar
dengyihao 已提交
735
}
dengyihao's avatar
dengyihao 已提交
736
static bool cliHandleNoResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
737 738
  bool res = false;
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
739
    SCliMsg* pMsg = transQueueGet(&conn->cliMsgs, 0);
dengyihao's avatar
dengyihao 已提交
740
    if (REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
741
      transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
742 743 744 745 746
      destroyCmsg(pMsg);
      res = true;
    }
    if (res == true) {
      if (cliMaySendCachedMsg(conn) == false) {
dengyihao's avatar
dengyihao 已提交
747
        SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
748
        addConnToPool(thrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
749 750 751
        res = false;
      } else {
        res = true;
dengyihao's avatar
dengyihao 已提交
752 753 754 755 756
      }
    }
  }
  return res;
}
U
ubuntu 已提交
757
static void cliSendCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
758 759
  SCliConn* pConn = transReqQueueRemove(req);
  if (pConn == NULL) return;
dengyihao's avatar
dengyihao 已提交
760

dengyihao's avatar
dengyihao 已提交
761 762 763 764 765 766 767 768
  SCliMsg* pMsg = !transQueueEmpty(&pConn->cliMsgs) ? transQueueGet(&pConn->cliMsgs, 0) : NULL;
  if (pMsg != NULL) {
    int64_t cost = taosGetTimestampUs() - pMsg->st;
    if (cost > 1000) {
      tWarn("%s conn %p send cost:%dus, send exception", CONN_GET_INST_LABEL(pConn), pConn, (int)cost);
    }
  }

dengyihao's avatar
dengyihao 已提交
769
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
770
    tTrace("%s conn %p data already was written out", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
771
  } else {
dengyihao's avatar
dengyihao 已提交
772 773 774 775
    if (!uv_is_closing((uv_handle_t*)&pConn->stream)) {
      tError("%s conn %p failed to write:%s", CONN_GET_INST_LABEL(pConn), pConn, uv_err_name(status));
      cliHandleExcept(pConn);
    }
dengyihao's avatar
dengyihao 已提交
776 777
    return;
  }
dengyihao's avatar
dengyihao 已提交
778
  if (cliHandleNoResp(pConn) == true) {
dengyihao's avatar
dengyihao 已提交
779
    tTrace("%s conn %p no resp required", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
780 781
    return;
  }
dengyihao's avatar
dengyihao 已提交
782
  uv_read_start((uv_stream_t*)pConn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
783
}
dengyihao's avatar
dengyihao 已提交
784

U
ubuntu 已提交
785
void cliSend(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
786
  assert(!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
787 788

  SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
789
  CONN_GET_NEXT_SENDMSG(pConn);
dengyihao's avatar
dengyihao 已提交
790 791
  pCliMsg->sent = 1;

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

dengyihao's avatar
dengyihao 已提交
794 795
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
796

U
ubuntu 已提交
797
  STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
dengyihao's avatar
dengyihao 已提交
798 799 800 801
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
dengyihao's avatar
dengyihao 已提交
802

dengyihao's avatar
dengyihao 已提交
803
  int            msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
804
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
dengyihao's avatar
dengyihao 已提交
805

dengyihao's avatar
dengyihao 已提交
806 807 808 809 810 811 812 813 814 815 816
  if (pHead->comp == 0) {
    pHead->ahandle = pCtx != NULL ? (uint64_t)pCtx->ahandle : 0;
    pHead->noResp = REQUEST_NO_RESP(pMsg) ? 1 : 0;
    pHead->persist = REQUEST_PERSIS_HANDLE(pMsg) ? 1 : 0;
    pHead->msgType = pMsg->msgType;
    pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);
    pHead->release = REQUEST_RELEASE_HANDLE(pCliMsg) ? 1 : 0;
    memcpy(pHead->user, pTransInst->user, strlen(pTransInst->user));
    pHead->traceId = pMsg->info.traceId;
    pHead->magicNum = htonl(TRANS_MAGIC_NUM);
  }
dengyihao's avatar
dengyihao 已提交
817
  pHead->timestamp = taosHton64(taosGetTimestampUs());
dengyihao's avatar
dengyihao 已提交
818

dengyihao's avatar
dengyihao 已提交
819 820 821
  if (pHead->persist == 1) {
    CONN_SET_PERSIST_BY_APP(pConn);
  }
dengyihao's avatar
dengyihao 已提交
822

dengyihao's avatar
dengyihao 已提交
823
  STraceId* trace = &pMsg->info.traceId;
dengyihao's avatar
dengyihao 已提交
824

dengyihao's avatar
dengyihao 已提交
825
  if (pTransInst->startTimer != NULL && pTransInst->startTimer(0, pMsg->msgType)) {
dengyihao's avatar
dengyihao 已提交
826
    uv_timer_t* timer = taosArrayGetSize(pThrd->timerList) > 0 ? *(uv_timer_t**)taosArrayPop(pThrd->timerList) : NULL;
dengyihao's avatar
dengyihao 已提交
827 828
    if (timer == NULL) {
      timer = taosMemoryCalloc(1, sizeof(uv_timer_t));
dengyihao's avatar
dengyihao 已提交
829
      tDebug("no available timer, create a timer %p", timer);
dengyihao's avatar
dengyihao 已提交
830 831 832 833 834
      uv_timer_init(pThrd->loop, timer);
    }
    timer->data = pConn;
    pConn->timer = timer;

dengyihao's avatar
dengyihao 已提交
835 836 837
    tGTrace("%s conn %p start timer for msg:%s", CONN_GET_INST_LABEL(pConn), pConn, TMSG_INFO(pMsg->msgType));
    uv_timer_start((uv_timer_t*)pConn->timer, cliReadTimeoutCb, TRANS_READ_TIMEOUT, 0);
  }
dengyihao's avatar
dengyihao 已提交
838

dengyihao's avatar
dengyihao 已提交
839 840 841 842 843 844 845
  if (pHead->comp == 0) {
    if (pTransInst->compressSize != -1 && pTransInst->compressSize < pMsg->contLen) {
      msgLen = transCompressMsg(pMsg->pCont, pMsg->contLen) + sizeof(STransMsgHead);
      pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);
    }
  } else {
    msgLen = (int32_t)ntohl((uint32_t)(pHead->msgLen));
dengyihao's avatar
dengyihao 已提交
846
  }
dengyihao's avatar
dengyihao 已提交
847

dengyihao's avatar
dengyihao 已提交
848 849
  tGDebug("%s conn %p %s is sent to %s, local info %s, len:%d", CONN_GET_INST_LABEL(pConn), pConn,
          TMSG_INFO(pHead->msgType), pConn->dst, pConn->src, msgLen);
dengyihao's avatar
dengyihao 已提交
850

dengyihao's avatar
dengyihao 已提交
851
  uv_buf_t    wb = uv_buf_init((char*)pHead, msgLen);
dengyihao's avatar
dengyihao 已提交
852
  uv_write_t* req = transReqQueuePush(&pConn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
853 854 855 856 857 858 859

  int status = uv_write(req, (uv_stream_t*)pConn->stream, &wb, 1, cliSendCb);
  if (status != 0) {
    tGError("%s conn %p failed to sent msg:%s, errmsg:%s", CONN_GET_INST_LABEL(pConn), pConn, TMSG_INFO(pMsg->msgType),
            uv_err_name(status));
    cliHandleExcept(pConn);
  }
U
ubuntu 已提交
860 861
  return;
_RETURN:
dengyihao's avatar
dengyihao 已提交
862
  return;
dengyihao's avatar
dengyihao 已提交
863
}
U
ubuntu 已提交
864 865

void cliConnCb(uv_connect_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
866
  // impl later
dengyihao's avatar
dengyihao 已提交
867
  SCliConn* pConn = req->data;
dengyihao's avatar
dengyihao 已提交
868 869
  SCliThrd* pThrd = pConn->hostThrd;

dengyihao's avatar
dengyihao 已提交
870 871 872 873 874 875
  if (pConn->timer != NULL) {
    uv_timer_stop(pConn->timer);
    pConn->timer->data = NULL;
    taosArrayPush(pThrd->timerList, &pConn->timer);
    pConn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
876

dengyihao's avatar
dengyihao 已提交
877
  if (status != 0) {
S
Shengliang Guan 已提交
878
    tError("%s conn %p failed to connect server:%s", CONN_GET_INST_LABEL(pConn), pConn, uv_strerror(status));
U
ubuntu 已提交
879
    cliHandleExcept(pConn);
880
    return;
dengyihao's avatar
dengyihao 已提交
881
  }
dengyihao's avatar
dengyihao 已提交
882 883
  struct sockaddr peername, sockname;

dengyihao's avatar
dengyihao 已提交
884
  int addrlen = sizeof(peername);
dengyihao's avatar
dengyihao 已提交
885
  uv_tcp_getpeername((uv_tcp_t*)pConn->stream, &peername, &addrlen);
dengyihao's avatar
dengyihao 已提交
886
  transSockInfo2Str(&peername, pConn->dst);
dengyihao's avatar
dengyihao 已提交
887

dengyihao's avatar
dengyihao 已提交
888 889
  addrlen = sizeof(sockname);
  uv_tcp_getsockname((uv_tcp_t*)pConn->stream, &sockname, &addrlen);
dengyihao's avatar
dengyihao 已提交
890
  transSockInfo2Str(&sockname, pConn->src);
dengyihao's avatar
dengyihao 已提交
891

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

U
ubuntu 已提交
895
  cliSend(pConn);
dengyihao's avatar
dengyihao 已提交
896 897
}

dengyihao's avatar
dengyihao 已提交
898
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
899 900 901 902 903
  if (!transAsyncPoolIsEmpty(pThrd->asyncPool)) {
    pThrd->stopMsg = pMsg;
    return;
  }
  pThrd->stopMsg = NULL;
dengyihao's avatar
dengyihao 已提交
904
  pThrd->quit = true;
U
ubuntu 已提交
905
  tDebug("cli work thread %p start to quit", pThrd);
dengyihao's avatar
dengyihao 已提交
906
  destroyCmsg(pMsg);
dengyihao's avatar
fix bug  
dengyihao 已提交
907
  destroyConnPool(pThrd->pool);
dengyihao's avatar
dengyihao 已提交
908
  uv_walk(pThrd->loop, cliWalkCb, NULL);
dengyihao's avatar
dengyihao 已提交
909
}
dengyihao's avatar
dengyihao 已提交
910
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
911
  int64_t    refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
912
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
913
  if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
914
    tDebug("%" PRId64 " already released", refId);
dengyihao's avatar
dengyihao 已提交
915 916
    destroyCmsg(pMsg);
    return;
dengyihao's avatar
dengyihao 已提交
917 918 919
  }

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

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

dengyihao's avatar
dengyihao 已提交
924 925
  if (T_REF_VAL_GET(conn) == 2) {
    transUnrefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
926 927
    if (!transQueuePush(&conn->cliMsgs, pMsg)) {
      return;
dengyihao's avatar
dengyihao 已提交
928 929
    }
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
930 931 932
  } else {
    tError("%s conn %p already released", CONN_GET_INST_LABEL(conn), conn);
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
933 934
  }
}
dengyihao's avatar
dengyihao 已提交
935
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
936
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
937
  pThrd->cvtAddr = pCtx->cvtAddr;
dengyihao's avatar
dengyihao 已提交
938 939
  destroyCmsg(pMsg);
}
U
ubuntu 已提交
940

dengyihao's avatar
dengyihao 已提交
941
SCliConn* cliGetConn(SCliMsg* pMsg, SCliThrd* pThrd, bool* ignore) {
dengyihao's avatar
dengyihao 已提交
942 943 944 945
  STransConnCtx* pCtx = pMsg->ctx;
  SCliConn*      conn = NULL;

  int64_t refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
946
  if (refId != 0) {
dengyihao's avatar
dengyihao 已提交
947
    SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
948
    if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
949
      tError("failed to get conn, refId: %" PRId64 "", refId);
dengyihao's avatar
dengyihao 已提交
950 951
      *ignore = true;
      return NULL;
dengyihao's avatar
dengyihao 已提交
952 953
    } else {
      conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
954 955
      if (conn == NULL) {
        conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
dengyihao's avatar
dengyihao 已提交
956
        if (conn != NULL) specifyConnRef(conn, true, refId);
dengyihao's avatar
dengyihao 已提交
957
      }
dengyihao's avatar
dengyihao 已提交
958
      transReleaseExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
959 960 961
    }
    return conn;
  };
dengyihao's avatar
dengyihao 已提交
962 963 964

  conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
965
    tTrace("%s conn %p get from conn pool:%p", CONN_GET_INST_LABEL(conn), conn, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
966
  } else {
dengyihao's avatar
dengyihao 已提交
967
    tTrace("%s not found conn in conn pool:%p", ((STrans*)pThrd->pTransInst)->label, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
968
  }
dengyihao's avatar
dengyihao 已提交
969 970
  return conn;
}
dengyihao's avatar
dengyihao 已提交
971
FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr) {
dengyihao's avatar
dengyihao 已提交
972 973 974
  if (pCvtAddr->cvt == false) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
975 976 977
  if (pEpSet->numOfEps == 1 && strncmp(pEpSet->eps[0].fqdn, pCvtAddr->fqdn, TSDB_FQDN_LEN) == 0) {
    memset(pEpSet->eps[0].fqdn, 0, TSDB_FQDN_LEN);
    memcpy(pEpSet->eps[0].fqdn, pCvtAddr->ip, TSDB_FQDN_LEN);
dengyihao's avatar
dengyihao 已提交
978 979
  }
}
dengyihao's avatar
dengyihao 已提交
980

dengyihao's avatar
dengyihao 已提交
981
FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx) {
dengyihao's avatar
dengyihao 已提交
982
  if (code != 0) return false;
dengyihao's avatar
dengyihao 已提交
983
  // if (pCtx->retryCnt == 0) return false;
dengyihao's avatar
dengyihao 已提交
984 985 986
  if (transEpSetIsEqual(&pCtx->epSet, &pCtx->origEpSet)) return false;
  return true;
}
dengyihao's avatar
dengyihao 已提交
987
FORCE_INLINE int32_t cliBuildExceptResp(SCliMsg* pMsg, STransMsg* pResp) {
dengyihao's avatar
dengyihao 已提交
988 989 990 991 992 993 994 995 996 997 998
  if (pMsg == NULL) return -1;

  memset(pResp, 0, sizeof(STransMsg));

  pResp->code = TSDB_CODE_RPC_BROKEN_LINK;
  pResp->msgType = pMsg->msg.msgType + 1;
  pResp->info.ahandle = pMsg->ctx ? pMsg->ctx->ahandle : NULL;
  pResp->info.traceId = pMsg->msg.info.traceId;

  return 0;
}
dengyihao's avatar
dengyihao 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
static FORCE_INLINE uint32_t cliGetIpFromFqdnCache(SHashObj* cache, char* fqdn) {
  uint32_t  addr = 0;
  uint32_t* v = taosHashGet(cache, fqdn, strlen(fqdn));
  if (v == NULL) {
    addr = taosGetIpv4FromFqdn(fqdn);
    taosHashPut(cache, fqdn, strlen(fqdn), &addr, sizeof(addr));
  } else {
    addr = *v;
  }
  return addr;
}
static FORCE_INLINE void cliUpdateFqdnCache(SHashObj* cache, char* fqdn) {
  // impl later
  return;
}
dengyihao's avatar
dengyihao 已提交
1014

dengyihao's avatar
dengyihao 已提交
1015
void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
formate  
dengyihao 已提交
1016
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1017
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1018

dengyihao's avatar
dengyihao 已提交
1019
  cliMayCvtFqdnToIp(&pCtx->epSet, &pThrd->cvtAddr);
dengyihao's avatar
dengyihao 已提交
1020 1021 1022 1023

  char tbuf[256] = {0};
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);

dengyihao's avatar
dengyihao 已提交
1024 1025
  if (!EPSET_IS_VALID(&pCtx->epSet)) {
    tError("invalid epset");
dengyihao's avatar
dengyihao 已提交
1026
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1027 1028
    return;
  }
dengyihao's avatar
dengyihao 已提交
1029

dengyihao's avatar
dengyihao 已提交
1030 1031 1032
  bool      ignore = false;
  SCliConn* conn = cliGetConn(pMsg, pThrd, &ignore);
  if (ignore == true) {
dengyihao's avatar
dengyihao 已提交
1033
    // persist conn already release by server
dengyihao's avatar
dengyihao 已提交
1034 1035
    STransMsg resp;
    cliBuildExceptResp(pMsg, &resp);
dengyihao's avatar
dengyihao 已提交
1036 1037 1038
    if (pMsg->type != Release) {
      pTransInst->cfp(pTransInst->parent, &resp, NULL);
    }
dengyihao's avatar
dengyihao 已提交
1039
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1040 1041
    return;
  }
dengyihao's avatar
dengyihao 已提交
1042

dengyihao's avatar
dengyihao 已提交
1043
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
1044
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1045
    transQueuePush(&conn->cliMsgs, pMsg);
U
ubuntu 已提交
1046
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
1047
  } else {
U
ubuntu 已提交
1048
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
1049 1050 1051 1052

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

dengyihao's avatar
dengyihao 已提交
1053
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1054
    transQueuePush(&conn->cliMsgs, pMsg);
dengyihao's avatar
dengyihao 已提交
1055

dengyihao's avatar
dengyihao 已提交
1056 1057
    conn->ip = strdup(EPSET_GET_INUSE_IP(&pCtx->epSet));
    conn->port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1058

dengyihao's avatar
dengyihao 已提交
1059
    struct sockaddr_in addr;
1060
    addr.sin_family = AF_INET;
dengyihao's avatar
dengyihao 已提交
1061
    addr.sin_addr.s_addr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, conn->ip);
1062
    addr.sin_port = (uint16_t)htons((uint16_t)conn->port);
dengyihao's avatar
dengyihao 已提交
1063 1064 1065

    STraceId* trace = &(pMsg->msg.info.traceId);
    tGTrace("%s conn %p try to connect to %s:%d", pTransInst->label, conn, conn->ip, conn->port);
dengyihao's avatar
dengyihao 已提交
1066 1067

    int ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
dengyihao's avatar
dengyihao 已提交
1068
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1069 1070
      tGTrace("%s conn %p failed to connect to %s:%d, reason:%s", pTransInst->label, conn, conn->ip, conn->port,
              uv_err_name(ret));
dengyihao's avatar
dengyihao 已提交
1071 1072 1073 1074 1075 1076

      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

dengyihao's avatar
dengyihao 已提交
1077 1078 1079
      cliHandleExcept(conn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
1080
    uv_timer_start(conn->timer, cliConnTimeout, TRANS_CONN_TIMEOUT, 0);
dengyihao's avatar
dengyihao 已提交
1081
  }
dengyihao's avatar
dengyihao 已提交
1082 1083
  STraceId* trace = &pMsg->msg.info.traceId;
  tGTrace("%s conn %p ready", pTransInst->label, conn);
dengyihao's avatar
dengyihao 已提交
1084
}
U
ubuntu 已提交
1085
static void cliAsyncCb(uv_async_t* handle) {
dengyihao's avatar
dengyihao 已提交
1086 1087 1088
  SAsyncItem* item = handle->data;
  SCliThrd*   pThrd = item->pThrd;
  SCliMsg*    pMsg = NULL;
dengyihao's avatar
dengyihao 已提交
1089

dengyihao's avatar
dengyihao 已提交
1090
  // batch process to avoid to lock/unlock frequently
dengyihao's avatar
formate  
dengyihao 已提交
1091
  queue wq;
wafwerar's avatar
wafwerar 已提交
1092
  taosThreadMutexLock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
1093
  QUEUE_MOVE(&item->qmsg, &wq);
wafwerar's avatar
wafwerar 已提交
1094
  taosThreadMutexUnlock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
1095

dengyihao's avatar
dengyihao 已提交
1096 1097 1098 1099
  int count = 0;
  while (!QUEUE_IS_EMPTY(&wq)) {
    queue* h = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
1100 1101

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1102
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1103
    count++;
dengyihao's avatar
dengyihao 已提交
1104 1105
  }
  if (count >= 2) {
S
Shengliang Guan 已提交
1106
    tTrace("cli process batch size:%d", count);
dengyihao's avatar
dengyihao 已提交
1107
  }
dengyihao's avatar
dengyihao 已提交
1108
  // if (!uv_is_active((uv_handle_t*)pThrd->prepare)) uv_prepare_start(pThrd->prepare, cliPrepareCb);
dengyihao's avatar
dengyihao 已提交
1109

dengyihao's avatar
dengyihao 已提交
1110
  if (pThrd->stopMsg != NULL) cliHandleQuit(pThrd->stopMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1111
}
dengyihao's avatar
dengyihao 已提交
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
static void cliPrepareCb(uv_prepare_t* handle) {
  SCliThrd* thrd = handle->data;
  tTrace("prepare work start");

  SAsyncPool* pool = thrd->asyncPool;
  for (int i = 0; i < pool->nAsync; i++) {
    uv_async_t* async = &(pool->asyncs[i]);
    SAsyncItem* item = async->data;

    queue wq;
    taosThreadMutexLock(&item->mtx);
    QUEUE_MOVE(&item->qmsg, &wq);
    taosThreadMutexUnlock(&item->mtx);

    int count = 0;
    while (!QUEUE_IS_EMPTY(&wq)) {
      queue* h = QUEUE_HEAD(&wq);
      QUEUE_REMOVE(h);

      SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
      (*cliAsyncHandle[pMsg->type])(pMsg, thrd);
      count++;
    }
  }
  tTrace("prepare work end");
  if (thrd->stopMsg != NULL) cliHandleQuit(thrd->stopMsg, thrd);
dengyihao's avatar
dengyihao 已提交
1138
}
dengyihao's avatar
dengyihao 已提交
1139

dengyihao's avatar
dengyihao 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
void cliDestroyConnMsgs(SCliConn* conn, bool destroy) {
  transCtxCleanup(&conn->ctx);
  cliReleaseUnfinishedMsg(conn);
  if (destroy == 1) {
    transQueueDestroy(&conn->cliMsgs);
  } else {
    transQueueClear(&conn->cliMsgs);
  }
}

void cliIteraConnMsgs(SCliConn* conn) {
  SCliThrd* pThrd = conn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;

  for (int i = 0; i < transQueueSize(&conn->cliMsgs); i++) {
    SCliMsg* cmsg = transQueueGet(&conn->cliMsgs, i);
    if (cmsg->type == Release || REQUEST_NO_RESP(&cmsg->msg) || cmsg->msg.msgType == TDMT_SCH_DROP_TASK) {
      continue;
    }

    STransMsg resp = {0};
    if (-1 == cliBuildExceptResp(cmsg, &resp)) {
      continue;
    }
    pTransInst->cfp(pTransInst->parent, &resp, NULL);

    cmsg->ctx->ahandle = NULL;
  }
}
dengyihao's avatar
dengyihao 已提交
1169 1170 1171
bool cliRecvReleaseReq(SCliConn* conn, STransMsgHead* pHead) {
  if (pHead->release == 1 && (pHead->msgLen) == sizeof(*pHead)) {
    uint64_t ahandle = pHead->ahandle;
dengyihao's avatar
dengyihao 已提交
1172
    tDebug("ahandle = %" PRIu64 "", ahandle);
dengyihao's avatar
dengyihao 已提交
1173 1174
    SCliMsg* pMsg = NULL;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
dengyihao's avatar
dengyihao 已提交
1175

dengyihao's avatar
dengyihao 已提交
1176 1177
    transClearBuffer(&conn->readBuf);
    transFreeMsg(transContFromHead((char*)pHead));
dengyihao's avatar
dengyihao 已提交
1178 1179 1180 1181 1182 1183 1184

    for (int i = 0; ahandle == 0 && i < transQueueSize(&conn->cliMsgs); i++) {
      SCliMsg* cliMsg = transQueueGet(&conn->cliMsgs, i);
      if (cliMsg->type == Release) {
        assert(pMsg == NULL);
        return true;
      }
dengyihao's avatar
dengyihao 已提交
1185
    }
dengyihao's avatar
dengyihao 已提交
1186 1187 1188

    cliIteraConnMsgs(conn);

dengyihao's avatar
dengyihao 已提交
1189 1190
    tDebug("%s conn %p receive release request, refId:%" PRId64 "", CONN_GET_INST_LABEL(conn), conn, conn->refId);
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1191

dengyihao's avatar
dengyihao 已提交
1192 1193 1194 1195 1196 1197
    addConnToPool(((SCliThrd*)conn->hostThrd)->pool, conn);
    return true;
  }
  return false;
}

U
ubuntu 已提交
1198
static void* cliWorkThread(void* arg) {
dengyihao's avatar
dengyihao 已提交
1199
  SCliThrd* pThrd = (SCliThrd*)arg;
dengyihao's avatar
dengyihao 已提交
1200
  pThrd->pid = taosGetSelfPthreadId();
G
gccgdb1234 已提交
1201
  setThreadName("trans-cli-work");
dengyihao's avatar
dengyihao 已提交
1202
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
dengyihao's avatar
dengyihao 已提交
1203 1204

  tDebug("thread quit-thread:%08" PRId64, pThrd->pid);
1205
  return NULL;
dengyihao's avatar
dengyihao 已提交
1206 1207
}

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

dengyihao's avatar
dengyihao 已提交
1211
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
1212
  memcpy(cli->label, label, TSDB_LABEL_LEN);
dengyihao's avatar
dengyihao 已提交
1213
  cli->numOfThreads = numOfThreads;
dengyihao's avatar
dengyihao 已提交
1214
  cli->pThreadObj = (SCliThrd**)taosMemoryCalloc(cli->numOfThreads, sizeof(SCliThrd*));
dengyihao's avatar
dengyihao 已提交
1215 1216

  for (int i = 0; i < cli->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
1217 1218
    SCliThrd* pThrd = createThrdObj(shandle);
    int       err = taosThreadCreate(&pThrd->thread, NULL, cliWorkThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
1219
    if (err == 0) {
S
Shengliang Guan 已提交
1220
      tDebug("success to create tranport-cli thread:%d", i);
dengyihao's avatar
dengyihao 已提交
1221
    }
dengyihao's avatar
dengyihao 已提交
1222
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
1223
  }
dengyihao's avatar
dengyihao 已提交
1224

dengyihao's avatar
dengyihao 已提交
1225 1226
  return cli;
}
dengyihao's avatar
dengyihao 已提交
1227

dengyihao's avatar
dengyihao 已提交
1228
static FORCE_INLINE void destroyUserdata(STransMsg* userdata) {
dengyihao's avatar
dengyihao 已提交
1229 1230 1231 1232 1233 1234
  if (userdata->pCont == NULL) {
    return;
  }
  transFreeMsg(userdata->pCont);
  userdata->pCont = NULL;
}
dengyihao's avatar
dengyihao 已提交
1235

dengyihao's avatar
dengyihao 已提交
1236
static FORCE_INLINE void destroyCmsg(void* arg) {
dengyihao's avatar
dengyihao 已提交
1237
  SCliMsg* pMsg = arg;
dengyihao's avatar
dengyihao 已提交
1238 1239 1240
  if (pMsg == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1241

dengyihao's avatar
dengyihao 已提交
1242 1243
  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
wafwerar's avatar
wafwerar 已提交
1244
  taosMemoryFree(pMsg);
dengyihao's avatar
dengyihao 已提交
1245
}
dengyihao's avatar
dengyihao 已提交
1246

dengyihao's avatar
dengyihao 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
static FORCE_INLINE void destroyCmsgAndAhandle(void* param) {
  if (param == NULL) return;

  STaskArg* arg = param;
  SCliMsg*  pMsg = arg->param1;
  SCliThrd* pThrd = arg->param2;

  tDebug("destroy Ahandle A");
  if (pThrd != NULL && pThrd->destroyAhandleFp != NULL) {
    tDebug("destroy Ahandle B");
    pThrd->destroyAhandleFp(pMsg->ctx->ahandle);
  }
  tDebug("destroy Ahandle C");

  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
  taosMemoryFree(pMsg);
}

dengyihao's avatar
dengyihao 已提交
1266 1267 1268
static SCliThrd* createThrdObj(void* trans) {
  STrans* pTransInst = trans;

dengyihao's avatar
dengyihao 已提交
1269
  SCliThrd* pThrd = (SCliThrd*)taosMemoryCalloc(1, sizeof(SCliThrd));
U
ubuntu 已提交
1270

dengyihao's avatar
dengyihao 已提交
1271
  QUEUE_INIT(&pThrd->msg);
wafwerar's avatar
wafwerar 已提交
1272
  taosThreadMutexInit(&pThrd->msgMtx, NULL);
dengyihao's avatar
dengyihao 已提交
1273

wafwerar's avatar
wafwerar 已提交
1274
  pThrd->loop = (uv_loop_t*)taosMemoryMalloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
1275 1276
  uv_loop_init(pThrd->loop);

dengyihao's avatar
dengyihao 已提交
1277
  pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 8, pThrd, cliAsyncCb);
dengyihao's avatar
dengyihao 已提交
1278 1279 1280 1281

  pThrd->prepare = taosMemoryCalloc(1, sizeof(uv_prepare_t));
  uv_prepare_init(pThrd->loop, pThrd->prepare);
  pThrd->prepare->data = pThrd;
dengyihao's avatar
dengyihao 已提交
1282
  // uv_prepare_start(pThrd->prepare, cliPrepareCb);
dengyihao's avatar
dengyihao 已提交
1283

dengyihao's avatar
dengyihao 已提交
1284
  int32_t timerSize = 64;
dengyihao's avatar
dengyihao 已提交
1285 1286 1287 1288 1289 1290 1291
  pThrd->timerList = taosArrayInit(timerSize, sizeof(void*));
  for (int i = 0; i < timerSize; i++) {
    uv_timer_t* timer = taosMemoryCalloc(1, sizeof(uv_timer_t));
    uv_timer_init(pThrd->loop, timer);
    taosArrayPush(pThrd->timerList, &timer);
  }

dengyihao's avatar
dengyihao 已提交
1292
  pThrd->pool = createConnPool(4);
dengyihao's avatar
dengyihao 已提交
1293
  transDQCreate(pThrd->loop, &pThrd->delayQueue);
dengyihao's avatar
dengyihao 已提交
1294

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

dengyihao's avatar
dengyihao 已提交
1297 1298 1299
  pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
  pThrd->pTransInst = trans;

dengyihao's avatar
dengyihao 已提交
1300
  pThrd->destroyAhandleFp = pTransInst->destroyFp;
dengyihao's avatar
dengyihao 已提交
1301
  pThrd->fqdn2ipCache = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1302
  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
1303 1304
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1305
static void destroyThrdObj(SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1306 1307 1308
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1309

wafwerar's avatar
wafwerar 已提交
1310
  taosThreadJoin(pThrd->thread, NULL);
dengyihao's avatar
dengyihao 已提交
1311
  CLI_RELEASE_UV(pThrd->loop);
wafwerar's avatar
wafwerar 已提交
1312
  taosThreadMutexDestroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
1313
  TRANS_DESTROY_ASYNC_POOL_MSG(pThrd->asyncPool, SCliMsg, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1314
  transAsyncPoolDestroy(pThrd->asyncPool);
dengyihao's avatar
dengyihao 已提交
1315

dengyihao's avatar
dengyihao 已提交
1316
  transDQDestroy(pThrd->delayQueue, destroyCmsgAndAhandle);
dengyihao's avatar
dengyihao 已提交
1317
  transDQDestroy(pThrd->timeoutQueue, NULL);
dengyihao's avatar
dengyihao 已提交
1318

dengyihao's avatar
dengyihao 已提交
1319
  tDebug("thread destroy %" PRId64, pThrd->pid);
dengyihao's avatar
dengyihao 已提交
1320 1321 1322 1323 1324
  for (int i = 0; i < taosArrayGetSize(pThrd->timerList); i++) {
    uv_timer_t* timer = taosArrayGetP(pThrd->timerList, i);
    taosMemoryFree(timer);
  }
  taosArrayDestroy(pThrd->timerList);
dengyihao's avatar
dengyihao 已提交
1325
  taosMemoryFree(pThrd->prepare);
wafwerar's avatar
wafwerar 已提交
1326
  taosMemoryFree(pThrd->loop);
dengyihao's avatar
dengyihao 已提交
1327
  taosHashCleanup(pThrd->fqdn2ipCache);
wafwerar's avatar
wafwerar 已提交
1328
  taosMemoryFree(pThrd);
dengyihao's avatar
dengyihao 已提交
1329
}
dengyihao's avatar
dengyihao 已提交
1330

dengyihao's avatar
dengyihao 已提交
1331
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1332
  //
wafwerar's avatar
wafwerar 已提交
1333
  taosMemoryFree(ctx);
dengyihao's avatar
dengyihao 已提交
1334
}
dengyihao's avatar
dengyihao 已提交
1335

dengyihao's avatar
dengyihao 已提交
1336
void cliSendQuit(SCliThrd* thrd) {
dengyihao's avatar
dengyihao 已提交
1337
  // cli can stop gracefully
wafwerar's avatar
wafwerar 已提交
1338
  SCliMsg* msg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1339
  msg->type = Quit;
dengyihao's avatar
dengyihao 已提交
1340
  transAsyncSend(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
1341
  atomic_store_8(&thrd->asyncPool->stop, 1);
dengyihao's avatar
dengyihao 已提交
1342
}
dengyihao's avatar
dengyihao 已提交
1343 1344
void cliWalkCb(uv_handle_t* handle, void* arg) {
  if (!uv_is_closing(handle)) {
dengyihao's avatar
dengyihao 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    if (uv_handle_get_type(handle) == UV_TIMER) {
      // SCliConn* pConn = handle->data;
      //  if (pConn != NULL && pConn->timer != NULL) {
      //    SCliThrd* pThrd = pConn->hostThrd;
      //    uv_timer_stop((uv_timer_t*)handle);
      //    handle->data = NULL;
      //    taosArrayPush(pThrd->timerList, &pConn->timer);
      //    pConn->timer = NULL;
      //  }
    } else {
      uv_read_stop((uv_stream_t*)handle);
    }
dengyihao's avatar
dengyihao 已提交
1357
    uv_close(handle, cliDestroy);
dengyihao's avatar
dengyihao 已提交
1358 1359
  }
}
dengyihao's avatar
dengyihao 已提交
1360

dengyihao's avatar
dengyihao 已提交
1361
FORCE_INLINE int cliRBChoseIdx(STrans* pTransInst) {
dengyihao's avatar
dengyihao 已提交
1362
  int32_t index = pTransInst->index;
dengyihao's avatar
dengyihao 已提交
1363 1364 1365
  if (pTransInst->numOfThreads == 0) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1366 1367 1368 1369
  /*
   * no lock, and to avoid CPU load imbalance, set limit pTransInst->numOfThreads * 2000;
   */
  if (pTransInst->index++ >= pTransInst->numOfThreads * 2000) {
U
ubuntu 已提交
1370 1371 1372 1373
    pTransInst->index = 0;
  }
  return index % pTransInst->numOfThreads;
}
dengyihao's avatar
dengyihao 已提交
1374
static FORCE_INLINE void doDelayTask(void* param) {
dengyihao's avatar
dengyihao 已提交
1375
  STaskArg* arg = param;
dengyihao's avatar
dengyihao 已提交
1376
  cliHandleReq((SCliMsg*)arg->param1, (SCliThrd*)arg->param2);
dengyihao's avatar
dengyihao 已提交
1377 1378
  taosMemoryFree(arg);
}
dengyihao's avatar
dengyihao 已提交
1379

dengyihao's avatar
dengyihao 已提交
1380 1381 1382
static void doCloseIdleConn(void* param) {
  STaskArg* arg = param;
  SCliConn* conn = arg->param1;
dengyihao's avatar
dengyihao 已提交
1383
  tDebug("%s conn %p idle, close it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
1384
  conn->task = NULL;
dengyihao's avatar
dengyihao 已提交
1385 1386
  cliDestroyConn(conn, true);
  taosMemoryFree(arg);
dengyihao's avatar
dengyihao 已提交
1387 1388
}

dengyihao's avatar
dengyihao 已提交
1389
static void cliSchedMsgToNextNode(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1390
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1391 1392
  STransConnCtx* pCtx = pMsg->ctx;

dengyihao's avatar
dengyihao 已提交
1393 1394
  STraceId* trace = &pMsg->msg.info.traceId;
  char      tbuf[256] = {0};
dengyihao's avatar
dengyihao 已提交
1395
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1396 1397
  tGDebug("%s retry on next node,use:%s, step: %d,timeout:%" PRId64 "", transLabel(pThrd->pTransInst), tbuf,
          pCtx->retryStep, pCtx->retryNextInterval);
dengyihao's avatar
dengyihao 已提交
1398 1399 1400 1401

  STaskArg* arg = taosMemoryMalloc(sizeof(STaskArg));
  arg->param1 = pMsg;
  arg->param2 = pThrd;
dengyihao's avatar
dengyihao 已提交
1402 1403

  transDQSched(pThrd->delayQueue, doDelayTask, arg, pCtx->retryNextInterval);
dengyihao's avatar
dengyihao 已提交
1404
}
dengyihao's avatar
dengyihao 已提交
1405

dengyihao's avatar
dengyihao 已提交
1406
FORCE_INLINE void cliCompareAndSwap(int8_t* val, int8_t exp, int8_t newVal) {
dengyihao's avatar
dengyihao 已提交
1407 1408 1409 1410
  if (*val != exp) {
    *val = newVal;
  }
}
dengyihao's avatar
dengyihao 已提交
1411

dengyihao's avatar
dengyihao 已提交
1412
FORCE_INLINE bool cliTryExtractEpSet(STransMsg* pResp, SEpSet* dst) {
dengyihao's avatar
dengyihao 已提交
1413 1414 1415 1416 1417 1418
  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 已提交
1419 1420 1421 1422
    return false;
  }
  int32_t tlen = tSerializeSEpSet(NULL, 0, dst);

dengyihao's avatar
dengyihao 已提交
1423 1424 1425 1426 1427 1428 1429
  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 已提交
1430 1431

  pResp->pCont = buf;
dengyihao's avatar
dengyihao 已提交
1432 1433 1434
  pResp->contLen = len;

  *dst = epset;
dengyihao's avatar
dengyihao 已提交
1435 1436
  return true;
}
dengyihao's avatar
dengyihao 已提交
1437
bool cliResetEpset(STransConnCtx* pCtx, STransMsg* pResp, bool hasEpSet) {
dengyihao's avatar
dengyihao 已提交
1438
  bool noDelay = true;
dengyihao's avatar
dengyihao 已提交
1439
  if (hasEpSet == false) {
dengyihao's avatar
dengyihao 已提交
1440
    // assert(pResp->contLen == 0);
dengyihao's avatar
dengyihao 已提交
1441 1442 1443 1444 1445 1446
    if (pResp->contLen == 0) {
      if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
        noDelay = false;
      } else {
        EPSET_FORWARD_INUSE(&pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1447 1448 1449 1450 1451 1452
    } else {
      if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
        noDelay = false;
      } else {
        EPSET_FORWARD_INUSE(&pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1453 1454
    }
  } else {
dengyihao's avatar
dengyihao 已提交
1455
    SEpSet  epSet;
dengyihao's avatar
dengyihao 已提交
1456 1457
    int32_t valid = tDeserializeSEpSet(pResp->pCont, pResp->contLen, &epSet);
    if (valid < 0) {
dengyihao's avatar
dengyihao 已提交
1458 1459 1460 1461 1462 1463
      tDebug("get invalid epset, epset equal, continue");
      if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
        noDelay = false;
      } else {
        EPSET_FORWARD_INUSE(&pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1464
    } else {
dengyihao's avatar
dengyihao 已提交
1465 1466 1467
      if (!transEpSetIsEqual(&pCtx->epSet, &epSet)) {
        tDebug("epset not equal, retry new epset");
        pCtx->epSet = epSet;
dengyihao's avatar
dengyihao 已提交
1468
        noDelay = false;
dengyihao's avatar
dengyihao 已提交
1469
      } else {
dengyihao's avatar
dengyihao 已提交
1470 1471 1472 1473 1474 1475
        if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
          noDelay = false;
        } else {
          tDebug("epset equal, continue");
          EPSET_FORWARD_INUSE(&pCtx->epSet);
        }
dengyihao's avatar
dengyihao 已提交
1476
      }
dengyihao's avatar
dengyihao 已提交
1477 1478 1479 1480 1481
    }
  }
  return noDelay;
}
bool cliGenRetryRule(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
1482 1483
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1484

dengyihao's avatar
dengyihao 已提交
1485 1486
  STransConnCtx* pCtx = pMsg->ctx;
  int32_t        code = pResp->code;
dengyihao's avatar
dengyihao 已提交
1487

dengyihao's avatar
dengyihao 已提交
1488
  bool retry = pTransInst->retry != NULL ? pTransInst->retry(code, pResp->msgType - 1) : false;
dengyihao's avatar
dengyihao 已提交
1489 1490 1491
  if (retry == false) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
1492 1493 1494 1495 1496 1497 1498 1499

  if (!pCtx->retryInit) {
    pCtx->retryMinInterval = pTransInst->retryMinInterval;
    pCtx->retryMaxInterval = pTransInst->retryMaxInterval;
    pCtx->retryStepFactor = pTransInst->retryStepFactor;
    pCtx->retryMaxTimeout = pTransInst->retryMaxTimouet;
    pCtx->retryInitTimestamp = taosGetTimestampMs();
    pCtx->retryNextInterval = pCtx->retryMinInterval;
dengyihao's avatar
dengyihao 已提交
1500
    pCtx->retryStep = 0;
dengyihao's avatar
dengyihao 已提交
1501
    pCtx->retryInit = true;
dengyihao's avatar
dengyihao 已提交
1502
    pCtx->retryCode = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
1503
  }
dengyihao's avatar
dengyihao 已提交
1504

dengyihao's avatar
dengyihao 已提交
1505 1506
  if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
    return false;
dengyihao's avatar
dengyihao 已提交
1507
  }
dengyihao's avatar
dengyihao 已提交
1508

dengyihao's avatar
dengyihao 已提交
1509 1510 1511 1512 1513 1514
  // code, msgType

  // A:  epset,   leader, not self
  // B:  epset,   not know leader
  // C:  no epset, leader but not serivce

dengyihao's avatar
dengyihao 已提交
1515 1516
  bool noDelay = false;
  if (code == TSDB_CODE_RPC_BROKEN_LINK || code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
dengyihao's avatar
dengyihao 已提交
1517
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
1518
    noDelay = cliResetEpset(pCtx, pResp, false);
dengyihao's avatar
dengyihao 已提交
1519 1520
    transFreeMsg(pResp->pCont);
    transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
1521
  } else if (code == TSDB_CODE_SYN_NOT_LEADER || code == TSDB_CODE_SYN_INTERNAL_ERROR ||
D
dapan1121 已提交
1522
             code == TSDB_CODE_SYN_PROPOSE_NOT_READY || code == TSDB_CODE_RPC_REDIRECT || code == TSDB_CODE_VND_STOPPED) {
dengyihao's avatar
dengyihao 已提交
1523
    tTrace("code str %s, contlen:%d 1", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
1524
    noDelay = cliResetEpset(pCtx, pResp, true);
dengyihao's avatar
dengyihao 已提交
1525 1526
    transFreeMsg(pResp->pCont);
    addConnToPool(pThrd->pool, pConn);
dengyihao's avatar
dengyihao 已提交
1527
  } else if (code == TSDB_CODE_SYN_RESTORING) {
dengyihao's avatar
dengyihao 已提交
1528
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
1529
    noDelay = cliResetEpset(pCtx, pResp, false);
dengyihao's avatar
dengyihao 已提交
1530 1531
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
1532
  } else {
dengyihao's avatar
dengyihao 已提交
1533
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
1534 1535 1536
    noDelay = cliResetEpset(pCtx, pResp, false);
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
1537
  }
dengyihao's avatar
dengyihao 已提交
1538 1539 1540 1541
  if (code != TSDB_CODE_RPC_BROKEN_LINK && code != TSDB_CODE_RPC_NETWORK_UNAVAIL && code != TSDB_CODE_SUCCESS) {
    // save one internal code
    pCtx->retryCode = code;
  }
dengyihao's avatar
dengyihao 已提交
1542

dengyihao's avatar
dengyihao 已提交
1543 1544 1545
  if (noDelay == false) {
    pCtx->epsetRetryCnt = 1;
    pCtx->retryStep++;
dengyihao's avatar
dengyihao 已提交
1546

dengyihao's avatar
dengyihao 已提交
1547 1548 1549 1550 1551 1552 1553 1554
    int64_t factor = pow(pCtx->retryStepFactor, pCtx->retryStep - 1);
    pCtx->retryNextInterval = factor * pCtx->retryMinInterval;
    if (pCtx->retryNextInterval >= pCtx->retryMaxInterval) {
      pCtx->retryNextInterval = pCtx->retryMaxInterval;
    }

    if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
      return false;
dengyihao's avatar
dengyihao 已提交
1555
    }
dengyihao's avatar
dengyihao 已提交
1556 1557 1558
  } else {
    pCtx->retryNextInterval = 0;
    pCtx->epsetRetryCnt++;
dengyihao's avatar
dengyihao 已提交
1559
  }
dengyihao's avatar
dengyihao 已提交
1560

dengyihao's avatar
dengyihao 已提交
1561
  pMsg->sent = 0;
dengyihao's avatar
dengyihao 已提交
1562
  cliSchedMsgToNextNode(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1563
  return true;
dengyihao's avatar
dengyihao 已提交
1564
}
dengyihao's avatar
dengyihao 已提交
1565
int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
1566 1567
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1568

dengyihao's avatar
dengyihao 已提交
1569
  if (pMsg == NULL || pMsg->ctx == NULL) {
dengyihao's avatar
dengyihao 已提交
1570
    tTrace("%s conn %p handle resp", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
1571 1572 1573
    pTransInst->cfp(pTransInst->parent, pResp, NULL);
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
1574

dengyihao's avatar
dengyihao 已提交
1575
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1576

dengyihao's avatar
dengyihao 已提交
1577 1578 1579
  bool retry = cliGenRetryRule(pConn, pResp, pMsg);
  if (retry == true) {
    return -1;
dengyihao's avatar
dengyihao 已提交
1580
  }
dengyihao's avatar
dengyihao 已提交
1581

dengyihao's avatar
dengyihao 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
  if (pCtx->retryCode != TSDB_CODE_SUCCESS) {
    int32_t code = pResp->code;
    // return internal code app
    if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK) {
      pResp->code = pCtx->retryCode;
    }
  }

  STraceId* trace = &pResp->info.traceId;
  bool      hasEpSet = cliTryExtractEpSet(pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1592
  if (hasEpSet) {
dengyihao's avatar
dengyihao 已提交
1593 1594
    char tbuf[256] = {0};
    EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1595
    tGTrace("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1596
  }
dengyihao's avatar
dengyihao 已提交
1597

dengyihao's avatar
dengyihao 已提交
1598
  if (pCtx->pSem != NULL) {
dengyihao's avatar
dengyihao 已提交
1599
    tGTrace("%s conn %p(sync) handle resp", CONN_GET_INST_LABEL(pConn), pConn);
1600
    if (pCtx->pRsp == NULL) {
dengyihao's avatar
dengyihao 已提交
1601
      tGTrace("%s conn %p(sync) failed to resp, ignore", CONN_GET_INST_LABEL(pConn), pConn);
1602 1603 1604
    } else {
      memcpy((char*)pCtx->pRsp, (char*)pResp, sizeof(*pResp));
    }
dengyihao's avatar
dengyihao 已提交
1605
    tsem_post(pCtx->pSem);
1606
    pCtx->pRsp = NULL;
dengyihao's avatar
dengyihao 已提交
1607
  } else {
dengyihao's avatar
dengyihao 已提交
1608
    tGTrace("%s conn %p handle resp", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1609
    if (retry == false && hasEpSet == true) {
dengyihao's avatar
dengyihao 已提交
1610
      pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1611
    } else {
dengyihao's avatar
dengyihao 已提交
1612
      if (!cliIsEpsetUpdated(pResp->code, pCtx)) {
dengyihao's avatar
dengyihao 已提交
1613 1614 1615 1616
        pTransInst->cfp(pTransInst->parent, pResp, NULL);
      } else {
        pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1617
    }
dengyihao's avatar
dengyihao 已提交
1618
  }
dengyihao's avatar
dengyihao 已提交
1619
  return 0;
dengyihao's avatar
dengyihao 已提交
1620
}
U
ubuntu 已提交
1621 1622

void transCloseClient(void* arg) {
U
ubuntu 已提交
1623
  SCliObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
1624
  for (int i = 0; i < cli->numOfThreads; i++) {
U
ubuntu 已提交
1625
    cliSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1626
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1627
  }
wafwerar's avatar
wafwerar 已提交
1628 1629
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
dengyihao's avatar
dengyihao 已提交
1630
}
dengyihao's avatar
dengyihao 已提交
1631 1632 1633 1634 1635
void transRefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_INC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1636
  tTrace("%s conn %p ref %d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1637 1638 1639 1640 1641 1642 1643
  UNUSED(ref);
}
void transUnrefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_DEC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1644
  tTrace("%s conn %p ref:%d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1645
  if (ref == 0) {
U
ubuntu 已提交
1646
    cliDestroyConn((SCliConn*)handle, true);
dengyihao's avatar
dengyihao 已提交
1647 1648
  }
}
dengyihao's avatar
dengyihao 已提交
1649
static FORCE_INLINE SCliThrd* transGetWorkThrdFromHandle(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
1650
  SCliThrd*  pThrd = NULL;
dengyihao's avatar
dengyihao 已提交
1651
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
1652 1653 1654
  if (exh == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1655

dengyihao's avatar
dengyihao 已提交
1656 1657 1658 1659 1660 1661
  if (exh->pThrd == NULL && trans != NULL) {
    int idx = cliRBChoseIdx(trans);
    if (idx < 0) return NULL;
    exh->pThrd = ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }

dengyihao's avatar
dengyihao 已提交
1662
  pThrd = exh->pThrd;
dengyihao's avatar
dengyihao 已提交
1663
  transReleaseExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
1664 1665
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1666
SCliThrd* transGetWorkThrd(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
1667
  if (handle == 0) {
dengyihao's avatar
dengyihao 已提交
1668
    int idx = cliRBChoseIdx(trans);
dengyihao's avatar
dengyihao 已提交
1669
    if (idx < 0) return NULL;
dengyihao's avatar
dengyihao 已提交
1670 1671
    return ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
dengyihao's avatar
dengyihao 已提交
1672
  SCliThrd* pThrd = transGetWorkThrdFromHandle(trans, handle);
D
dapan1121 已提交
1673
  return pThrd;
dengyihao's avatar
dengyihao 已提交
1674
}
dengyihao's avatar
dengyihao 已提交
1675
int transReleaseCliHandle(void* handle) {
dengyihao's avatar
dengyihao 已提交
1676 1677 1678
  int  idx = -1;
  bool valid = false;

dengyihao's avatar
dengyihao 已提交
1679
  SCliThrd* pThrd = transGetWorkThrdFromHandle(NULL, (int64_t)handle);
dengyihao's avatar
dengyihao 已提交
1680
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
1681
    return -1;
dengyihao's avatar
dengyihao 已提交
1682
  }
dengyihao's avatar
dengyihao 已提交
1683

dengyihao's avatar
dengyihao 已提交
1684
  STransMsg tmsg = {.info.handle = handle, .info.ahandle = (void*)0x9527};
dengyihao's avatar
rm code  
dengyihao 已提交
1685
  TRACE_SET_MSGID(&tmsg.info.traceId, tGenIdPI64());
dengyihao's avatar
dengyihao 已提交
1686

dengyihao's avatar
dengyihao 已提交
1687 1688 1689
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
  pCtx->ahandle = tmsg.info.ahandle;

dengyihao's avatar
dengyihao 已提交
1690
  SCliMsg* cmsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1691
  cmsg->msg = tmsg;
dengyihao's avatar
dengyihao 已提交
1692
  cmsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1693
  cmsg->type = Release;
dengyihao's avatar
dengyihao 已提交
1694
  cmsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
1695

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

dengyihao's avatar
dengyihao 已提交
1699
  if (0 != transAsyncSend(pThrd->asyncPool, &cmsg->q)) {
dengyihao's avatar
dengyihao 已提交
1700
    destroyCmsg(cmsg);
dengyihao's avatar
dengyihao 已提交
1701 1702
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1703
  return 0;
dengyihao's avatar
dengyihao 已提交
1704
}
dengyihao's avatar
dengyihao 已提交
1705

dengyihao's avatar
dengyihao 已提交
1706
int transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1707 1708 1709 1710 1711
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1712

dengyihao's avatar
dengyihao 已提交
1713
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
dengyihao's avatar
dengyihao 已提交
1714
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
1715
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1716
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1717
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
1718 1719
  }

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

wafwerar's avatar
wafwerar 已提交
1722
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1723
  pCtx->epSet = *pEpSet;
S
Shengliang Guan 已提交
1724
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1725
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1726

H
Haojun Liao 已提交
1727
  if (ctx != NULL) pCtx->appCtx = *ctx;
dengyihao's avatar
dengyihao 已提交
1728

wafwerar's avatar
wafwerar 已提交
1729
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1730
  cliMsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
1731
  cliMsg->msg = *pReq;
dengyihao's avatar
dengyihao 已提交
1732
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1733
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1734
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
1735

dengyihao's avatar
dengyihao 已提交
1736
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
1737 1738
  tGDebug("%s send request at thread:%08" PRId64 ", dst:%s:%d, app:%p", transLabel(pTransInst), pThrd->pid,
          EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet), pReq->info.ahandle);
dengyihao's avatar
dengyihao 已提交
1739 1740
  if (0 != transAsyncSend(pThrd->asyncPool, &(cliMsg->q))) {
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1741
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1742 1743
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1744
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1745
  return 0;
dengyihao's avatar
dengyihao 已提交
1746
}
dengyihao's avatar
dengyihao 已提交
1747

dengyihao's avatar
dengyihao 已提交
1748
int transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMsg* pRsp) {
dengyihao's avatar
dengyihao 已提交
1749 1750 1751 1752 1753
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1754

dengyihao's avatar
dengyihao 已提交
1755 1756
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
1757
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1758
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1759
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
1760
  }
dengyihao's avatar
dengyihao 已提交
1761

dengyihao's avatar
dengyihao 已提交
1762 1763
  tsem_t* sem = taosMemoryCalloc(1, sizeof(tsem_t));
  tsem_init(sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
1764

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

wafwerar's avatar
wafwerar 已提交
1767
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1768
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
1769
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
1770
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1771
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1772
  pCtx->pSem = sem;
dengyihao's avatar
dengyihao 已提交
1773 1774
  pCtx->pRsp = pRsp;

wafwerar's avatar
wafwerar 已提交
1775
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1776 1777 1778
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pReq;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1779
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1780
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
1781

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

dengyihao's avatar
dengyihao 已提交
1786 1787
  int ret = transAsyncSend(pThrd->asyncPool, &cliMsg->q);
  if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1788
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1789
    goto _RETURN;
dengyihao's avatar
dengyihao 已提交
1790
  }
dengyihao's avatar
dengyihao 已提交
1791
  tsem_wait(sem);
dengyihao's avatar
dengyihao 已提交
1792 1793

_RETURN:
dengyihao's avatar
dengyihao 已提交
1794 1795
  tsem_destroy(sem);
  taosMemoryFree(sem);
dengyihao's avatar
dengyihao 已提交
1796
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1797
  return ret;
dengyihao's avatar
dengyihao 已提交
1798
}
dengyihao's avatar
dengyihao 已提交
1799 1800 1801
/*
 *
 **/
dengyihao's avatar
dengyihao 已提交
1802
int transSetDefaultAddr(void* shandle, const char* ip, const char* fqdn) {
dengyihao's avatar
dengyihao 已提交
1803
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1804 1805 1806
  if (pTransInst == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1807 1808 1809

  SCvtAddr cvtAddr = {0};
  if (ip != NULL && fqdn != NULL) {
dengyihao's avatar
dengyihao 已提交
1810 1811
    tstrncpy(cvtAddr.ip, ip, sizeof(cvtAddr.ip));
    tstrncpy(cvtAddr.fqdn, fqdn, sizeof(cvtAddr.fqdn));
dengyihao's avatar
dengyihao 已提交
1812 1813
    cvtAddr.cvt = true;
  }
dengyihao's avatar
dengyihao 已提交
1814 1815
  for (int i = 0; i < pTransInst->numOfThreads; i++) {
    STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1816
    pCtx->cvtAddr = cvtAddr;
dengyihao's avatar
dengyihao 已提交
1817 1818 1819 1820

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

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

dengyihao's avatar
dengyihao 已提交
1826 1827
    if (transAsyncSend(thrd->asyncPool, &(cliMsg->q)) != 0) {
      destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1828
      transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1829 1830
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
1831
  }
dengyihao's avatar
dengyihao 已提交
1832
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1833
  return 0;
dengyihao's avatar
dengyihao 已提交
1834
}
dengyihao's avatar
dengyihao 已提交
1835 1836 1837 1838 1839

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

dengyihao's avatar
dengyihao 已提交
1841 1842
  return exh->refId;
}
dengyihao's avatar
dengyihao 已提交
1843
#endif