transCli.c 75.5 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 24 25 26 27 28 29 30 31
typedef struct {
  queue    wq;
  int32_t  wLen;
  int32_t  batchSize;  //
  int32_t  batch;
  char*    dst;
  char*    ip;
  uint16_t port;
} SCliBatch;
dengyihao's avatar
dengyihao 已提交
32
typedef struct SCliConn {
dengyihao's avatar
dengyihao 已提交
33
  T_REF_DECLARE()
dengyihao's avatar
dengyihao 已提交
34 35
  uv_connect_t connReq;
  uv_stream_t* stream;
dengyihao's avatar
dengyihao 已提交
36
  queue        wreqQueue;
dengyihao's avatar
dengyihao 已提交
37 38

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

dengyihao's avatar
dengyihao 已提交
40 41 42 43
  void* hostThrd;

  SConnBuffer readBuf;
  STransQueue cliMsgs;
dengyihao's avatar
dengyihao 已提交
44 45 46

  queue      q;
  SConnList* list;
dengyihao's avatar
dengyihao 已提交
47 48

  STransCtx  ctx;
dengyihao's avatar
dengyihao 已提交
49 50
  bool       broken;  // link broken or not
  ConnStatus status;  //
dengyihao's avatar
dengyihao 已提交
51

dengyihao's avatar
dengyihao 已提交
52 53
  SCliBatch* pBatch;

dengyihao's avatar
dengyihao 已提交
54 55
  int64_t refId;
  char*   ip;
dengyihao's avatar
dengyihao 已提交
56

dengyihao's avatar
dengyihao 已提交
57
  SDelayTask* task;
dengyihao's avatar
dengyihao 已提交
58

dengyihao's avatar
dengyihao 已提交
59
  // debug and log info
dengyihao's avatar
dengyihao 已提交
60 61 62
  char src[32];
  char dst[32];

dengyihao's avatar
dengyihao 已提交
63
} SCliConn;
dengyihao's avatar
dengyihao 已提交
64

dengyihao's avatar
dengyihao 已提交
65
typedef struct SCliMsg {
dengyihao's avatar
dengyihao 已提交
66
  STransConnCtx* ctx;
dengyihao's avatar
formate  
dengyihao 已提交
67
  STransMsg      msg;
dengyihao's avatar
dengyihao 已提交
68
  queue          q;
dengyihao's avatar
dengyihao 已提交
69
  STransMsgType  type;
dengyihao's avatar
dengyihao 已提交
70

dengyihao's avatar
dengyihao 已提交
71
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
72 73
  uint64_t st;
  int      sent;  //(0: no send, 1: alread sent)
dengyihao's avatar
dengyihao 已提交
74 75
} SCliMsg;

dengyihao's avatar
dengyihao 已提交
76
typedef struct SCliThrd {
dengyihao's avatar
dengyihao 已提交
77 78 79 80 81 82
  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 已提交
83
  // timer handles
dengyihao's avatar
dengyihao 已提交
84
  SArray* timerList;
dengyihao's avatar
dengyihao 已提交
85
  // msg queue
dengyihao's avatar
dengyihao 已提交
86
  queue         msg;
wafwerar's avatar
wafwerar 已提交
87
  TdThreadMutex msgMtx;
dengyihao's avatar
dengyihao 已提交
88
  SDelayQueue*  delayQueue;
dengyihao's avatar
dengyihao 已提交
89
  SDelayQueue*  timeoutQueue;
dengyihao's avatar
dengyihao 已提交
90 91
  uint64_t      nextTimeout;  // next timeout
  void*         pTransInst;   //
dengyihao's avatar
dengyihao 已提交
92

dengyihao's avatar
dengyihao 已提交
93
  int connCount;
dengyihao's avatar
dengyihao 已提交
94
  void (*destroyAhandleFp)(void* ahandle);
dengyihao's avatar
dengyihao 已提交
95 96
  SHashObj* fqdn2ipCache;
  SCvtAddr  cvtAddr;
dengyihao's avatar
dengyihao 已提交
97

dengyihao's avatar
dengyihao 已提交
98
  SHashObj* failFastCache;
dengyihao's avatar
dengyihao 已提交
99
  SHashObj* connLimitCache;
dengyihao's avatar
dengyihao 已提交
100
  SHashObj* batchCache;
dengyihao's avatar
dengyihao 已提交
101

dengyihao's avatar
dengyihao 已提交
102 103
  SCliMsg* stopMsg;

dengyihao's avatar
dengyihao 已提交
104
  bool quit;
dengyihao's avatar
dengyihao 已提交
105
} SCliThrd;
dengyihao's avatar
dengyihao 已提交
106

U
ubuntu 已提交
107
typedef struct SCliObj {
dengyihao's avatar
dengyihao 已提交
108 109 110 111
  char       label[TSDB_LABEL_LEN];
  int32_t    index;
  int        numOfThreads;
  SCliThrd** pThreadObj;
U
ubuntu 已提交
112
} SCliObj;
dengyihao's avatar
dengyihao 已提交
113

dengyihao's avatar
dengyihao 已提交
114 115 116 117 118 119 120
typedef struct {
  int32_t reinit;
  int64_t timestamp;
  int32_t count;
  int32_t threshold;
  int64_t interval;
} SFailFastItem;
dengyihao's avatar
dengyihao 已提交
121
// conn pool
dengyihao's avatar
dengyihao 已提交
122
// add expire timeout and capacity limit
dengyihao's avatar
dengyihao 已提交
123
static void*     createConnPool(int size);
124
static void*     destroyConnPool(void* pool);
dengyihao's avatar
dengyihao 已提交
125
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port);
dengyihao's avatar
dengyihao 已提交
126
static void      addConnToPool(void* pool, SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
127
static void      doCloseIdleConn(void* param);
dengyihao's avatar
dengyihao 已提交
128

dengyihao's avatar
dengyihao 已提交
129 130
// register conn timer
static void cliConnTimeout(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
131 132
// register timer for read
static void cliReadTimeoutCb(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
133
// register timer in each thread to clear expire conn
dengyihao's avatar
dengyihao 已提交
134
// static void cliTimeoutCb(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
135
// alloc buffer for recv
dengyihao's avatar
dengyihao 已提交
136
static FORCE_INLINE void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
137
// callback after recv nbytes from socket
U
ubuntu 已提交
138
static void cliRecvCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
139
// callback after send data to socket
U
ubuntu 已提交
140
static void cliSendCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
141
// callback after conn to server
U
ubuntu 已提交
142 143
static void cliConnCb(uv_connect_t* req, int status);
static void cliAsyncCb(uv_async_t* handle);
dengyihao's avatar
dengyihao 已提交
144
static void cliIdleCb(uv_idle_t* handle);
dengyihao's avatar
dengyihao 已提交
145
static void cliPrepareCb(uv_prepare_t* handle);
dengyihao's avatar
dengyihao 已提交
146

dengyihao's avatar
dengyihao 已提交
147 148
static void cliHandleBatchReq(SCliBatch* pBatch, SCliThrd* pThrd);
// static void cliConnBatchCb(uv_connect_t* req, int status);
dengyihao's avatar
dengyihao 已提交
149
static void cliSendBatchCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
150 151 152
// static void cliConnBatchCb(uv_connect_t* req, int status);
//  callback after conn to server
// static void cliConnBatchCb(uv_connect_t* req, int status);
dengyihao's avatar
dengyihao 已提交
153

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

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

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

dengyihao's avatar
dengyihao 已提交
160
static SCliConn* cliCreateConn(SCliThrd* thrd);
U
ubuntu 已提交
161 162
static void      cliDestroyConn(SCliConn* pConn, bool clear /*clear tcp handle or not*/);
static void      cliDestroy(uv_handle_t* handle);
dengyihao's avatar
dengyihao 已提交
163
static void      cliSend(SCliConn* pConn);
dengyihao's avatar
dengyihao 已提交
164
static void      cliSendBatch(SCliConn* pConn);
dengyihao's avatar
dengyihao 已提交
165
static void      cliDestroyConnMsgs(SCliConn* conn, bool destroy);
dengyihao's avatar
dengyihao 已提交
166

dengyihao's avatar
dengyihao 已提交
167 168
static int32_t cliPreCheckSessionLimit(SCliThrd* pThrd, char* ip, uint16_t port);

dengyihao's avatar
dengyihao 已提交
169
// cli util func
dengyihao's avatar
dengyihao 已提交
170 171
static FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx);
static FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr);
dengyihao's avatar
dengyihao 已提交
172

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

dengyihao's avatar
dengyihao 已提交
175 176 177
static FORCE_INLINE uint32_t cliGetIpFromFqdnCache(SHashObj* cache, char* fqdn);
static FORCE_INLINE void     cliUpdateFqdnCache(SHashObj* cache, char* fqdn);

dengyihao's avatar
dengyihao 已提交
178
// process data read from server, add decompress etc later
U
ubuntu 已提交
179
static void cliHandleResp(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
180
// handle except about conn
U
ubuntu 已提交
181
static void cliHandleExcept(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
182
static void cliReleaseUnfinishedMsg(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
183
static void cliHandleFastFail(SCliConn* pConn, int status);
dengyihao's avatar
dengyihao 已提交
184

185
// handle req from app
dengyihao's avatar
dengyihao 已提交
186 187 188 189 190 191
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 已提交
192 193
/// static void (*cliAsyncHandle[])(SCliMsg* pMsg, SCliThrd* pThrd) = {cliHandleReq, cliHandleQuit, cliHandleRelease,
/// NULL,cliHandleUpdate};
dengyihao's avatar
dengyihao 已提交
194

dengyihao's avatar
dengyihao 已提交
195 196
static FORCE_INLINE void destroyUserdata(STransMsg* userdata);
static FORCE_INLINE void destroyCmsg(void* cmsg);
dengyihao's avatar
dengyihao 已提交
197
static FORCE_INLINE void destroyCmsgAndAhandle(void* cmsg);
dengyihao's avatar
dengyihao 已提交
198
static FORCE_INLINE int  cliRBChoseIdx(STrans* pTransInst);
dengyihao's avatar
dengyihao 已提交
199
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx);
dengyihao's avatar
dengyihao 已提交
200

dengyihao's avatar
dengyihao 已提交
201
// thread obj
dengyihao's avatar
dengyihao 已提交
202
static SCliThrd* createThrdObj(void* trans);
dengyihao's avatar
dengyihao 已提交
203
static void      destroyThrdObj(SCliThrd* pThrd);
dengyihao's avatar
dengyihao 已提交
204

dengyihao's avatar
dengyihao 已提交
205 206 207 208 209 210 211 212 213
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 已提交
214 215 216 217 218 219
// 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 已提交
220 221
#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 已提交
222

dengyihao's avatar
dengyihao 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
#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 已提交
239
  } while (0)
dengyihao's avatar
dengyihao 已提交
240

U
ubuntu 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253
#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 已提交
254

dengyihao's avatar
formate  
dengyihao 已提交
255 256
#define CONN_SET_PERSIST_BY_APP(conn) \
  do {                                \
dengyihao's avatar
dengyihao 已提交
257 258
    if (conn->status == ConnNormal) { \
      conn->status = ConnAcquire;     \
dengyihao's avatar
formate  
dengyihao 已提交
259 260 261
      transRefCliHandle(conn);        \
    }                                 \
  } while (0)
262

dengyihao's avatar
dengyihao 已提交
263 264 265 266
#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)
267

S
Shengliang Guan 已提交
268 269
#define REQUEST_NO_RESP(msg)         ((msg)->info.noResp == 1)
#define REQUEST_PERSIS_HANDLE(msg)   ((msg)->info.persistHandle == 1)
dengyihao's avatar
dengyihao 已提交
270
#define REQUEST_RELEASE_HANDLE(cmsg) ((cmsg)->type == Release)
dengyihao's avatar
dengyihao 已提交
271

dengyihao's avatar
dengyihao 已提交
272
#define EPSET_IS_VALID(epSet)       ((epSet) != NULL && (epSet)->numOfEps >= 0 && (epSet)->inUse >= 0)
dengyihao's avatar
dengyihao 已提交
273
#define EPSET_GET_SIZE(epSet)       (epSet)->numOfEps
dengyihao's avatar
dengyihao 已提交
274
#define EPSET_GET_INUSE_IP(epSet)   ((epSet)->eps[(epSet)->inUse].fqdn)
dengyihao's avatar
dengyihao 已提交
275
#define EPSET_GET_INUSE_PORT(epSet) ((epSet)->eps[(epSet)->inUse].port)
dengyihao's avatar
dengyihao 已提交
276 277 278 279 280 281
#define EPSET_FORWARD_INUSE(epSet)                             \
  do {                                                         \
    if ((epSet)->numOfEps != 0) {                              \
      ++((epSet)->inUse);                                      \
      (epSet)->inUse = ((epSet)->inUse) % ((epSet)->numOfEps); \
    }                                                          \
dengyihao's avatar
dengyihao 已提交
282
  } while (0)
dengyihao's avatar
dengyihao 已提交
283

dengyihao's avatar
dengyihao 已提交
284 285 286 287 288 289 290 291 292 293 294
#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 已提交
295
  } while (0);
dengyihao's avatar
dengyihao 已提交
296

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

dengyihao's avatar
dengyihao 已提交
299 300 301 302 303 304 305 306
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 已提交
307
      } else if (msg->ctx->ahandle != NULL && pThrd->destroyAhandleFp != NULL) {
dengyihao's avatar
dengyihao 已提交
308
        tDebug("%s conn %p destroy unfinished ahandle %p", CONN_GET_INST_LABEL(conn), conn, msg->ctx->ahandle);
dengyihao's avatar
dengyihao 已提交
309
        pThrd->destroyAhandleFp(msg->ctx->ahandle);
dengyihao's avatar
dengyihao 已提交
310 311 312 313
      }
    }
    destroyCmsg(msg);
  }
dengyihao's avatar
dengyihao 已提交
314
  transQueueClear(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
315
  memset(&conn->ctx, 0, sizeof(conn->ctx));
dengyihao's avatar
dengyihao 已提交
316
}
dengyihao's avatar
dengyihao 已提交
317
bool cliMaySendCachedMsg(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
318
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
319
    SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
320
    CONN_GET_NEXT_SENDMSG(conn);
dengyihao's avatar
dengyihao 已提交
321 322 323 324 325 326
    if (pCliMsg == NULL)
      return false;
    else {
      cliSend(conn);
      return true;
    }
dengyihao's avatar
dengyihao 已提交
327
  }
dengyihao's avatar
dengyihao 已提交
328
  return false;
U
ubuntu 已提交
329 330
_RETURN:
  return false;
dengyihao's avatar
dengyihao 已提交
331
}
dengyihao's avatar
formate  
dengyihao 已提交
332
void cliHandleResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
333 334
  SCliThrd* pThrd = conn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
335

dengyihao's avatar
dengyihao 已提交
336 337 338 339 340 341
  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 已提交
342
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
343
    conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
344 345
  }

dengyihao's avatar
opt rpc  
dengyihao 已提交
346
  STransMsgHead* pHead = NULL;
dengyihao's avatar
dengyihao 已提交
347 348 349

  int32_t msgLen = transDumpFromBuffer(&conn->readBuf, (char**)&pHead);
  if (msgLen <= 0) {
dengyihao's avatar
dengyihao 已提交
350 351 352
    tDebug("%s conn %p recv invalid packet ", CONN_GET_INST_LABEL(conn), conn);
    return;
  }
dengyihao's avatar
dengyihao 已提交
353 354 355 356

  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 已提交
357 358
  pHead->code = htonl(pHead->code);
  pHead->msgLen = htonl(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
359 360 361 362
  if (cliRecvReleaseReq(conn, pHead)) {
    return;
  }

dengyihao's avatar
dengyihao 已提交
363 364 365 366 367
  STransMsg transMsg = {0};
  transMsg.contLen = transContLenFromMsg(pHead->msgLen);
  transMsg.pCont = transContFromHead((char*)pHead);
  transMsg.code = pHead->code;
  transMsg.msgType = pHead->msgType;
S
Shengliang Guan 已提交
368
  transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
369
  transMsg.info.traceId = pHead->traceId;
dengyihao's avatar
dengyihao 已提交
370
  transMsg.info.hasEpSet = pHead->hasEpSet;
dengyihao's avatar
dengyihao 已提交
371

dengyihao's avatar
dengyihao 已提交
372 373 374 375
  SCliMsg*       pMsg = NULL;
  STransConnCtx* pCtx = NULL;
  if (CONN_NO_PERSIST_BY_APP(conn)) {
    pMsg = transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
376 377 378

    pCtx = pMsg ? pMsg->ctx : NULL;
    transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
379
    tDebug("%s conn %p get ahandle %p, persist: 0", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
U
ubuntu 已提交
380
  } else {
dengyihao's avatar
dengyihao 已提交
381 382 383
    uint64_t ahandle = (uint64_t)pHead->ahandle;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
    if (pMsg == NULL) {
S
Shengliang Guan 已提交
384
      transMsg.info.ahandle = transCtxDumpVal(&conn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
385 386
      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 已提交
387
      if (!CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
D
dapan1121 已提交
388
        transMsg.code = TSDB_CODE_RPC_BROKEN_LINK;
S
Shengliang Guan 已提交
389
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&conn->ctx, (int32_t*)&(transMsg.msgType));
dengyihao's avatar
dengyihao 已提交
390 391
        tDebug("%s conn %p construct ahandle %p due brokenlink, persist: 1", CONN_GET_INST_LABEL(conn), conn,
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
392 393
      }
    } else {
dengyihao's avatar
dengyihao 已提交
394
      pCtx = pMsg->ctx;
S
Shengliang Guan 已提交
395
      transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
396
      tDebug("%s conn %p get ahandle %p, persist: 1", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
397
    }
U
ubuntu 已提交
398
  }
dengyihao's avatar
dengyihao 已提交
399
  // buf's mem alread translated to transMsg.pCont
dengyihao's avatar
dengyihao 已提交
400
  if (!CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
401
    transMsg.info.handle = (void*)conn->refId;
dengyihao's avatar
dengyihao 已提交
402
    tDebug("%s conn %p ref by app", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
403
  }
dengyihao's avatar
dengyihao 已提交
404

dengyihao's avatar
dengyihao 已提交
405
  STraceId* trace = &transMsg.info.traceId;
dengyihao's avatar
dengyihao 已提交
406
  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 已提交
407
          TMSG_INFO(pHead->msgType), conn->dst, conn->src, pHead->msgLen, tstrerror(transMsg.code));
dengyihao's avatar
dengyihao 已提交
408

dengyihao's avatar
dengyihao 已提交
409
  if (pCtx == NULL && CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
410
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
411
    transFreeMsg(transMsg.pCont);
dengyihao's avatar
dengyihao 已提交
412 413
    return;
  }
S
Shengliang Guan 已提交
414
  if (CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
415
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
416
    transFreeMsg(transMsg.pCont);
dengyihao's avatar
dengyihao 已提交
417 418
    return;
  }
dengyihao's avatar
dengyihao 已提交
419

dengyihao's avatar
dengyihao 已提交
420
  if (pMsg == NULL || (pMsg && pMsg->type != Release)) {
dengyihao's avatar
dengyihao 已提交
421 422 423
    if (cliAppCb(conn, &transMsg, pMsg) != 0) {
      return;
    }
dengyihao's avatar
dengyihao 已提交
424
  }
dengyihao's avatar
dengyihao 已提交
425 426
  destroyCmsg(pMsg);

dengyihao's avatar
dengyihao 已提交
427
  if (cliMaySendCachedMsg(conn) == true) {
dengyihao's avatar
dengyihao 已提交
428 429
    return;
  }
dengyihao's avatar
dengyihao 已提交
430

U
ubuntu 已提交
431
  if (CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
432
    return addConnToPool(pThrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
433
  }
dengyihao's avatar
test  
dengyihao 已提交
434

dengyihao's avatar
dengyihao 已提交
435
  uv_read_start((uv_stream_t*)conn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
436
}
U
ubuntu 已提交
437

dengyihao's avatar
dengyihao 已提交
438
void cliHandleExceptImpl(SCliConn* pConn, int32_t code) {
dengyihao's avatar
dengyihao 已提交
439
  if (transQueueEmpty(&pConn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
440
    if (pConn->broken == true && CONN_NO_PERSIST_BY_APP(pConn)) {
dengyihao's avatar
dengyihao 已提交
441
      tTrace("%s conn %p handle except, persist:0", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
formate  
dengyihao 已提交
442 443 444
      transUnrefCliHandle(pConn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
445
  }
dengyihao's avatar
dengyihao 已提交
446 447 448
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
  bool      once = false;
D
dapan1121 已提交
449
  do {
dengyihao's avatar
dengyihao 已提交
450
    SCliMsg* pMsg = transQueuePop(&pConn->cliMsgs);
dengyihao's avatar
enh log  
dengyihao 已提交
451

D
dapan1121 已提交
452 453
    if (pMsg == NULL && once) {
      break;
dengyihao's avatar
dengyihao 已提交
454
    }
dengyihao's avatar
enh log  
dengyihao 已提交
455 456 457 458 459 460

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

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

dengyihao's avatar
dengyihao 已提交
463
    STransMsg transMsg = {0};
dengyihao's avatar
dengyihao 已提交
464
    transMsg.code = code == -1 ? (pConn->broken ? TSDB_CODE_RPC_BROKEN_LINK : TSDB_CODE_RPC_NETWORK_UNAVAIL) : code;
dengyihao's avatar
dengyihao 已提交
465
    transMsg.msgType = pMsg ? pMsg->msg.msgType + 1 : 0;
S
Shengliang Guan 已提交
466
    transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
467

dengyihao's avatar
dengyihao 已提交
468
    if (pMsg == NULL && !CONN_NO_PERSIST_BY_APP(pConn)) {
S
Shengliang Guan 已提交
469
      transMsg.info.ahandle = transCtxDumpVal(&pConn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
470
      tDebug("%s conn %p construct ahandle %p by %s", CONN_GET_INST_LABEL(pConn), pConn, transMsg.info.ahandle,
dengyihao's avatar
dengyihao 已提交
471
             TMSG_INFO(transMsg.msgType));
S
Shengliang Guan 已提交
472
      if (transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
473 474 475
        int32_t msgType = 0;
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&pConn->ctx, &msgType);
        transMsg.msgType = msgType;
dengyihao's avatar
dengyihao 已提交
476
        tDebug("%s conn %p construct ahandle %p due to brokenlink", CONN_GET_INST_LABEL(pConn), pConn,
S
Shengliang Guan 已提交
477
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
478
      }
dengyihao's avatar
dengyihao 已提交
479
    } else {
dengyihao's avatar
dengyihao 已提交
480
      transMsg.info.ahandle = (pMsg != NULL && pMsg->type != Release && pCtx) ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
481 482 483
    }

    if (pCtx == NULL || pCtx->pSem == NULL) {
S
Shengliang Guan 已提交
484
      if (transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
485 486 487 488 489
        if (pMsg == NULL || REQUEST_NO_RESP(&pMsg->msg) || pMsg->type == Release) {
          destroyCmsg(pMsg);
          once = true;
          continue;
        }
U
ubuntu 已提交
490
      }
dengyihao's avatar
dengyihao 已提交
491
    }
dengyihao's avatar
enh log  
dengyihao 已提交
492

dengyihao's avatar
dengyihao 已提交
493
    if (pMsg == NULL || (pMsg && pMsg->type != Release)) {
dengyihao's avatar
dengyihao 已提交
494 495 496
      if (cliAppCb(pConn, &transMsg, pMsg) != 0) {
        return;
      }
dengyihao's avatar
dengyihao 已提交
497 498
    }
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
499
    tTrace("%s conn %p start to destroy, ref:%d", CONN_GET_INST_LABEL(pConn), pConn, T_REF_VAL_GET(pConn));
D
dapan1121 已提交
500
  } while (!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
501
  transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
502
}
dengyihao's avatar
dengyihao 已提交
503
void cliHandleExcept(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
504
  tTrace("%s conn %p except ref:%d", CONN_GET_INST_LABEL(conn), conn, T_REF_VAL_GET(conn));
dengyihao's avatar
dengyihao 已提交
505 506
  cliHandleExceptImpl(conn, -1);
}
dengyihao's avatar
dengyihao 已提交
507

dengyihao's avatar
dengyihao 已提交
508 509
void cliConnTimeout(uv_timer_t* handle) {
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
510 511
  SCliThrd* pThrd = conn->hostThrd;

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

dengyihao's avatar
dengyihao 已提交
514
  uv_timer_stop(handle);
dengyihao's avatar
dengyihao 已提交
515 516 517
  handle->data = NULL;
  taosArrayPush(pThrd->timerList, &conn->timer);
  conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
518 519

  cliHandleFastFail(conn, UV_ECANCELED);
dengyihao's avatar
dengyihao 已提交
520
}
dengyihao's avatar
dengyihao 已提交
521 522 523 524
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 已提交
525
  uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
526 527
  cliHandleExceptImpl(conn, TSDB_CODE_RPC_TIMEOUT);
}
U
ubuntu 已提交
528 529

void* createConnPool(int size) {
530 531
  // thread local, no lock
  return taosHashInit(size, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
532
}
U
ubuntu 已提交
533
void* destroyConnPool(void* pool) {
dengyihao's avatar
dengyihao 已提交
534
  SConnList* connList = taosHashIterate((SHashObj*)pool, NULL);
dengyihao's avatar
dengyihao 已提交
535
  while (connList != NULL) {
dengyihao's avatar
dengyihao 已提交
536 537
    while (!QUEUE_IS_EMPTY(&connList->conns)) {
      queue*    h = QUEUE_HEAD(&connList->conns);
dengyihao's avatar
dengyihao 已提交
538
      SCliConn* c = QUEUE_DATA(h, SCliConn, q);
U
ubuntu 已提交
539
      cliDestroyConn(c, true);
dengyihao's avatar
dengyihao 已提交
540
    }
dengyihao's avatar
dengyihao 已提交
541
    connList = taosHashIterate((SHashObj*)pool, connList);
dengyihao's avatar
dengyihao 已提交
542
  }
dengyihao's avatar
dengyihao 已提交
543
  taosHashCleanup(pool);
544
  return NULL;
dengyihao's avatar
dengyihao 已提交
545 546
}

dengyihao's avatar
dengyihao 已提交
547
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port) {
dengyihao's avatar
TS-2015  
dengyihao 已提交
548
  char key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
549
  CONN_CONSTRUCT_HASH_KEY(key, ip, port);
dengyihao's avatar
dengyihao 已提交
550 551

  SConnList* plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
552
  if (plist == NULL) {
dengyihao's avatar
dengyihao 已提交
553
    SConnList list = {0};
dengyihao's avatar
dengyihao 已提交
554 555
    taosHashPut((SHashObj*)pool, key, strlen(key), (void*)&list, sizeof(list));
    plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
556
    if (plist == NULL) return NULL;
dengyihao's avatar
dengyihao 已提交
557
    QUEUE_INIT(&plist->conns);
dengyihao's avatar
dengyihao 已提交
558 559
  }

dengyihao's avatar
dengyihao 已提交
560
  if (QUEUE_IS_EMPTY(&plist->conns)) {
dengyihao's avatar
dengyihao 已提交
561 562
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
563 564

  plist->size -= 1;
dengyihao's avatar
dengyihao 已提交
565
  queue*    h = QUEUE_HEAD(&plist->conns);
dengyihao's avatar
dengyihao 已提交
566
  SCliConn* conn = QUEUE_DATA(h, SCliConn, q);
dengyihao's avatar
dengyihao 已提交
567
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
568 569
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
570

dengyihao's avatar
dengyihao 已提交
571 572 573 574
  if (conn->task != NULL) {
    transDQCancel(((SCliThrd*)conn->hostThrd)->timeoutQueue, conn->task);
    conn->task = NULL;
  }
dengyihao's avatar
dengyihao 已提交
575
  return conn;
dengyihao's avatar
dengyihao 已提交
576
}
dengyihao's avatar
dengyihao 已提交
577 578 579 580 581 582
static void addConnToPool(void* pool, SCliConn* conn) {
  if (conn->status == ConnInPool) {
    return;
  }
  allocConnRef(conn, true);

dengyihao's avatar
dengyihao 已提交
583
  SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
584 585 586 587 588 589
  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 已提交
590 591 592 593 594
  if (T_REF_VAL_GET(conn) > 1) {
    transUnrefCliHandle(conn);
  }

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

dengyihao's avatar
dengyihao 已提交
596 597 598 599
  conn->status = ConnInPool;

  if (conn->list == NULL) {
    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 已提交
600
    conn->list = taosHashGet((SHashObj*)pool, conn->ip, strlen(conn->ip));
dengyihao's avatar
dengyihao 已提交
601 602
  } 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 已提交
603
  }
dengyihao's avatar
dengyihao 已提交
604
  QUEUE_PUSH(&conn->list->conns, &conn->q);
dengyihao's avatar
dengyihao 已提交
605
  conn->list->size += 1;
dengyihao's avatar
dengyihao 已提交
606

dengyihao's avatar
dengyihao 已提交
607
  if (conn->list->size >= 250) {
dengyihao's avatar
dengyihao 已提交
608 609
    STaskArg* arg = taosMemoryCalloc(1, sizeof(STaskArg));
    arg->param1 = conn;
dengyihao's avatar
dengyihao 已提交
610
    arg->param2 = thrd;
dengyihao's avatar
dengyihao 已提交
611 612

    STrans* pTransInst = thrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
613 614
    conn->task = transDQSched(thrd->timeoutQueue, doCloseIdleConn, arg, CONN_PERSIST_TIME(pTransInst->idleTime));
  }
dengyihao's avatar
dengyihao 已提交
615
}
dengyihao's avatar
dengyihao 已提交
616
static int32_t allocConnRef(SCliConn* conn, bool update) {
dengyihao's avatar
dengyihao 已提交
617
  if (update) {
dengyihao's avatar
dengyihao 已提交
618
    transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
619
    transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
620
    conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
621 622 623 624
  }
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
625
  exh->refId = transAddExHandle(transGetRefMgt(), exh);
dengyihao's avatar
dengyihao 已提交
626
  conn->refId = exh->refId;
627 628 629 630

  if (conn->refId == -1) {
    taosMemoryFree(exh);
  }
dengyihao's avatar
dengyihao 已提交
631 632 633 634 635
  return 0;
}

static int32_t specifyConnRef(SCliConn* conn, bool update, int64_t handle) {
  if (update) {
dengyihao's avatar
dengyihao 已提交
636
    transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
637 638 639 640 641 642 643 644 645 646 647 648 649
    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 已提交
650
}
dengyihao's avatar
dengyihao 已提交
651

dengyihao's avatar
dengyihao 已提交
652
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
653
  SCliConn*    conn = handle->data;
dengyihao's avatar
dengyihao 已提交
654
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
655
  tDebug("%s conn %p alloc read buf", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
656
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
657
}
U
ubuntu 已提交
658
static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
659
  // impl later
dengyihao's avatar
dengyihao 已提交
660 661 662
  if (handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
663 664
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
665
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
666
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
667
    while (transReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
668
      tDebug("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
669 670 671 672 673 674
      if (pBuf->invalid) {
        cliHandleExcept(conn);
        break;
      } else {
        cliHandleResp(conn);
      }
dengyihao's avatar
dengyihao 已提交
675
    }
dengyihao's avatar
dengyihao 已提交
676 677
    return;
  }
dengyihao's avatar
dengyihao 已提交
678

679
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
680 681 682
    // 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 已提交
683
    tTrace("%s conn %p read empty", CONN_GET_INST_LABEL(conn), conn);
684 685
    return;
  }
dengyihao's avatar
fix bug  
dengyihao 已提交
686
  if (nread < 0) {
dengyihao's avatar
dengyihao 已提交
687
    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 已提交
688
    conn->broken = true;
U
ubuntu 已提交
689
    cliHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
690
  }
dengyihao's avatar
dengyihao 已提交
691
}
dengyihao's avatar
dengyihao 已提交
692

dengyihao's avatar
dengyihao 已提交
693
static SCliConn* cliCreateConn(SCliThrd* pThrd) {
wafwerar's avatar
wafwerar 已提交
694
  SCliConn* conn = taosMemoryCalloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
695
  // read/write stream handle
G
gccgdb1234 已提交
696
  conn->stream = (uv_stream_t*)taosMemoryMalloc(sizeof(uv_tcp_t));
dengyihao's avatar
dengyihao 已提交
697 698 699
  uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
  conn->stream->data = conn;

dengyihao's avatar
dengyihao 已提交
700 701 702 703 704 705 706 707
  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 已提交
708

dengyihao's avatar
dengyihao 已提交
709
  conn->connReq.data = conn;
dengyihao's avatar
dengyihao 已提交
710 711
  transReqQueueInit(&conn->wreqQueue);

dengyihao's avatar
dengyihao 已提交
712
  transQueueInit(&conn->cliMsgs, NULL);
dengyihao's avatar
opt rpc  
dengyihao 已提交
713 714

  transInitBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
715
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
716
  conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
717 718
  conn->status = ConnNormal;
  conn->broken = 0;
dengyihao's avatar
dengyihao 已提交
719
  transRefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
720

dengyihao's avatar
dengyihao 已提交
721
  atomic_add_fetch_32(&pThrd->connCount, 1);
dengyihao's avatar
dengyihao 已提交
722
  allocConnRef(conn, false);
dengyihao's avatar
dengyihao 已提交
723

dengyihao's avatar
dengyihao 已提交
724 725
  return conn;
}
U
ubuntu 已提交
726
static void cliDestroyConn(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
727
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
728
  tTrace("%s conn %p remove from conn pool", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
729 730
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
731
  transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
732
  transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
opt rpc  
dengyihao 已提交
733
  conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
734

dengyihao's avatar
dengyihao 已提交
735 736 737 738 739 740 741
  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 已提交
742
    taosArrayPush(pThrd->timerList, &conn->timer);
dengyihao's avatar
dengyihao 已提交
743 744
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
745

dengyihao's avatar
dengyihao 已提交
746
  if (clear) {
dengyihao's avatar
dengyihao 已提交
747
    if (!uv_is_closing((uv_handle_t*)conn->stream)) {
dengyihao's avatar
dengyihao 已提交
748
      uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
749 750
      uv_close((uv_handle_t*)conn->stream, cliDestroy);
    }
751
  }
dengyihao's avatar
dengyihao 已提交
752
}
U
ubuntu 已提交
753
static void cliDestroy(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
754 755 756
  if (uv_handle_get_type(handle) != UV_TCP || handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
757
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
758
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
759 760
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
dengyihao's avatar
dengyihao 已提交
761 762
    taosArrayPush(pThrd->timerList, &conn->timer);
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
763 764
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
765 766 767
  int32_t* oVal = taosHashGet(pThrd->connLimitCache, conn->ip, strlen(conn->ip));
  int32_t  nVal = oVal == NULL ? 0 : (*oVal) - 1;
  taosHashPut(pThrd->connLimitCache, conn->ip, strlen(conn->ip), &nVal, sizeof(nVal));
dengyihao's avatar
dengyihao 已提交
768

dengyihao's avatar
dengyihao 已提交
769 770
  atomic_sub_fetch_32(&pThrd->connCount, 1);

dengyihao's avatar
dengyihao 已提交
771
  transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
772
  transRemoveExHandle(transGetRefMgt(), conn->refId);
wafwerar's avatar
wafwerar 已提交
773 774
  taosMemoryFree(conn->ip);
  taosMemoryFree(conn->stream);
dengyihao's avatar
dengyihao 已提交
775 776 777

  cliDestroyConnMsgs(conn, true);

dengyihao's avatar
dengyihao 已提交
778
  tTrace("%s conn %p destroy successfully", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
779
  transReqQueueClear(&conn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
780
  transDestroyBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
781

wafwerar's avatar
wafwerar 已提交
782
  taosMemoryFree(conn);
dengyihao's avatar
dengyihao 已提交
783
}
dengyihao's avatar
dengyihao 已提交
784
static bool cliHandleNoResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
785 786
  bool res = false;
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
787
    SCliMsg* pMsg = transQueueGet(&conn->cliMsgs, 0);
dengyihao's avatar
dengyihao 已提交
788
    if (REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
789
      transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
790 791 792 793 794
      destroyCmsg(pMsg);
      res = true;
    }
    if (res == true) {
      if (cliMaySendCachedMsg(conn) == false) {
dengyihao's avatar
dengyihao 已提交
795
        SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
796
        addConnToPool(thrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
797 798 799
        res = false;
      } else {
        res = true;
dengyihao's avatar
dengyihao 已提交
800 801 802 803 804
      }
    }
  }
  return res;
}
U
ubuntu 已提交
805
static void cliSendCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
806 807
  SCliConn* pConn = transReqQueueRemove(req);
  if (pConn == NULL) return;
dengyihao's avatar
dengyihao 已提交
808

dengyihao's avatar
dengyihao 已提交
809 810 811
  SCliMsg* pMsg = !transQueueEmpty(&pConn->cliMsgs) ? transQueueGet(&pConn->cliMsgs, 0) : NULL;
  if (pMsg != NULL) {
    int64_t cost = taosGetTimestampUs() - pMsg->st;
dengyihao's avatar
dengyihao 已提交
812
    if (cost > 1000 * 20) {
dengyihao's avatar
dengyihao 已提交
813 814 815 816
      tWarn("%s conn %p send cost:%dus, send exception", CONN_GET_INST_LABEL(pConn), pConn, (int)cost);
    }
  }

dengyihao's avatar
dengyihao 已提交
817
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
818
    tTrace("%s conn %p data already was written out", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
819
  } else {
dengyihao's avatar
dengyihao 已提交
820 821 822 823
    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 已提交
824 825
    return;
  }
dengyihao's avatar
dengyihao 已提交
826
  if (cliHandleNoResp(pConn) == true) {
dengyihao's avatar
dengyihao 已提交
827
    tTrace("%s conn %p no resp required", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
828 829
    return;
  }
dengyihao's avatar
dengyihao 已提交
830
  uv_read_start((uv_stream_t*)pConn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
831
}
dengyihao's avatar
dengyihao 已提交
832 833 834 835 836 837 838 839 840 841
void cliSendBatch(SCliConn* pConn) {
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;

  SCliBatch* pBatch = pConn->pBatch;
  int32_t    wLen = pBatch->wLen;

  uv_buf_t* wb = taosMemoryCalloc(wLen, sizeof(uv_buf_t));
  int       i = 0;

dengyihao's avatar
dengyihao 已提交
842 843
  queue* h = NULL;
  QUEUE_FOREACH(h, &pBatch->wq) {
dengyihao's avatar
dengyihao 已提交
844 845 846 847 848 849 850 851 852
    SCliMsg* pCliMsg = QUEUE_DATA(h, SCliMsg, q);

    STransConnCtx* pCtx = pCliMsg->ctx;

    STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
    if (pMsg->pCont == 0) {
      pMsg->pCont = (void*)rpcMallocCont(0);
      pMsg->contLen = 0;
    }
dengyihao's avatar
dengyihao 已提交
853

dengyihao's avatar
dengyihao 已提交
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
    int            msgLen = transMsgLenFromCont(pMsg->contLen);
    STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);

    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);
    }
    pHead->timestamp = taosHton64(taosGetTimestampUs());
dengyihao's avatar
dengyihao 已提交
869
    msgLen = (int32_t)ntohl((uint32_t)(pHead->msgLen));
dengyihao's avatar
dengyihao 已提交
870 871 872 873 874 875

    wb[i++] = uv_buf_init((char*)pHead, msgLen);
  }

  uv_write_t* req = taosMemoryCalloc(1, sizeof(uv_write_t));
  req->data = pConn;
dengyihao's avatar
dengyihao 已提交
876 877
  tDebug("%p conn %p start to send batch msg, batch size:%d, msgLen:%d", CONN_GET_INST_LABEL(pConn), pConn,
         pBatch->wLen, pBatch->batchSize);
dengyihao's avatar
dengyihao 已提交
878 879 880
  uv_write(req, (uv_stream_t*)pConn->stream, wb, wLen, cliSendBatchCb);
  taosMemoryFree(wb);
}
U
ubuntu 已提交
881
void cliSend(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
882 883 884 885 886
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;

  if (transQueueEmpty(&pConn->cliMsgs)) {
    tError("%s conn %p not msg to send", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
887
    cliHandleExcept(pConn);
dengyihao's avatar
dengyihao 已提交
888 889
    return;
  }
dengyihao's avatar
dengyihao 已提交
890 891

  SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
892
  CONN_GET_NEXT_SENDMSG(pConn);
dengyihao's avatar
dengyihao 已提交
893 894
  pCliMsg->sent = 1;

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

U
ubuntu 已提交
897
  STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
dengyihao's avatar
dengyihao 已提交
898 899 900 901
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
dengyihao's avatar
dengyihao 已提交
902

dengyihao's avatar
dengyihao 已提交
903
  int            msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
904
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
dengyihao's avatar
dengyihao 已提交
905

dengyihao's avatar
dengyihao 已提交
906 907 908 909 910 911 912 913 914 915 916
  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 已提交
917
  pHead->timestamp = taosHton64(taosGetTimestampUs());
dengyihao's avatar
dengyihao 已提交
918

dengyihao's avatar
dengyihao 已提交
919 920 921
  if (pHead->persist == 1) {
    CONN_SET_PERSIST_BY_APP(pConn);
  }
dengyihao's avatar
dengyihao 已提交
922

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

dengyihao's avatar
dengyihao 已提交
925
  if (pTransInst->startTimer != NULL && pTransInst->startTimer(0, pMsg->msgType)) {
dengyihao's avatar
dengyihao 已提交
926
    uv_timer_t* timer = taosArrayGetSize(pThrd->timerList) > 0 ? *(uv_timer_t**)taosArrayPop(pThrd->timerList) : NULL;
dengyihao's avatar
dengyihao 已提交
927 928
    if (timer == NULL) {
      timer = taosMemoryCalloc(1, sizeof(uv_timer_t));
dengyihao's avatar
dengyihao 已提交
929
      tDebug("no available timer, create a timer %p", timer);
dengyihao's avatar
dengyihao 已提交
930 931 932 933 934
      uv_timer_init(pThrd->loop, timer);
    }
    timer->data = pConn;
    pConn->timer = timer;

dengyihao's avatar
dengyihao 已提交
935 936 937
    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 已提交
938

dengyihao's avatar
dengyihao 已提交
939 940 941 942 943 944 945
  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 已提交
946
  }
dengyihao's avatar
dengyihao 已提交
947

dengyihao's avatar
dengyihao 已提交
948 949
  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 已提交
950

dengyihao's avatar
dengyihao 已提交
951
  uv_buf_t    wb = uv_buf_init((char*)pHead, msgLen);
dengyihao's avatar
dengyihao 已提交
952
  uv_write_t* req = transReqQueuePush(&pConn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
953 954 955

  int status = uv_write(req, (uv_stream_t*)pConn->stream, &wb, 1, cliSendCb);
  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
956
    tGError("%s conn %p failed to send msg:%s, errmsg:%s", CONN_GET_INST_LABEL(pConn), pConn, TMSG_INFO(pMsg->msgType),
dengyihao's avatar
dengyihao 已提交
957 958 959
            uv_err_name(status));
    cliHandleExcept(pConn);
  }
U
ubuntu 已提交
960 961
  return;
_RETURN:
dengyihao's avatar
dengyihao 已提交
962
  return;
dengyihao's avatar
dengyihao 已提交
963
}
dengyihao's avatar
dengyihao 已提交
964 965

static SCliBatch* cliDumpBatch(SCliBatch* pBatch) {
dengyihao's avatar
dengyihao 已提交
966
  SCliBatch* pNewBatch = taosMemoryCalloc(1, sizeof(SCliBatch));
dengyihao's avatar
dengyihao 已提交
967 968

  QUEUE_INIT(&pNewBatch->wq);
dengyihao's avatar
dengyihao 已提交
969
  QUEUE_MOVE(&pBatch->wq, &pNewBatch->wq);
dengyihao's avatar
dengyihao 已提交
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985

  pNewBatch->batchSize = pBatch->batchSize;
  pNewBatch->batch = pBatch->batch;
  pNewBatch->wLen = pBatch->wLen;
  pNewBatch->dst = strdup(pBatch->dst);
  pNewBatch->ip = strdup(pBatch->ip);
  pNewBatch->port = pBatch->port;

  QUEUE_INIT(&pBatch->wq);
  pBatch->batchSize = 0;
  pBatch->batch = 0;
  pBatch->wLen = 0;

  return pNewBatch;
}
static void cliDestroyBatch(SCliBatch* pBatch) {
dengyihao's avatar
dengyihao 已提交
986
  while (!QUEUE_IS_EMPTY(&pBatch->wq)) {
dengyihao's avatar
dengyihao 已提交
987
    queue*   h = QUEUE_HEAD(&pBatch->wq);
dengyihao's avatar
dengyihao 已提交
988
    SCliMsg* p = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
989

dengyihao's avatar
dengyihao 已提交
990
    QUEUE_REMOVE(&p->q);
dengyihao's avatar
dengyihao 已提交
991 992 993 994 995 996
    destroyCmsg(p);
  }
  taosMemoryFree(pBatch->ip);
  taosMemoryFree(pBatch->dst);
  taosMemoryFree(pBatch);
}
dengyihao's avatar
dengyihao 已提交
997 998
static void cliHandleBatchReq(SCliBatch* pBatch, SCliThrd* pThrd) {
  if (pBatch->wLen == 0 || QUEUE_IS_EMPTY(&pBatch->wq)) {
dengyihao's avatar
dengyihao 已提交
999 1000 1001 1002 1003 1004
    return;
  }
  STrans* pTransInst = pThrd->pTransInst;

  SCliBatch* pNewBatch = cliDumpBatch(pBatch);

dengyihao's avatar
dengyihao 已提交
1005 1006 1007 1008 1009 1010 1011 1012
  SCliConn* conn = getConnFromPool(pThrd->pool, pNewBatch->ip, pNewBatch->port);

  if (conn == NULL && 0 != cliPreCheckSessionLimit(pThrd, pNewBatch->ip, pNewBatch->port)) {
    tError("%s failed to send batch msg, batch size:%d, msgLen: %d", pTransInst->label, pNewBatch->wLen,
           pNewBatch->batchSize);
    cliDestroyBatch(pNewBatch);
    return;
  }
dengyihao's avatar
dengyihao 已提交
1013 1014 1015
  if (conn == NULL) {
    conn = cliCreateConn(pThrd);
    conn->pBatch = pNewBatch;
dengyihao's avatar
dengyihao 已提交
1016
    conn->ip = strdup(pNewBatch->dst);
dengyihao's avatar
dengyihao 已提交
1017

dengyihao's avatar
dengyihao 已提交
1018 1019 1020
    char*    ip = pNewBatch->ip;
    uint16_t port = pNewBatch->port;
    uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, ip);
dengyihao's avatar
dengyihao 已提交
1021 1022 1023 1024 1025 1026
    if (ipaddr == 0xffffffff) {
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

dengyihao's avatar
dengyihao 已提交
1027
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1028 1029 1030 1031 1032
      return;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = ipaddr;
dengyihao's avatar
dengyihao 已提交
1033
    addr.sin_port = (uint16_t)htons(port);
dengyihao's avatar
dengyihao 已提交
1034

dengyihao's avatar
dengyihao 已提交
1035
    tTrace("%s conn %p try to connect to %s", pTransInst->label, conn, pBatch->dst);
dengyihao's avatar
dengyihao 已提交
1036 1037
    int32_t fd = taosCreateSocketWithTimeout(TRANS_CONN_TIMEOUT * 4);
    if (fd == -1) {
dengyihao's avatar
dengyihao 已提交
1038 1039 1040
      tError("%s conn %p failed to create socket, reason:%s", transLabel(pTransInst), conn,
             tstrerror(TAOS_SYSTEM_ERROR(errno)));
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1041 1042 1043 1044
      return;
    }
    int ret = uv_tcp_open((uv_tcp_t*)conn->stream, fd);
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1045 1046
      tError("%s conn %p failed to set stream, reason:%s", transLabel(pTransInst), conn, uv_err_name(ret));
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1047 1048 1049 1050
      return;
    }
    ret = transSetConnOption((uv_tcp_t*)conn->stream);
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1051 1052
      tError("%s conn %p failed to set socket opt, reason:%s", transLabel(pTransInst), conn, uv_err_name(ret));
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061
      return;
    }

    ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
    if (ret != 0) {
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
1062
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1063 1064 1065 1066 1067 1068 1069
      return;
    }
    uv_timer_start(conn->timer, cliConnTimeout, TRANS_CONN_TIMEOUT, 0);
    return;
  }

  conn->pBatch = pNewBatch;
dengyihao's avatar
dengyihao 已提交
1070
  cliSendBatch(conn);
dengyihao's avatar
dengyihao 已提交
1071 1072
}
static void cliSendBatchCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
1073 1074 1075
  SCliConn*  conn = req->data;
  SCliThrd*  thrd = conn->hostThrd;
  SCliBatch* p = conn->pBatch;
dengyihao's avatar
dengyihao 已提交
1076

dengyihao's avatar
dengyihao 已提交
1077 1078 1079
  conn->pBatch = NULL;

  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
1080
    tDebug("%p conn %p failed to send batch msg, batch size:%d, msgLen:%d, reason:%s", CONN_GET_INST_LABEL(conn), conn,
dengyihao's avatar
dengyihao 已提交
1081
           p->wLen, p->batchSize, uv_err_name(status));
dengyihao's avatar
dengyihao 已提交
1082 1083
    cliHandleExcept(conn);
  } else {
dengyihao's avatar
dengyihao 已提交
1084 1085
    tDebug("%p conn %p succ to send batch msg, batch size:%d, msgLen:%d", CONN_GET_INST_LABEL(conn), conn, p->wLen,
           p->batchSize);
dengyihao's avatar
dengyihao 已提交
1086 1087
    addConnToPool(thrd->pool, conn);
  }
dengyihao's avatar
dengyihao 已提交
1088 1089 1090

  cliDestroyBatch(p);
  taosMemoryFree(req);
dengyihao's avatar
dengyihao 已提交
1091
}
dengyihao's avatar
dengyihao 已提交
1092
static void cliHandleFastFail(SCliConn* pConn, int status) {
dengyihao's avatar
dengyihao 已提交
1093
  SCliThrd* pThrd = pConn->hostThrd;
dengyihao's avatar
dengyihao 已提交
1094
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1095 1096 1097

  if (status == -1) status = ENETUNREACH;

dengyihao's avatar
dengyihao 已提交
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
  if (pConn->pBatch == NULL) {
    SCliMsg* pMsg = transQueueGet(&pConn->cliMsgs, 0);

    STraceId* trace = &pMsg->msg.info.traceId;
    tGError("%s msg %s failed to send, conn %p failed to connect to %s, reason: %s", CONN_GET_INST_LABEL(pConn),
            TMSG_INFO(pMsg->msg.msgType), pConn, pConn->ip, uv_strerror(status));

    if (pMsg != NULL && REQUEST_NO_RESP(&pMsg->msg) &&
        (pTransInst->failFastFp != NULL && pTransInst->failFastFp(pMsg->msg.msgType))) {
      SFailFastItem* item = taosHashGet(pThrd->failFastCache, pConn->ip, strlen(pConn->ip));
      int64_t        cTimestamp = taosGetTimestampMs();
      if (item != NULL) {
        int32_t elapse = cTimestamp - item->timestamp;
        if (elapse >= 0 && elapse <= pTransInst->failFastInterval) {
          item->count++;
        } else {
          item->count = 1;
          item->timestamp = cTimestamp;
        }
dengyihao's avatar
dengyihao 已提交
1117
      } else {
dengyihao's avatar
dengyihao 已提交
1118 1119
        SFailFastItem item = {.count = 1, .timestamp = cTimestamp};
        taosHashPut(pThrd->failFastCache, pConn->ip, strlen(pConn->ip), &item, sizeof(SFailFastItem));
dengyihao's avatar
dengyihao 已提交
1120 1121
      }
    }
dengyihao's avatar
dengyihao 已提交
1122
  } else {
dengyihao's avatar
dengyihao 已提交
1123 1124
    tError("%s batch msg failed to send, conn %p failed to connect to %s, reason: %s", CONN_GET_INST_LABEL(pConn),
           pConn, pConn->ip, uv_strerror(status));
dengyihao's avatar
dengyihao 已提交
1125 1126
    cliDestroyBatch(pConn->pBatch);
    pConn->pBatch = NULL;
dengyihao's avatar
dengyihao 已提交
1127 1128 1129
  }
  cliHandleExcept(pConn);
}
dengyihao's avatar
dengyihao 已提交
1130

dengyihao's avatar
dengyihao 已提交
1131 1132 1133
void cliConnCb(uv_connect_t* req, int status) {
  SCliConn* pConn = req->data;
  SCliThrd* pThrd = pConn->hostThrd;
dengyihao's avatar
dengyihao 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
  bool      timeout = false;

  if (pConn->timer == NULL) {
    timeout = true;
  } else {
    uv_timer_stop(pConn->timer);
    pConn->timer->data = NULL;
    taosArrayPush(pThrd->timerList, &pConn->timer);
    pConn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
1144 1145

  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
1146 1147 1148 1149 1150
    if (timeout == false) {
      cliHandleFastFail(pConn, status);
    } else if (timeout == true) {
      // already deal by timeout
    }
1151
    return;
dengyihao's avatar
dengyihao 已提交
1152
  }
dengyihao's avatar
dengyihao 已提交
1153

dengyihao's avatar
dengyihao 已提交
1154
  int32_t* oVal = taosHashGet(pThrd->connLimitCache, pConn->ip, strlen(pConn->ip));
dengyihao's avatar
dengyihao 已提交
1155
  int32_t  nVal = oVal == NULL ? 0 : (*oVal) + 1;
dengyihao's avatar
dengyihao 已提交
1156
  taosHashPut(pThrd->connLimitCache, pConn->ip, strlen(pConn->ip), &nVal, sizeof(nVal));
dengyihao's avatar
dengyihao 已提交
1157 1158 1159

  struct sockaddr peername, sockname;
  int             addrlen = sizeof(peername);
dengyihao's avatar
dengyihao 已提交
1160
  uv_tcp_getpeername((uv_tcp_t*)pConn->stream, &peername, &addrlen);
dengyihao's avatar
dengyihao 已提交
1161
  transSockInfo2Str(&peername, pConn->dst);
dengyihao's avatar
dengyihao 已提交
1162

dengyihao's avatar
dengyihao 已提交
1163 1164
  addrlen = sizeof(sockname);
  uv_tcp_getsockname((uv_tcp_t*)pConn->stream, &sockname, &addrlen);
dengyihao's avatar
dengyihao 已提交
1165
  transSockInfo2Str(&sockname, pConn->src);
dengyihao's avatar
dengyihao 已提交
1166

dengyihao's avatar
dengyihao 已提交
1167
  tTrace("%s conn %p connect to server successfully", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1168 1169 1170 1171 1172
  if (pConn->pBatch != NULL) {
    cliSendBatch(pConn);
  } else {
    cliSend(pConn);
  }
dengyihao's avatar
dengyihao 已提交
1173 1174
}

dengyihao's avatar
dengyihao 已提交
1175
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1176 1177 1178 1179 1180
  if (!transAsyncPoolIsEmpty(pThrd->asyncPool)) {
    pThrd->stopMsg = pMsg;
    return;
  }
  pThrd->stopMsg = NULL;
dengyihao's avatar
dengyihao 已提交
1181
  pThrd->quit = true;
U
ubuntu 已提交
1182
  tDebug("cli work thread %p start to quit", pThrd);
dengyihao's avatar
dengyihao 已提交
1183
  destroyCmsg(pMsg);
dengyihao's avatar
fix bug  
dengyihao 已提交
1184
  destroyConnPool(pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1185
  uv_walk(pThrd->loop, cliWalkCb, NULL);
dengyihao's avatar
dengyihao 已提交
1186
}
dengyihao's avatar
dengyihao 已提交
1187
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1188
  int64_t    refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
1189
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1190
  if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
1191
    tDebug("%" PRId64 " already released", refId);
dengyihao's avatar
dengyihao 已提交
1192 1193
    destroyCmsg(pMsg);
    return;
dengyihao's avatar
dengyihao 已提交
1194 1195 1196
  }

  SCliConn* conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
1197
  transReleaseExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1198
  tDebug("%s conn %p start to release to inst", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
1199

dengyihao's avatar
dengyihao 已提交
1200 1201
  if (T_REF_VAL_GET(conn) == 2) {
    transUnrefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
1202 1203
    if (!transQueuePush(&conn->cliMsgs, pMsg)) {
      return;
dengyihao's avatar
dengyihao 已提交
1204 1205
    }
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
1206 1207 1208
  } else {
    tError("%s conn %p already released", CONN_GET_INST_LABEL(conn), conn);
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1209 1210
  }
}
dengyihao's avatar
dengyihao 已提交
1211
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1212
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1213
  pThrd->cvtAddr = pCtx->cvtAddr;
dengyihao's avatar
dengyihao 已提交
1214 1215
  destroyCmsg(pMsg);
}
U
ubuntu 已提交
1216

dengyihao's avatar
dengyihao 已提交
1217
SCliConn* cliGetConn(SCliMsg* pMsg, SCliThrd* pThrd, bool* ignore) {
dengyihao's avatar
dengyihao 已提交
1218 1219 1220 1221
  STransConnCtx* pCtx = pMsg->ctx;
  SCliConn*      conn = NULL;

  int64_t refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
1222
  if (refId != 0) {
dengyihao's avatar
dengyihao 已提交
1223
    SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1224
    if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
1225
      tError("failed to get conn, refId: %" PRId64 "", refId);
dengyihao's avatar
dengyihao 已提交
1226 1227
      *ignore = true;
      return NULL;
dengyihao's avatar
dengyihao 已提交
1228 1229
    } else {
      conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
1230 1231
      if (conn == NULL) {
        conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
dengyihao's avatar
dengyihao 已提交
1232
        if (conn != NULL) specifyConnRef(conn, true, refId);
dengyihao's avatar
dengyihao 已提交
1233
      }
dengyihao's avatar
dengyihao 已提交
1234
      transReleaseExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1235 1236 1237
    }
    return conn;
  };
dengyihao's avatar
dengyihao 已提交
1238 1239 1240

  conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
1241
    tTrace("%s conn %p get from conn pool:%p", CONN_GET_INST_LABEL(conn), conn, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1242
  } else {
dengyihao's avatar
dengyihao 已提交
1243
    tTrace("%s not found conn in conn pool:%p", ((STrans*)pThrd->pTransInst)->label, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1244
  }
dengyihao's avatar
dengyihao 已提交
1245 1246
  return conn;
}
dengyihao's avatar
dengyihao 已提交
1247
FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr) {
dengyihao's avatar
dengyihao 已提交
1248 1249 1250
  if (pCvtAddr->cvt == false) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1251 1252 1253
  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 已提交
1254 1255
  }
}
dengyihao's avatar
dengyihao 已提交
1256

dengyihao's avatar
dengyihao 已提交
1257
FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx) {
dengyihao's avatar
dengyihao 已提交
1258
  if (code != 0) return false;
dengyihao's avatar
dengyihao 已提交
1259
  // if (pCtx->retryCnt == 0) return false;
dengyihao's avatar
dengyihao 已提交
1260 1261 1262
  if (transEpSetIsEqual(&pCtx->epSet, &pCtx->origEpSet)) return false;
  return true;
}
dengyihao's avatar
dengyihao 已提交
1263
FORCE_INLINE int32_t cliBuildExceptResp(SCliMsg* pMsg, STransMsg* pResp) {
dengyihao's avatar
dengyihao 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  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 已提交
1275 1276 1277 1278 1279
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);
1280 1281 1282 1283
    if (addr == 0xffffffff) {
      terrno = TAOS_SYSTEM_ERROR(errno);
      tError("failed to get ip from fqdn:%s since %s", fqdn, terrstr());
      return addr;
dengyihao's avatar
dengyihao 已提交
1284 1285
    }

dengyihao's avatar
dengyihao 已提交
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    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 已提交
1296

dengyihao's avatar
dengyihao 已提交
1297
static int32_t cliPreCheckSessionLimit(SCliThrd* pThrd, char* ip, uint16_t port) {
dengyihao's avatar
dengyihao 已提交
1298 1299
  STrans* pTransInst = pThrd->pTransInst;

dengyihao's avatar
dengyihao 已提交
1300 1301 1302
  // STransConnCtx* pCtx = pMsg->ctx;
  // char*          ip = EPSET_GET_INUSE_IP(&pCtx->epSet);
  // int32_t        port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1303 1304 1305 1306

  char key[TSDB_FQDN_LEN + 64] = {0};
  CONN_CONSTRUCT_HASH_KEY(key, ip, port);

dengyihao's avatar
dengyihao 已提交
1307
  int32_t* val = taosHashGet(pThrd->connLimitCache, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
1308 1309
  if (val == NULL) return 0;

dengyihao's avatar
dengyihao 已提交
1310
  if (*val >= pTransInst->connLimitNum) {
dengyihao's avatar
dengyihao 已提交
1311 1312 1313 1314
    return -1;
  }
  return 0;
}
dengyihao's avatar
dengyihao 已提交
1315
void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
formate  
dengyihao 已提交
1316
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1317
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1318

dengyihao's avatar
dengyihao 已提交
1319
  cliMayCvtFqdnToIp(&pCtx->epSet, &pThrd->cvtAddr);
1320
  STraceId* trace = &pMsg->msg.info.traceId;
dengyihao's avatar
dengyihao 已提交
1321 1322
  char*     ip = EPSET_GET_INUSE_IP(&pCtx->epSet);
  uint16_t  port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1323

dengyihao's avatar
dengyihao 已提交
1324
  if (!EPSET_IS_VALID(&pCtx->epSet)) {
1325
    tGError("%s, msg %s sent with invalid epset", pTransInst->label, TMSG_INFO(pMsg->msg.msgType));
dengyihao's avatar
dengyihao 已提交
1326
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1327 1328
    return;
  }
dengyihao's avatar
dengyihao 已提交
1329

dengyihao's avatar
dengyihao 已提交
1330
  if (REQUEST_NO_RESP(&pMsg->msg) && (pTransInst->failFastFp != NULL && pTransInst->failFastFp(pMsg->msg.msgType))) {
dengyihao's avatar
dengyihao 已提交
1331
    char key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
1332 1333 1334 1335
    CONN_CONSTRUCT_HASH_KEY(key, ip, port);

    SFailFastItem* item = taosHashGet(pThrd->failFastCache, key, strlen(key));
    if (item != NULL) {
dengyihao's avatar
dengyihao 已提交
1336 1337
      int32_t elapse = (int32_t)(taosGetTimestampMs() - item->timestamp);
      if (item->count >= pTransInst->failFastThreshold && (elapse >= 0 && elapse <= pTransInst->failFastInterval)) {
dengyihao's avatar
dengyihao 已提交
1338 1339
        tGTrace("%s, msg %s cancel to send, reason: failed to connect %s:%d: count: %d, at %d", pTransInst->label,
                TMSG_INFO(pMsg->msg.msgType), ip, port, item->count, elapse);
dengyihao's avatar
dengyihao 已提交
1340 1341 1342 1343 1344 1345
        destroyCmsg(pMsg);
        return;
      }
    }
  }

dengyihao's avatar
dengyihao 已提交
1346 1347 1348
  bool      ignore = false;
  SCliConn* conn = cliGetConn(pMsg, pThrd, &ignore);
  if (ignore == true) {
dengyihao's avatar
dengyihao 已提交
1349
    // persist conn already release by server
dengyihao's avatar
dengyihao 已提交
1350 1351
    STransMsg resp;
    cliBuildExceptResp(pMsg, &resp);
dengyihao's avatar
dengyihao 已提交
1352 1353 1354
    if (pMsg->type != Release) {
      pTransInst->cfp(pTransInst->parent, &resp, NULL);
    }
dengyihao's avatar
dengyihao 已提交
1355
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1356 1357
    return;
  }
dengyihao's avatar
dengyihao 已提交
1358

dengyihao's avatar
dengyihao 已提交
1359
  if (conn == NULL && REQUEST_NO_RESP(&pMsg->msg) && 0 != cliPreCheckSessionLimit(pThrd, ip, port)) {
dengyihao's avatar
dengyihao 已提交
1360 1361 1362 1363 1364 1365
    tGTrace("%s, msg %s cancel to send, reason: %s", pTransInst->label, TMSG_INFO(pMsg->msg.msgType),
            tstrerror(TSDB_CODE_RPC_MAX_SESSIONS));
    destroyCmsg(pMsg);
    return;
  }

dengyihao's avatar
dengyihao 已提交
1366
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
1367
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1368
    transQueuePush(&conn->cliMsgs, pMsg);
U
ubuntu 已提交
1369
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
1370
  } else {
U
ubuntu 已提交
1371
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
1372 1373 1374 1375

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

dengyihao's avatar
dengyihao 已提交
1376
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1377
    transQueuePush(&conn->cliMsgs, pMsg);
dengyihao's avatar
dengyihao 已提交
1378

dengyihao's avatar
dengyihao 已提交
1379
    char     key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
1380
    char*    fqdn = EPSET_GET_INUSE_IP(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1381
    uint16_t port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1382
    CONN_CONSTRUCT_HASH_KEY(key, fqdn, port);
dengyihao's avatar
dengyihao 已提交
1383 1384

    conn->ip = strdup(key);
dengyihao's avatar
dengyihao 已提交
1385

dengyihao's avatar
dengyihao 已提交
1386
    uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, fqdn);
1387 1388 1389 1390 1391 1392 1393 1394 1395
    if (ipaddr == 0xffffffff) {
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

      cliHandleExcept(conn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
1396

dengyihao's avatar
dengyihao 已提交
1397
    struct sockaddr_in addr;
1398
    addr.sin_family = AF_INET;
1399
    addr.sin_addr.s_addr = ipaddr;
dengyihao's avatar
dengyihao 已提交
1400
    addr.sin_port = (uint16_t)htons(port);
dengyihao's avatar
dengyihao 已提交
1401

dengyihao's avatar
dengyihao 已提交
1402
    tGTrace("%s conn %p try to connect to %s", pTransInst->label, conn, conn->ip);
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    int32_t fd = taosCreateSocketWithTimeout(TRANS_CONN_TIMEOUT * 4);
    if (fd == -1) {
      tGError("%s conn %p failed to create socket, reason:%s", transLabel(pTransInst), conn,
              tstrerror(TAOS_SYSTEM_ERROR(errno)));
      cliHandleExcept(conn);
      errno = 0;
      return;
    }
    int ret = uv_tcp_open((uv_tcp_t*)conn->stream, fd);
    if (ret != 0) {
      tGError("%s conn %p failed to set stream, reason:%s", transLabel(pTransInst), conn, uv_err_name(ret));
      cliHandleExcept(conn);
      return;
    }
    ret = transSetConnOption((uv_tcp_t*)conn->stream);
    if (ret != 0) {
      tGError("%s conn %p failed to set socket opt, reason:%s", transLabel(pTransInst), conn, uv_err_name(ret));
      cliHandleExcept(conn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
1423

1424
    ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
dengyihao's avatar
dengyihao 已提交
1425
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1426 1427 1428 1429 1430
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

dengyihao's avatar
dengyihao 已提交
1431
      cliHandleFastFail(conn, ret);
dengyihao's avatar
dengyihao 已提交
1432 1433
      return;
    }
dengyihao's avatar
dengyihao 已提交
1434
    uv_timer_start(conn->timer, cliConnTimeout, TRANS_CONN_TIMEOUT, 0);
dengyihao's avatar
dengyihao 已提交
1435
  }
dengyihao's avatar
dengyihao 已提交
1436
  tGTrace("%s conn %p ready", pTransInst->label, conn);
dengyihao's avatar
dengyihao 已提交
1437
}
dengyihao's avatar
dengyihao 已提交
1438

dengyihao's avatar
dengyihao 已提交
1439
static void cliNoBatchDealReq(queue* wq, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1440
  int count = 0;
dengyihao's avatar
dengyihao 已提交
1441

dengyihao's avatar
dengyihao 已提交
1442 1443
  while (!QUEUE_IS_EMPTY(wq)) {
    queue* h = QUEUE_HEAD(wq);
dengyihao's avatar
dengyihao 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    QUEUE_REMOVE(h);

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);

    count++;
  }
  if (count >= 2) {
    tTrace("cli process batch size:%d", count);
  }
}

dengyihao's avatar
dengyihao 已提交
1456
static void cliBatchDealReq(queue* wq, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1457
  int count = 0;
dengyihao's avatar
dengyihao 已提交
1458 1459
  while (!QUEUE_IS_EMPTY(wq)) {
    queue* h = QUEUE_HEAD(wq);
dengyihao's avatar
dengyihao 已提交
1460
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
1461 1462

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1463
    if (pMsg->type == Normal && REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
1464 1465 1466 1467 1468 1469 1470
      STransConnCtx* pCtx = pMsg->ctx;

      char*    ip = EPSET_GET_INUSE_IP(&pCtx->epSet);
      uint32_t port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
      char     key[TSDB_FQDN_LEN + 64] = {0};
      CONN_CONSTRUCT_HASH_KEY(key, ip, port);

dengyihao's avatar
dengyihao 已提交
1471 1472
      SCliBatch** ppBatch = taosHashGet(pThrd->batchCache, key, sizeof(key));
      if (ppBatch == NULL || *ppBatch == NULL) {
dengyihao's avatar
dengyihao 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
        SCliBatch* pBatch = taosMemoryCalloc(1, sizeof(SCliBatch));
        QUEUE_INIT(&pBatch->wq);
        QUEUE_PUSH(&pBatch->wq, h);
        pBatch->wLen += 1;
        pBatch->batchSize += pMsg->msg.contLen;

        pBatch->dst = strdup(key);
        pBatch->ip = strdup(ip);
        pBatch->port = (uint16_t)port;

        taosHashPut(pThrd->batchCache, key, sizeof(key), &pBatch, sizeof(void*));
      } else {
        QUEUE_PUSH(&(*ppBatch)->wq, h);
dengyihao's avatar
dengyihao 已提交
1486 1487
        (*ppBatch)->wLen += 1;
        (*ppBatch)->batchSize += pMsg->msg.contLen;
dengyihao's avatar
dengyihao 已提交
1488
      }
dengyihao's avatar
dengyihao 已提交
1489
      continue;
dengyihao's avatar
dengyihao 已提交
1490
    }
dengyihao's avatar
dengyihao 已提交
1491
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1492
    count++;
dengyihao's avatar
dengyihao 已提交
1493
  }
dengyihao's avatar
dengyihao 已提交
1494

dengyihao's avatar
dengyihao 已提交
1495
  void** pIter = taosHashIterate(pThrd->batchCache, NULL);
dengyihao's avatar
dengyihao 已提交
1496 1497 1498
  while (pIter != NULL) {
    SCliBatch* batch = (SCliBatch*)(*pIter);

dengyihao's avatar
dengyihao 已提交
1499 1500
    cliHandleBatchReq(batch, pThrd);
    pIter = (void**)taosHashIterate(pThrd->batchCache, pIter);
dengyihao's avatar
dengyihao 已提交
1501 1502
  }

dengyihao's avatar
dengyihao 已提交
1503
  if (count >= 2) {
S
Shengliang Guan 已提交
1504
    tTrace("cli process batch size:%d", count);
dengyihao's avatar
dengyihao 已提交
1505
  }
dengyihao's avatar
dengyihao 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
}

static void cliAsyncCb(uv_async_t* handle) {
  SAsyncItem* item = handle->data;
  SCliThrd*   pThrd = item->pThrd;
  STrans*     pTransInst = pThrd->pTransInst;

  SCliMsg* pMsg = NULL;
  // batch process to avoid to lock/unlock frequently
  queue wq;
  taosThreadMutexLock(&item->mtx);
  QUEUE_MOVE(&item->qmsg, &wq);
  taosThreadMutexUnlock(&item->mtx);

dengyihao's avatar
dengyihao 已提交
1520
  int8_t supportBatch = pTransInst->supportBatch;
dengyihao's avatar
dengyihao 已提交
1521
  if (supportBatch == 0) {
dengyihao's avatar
dengyihao 已提交
1522
    cliNoBatchDealReq(&wq, pThrd);
dengyihao's avatar
dengyihao 已提交
1523
  } else if (supportBatch == 1) {
dengyihao's avatar
dengyihao 已提交
1524
    cliBatchDealReq(&wq, pThrd);
dengyihao's avatar
dengyihao 已提交
1525
  }
dengyihao's avatar
dengyihao 已提交
1526

dengyihao's avatar
dengyihao 已提交
1527
  if (pThrd->stopMsg != NULL) cliHandleQuit(pThrd->stopMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1528
}
dengyihao's avatar
dengyihao 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
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 已提交
1555
}
dengyihao's avatar
dengyihao 已提交
1556

dengyihao's avatar
dengyihao 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
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 已提交
1586 1587 1588
bool cliRecvReleaseReq(SCliConn* conn, STransMsgHead* pHead) {
  if (pHead->release == 1 && (pHead->msgLen) == sizeof(*pHead)) {
    uint64_t ahandle = pHead->ahandle;
dengyihao's avatar
dengyihao 已提交
1589
    tDebug("ahandle = %" PRIu64 "", ahandle);
dengyihao's avatar
dengyihao 已提交
1590 1591
    SCliMsg* pMsg = NULL;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
dengyihao's avatar
dengyihao 已提交
1592

dengyihao's avatar
dengyihao 已提交
1593 1594
    transClearBuffer(&conn->readBuf);
    transFreeMsg(transContFromHead((char*)pHead));
dengyihao's avatar
dengyihao 已提交
1595 1596 1597 1598

    for (int i = 0; ahandle == 0 && i < transQueueSize(&conn->cliMsgs); i++) {
      SCliMsg* cliMsg = transQueueGet(&conn->cliMsgs, i);
      if (cliMsg->type == Release) {
dengyihao's avatar
dengyihao 已提交
1599
        ASSERTS(pMsg == NULL, "trans-cli recv invaid release-req");
dengyihao's avatar
dengyihao 已提交
1600 1601
        return true;
      }
dengyihao's avatar
dengyihao 已提交
1602
    }
dengyihao's avatar
dengyihao 已提交
1603 1604 1605

    cliIteraConnMsgs(conn);

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

dengyihao's avatar
dengyihao 已提交
1609 1610 1611 1612 1613 1614
    addConnToPool(((SCliThrd*)conn->hostThrd)->pool, conn);
    return true;
  }
  return false;
}

U
ubuntu 已提交
1615
static void* cliWorkThread(void* arg) {
dengyihao's avatar
dengyihao 已提交
1616
  SCliThrd* pThrd = (SCliThrd*)arg;
dengyihao's avatar
dengyihao 已提交
1617
  pThrd->pid = taosGetSelfPthreadId();
G
gccgdb1234 已提交
1618
  setThreadName("trans-cli-work");
dengyihao's avatar
dengyihao 已提交
1619
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
dengyihao's avatar
dengyihao 已提交
1620 1621

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

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

dengyihao's avatar
dengyihao 已提交
1628
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
1629
  memcpy(cli->label, label, TSDB_LABEL_LEN);
dengyihao's avatar
dengyihao 已提交
1630
  cli->numOfThreads = numOfThreads;
dengyihao's avatar
dengyihao 已提交
1631
  cli->pThreadObj = (SCliThrd**)taosMemoryCalloc(cli->numOfThreads, sizeof(SCliThrd*));
dengyihao's avatar
dengyihao 已提交
1632 1633

  for (int i = 0; i < cli->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
1634
    SCliThrd* pThrd = createThrdObj(shandle);
dengyihao's avatar
dengyihao 已提交
1635 1636 1637 1638 1639
    if (pThrd == NULL) {
      return NULL;
    }

    int err = taosThreadCreate(&pThrd->thread, NULL, cliWorkThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
1640
    if (err == 0) {
S
Shengliang Guan 已提交
1641
      tDebug("success to create tranport-cli thread:%d", i);
dengyihao's avatar
dengyihao 已提交
1642
    }
dengyihao's avatar
dengyihao 已提交
1643
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
1644
  }
dengyihao's avatar
dengyihao 已提交
1645

dengyihao's avatar
dengyihao 已提交
1646 1647
  return cli;
}
dengyihao's avatar
dengyihao 已提交
1648

dengyihao's avatar
dengyihao 已提交
1649
static FORCE_INLINE void destroyUserdata(STransMsg* userdata) {
dengyihao's avatar
dengyihao 已提交
1650 1651 1652 1653 1654 1655
  if (userdata->pCont == NULL) {
    return;
  }
  transFreeMsg(userdata->pCont);
  userdata->pCont = NULL;
}
dengyihao's avatar
dengyihao 已提交
1656

dengyihao's avatar
dengyihao 已提交
1657
static FORCE_INLINE void destroyCmsg(void* arg) {
dengyihao's avatar
dengyihao 已提交
1658
  SCliMsg* pMsg = arg;
dengyihao's avatar
dengyihao 已提交
1659 1660 1661
  if (pMsg == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1662

dengyihao's avatar
dengyihao 已提交
1663 1664
  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
wafwerar's avatar
wafwerar 已提交
1665
  taosMemoryFree(pMsg);
dengyihao's avatar
dengyihao 已提交
1666
}
dengyihao's avatar
dengyihao 已提交
1667

dengyihao's avatar
dengyihao 已提交
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
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 已提交
1687 1688 1689
static SCliThrd* createThrdObj(void* trans) {
  STrans* pTransInst = trans;

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

dengyihao's avatar
dengyihao 已提交
1692
  QUEUE_INIT(&pThrd->msg);
wafwerar's avatar
wafwerar 已提交
1693
  taosThreadMutexInit(&pThrd->msgMtx, NULL);
dengyihao's avatar
dengyihao 已提交
1694

wafwerar's avatar
wafwerar 已提交
1695
  pThrd->loop = (uv_loop_t*)taosMemoryMalloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
1696 1697 1698 1699 1700 1701 1702 1703
  int err = uv_loop_init(pThrd->loop);
  if (err != 0) {
    tError("failed to init uv_loop, reason:%s", uv_err_name(err));
    taosMemoryFree(pThrd->loop);
    taosThreadMutexDestroy(&pThrd->msgMtx);
    taosMemoryFree(pThrd);
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1704 1705 1706 1707 1708
  if (pTransInst->supportBatch) {
    pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 4, pThrd, cliAsyncCb);
  } else {
    pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 8, pThrd, cliAsyncCb);
  }
dengyihao's avatar
dengyihao 已提交
1709
  if (pThrd->asyncPool == NULL) {
dengyihao's avatar
ref log  
dengyihao 已提交
1710
    tError("failed to init async pool");
dengyihao's avatar
dengyihao 已提交
1711 1712 1713 1714 1715 1716
    uv_loop_close(pThrd->loop);
    taosMemoryFree(pThrd->loop);
    taosThreadMutexDestroy(&pThrd->msgMtx);
    taosMemoryFree(pThrd);
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1717 1718 1719 1720

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

dengyihao's avatar
dengyihao 已提交
1723
  int32_t timerSize = 64;
dengyihao's avatar
dengyihao 已提交
1724 1725 1726 1727 1728 1729 1730
  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 已提交
1731
  pThrd->pool = createConnPool(4);
dengyihao's avatar
dengyihao 已提交
1732
  transDQCreate(pThrd->loop, &pThrd->delayQueue);
dengyihao's avatar
dengyihao 已提交
1733

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

dengyihao's avatar
dengyihao 已提交
1736 1737 1738
  pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
  pThrd->pTransInst = trans;

dengyihao's avatar
dengyihao 已提交
1739
  pThrd->destroyAhandleFp = pTransInst->destroyFp;
dengyihao's avatar
dengyihao 已提交
1740
  pThrd->fqdn2ipCache = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1741
  pThrd->failFastCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1742 1743
  pThrd->connLimitCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true,
                                       pTransInst->connLimitLock == 0 ? HASH_NO_LOCK : HASH_ENTRY_LOCK);
dengyihao's avatar
dengyihao 已提交
1744

dengyihao's avatar
dengyihao 已提交
1745
  pThrd->batchCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1746

dengyihao's avatar
dengyihao 已提交
1747
  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
1748 1749
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1750
static void destroyThrdObj(SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1751 1752 1753
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1754

wafwerar's avatar
wafwerar 已提交
1755
  taosThreadJoin(pThrd->thread, NULL);
dengyihao's avatar
dengyihao 已提交
1756
  CLI_RELEASE_UV(pThrd->loop);
wafwerar's avatar
wafwerar 已提交
1757
  taosThreadMutexDestroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
1758
  TRANS_DESTROY_ASYNC_POOL_MSG(pThrd->asyncPool, SCliMsg, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1759
  transAsyncPoolDestroy(pThrd->asyncPool);
dengyihao's avatar
dengyihao 已提交
1760

dengyihao's avatar
dengyihao 已提交
1761
  transDQDestroy(pThrd->delayQueue, destroyCmsgAndAhandle);
dengyihao's avatar
dengyihao 已提交
1762
  transDQDestroy(pThrd->timeoutQueue, NULL);
dengyihao's avatar
dengyihao 已提交
1763

dengyihao's avatar
dengyihao 已提交
1764
  tDebug("thread destroy %" PRId64, pThrd->pid);
dengyihao's avatar
dengyihao 已提交
1765 1766 1767 1768 1769
  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 已提交
1770
  taosMemoryFree(pThrd->prepare);
wafwerar's avatar
wafwerar 已提交
1771
  taosMemoryFree(pThrd->loop);
dengyihao's avatar
dengyihao 已提交
1772
  taosHashCleanup(pThrd->fqdn2ipCache);
dengyihao's avatar
dengyihao 已提交
1773
  taosHashCleanup(pThrd->failFastCache);
dengyihao's avatar
dengyihao 已提交
1774
  taosHashCleanup(pThrd->connLimitCache);
dengyihao's avatar
dengyihao 已提交
1775 1776 1777 1778 1779 1780 1781

  void** pIter = taosHashIterate(pThrd->batchCache, NULL);
  while (pIter != NULL) {
    SCliBatch* batch = (SCliBatch*)(*pIter);
    cliDestroyBatch(batch);
    pIter = (void**)taosHashIterate(pThrd->batchCache, pIter);
  }
dengyihao's avatar
dengyihao 已提交
1782
  taosHashCleanup(pThrd->batchCache);
wafwerar's avatar
wafwerar 已提交
1783
  taosMemoryFree(pThrd);
dengyihao's avatar
dengyihao 已提交
1784
}
dengyihao's avatar
dengyihao 已提交
1785

dengyihao's avatar
dengyihao 已提交
1786
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1787
  //
wafwerar's avatar
wafwerar 已提交
1788
  taosMemoryFree(ctx);
dengyihao's avatar
dengyihao 已提交
1789
}
dengyihao's avatar
dengyihao 已提交
1790

dengyihao's avatar
dengyihao 已提交
1791
void cliSendQuit(SCliThrd* thrd) {
dengyihao's avatar
dengyihao 已提交
1792
  // cli can stop gracefully
wafwerar's avatar
wafwerar 已提交
1793
  SCliMsg* msg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1794
  msg->type = Quit;
dengyihao's avatar
dengyihao 已提交
1795
  transAsyncSend(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
1796
  atomic_store_8(&thrd->asyncPool->stop, 1);
dengyihao's avatar
dengyihao 已提交
1797
}
dengyihao's avatar
dengyihao 已提交
1798 1799
void cliWalkCb(uv_handle_t* handle, void* arg) {
  if (!uv_is_closing(handle)) {
dengyihao's avatar
dengyihao 已提交
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    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 已提交
1812
    uv_close(handle, cliDestroy);
dengyihao's avatar
dengyihao 已提交
1813 1814
  }
}
dengyihao's avatar
dengyihao 已提交
1815

dengyihao's avatar
dengyihao 已提交
1816
FORCE_INLINE int cliRBChoseIdx(STrans* pTransInst) {
dengyihao's avatar
dengyihao 已提交
1817
  int32_t index = pTransInst->index;
dengyihao's avatar
dengyihao 已提交
1818 1819 1820
  if (pTransInst->numOfThreads == 0) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1821 1822 1823 1824
  /*
   * no lock, and to avoid CPU load imbalance, set limit pTransInst->numOfThreads * 2000;
   */
  if (pTransInst->index++ >= pTransInst->numOfThreads * 2000) {
U
ubuntu 已提交
1825 1826 1827 1828
    pTransInst->index = 0;
  }
  return index % pTransInst->numOfThreads;
}
dengyihao's avatar
dengyihao 已提交
1829
static FORCE_INLINE void doDelayTask(void* param) {
dengyihao's avatar
dengyihao 已提交
1830
  STaskArg* arg = param;
dengyihao's avatar
dengyihao 已提交
1831
  cliHandleReq((SCliMsg*)arg->param1, (SCliThrd*)arg->param2);
dengyihao's avatar
dengyihao 已提交
1832 1833
  taosMemoryFree(arg);
}
dengyihao's avatar
dengyihao 已提交
1834

dengyihao's avatar
dengyihao 已提交
1835 1836 1837
static void doCloseIdleConn(void* param) {
  STaskArg* arg = param;
  SCliConn* conn = arg->param1;
dengyihao's avatar
dengyihao 已提交
1838
  tDebug("%s conn %p idle, close it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
1839
  conn->task = NULL;
dengyihao's avatar
dengyihao 已提交
1840 1841
  cliDestroyConn(conn, true);
  taosMemoryFree(arg);
dengyihao's avatar
dengyihao 已提交
1842 1843
}

dengyihao's avatar
dengyihao 已提交
1844
static void cliSchedMsgToNextNode(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1845
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1846 1847
  STransConnCtx* pCtx = pMsg->ctx;

dengyihao's avatar
dengyihao 已提交
1848 1849
  STraceId* trace = &pMsg->msg.info.traceId;
  char      tbuf[256] = {0};
dengyihao's avatar
dengyihao 已提交
1850
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1851 1852
  tGDebug("%s retry on next node,use:%s, step: %d,timeout:%" PRId64 "", transLabel(pThrd->pTransInst), tbuf,
          pCtx->retryStep, pCtx->retryNextInterval);
dengyihao's avatar
dengyihao 已提交
1853 1854 1855 1856

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

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

dengyihao's avatar
dengyihao 已提交
1861
FORCE_INLINE void cliCompareAndSwap(int8_t* val, int8_t exp, int8_t newVal) {
dengyihao's avatar
dengyihao 已提交
1862 1863 1864 1865
  if (*val != exp) {
    *val = newVal;
  }
}
dengyihao's avatar
dengyihao 已提交
1866

dengyihao's avatar
dengyihao 已提交
1867
FORCE_INLINE bool cliTryExtractEpSet(STransMsg* pResp, SEpSet* dst) {
dengyihao's avatar
dengyihao 已提交
1868 1869 1870 1871 1872 1873
  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 已提交
1874 1875 1876 1877
    return false;
  }
  int32_t tlen = tSerializeSEpSet(NULL, 0, dst);

dengyihao's avatar
dengyihao 已提交
1878 1879 1880 1881 1882 1883 1884
  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 已提交
1885 1886

  pResp->pCont = buf;
dengyihao's avatar
dengyihao 已提交
1887 1888 1889
  pResp->contLen = len;

  *dst = epset;
dengyihao's avatar
dengyihao 已提交
1890 1891
  return true;
}
dengyihao's avatar
dengyihao 已提交
1892
bool cliResetEpset(STransConnCtx* pCtx, STransMsg* pResp, bool hasEpSet) {
dengyihao's avatar
dengyihao 已提交
1893
  bool noDelay = true;
dengyihao's avatar
dengyihao 已提交
1894 1895 1896 1897 1898 1899 1900
  if (hasEpSet == false) {
    if (pResp->contLen == 0) {
      if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
        noDelay = false;
      } else {
        EPSET_FORWARD_INUSE(&pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
    } else if (pResp->contLen != 0) {
      SEpSet  epSet;
      int32_t valid = tDeserializeSEpSet(pResp->pCont, pResp->contLen, &epSet);
      if (valid < 0) {
        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 已提交
1911
      } else {
dengyihao's avatar
dengyihao 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
        if (!transEpSetIsEqual(&pCtx->epSet, &epSet)) {
          tDebug("epset not equal, retry new epset");
          pCtx->epSet = epSet;
          noDelay = false;
        } else {
          if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
            noDelay = false;
          } else {
            tDebug("epset equal, continue");
            EPSET_FORWARD_INUSE(&pCtx->epSet);
          }
        }
dengyihao's avatar
dengyihao 已提交
1924
      }
dengyihao's avatar
dengyihao 已提交
1925 1926
    }
  } else {
dengyihao's avatar
dengyihao 已提交
1927
    SEpSet  epSet;
dengyihao's avatar
dengyihao 已提交
1928 1929
    int32_t valid = tDeserializeSEpSet(pResp->pCont, pResp->contLen, &epSet);
    if (valid < 0) {
dengyihao's avatar
dengyihao 已提交
1930 1931 1932 1933 1934 1935
      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 已提交
1936
    } else {
dengyihao's avatar
dengyihao 已提交
1937 1938 1939
      if (!transEpSetIsEqual(&pCtx->epSet, &epSet)) {
        tDebug("epset not equal, retry new epset");
        pCtx->epSet = epSet;
dengyihao's avatar
dengyihao 已提交
1940
        noDelay = false;
dengyihao's avatar
dengyihao 已提交
1941
      } else {
dengyihao's avatar
dengyihao 已提交
1942 1943 1944 1945 1946 1947
        if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
          noDelay = false;
        } else {
          tDebug("epset equal, continue");
          EPSET_FORWARD_INUSE(&pCtx->epSet);
        }
dengyihao's avatar
dengyihao 已提交
1948
      }
dengyihao's avatar
dengyihao 已提交
1949 1950 1951 1952 1953
    }
  }
  return noDelay;
}
bool cliGenRetryRule(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
1954 1955
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1956

dengyihao's avatar
dengyihao 已提交
1957 1958
  STransConnCtx* pCtx = pMsg->ctx;
  int32_t        code = pResp->code;
dengyihao's avatar
dengyihao 已提交
1959

dengyihao's avatar
dengyihao 已提交
1960
  bool retry = pTransInst->retry != NULL ? pTransInst->retry(code, pResp->msgType - 1) : false;
dengyihao's avatar
dengyihao 已提交
1961 1962 1963
  if (retry == false) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
1964 1965 1966 1967 1968 1969 1970 1971

  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 已提交
1972
    pCtx->retryStep = 0;
dengyihao's avatar
dengyihao 已提交
1973
    pCtx->retryInit = true;
dengyihao's avatar
dengyihao 已提交
1974
    pCtx->retryCode = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
1975 1976 1977

    // already retry, not use handle specified by app;
    pMsg->msg.info.handle = 0;
dengyihao's avatar
dengyihao 已提交
1978
  }
dengyihao's avatar
dengyihao 已提交
1979

dengyihao's avatar
dengyihao 已提交
1980 1981
  if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
    return false;
dengyihao's avatar
dengyihao 已提交
1982
  }
dengyihao's avatar
dengyihao 已提交
1983

dengyihao's avatar
dengyihao 已提交
1984 1985 1986 1987 1988 1989
  // code, msgType

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

dengyihao's avatar
dengyihao 已提交
1990 1991
  bool noDelay = false;
  if (code == TSDB_CODE_RPC_BROKEN_LINK || code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
dengyihao's avatar
dengyihao 已提交
1992
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
1993
    noDelay = cliResetEpset(pCtx, pResp, false);
dengyihao's avatar
dengyihao 已提交
1994 1995
    transFreeMsg(pResp->pCont);
    transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
1996
  } else if (code == TSDB_CODE_SYN_NOT_LEADER || code == TSDB_CODE_SYN_INTERNAL_ERROR ||
1997 1998
             code == TSDB_CODE_SYN_PROPOSE_NOT_READY || code == TSDB_CODE_VND_STOPPED ||
             code == TSDB_CODE_MNODE_NOT_FOUND || code == TSDB_CODE_APP_IS_STARTING ||
dengyihao's avatar
dengyihao 已提交
1999
             code == TSDB_CODE_APP_IS_STOPPING || code == TSDB_CODE_VND_STOPPED) {
dengyihao's avatar
dengyihao 已提交
2000
    tTrace("code str %s, contlen:%d 1", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2001
    noDelay = cliResetEpset(pCtx, pResp, true);
dengyihao's avatar
dengyihao 已提交
2002 2003
    transFreeMsg(pResp->pCont);
    addConnToPool(pThrd->pool, pConn);
dengyihao's avatar
dengyihao 已提交
2004
  } else if (code == TSDB_CODE_SYN_RESTORING) {
dengyihao's avatar
dengyihao 已提交
2005
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2006
    noDelay = cliResetEpset(pCtx, pResp, true);
dengyihao's avatar
dengyihao 已提交
2007 2008
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
2009
  } else {
dengyihao's avatar
dengyihao 已提交
2010
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2011 2012 2013
    noDelay = cliResetEpset(pCtx, pResp, false);
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
2014
  }
dengyihao's avatar
dengyihao 已提交
2015 2016 2017 2018
  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 已提交
2019

dengyihao's avatar
dengyihao 已提交
2020 2021 2022
  if (noDelay == false) {
    pCtx->epsetRetryCnt = 1;
    pCtx->retryStep++;
dengyihao's avatar
dengyihao 已提交
2023

dengyihao's avatar
dengyihao 已提交
2024 2025 2026 2027 2028 2029
    int64_t factor = pow(pCtx->retryStepFactor, pCtx->retryStep - 1);
    pCtx->retryNextInterval = factor * pCtx->retryMinInterval;
    if (pCtx->retryNextInterval >= pCtx->retryMaxInterval) {
      pCtx->retryNextInterval = pCtx->retryMaxInterval;
    }

dengyihao's avatar
dengyihao 已提交
2030 2031 2032
    // if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
    //   return false;
    // }
dengyihao's avatar
dengyihao 已提交
2033 2034 2035
  } else {
    pCtx->retryNextInterval = 0;
    pCtx->epsetRetryCnt++;
dengyihao's avatar
dengyihao 已提交
2036
  }
dengyihao's avatar
dengyihao 已提交
2037

dengyihao's avatar
dengyihao 已提交
2038
  pMsg->sent = 0;
dengyihao's avatar
dengyihao 已提交
2039
  cliSchedMsgToNextNode(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
2040
  return true;
dengyihao's avatar
dengyihao 已提交
2041
}
dengyihao's avatar
dengyihao 已提交
2042
int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
2043 2044
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
2045

dengyihao's avatar
dengyihao 已提交
2046
  if (pMsg == NULL || pMsg->ctx == NULL) {
dengyihao's avatar
dengyihao 已提交
2047
    tTrace("%s conn %p handle resp", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
2048 2049 2050
    pTransInst->cfp(pTransInst->parent, pResp, NULL);
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
2051

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

dengyihao's avatar
dengyihao 已提交
2054 2055 2056
  bool retry = cliGenRetryRule(pConn, pResp, pMsg);
  if (retry == true) {
    return -1;
dengyihao's avatar
dengyihao 已提交
2057
  }
dengyihao's avatar
dengyihao 已提交
2058

dengyihao's avatar
dengyihao 已提交
2059 2060 2061
  if (pCtx->retryCode != TSDB_CODE_SUCCESS) {
    int32_t code = pResp->code;
    // return internal code app
dengyihao's avatar
dengyihao 已提交
2062 2063
    if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK ||
        code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
dengyihao's avatar
dengyihao 已提交
2064 2065 2066 2067
      pResp->code = pCtx->retryCode;
    }
  }

2068
  // check whole vnodes is offline on this vgroup
2069 2070
  if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps || pCtx->retryStep > 0) {
    if (pResp->code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
A
Alex Duan 已提交
2071
      pResp->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
2072
    } else if (pResp->code == TSDB_CODE_RPC_BROKEN_LINK) {
A
Alex Duan 已提交
2073
      pResp->code = TSDB_CODE_RPC_SOMENODE_BROKEN_LINK;
2074 2075 2076
    }
  }

dengyihao's avatar
dengyihao 已提交
2077 2078
  STraceId* trace = &pResp->info.traceId;
  bool      hasEpSet = cliTryExtractEpSet(pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
2079
  if (hasEpSet) {
dengyihao's avatar
dengyihao 已提交
2080 2081
    char tbuf[256] = {0};
    EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
2082
    tGTrace("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
2083
  }
dengyihao's avatar
dengyihao 已提交
2084

dengyihao's avatar
dengyihao 已提交
2085
  if (pCtx->pSem != NULL) {
dengyihao's avatar
dengyihao 已提交
2086
    tGTrace("%s conn %p(sync) handle resp", CONN_GET_INST_LABEL(pConn), pConn);
2087
    if (pCtx->pRsp == NULL) {
dengyihao's avatar
dengyihao 已提交
2088
      tGTrace("%s conn %p(sync) failed to resp, ignore", CONN_GET_INST_LABEL(pConn), pConn);
2089 2090 2091
    } else {
      memcpy((char*)pCtx->pRsp, (char*)pResp, sizeof(*pResp));
    }
dengyihao's avatar
dengyihao 已提交
2092
    tsem_post(pCtx->pSem);
2093
    pCtx->pRsp = NULL;
dengyihao's avatar
dengyihao 已提交
2094
  } else {
dengyihao's avatar
dengyihao 已提交
2095
    tGTrace("%s conn %p handle resp", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
2096
    if (retry == false && hasEpSet == true) {
dengyihao's avatar
dengyihao 已提交
2097
      pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
2098
    } else {
dengyihao's avatar
dengyihao 已提交
2099
      if (!cliIsEpsetUpdated(pResp->code, pCtx)) {
dengyihao's avatar
dengyihao 已提交
2100 2101 2102 2103
        pTransInst->cfp(pTransInst->parent, pResp, NULL);
      } else {
        pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
2104
    }
dengyihao's avatar
dengyihao 已提交
2105
  }
dengyihao's avatar
dengyihao 已提交
2106
  return 0;
dengyihao's avatar
dengyihao 已提交
2107
}
U
ubuntu 已提交
2108 2109

void transCloseClient(void* arg) {
U
ubuntu 已提交
2110
  SCliObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
2111
  for (int i = 0; i < cli->numOfThreads; i++) {
U
ubuntu 已提交
2112
    cliSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
2113
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
2114
  }
wafwerar's avatar
wafwerar 已提交
2115 2116
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
dengyihao's avatar
dengyihao 已提交
2117
}
dengyihao's avatar
dengyihao 已提交
2118 2119 2120 2121 2122
void transRefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_INC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
2123
  tTrace("%s conn %p ref %d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
2124 2125 2126 2127 2128 2129 2130
  UNUSED(ref);
}
void transUnrefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_DEC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
2131
  tTrace("%s conn %p ref:%d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
2132
  if (ref == 0) {
U
ubuntu 已提交
2133
    cliDestroyConn((SCliConn*)handle, true);
dengyihao's avatar
dengyihao 已提交
2134 2135
  }
}
dengyihao's avatar
dengyihao 已提交
2136
static FORCE_INLINE SCliThrd* transGetWorkThrdFromHandle(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
2137
  SCliThrd*  pThrd = NULL;
dengyihao's avatar
dengyihao 已提交
2138
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
2139 2140 2141
  if (exh == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
2142

dengyihao's avatar
dengyihao 已提交
2143 2144 2145 2146 2147 2148
  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 已提交
2149
  pThrd = exh->pThrd;
dengyihao's avatar
dengyihao 已提交
2150
  transReleaseExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
2151 2152
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
2153
SCliThrd* transGetWorkThrd(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
2154
  if (handle == 0) {
dengyihao's avatar
dengyihao 已提交
2155
    int idx = cliRBChoseIdx(trans);
dengyihao's avatar
dengyihao 已提交
2156
    if (idx < 0) return NULL;
dengyihao's avatar
dengyihao 已提交
2157 2158
    return ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
dengyihao's avatar
dengyihao 已提交
2159
  SCliThrd* pThrd = transGetWorkThrdFromHandle(trans, handle);
D
dapan1121 已提交
2160
  return pThrd;
dengyihao's avatar
dengyihao 已提交
2161
}
dengyihao's avatar
dengyihao 已提交
2162
int transReleaseCliHandle(void* handle) {
dengyihao's avatar
dengyihao 已提交
2163 2164 2165
  int  idx = -1;
  bool valid = false;

dengyihao's avatar
dengyihao 已提交
2166
  SCliThrd* pThrd = transGetWorkThrdFromHandle(NULL, (int64_t)handle);
dengyihao's avatar
dengyihao 已提交
2167
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2168
    return -1;
dengyihao's avatar
dengyihao 已提交
2169
  }
dengyihao's avatar
dengyihao 已提交
2170

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

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

dengyihao's avatar
dengyihao 已提交
2177
  SCliMsg* cmsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2178
  cmsg->msg = tmsg;
dengyihao's avatar
dengyihao 已提交
2179
  cmsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2180
  cmsg->type = Release;
dengyihao's avatar
dengyihao 已提交
2181
  cmsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
2182

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

dengyihao's avatar
dengyihao 已提交
2186
  if (0 != transAsyncSend(pThrd->asyncPool, &cmsg->q)) {
dengyihao's avatar
dengyihao 已提交
2187
    destroyCmsg(cmsg);
dengyihao's avatar
dengyihao 已提交
2188 2189
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2190
  return 0;
dengyihao's avatar
dengyihao 已提交
2191
}
dengyihao's avatar
dengyihao 已提交
2192

dengyihao's avatar
dengyihao 已提交
2193
int transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
2194 2195 2196 2197 2198
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2199

dengyihao's avatar
dengyihao 已提交
2200
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
dengyihao's avatar
dengyihao 已提交
2201
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2202
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
2203
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2204
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
2205
  }
dengyihao's avatar
dengyihao 已提交
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
  if (pTransInst->connLimitNum > 0 && REQUEST_NO_RESP(pReq)) {
    char     key[TSDB_FQDN_LEN + 64] = {0};
    char*    ip = EPSET_GET_INUSE_IP((SEpSet*)pEpSet);
    uint16_t port = EPSET_GET_INUSE_PORT((SEpSet*)pEpSet);
    CONN_CONSTRUCT_HASH_KEY(key, ip, port);

    int32_t* val = taosHashGet(pThrd->connLimitCache, key, strlen(key));
    if (val != NULL && *val >= pTransInst->connLimitNum) {
      transFreeMsg(pReq->pCont);
      transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2216
      return TSDB_CODE_RPC_MAX_SESSIONS;
dengyihao's avatar
dengyihao 已提交
2217 2218
    }
  }
dengyihao's avatar
dengyihao 已提交
2219

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

wafwerar's avatar
wafwerar 已提交
2222
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2223
  pCtx->epSet = *pEpSet;
S
Shengliang Guan 已提交
2224
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
2225
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
2226

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

wafwerar's avatar
wafwerar 已提交
2229
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2230
  cliMsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
2231
  cliMsg->msg = *pReq;
dengyihao's avatar
dengyihao 已提交
2232
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2233
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
2234
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
2235

dengyihao's avatar
dengyihao 已提交
2236
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
2237 2238
  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 已提交
2239 2240
  if (0 != transAsyncSend(pThrd->asyncPool, &(cliMsg->q))) {
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2241
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2242 2243
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2244
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2245
  return 0;
dengyihao's avatar
dengyihao 已提交
2246
}
dengyihao's avatar
dengyihao 已提交
2247

dengyihao's avatar
dengyihao 已提交
2248
int transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMsg* pRsp) {
dengyihao's avatar
dengyihao 已提交
2249 2250 2251 2252 2253
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2254

dengyihao's avatar
dengyihao 已提交
2255 2256
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2257
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
2258
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2259
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
2260
  }
dengyihao's avatar
dengyihao 已提交
2261

dengyihao's avatar
dengyihao 已提交
2262 2263
  tsem_t* sem = taosMemoryCalloc(1, sizeof(tsem_t));
  tsem_init(sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
2264

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

wafwerar's avatar
wafwerar 已提交
2267
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2268
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
2269
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
2270
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
2271
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
2272
  pCtx->pSem = sem;
dengyihao's avatar
dengyihao 已提交
2273 2274
  pCtx->pRsp = pRsp;

wafwerar's avatar
wafwerar 已提交
2275
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2276 2277 2278
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pReq;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2279
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
2280
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
2281

dengyihao's avatar
dengyihao 已提交
2282
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
2283 2284
  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 已提交
2285

dengyihao's avatar
dengyihao 已提交
2286 2287
  int ret = transAsyncSend(pThrd->asyncPool, &cliMsg->q);
  if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
2288
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2289
    goto _RETURN;
dengyihao's avatar
dengyihao 已提交
2290
  }
dengyihao's avatar
dengyihao 已提交
2291
  tsem_wait(sem);
dengyihao's avatar
dengyihao 已提交
2292 2293

_RETURN:
dengyihao's avatar
dengyihao 已提交
2294 2295
  tsem_destroy(sem);
  taosMemoryFree(sem);
dengyihao's avatar
dengyihao 已提交
2296
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2297
  return ret;
dengyihao's avatar
dengyihao 已提交
2298
}
dengyihao's avatar
dengyihao 已提交
2299 2300 2301
/*
 *
 **/
dengyihao's avatar
dengyihao 已提交
2302
int transSetDefaultAddr(void* shandle, const char* ip, const char* fqdn) {
dengyihao's avatar
dengyihao 已提交
2303
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2304 2305 2306
  if (pTransInst == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2307 2308 2309

  SCvtAddr cvtAddr = {0};
  if (ip != NULL && fqdn != NULL) {
dengyihao's avatar
dengyihao 已提交
2310 2311
    tstrncpy(cvtAddr.ip, ip, sizeof(cvtAddr.ip));
    tstrncpy(cvtAddr.fqdn, fqdn, sizeof(cvtAddr.fqdn));
dengyihao's avatar
dengyihao 已提交
2312 2313
    cvtAddr.cvt = true;
  }
dengyihao's avatar
dengyihao 已提交
2314 2315
  for (int i = 0; i < pTransInst->numOfThreads; i++) {
    STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2316
    pCtx->cvtAddr = cvtAddr;
dengyihao's avatar
dengyihao 已提交
2317 2318 2319 2320

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

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

dengyihao's avatar
dengyihao 已提交
2326 2327
    if (transAsyncSend(thrd->asyncPool, &(cliMsg->q)) != 0) {
      destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2328
      transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2329 2330
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
2331
  }
dengyihao's avatar
dengyihao 已提交
2332
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2333
  return 0;
dengyihao's avatar
dengyihao 已提交
2334
}
dengyihao's avatar
dengyihao 已提交
2335 2336 2337 2338 2339

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 已提交
2340

dengyihao's avatar
dengyihao 已提交
2341 2342
  return exh->refId;
}
dengyihao's avatar
dengyihao 已提交
2343
#endif