transCli.c 78.1 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
 *
 * 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/>.
 */

dengyihao's avatar
dengyihao 已提交
15
// #include "osMemory.h"
dengyihao's avatar
dengyihao 已提交
16
#include "transComm.h"
dengyihao's avatar
dengyihao 已提交
17
#include "tutil.h"
dengyihao's avatar
dengyihao 已提交
18

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

dengyihao's avatar
dengyihao 已提交
24
typedef struct {
dengyihao's avatar
dengyihao 已提交
25 26 27 28 29 30
  queue   wq;
  int32_t len;

  int connMax;
  int connCnt;
  int batchLenLimit;
dengyihao's avatar
dengyihao 已提交
31
  int sending;
dengyihao's avatar
dengyihao 已提交
32

dengyihao's avatar
dengyihao 已提交
33 34 35
  char*    dst;
  char*    ip;
  uint16_t port;
dengyihao's avatar
dengyihao 已提交
36 37 38 39 40 41 42 43 44 45

} SCliBatchList;

typedef struct {
  queue          wq;
  queue          listq;
  int32_t        wLen;
  int32_t        batchSize;  //
  int32_t        batch;
  SCliBatchList* pList;
dengyihao's avatar
dengyihao 已提交
46
} SCliBatch;
dengyihao's avatar
dengyihao 已提交
47

dengyihao's avatar
dengyihao 已提交
48
typedef struct SCliConn {
dengyihao's avatar
dengyihao 已提交
49
  T_REF_DECLARE()
dengyihao's avatar
dengyihao 已提交
50 51
  uv_connect_t connReq;
  uv_stream_t* stream;
dengyihao's avatar
dengyihao 已提交
52
  queue        wreqQueue;
dengyihao's avatar
dengyihao 已提交
53 54

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

dengyihao's avatar
dengyihao 已提交
56 57 58 59
  void* hostThrd;

  SConnBuffer readBuf;
  STransQueue cliMsgs;
dengyihao's avatar
dengyihao 已提交
60 61 62

  queue      q;
  SConnList* list;
dengyihao's avatar
dengyihao 已提交
63 64

  STransCtx  ctx;
dengyihao's avatar
dengyihao 已提交
65 66
  bool       broken;  // link broken or not
  ConnStatus status;  //
dengyihao's avatar
dengyihao 已提交
67

dengyihao's avatar
dengyihao 已提交
68 69
  SCliBatch* pBatch;

dengyihao's avatar
dengyihao 已提交
70
  SDelayTask* task;
dengyihao's avatar
dengyihao 已提交
71

dengyihao's avatar
dengyihao 已提交
72 73 74
  char* ip;
  char  src[32];
  char  dst[32];
dengyihao's avatar
dengyihao 已提交
75

dengyihao's avatar
dengyihao 已提交
76
  int64_t refId;
dengyihao's avatar
dengyihao 已提交
77
} SCliConn;
dengyihao's avatar
dengyihao 已提交
78

dengyihao's avatar
dengyihao 已提交
79
typedef struct SCliMsg {
dengyihao's avatar
dengyihao 已提交
80
  STransConnCtx* ctx;
dengyihao's avatar
formate  
dengyihao 已提交
81
  STransMsg      msg;
dengyihao's avatar
dengyihao 已提交
82
  queue          q;
dengyihao's avatar
dengyihao 已提交
83
  STransMsgType  type;
dengyihao's avatar
dengyihao 已提交
84

dengyihao's avatar
dengyihao 已提交
85
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
86 87
  uint64_t st;
  int      sent;  //(0: no send, 1: alread sent)
dengyihao's avatar
dengyihao 已提交
88 89
} SCliMsg;

dengyihao's avatar
dengyihao 已提交
90
typedef struct SCliThrd {
dengyihao's avatar
dengyihao 已提交
91 92 93 94 95 96
  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 已提交
97
  // timer handles
dengyihao's avatar
dengyihao 已提交
98
  SArray* timerList;
dengyihao's avatar
dengyihao 已提交
99
  // msg queue
dengyihao's avatar
dengyihao 已提交
100
  queue         msg;
wafwerar's avatar
wafwerar 已提交
101
  TdThreadMutex msgMtx;
dengyihao's avatar
dengyihao 已提交
102
  SDelayQueue*  delayQueue;
dengyihao's avatar
dengyihao 已提交
103
  SDelayQueue*  timeoutQueue;
dengyihao's avatar
dengyihao 已提交
104 105
  uint64_t      nextTimeout;  // next timeout
  void*         pTransInst;   //
dengyihao's avatar
dengyihao 已提交
106

dengyihao's avatar
dengyihao 已提交
107
  int connCount;
dengyihao's avatar
dengyihao 已提交
108
  void (*destroyAhandleFp)(void* ahandle);
dengyihao's avatar
dengyihao 已提交
109 110
  SHashObj* fqdn2ipCache;
  SCvtAddr  cvtAddr;
dengyihao's avatar
dengyihao 已提交
111

dengyihao's avatar
dengyihao 已提交
112
  SHashObj* failFastCache;
dengyihao's avatar
dengyihao 已提交
113
  SHashObj* connLimitCache;
dengyihao's avatar
dengyihao 已提交
114
  SHashObj* batchCache;
dengyihao's avatar
dengyihao 已提交
115

dengyihao's avatar
dengyihao 已提交
116 117
  SCliMsg* stopMsg;

dengyihao's avatar
dengyihao 已提交
118
  bool quit;
dengyihao's avatar
dengyihao 已提交
119
} SCliThrd;
dengyihao's avatar
dengyihao 已提交
120

U
ubuntu 已提交
121
typedef struct SCliObj {
dengyihao's avatar
dengyihao 已提交
122 123 124 125
  char       label[TSDB_LABEL_LEN];
  int32_t    index;
  int        numOfThreads;
  SCliThrd** pThreadObj;
U
ubuntu 已提交
126
} SCliObj;
dengyihao's avatar
dengyihao 已提交
127

dengyihao's avatar
dengyihao 已提交
128 129 130 131 132 133 134
typedef struct {
  int32_t reinit;
  int64_t timestamp;
  int32_t count;
  int32_t threshold;
  int64_t interval;
} SFailFastItem;
dengyihao's avatar
dengyihao 已提交
135

dengyihao's avatar
dengyihao 已提交
136
// conn pool
dengyihao's avatar
dengyihao 已提交
137
// add expire timeout and capacity limit
dengyihao's avatar
dengyihao 已提交
138
static void*     createConnPool(int size);
139
static void*     destroyConnPool(void* pool);
dengyihao's avatar
dengyihao 已提交
140
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port);
dengyihao's avatar
dengyihao 已提交
141
static void      addConnToPool(void* pool, SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
142
static void      doCloseIdleConn(void* param);
dengyihao's avatar
dengyihao 已提交
143

dengyihao's avatar
dengyihao 已提交
144 145
// register conn timer
static void cliConnTimeout(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
146 147
// register timer for read
static void cliReadTimeoutCb(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
148
// register timer in each thread to clear expire conn
dengyihao's avatar
dengyihao 已提交
149
// static void cliTimeoutCb(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
150
// alloc buffer for recv
dengyihao's avatar
dengyihao 已提交
151
static FORCE_INLINE void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
152
// callback after recv nbytes from socket
U
ubuntu 已提交
153
static void cliRecvCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
154
// callback after send data to socket
U
ubuntu 已提交
155
static void cliSendCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
156
// callback after conn to server
U
ubuntu 已提交
157 158
static void cliConnCb(uv_connect_t* req, int status);
static void cliAsyncCb(uv_async_t* handle);
dengyihao's avatar
dengyihao 已提交
159
static void cliIdleCb(uv_idle_t* handle);
dengyihao's avatar
dengyihao 已提交
160
static void cliPrepareCb(uv_prepare_t* handle);
dengyihao's avatar
dengyihao 已提交
161

dengyihao's avatar
dengyihao 已提交
162
static void cliHandleBatchReq(SCliBatch* pBatch, SCliThrd* pThrd);
dengyihao's avatar
dengyihao 已提交
163
static void cliSendBatchCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
164 165

SCliBatch* cliGetHeadFromList(SCliBatchList* pList);
dengyihao's avatar
dengyihao 已提交
166

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

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

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

dengyihao's avatar
dengyihao 已提交
173
static SCliConn* cliCreateConn(SCliThrd* thrd);
U
ubuntu 已提交
174 175
static void      cliDestroyConn(SCliConn* pConn, bool clear /*clear tcp handle or not*/);
static void      cliDestroy(uv_handle_t* handle);
dengyihao's avatar
dengyihao 已提交
176
static void      cliSend(SCliConn* pConn);
dengyihao's avatar
dengyihao 已提交
177
static void      cliSendBatch(SCliConn* pConn);
dengyihao's avatar
dengyihao 已提交
178
static void      cliDestroyConnMsgs(SCliConn* conn, bool destroy);
dengyihao's avatar
dengyihao 已提交
179

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

dengyihao's avatar
dengyihao 已提交
182
// cli util func
dengyihao's avatar
dengyihao 已提交
183 184
static FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx);
static FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr);
dengyihao's avatar
dengyihao 已提交
185

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

dengyihao's avatar
dengyihao 已提交
188 189 190
static FORCE_INLINE uint32_t cliGetIpFromFqdnCache(SHashObj* cache, char* fqdn);
static FORCE_INLINE void     cliUpdateFqdnCache(SHashObj* cache, char* fqdn);

dengyihao's avatar
dengyihao 已提交
191
// process data read from server, add decompress etc later
U
ubuntu 已提交
192
static void cliHandleResp(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
193
// handle except about conn
U
ubuntu 已提交
194
static void cliHandleExcept(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
195
static void cliReleaseUnfinishedMsg(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
196
static void cliHandleFastFail(SCliConn* pConn, int status);
dengyihao's avatar
dengyihao 已提交
197

198
// handle req from app
dengyihao's avatar
dengyihao 已提交
199 200 201 202 203 204
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 已提交
205 206
/// static void (*cliAsyncHandle[])(SCliMsg* pMsg, SCliThrd* pThrd) = {cliHandleReq, cliHandleQuit, cliHandleRelease,
/// NULL,cliHandleUpdate};
dengyihao's avatar
dengyihao 已提交
207

dengyihao's avatar
dengyihao 已提交
208 209
static FORCE_INLINE void destroyUserdata(STransMsg* userdata);
static FORCE_INLINE void destroyCmsg(void* cmsg);
dengyihao's avatar
dengyihao 已提交
210
static FORCE_INLINE void destroyCmsgAndAhandle(void* cmsg);
dengyihao's avatar
dengyihao 已提交
211
static FORCE_INLINE int  cliRBChoseIdx(STrans* pTransInst);
dengyihao's avatar
dengyihao 已提交
212
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx);
dengyihao's avatar
dengyihao 已提交
213

dengyihao's avatar
dengyihao 已提交
214
// thread obj
dengyihao's avatar
dengyihao 已提交
215
static SCliThrd* createThrdObj(void* trans);
dengyihao's avatar
dengyihao 已提交
216
static void      destroyThrdObj(SCliThrd* pThrd);
dengyihao's avatar
dengyihao 已提交
217

dengyihao's avatar
dengyihao 已提交
218 219 220 221 222 223 224 225 226
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 已提交
227
// snprintf may cause performance problem
dengyihao's avatar
dengyihao 已提交
228 229 230 231
#define CONN_CONSTRUCT_HASH_KEY(key, ip, port) \
  do {                                         \
    char*   t = key;                           \
    int16_t len = strlen(ip);                  \
dengyihao's avatar
dengyihao 已提交
232
    if (ip != NULL) memcpy(t, ip, len);        \
dengyihao's avatar
dengyihao 已提交
233 234
    t[len] = ':';                              \
    titoa(port, 10, &t[len + 1]);              \
dengyihao's avatar
dengyihao 已提交
235 236
  } while (0)

dengyihao's avatar
dengyihao 已提交
237 238
#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 已提交
239

dengyihao's avatar
dengyihao 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
#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 已提交
256
  } while (0)
dengyihao's avatar
dengyihao 已提交
257

U
ubuntu 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270
#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 已提交
271

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

dengyihao's avatar
dengyihao 已提交
280 281 282 283
#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)
284

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

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

dengyihao's avatar
dengyihao 已提交
301 302 303 304 305 306 307 308 309 310 311
#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 已提交
312
  } while (0);
dengyihao's avatar
dengyihao 已提交
313

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

dengyihao's avatar
dengyihao 已提交
316 317 318 319 320 321 322 323
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 已提交
324
      } else if (msg->ctx->ahandle != NULL && pThrd->destroyAhandleFp != NULL) {
dengyihao's avatar
dengyihao 已提交
325
        tDebug("%s conn %p destroy unfinished ahandle %p", CONN_GET_INST_LABEL(conn), conn, msg->ctx->ahandle);
dengyihao's avatar
dengyihao 已提交
326
        pThrd->destroyAhandleFp(msg->ctx->ahandle);
dengyihao's avatar
dengyihao 已提交
327 328 329 330
      }
    }
    destroyCmsg(msg);
  }
dengyihao's avatar
dengyihao 已提交
331
  transQueueClear(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
332
  memset(&conn->ctx, 0, sizeof(conn->ctx));
dengyihao's avatar
dengyihao 已提交
333
}
dengyihao's avatar
dengyihao 已提交
334
bool cliMaySendCachedMsg(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
335
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
336
    SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
337
    CONN_GET_NEXT_SENDMSG(conn);
dengyihao's avatar
dengyihao 已提交
338 339
    cliSend(conn);
    return true;
dengyihao's avatar
dengyihao 已提交
340
  }
dengyihao's avatar
dengyihao 已提交
341
  return false;
U
ubuntu 已提交
342 343
_RETURN:
  return false;
dengyihao's avatar
dengyihao 已提交
344
}
dengyihao's avatar
formate  
dengyihao 已提交
345
void cliHandleResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
346 347
  SCliThrd* pThrd = conn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
348

dengyihao's avatar
dengyihao 已提交
349 350 351 352 353 354
  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 已提交
355
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
356
    conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
357 358
  }

dengyihao's avatar
opt rpc  
dengyihao 已提交
359
  STransMsgHead* pHead = NULL;
dengyihao's avatar
dengyihao 已提交
360 361 362

  int32_t msgLen = transDumpFromBuffer(&conn->readBuf, (char**)&pHead);
  if (msgLen <= 0) {
dengyihao's avatar
dengyihao 已提交
363
    taosMemoryFree(pHead);
dengyihao's avatar
dengyihao 已提交
364 365 366
    tDebug("%s conn %p recv invalid packet ", CONN_GET_INST_LABEL(conn), conn);
    return;
  }
dengyihao's avatar
dengyihao 已提交
367 368 369 370

  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 已提交
371 372
  pHead->code = htonl(pHead->code);
  pHead->msgLen = htonl(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
373 374 375 376
  if (cliRecvReleaseReq(conn, pHead)) {
    return;
  }

dengyihao's avatar
dengyihao 已提交
377 378 379 380 381
  STransMsg transMsg = {0};
  transMsg.contLen = transContLenFromMsg(pHead->msgLen);
  transMsg.pCont = transContFromHead((char*)pHead);
  transMsg.code = pHead->code;
  transMsg.msgType = pHead->msgType;
S
Shengliang Guan 已提交
382
  transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
383
  transMsg.info.traceId = pHead->traceId;
dengyihao's avatar
dengyihao 已提交
384
  transMsg.info.hasEpSet = pHead->hasEpSet;
dengyihao's avatar
dengyihao 已提交
385

dengyihao's avatar
dengyihao 已提交
386 387 388 389
  SCliMsg*       pMsg = NULL;
  STransConnCtx* pCtx = NULL;
  if (CONN_NO_PERSIST_BY_APP(conn)) {
    pMsg = transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
390 391 392

    pCtx = pMsg ? pMsg->ctx : NULL;
    transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
393
    tDebug("%s conn %p get ahandle %p, persist: 0", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
U
ubuntu 已提交
394
  } else {
dengyihao's avatar
dengyihao 已提交
395 396 397
    uint64_t ahandle = (uint64_t)pHead->ahandle;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
    if (pMsg == NULL) {
S
Shengliang Guan 已提交
398
      transMsg.info.ahandle = transCtxDumpVal(&conn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
399 400
      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 已提交
401
      if (!CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
D
dapan1121 已提交
402
        transMsg.code = TSDB_CODE_RPC_BROKEN_LINK;
S
Shengliang Guan 已提交
403
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&conn->ctx, (int32_t*)&(transMsg.msgType));
dengyihao's avatar
dengyihao 已提交
404 405
        tDebug("%s conn %p construct ahandle %p due brokenlink, persist: 1", CONN_GET_INST_LABEL(conn), conn,
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
406 407
      }
    } else {
dengyihao's avatar
dengyihao 已提交
408
      pCtx = pMsg->ctx;
S
Shengliang Guan 已提交
409
      transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
410
      tDebug("%s conn %p get ahandle %p, persist: 1", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
411
    }
U
ubuntu 已提交
412
  }
dengyihao's avatar
dengyihao 已提交
413
  // buf's mem alread translated to transMsg.pCont
dengyihao's avatar
dengyihao 已提交
414
  if (!CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
415
    transMsg.info.handle = (void*)conn->refId;
dengyihao's avatar
dengyihao 已提交
416
    tDebug("%s conn %p ref by app", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
417
  }
dengyihao's avatar
dengyihao 已提交
418

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

dengyihao's avatar
dengyihao 已提交
423
  if (pCtx == NULL && CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
424
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
425
    transFreeMsg(transMsg.pCont);
dengyihao's avatar
dengyihao 已提交
426 427
    return;
  }
S
Shengliang Guan 已提交
428
  if (CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
429
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
430
    transFreeMsg(transMsg.pCont);
dengyihao's avatar
dengyihao 已提交
431 432
    return;
  }
dengyihao's avatar
dengyihao 已提交
433

dengyihao's avatar
dengyihao 已提交
434
  if (pMsg == NULL || (pMsg && pMsg->type != Release)) {
dengyihao's avatar
dengyihao 已提交
435 436 437
    if (cliAppCb(conn, &transMsg, pMsg) != 0) {
      return;
    }
dengyihao's avatar
dengyihao 已提交
438
  }
dengyihao's avatar
dengyihao 已提交
439 440
  destroyCmsg(pMsg);

dengyihao's avatar
dengyihao 已提交
441
  if (cliMaySendCachedMsg(conn) == true) {
dengyihao's avatar
dengyihao 已提交
442 443
    return;
  }
dengyihao's avatar
dengyihao 已提交
444

U
ubuntu 已提交
445
  if (CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
446
    return addConnToPool(pThrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
447
  }
dengyihao's avatar
test  
dengyihao 已提交
448

dengyihao's avatar
dengyihao 已提交
449
  uv_read_start((uv_stream_t*)conn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
450
}
U
ubuntu 已提交
451

dengyihao's avatar
dengyihao 已提交
452
void cliHandleExceptImpl(SCliConn* pConn, int32_t code) {
dengyihao's avatar
dengyihao 已提交
453
  if (transQueueEmpty(&pConn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
454
    if (pConn->broken == true && CONN_NO_PERSIST_BY_APP(pConn)) {
dengyihao's avatar
dengyihao 已提交
455
      tTrace("%s conn %p handle except, persist:0", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
formate  
dengyihao 已提交
456 457 458
      transUnrefCliHandle(pConn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
459
  }
dengyihao's avatar
dengyihao 已提交
460 461 462
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
  bool      once = false;
D
dapan1121 已提交
463
  do {
dengyihao's avatar
dengyihao 已提交
464
    SCliMsg* pMsg = transQueuePop(&pConn->cliMsgs);
dengyihao's avatar
enh log  
dengyihao 已提交
465

D
dapan1121 已提交
466 467
    if (pMsg == NULL && once) {
      break;
dengyihao's avatar
dengyihao 已提交
468
    }
dengyihao's avatar
enh log  
dengyihao 已提交
469 470 471 472 473 474

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

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

dengyihao's avatar
dengyihao 已提交
477
    STransMsg transMsg = {0};
dengyihao's avatar
dengyihao 已提交
478
    transMsg.code = code == -1 ? (pConn->broken ? TSDB_CODE_RPC_BROKEN_LINK : TSDB_CODE_RPC_NETWORK_UNAVAIL) : code;
dengyihao's avatar
dengyihao 已提交
479
    transMsg.msgType = pMsg ? pMsg->msg.msgType + 1 : 0;
S
Shengliang Guan 已提交
480
    transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
481

dengyihao's avatar
dengyihao 已提交
482
    if (pMsg == NULL && !CONN_NO_PERSIST_BY_APP(pConn)) {
S
Shengliang Guan 已提交
483
      transMsg.info.ahandle = transCtxDumpVal(&pConn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
484
      tDebug("%s conn %p construct ahandle %p by %s", CONN_GET_INST_LABEL(pConn), pConn, transMsg.info.ahandle,
dengyihao's avatar
dengyihao 已提交
485
             TMSG_INFO(transMsg.msgType));
S
Shengliang Guan 已提交
486
      if (transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
487 488 489
        int32_t msgType = 0;
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&pConn->ctx, &msgType);
        transMsg.msgType = msgType;
dengyihao's avatar
dengyihao 已提交
490
        tDebug("%s conn %p construct ahandle %p due to brokenlink", CONN_GET_INST_LABEL(pConn), pConn,
S
Shengliang Guan 已提交
491
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
492
      }
dengyihao's avatar
dengyihao 已提交
493
    } else {
dengyihao's avatar
dengyihao 已提交
494
      transMsg.info.ahandle = (pMsg != NULL && pMsg->type != Release && pCtx) ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
495 496 497
    }

    if (pCtx == NULL || pCtx->pSem == NULL) {
S
Shengliang Guan 已提交
498
      if (transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
499 500 501 502 503
        if (pMsg == NULL || REQUEST_NO_RESP(&pMsg->msg) || pMsg->type == Release) {
          destroyCmsg(pMsg);
          once = true;
          continue;
        }
U
ubuntu 已提交
504
      }
dengyihao's avatar
dengyihao 已提交
505
    }
dengyihao's avatar
enh log  
dengyihao 已提交
506

dengyihao's avatar
dengyihao 已提交
507
    if (pMsg == NULL || (pMsg && pMsg->type != Release)) {
dengyihao's avatar
dengyihao 已提交
508 509 510
      if (cliAppCb(pConn, &transMsg, pMsg) != 0) {
        return;
      }
dengyihao's avatar
dengyihao 已提交
511 512
    }
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
513
    tTrace("%s conn %p start to destroy, ref:%d", CONN_GET_INST_LABEL(pConn), pConn, T_REF_VAL_GET(pConn));
D
dapan1121 已提交
514
  } while (!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
515
  transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
516
}
dengyihao's avatar
dengyihao 已提交
517
void cliHandleExcept(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
518
  tTrace("%s conn %p except ref:%d", CONN_GET_INST_LABEL(conn), conn, T_REF_VAL_GET(conn));
dengyihao's avatar
dengyihao 已提交
519 520
  cliHandleExceptImpl(conn, -1);
}
dengyihao's avatar
dengyihao 已提交
521

dengyihao's avatar
dengyihao 已提交
522 523
void cliConnTimeout(uv_timer_t* handle) {
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
524 525
  SCliThrd* pThrd = conn->hostThrd;

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

dengyihao's avatar
dengyihao 已提交
528
  uv_timer_stop(handle);
dengyihao's avatar
dengyihao 已提交
529 530 531
  handle->data = NULL;
  taosArrayPush(pThrd->timerList, &conn->timer);
  conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
532 533

  cliHandleFastFail(conn, UV_ECANCELED);
dengyihao's avatar
dengyihao 已提交
534
}
dengyihao's avatar
dengyihao 已提交
535 536 537 538
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 已提交
539
  uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
540 541
  cliHandleExceptImpl(conn, TSDB_CODE_RPC_TIMEOUT);
}
U
ubuntu 已提交
542 543

void* createConnPool(int size) {
544 545
  // thread local, no lock
  return taosHashInit(size, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
546
}
U
ubuntu 已提交
547
void* destroyConnPool(void* pool) {
dengyihao's avatar
dengyihao 已提交
548
  SConnList* connList = taosHashIterate((SHashObj*)pool, NULL);
dengyihao's avatar
dengyihao 已提交
549
  while (connList != NULL) {
dengyihao's avatar
dengyihao 已提交
550 551
    while (!QUEUE_IS_EMPTY(&connList->conns)) {
      queue*    h = QUEUE_HEAD(&connList->conns);
dengyihao's avatar
dengyihao 已提交
552
      SCliConn* c = QUEUE_DATA(h, SCliConn, q);
U
ubuntu 已提交
553
      cliDestroyConn(c, true);
dengyihao's avatar
dengyihao 已提交
554
    }
dengyihao's avatar
dengyihao 已提交
555
    connList = taosHashIterate((SHashObj*)pool, connList);
dengyihao's avatar
dengyihao 已提交
556
  }
dengyihao's avatar
dengyihao 已提交
557
  taosHashCleanup(pool);
558
  return NULL;
dengyihao's avatar
dengyihao 已提交
559 560
}

dengyihao's avatar
dengyihao 已提交
561
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port) {
dengyihao's avatar
TS-2015  
dengyihao 已提交
562
  char key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
563
  CONN_CONSTRUCT_HASH_KEY(key, ip, port);
dengyihao's avatar
dengyihao 已提交
564 565

  SConnList* plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
566
  if (plist == NULL) {
dengyihao's avatar
dengyihao 已提交
567
    SConnList list = {0};
dengyihao's avatar
dengyihao 已提交
568 569
    taosHashPut((SHashObj*)pool, key, strlen(key), (void*)&list, sizeof(list));
    plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
570
    if (plist == NULL) return NULL;
dengyihao's avatar
dengyihao 已提交
571
    QUEUE_INIT(&plist->conns);
dengyihao's avatar
dengyihao 已提交
572 573
  }

dengyihao's avatar
dengyihao 已提交
574
  if (QUEUE_IS_EMPTY(&plist->conns)) {
dengyihao's avatar
dengyihao 已提交
575 576
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
577 578

  plist->size -= 1;
dengyihao's avatar
dengyihao 已提交
579
  queue*    h = QUEUE_HEAD(&plist->conns);
dengyihao's avatar
dengyihao 已提交
580
  SCliConn* conn = QUEUE_DATA(h, SCliConn, q);
dengyihao's avatar
dengyihao 已提交
581
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
582 583
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
584

dengyihao's avatar
dengyihao 已提交
585 586 587 588
  if (conn->task != NULL) {
    transDQCancel(((SCliThrd*)conn->hostThrd)->timeoutQueue, conn->task);
    conn->task = NULL;
  }
dengyihao's avatar
dengyihao 已提交
589
  return conn;
dengyihao's avatar
dengyihao 已提交
590
}
dengyihao's avatar
dengyihao 已提交
591 592 593 594 595 596
static void addConnToPool(void* pool, SCliConn* conn) {
  if (conn->status == ConnInPool) {
    return;
  }
  allocConnRef(conn, true);

dengyihao's avatar
dengyihao 已提交
597
  SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
598 599 600 601 602 603
  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 已提交
604 605 606 607 608
  if (T_REF_VAL_GET(conn) > 1) {
    transUnrefCliHandle(conn);
  }

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

dengyihao's avatar
dengyihao 已提交
610 611 612 613
  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 已提交
614
    conn->list = taosHashGet((SHashObj*)pool, conn->ip, strlen(conn->ip));
dengyihao's avatar
dengyihao 已提交
615 616
  } 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 已提交
617
  }
dengyihao's avatar
dengyihao 已提交
618
  QUEUE_PUSH(&conn->list->conns, &conn->q);
dengyihao's avatar
dengyihao 已提交
619
  conn->list->size += 1;
dengyihao's avatar
dengyihao 已提交
620

dengyihao's avatar
dengyihao 已提交
621
  if (conn->list->size >= 250) {
dengyihao's avatar
dengyihao 已提交
622 623
    STaskArg* arg = taosMemoryCalloc(1, sizeof(STaskArg));
    arg->param1 = conn;
dengyihao's avatar
dengyihao 已提交
624
    arg->param2 = thrd;
dengyihao's avatar
dengyihao 已提交
625 626

    STrans* pTransInst = thrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
627 628
    conn->task = transDQSched(thrd->timeoutQueue, doCloseIdleConn, arg, CONN_PERSIST_TIME(pTransInst->idleTime));
  }
dengyihao's avatar
dengyihao 已提交
629
}
dengyihao's avatar
dengyihao 已提交
630
static int32_t allocConnRef(SCliConn* conn, bool update) {
dengyihao's avatar
dengyihao 已提交
631
  if (update) {
dengyihao's avatar
dengyihao 已提交
632
    transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
633
    transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
634
    conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
635 636 637 638
  }
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
639
  exh->refId = transAddExHandle(transGetRefMgt(), exh);
dengyihao's avatar
dengyihao 已提交
640
  conn->refId = exh->refId;
641 642 643 644

  if (conn->refId == -1) {
    taosMemoryFree(exh);
  }
dengyihao's avatar
dengyihao 已提交
645 646 647 648 649
  return 0;
}

static int32_t specifyConnRef(SCliConn* conn, bool update, int64_t handle) {
  if (update) {
dengyihao's avatar
dengyihao 已提交
650
    transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663
    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 已提交
664
}
dengyihao's avatar
dengyihao 已提交
665

dengyihao's avatar
dengyihao 已提交
666
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
667
  SCliConn*    conn = handle->data;
dengyihao's avatar
dengyihao 已提交
668
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
669
  tDebug("%s conn %p alloc read buf", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
670
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
671
}
U
ubuntu 已提交
672
static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
673
  // impl later
dengyihao's avatar
dengyihao 已提交
674 675 676
  if (handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
677 678
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
679
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
680
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
681
    while (transReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
682
      tDebug("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
683 684 685 686 687 688
      if (pBuf->invalid) {
        cliHandleExcept(conn);
        break;
      } else {
        cliHandleResp(conn);
      }
dengyihao's avatar
dengyihao 已提交
689
    }
dengyihao's avatar
dengyihao 已提交
690 691
    return;
  }
dengyihao's avatar
dengyihao 已提交
692

693
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
694 695 696
    // 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 已提交
697
    tTrace("%s conn %p read empty", CONN_GET_INST_LABEL(conn), conn);
698 699
    return;
  }
dengyihao's avatar
fix bug  
dengyihao 已提交
700
  if (nread < 0) {
dengyihao's avatar
dengyihao 已提交
701
    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 已提交
702
    conn->broken = true;
U
ubuntu 已提交
703
    cliHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
704
  }
dengyihao's avatar
dengyihao 已提交
705
}
dengyihao's avatar
dengyihao 已提交
706

dengyihao's avatar
dengyihao 已提交
707
static SCliConn* cliCreateConn(SCliThrd* pThrd) {
wafwerar's avatar
wafwerar 已提交
708
  SCliConn* conn = taosMemoryCalloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
709
  // read/write stream handle
G
gccgdb1234 已提交
710
  conn->stream = (uv_stream_t*)taosMemoryMalloc(sizeof(uv_tcp_t));
dengyihao's avatar
dengyihao 已提交
711 712 713
  uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
  conn->stream->data = conn;

dengyihao's avatar
dengyihao 已提交
714 715 716 717 718 719 720 721
  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 已提交
722

dengyihao's avatar
dengyihao 已提交
723
  conn->connReq.data = conn;
dengyihao's avatar
dengyihao 已提交
724 725
  transReqQueueInit(&conn->wreqQueue);

dengyihao's avatar
dengyihao 已提交
726
  transQueueInit(&conn->cliMsgs, NULL);
dengyihao's avatar
opt rpc  
dengyihao 已提交
727 728

  transInitBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
729
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
730
  conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
731
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
732
  conn->broken = false;
dengyihao's avatar
dengyihao 已提交
733
  transRefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
734

dengyihao's avatar
dengyihao 已提交
735
  atomic_add_fetch_32(&pThrd->connCount, 1);
dengyihao's avatar
dengyihao 已提交
736
  allocConnRef(conn, false);
dengyihao's avatar
dengyihao 已提交
737

dengyihao's avatar
dengyihao 已提交
738 739
  return conn;
}
U
ubuntu 已提交
740
static void cliDestroyConn(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
741
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
742
  tTrace("%s conn %p remove from conn pool", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
743 744
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
745
  transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
746
  transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
opt rpc  
dengyihao 已提交
747
  conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
748

dengyihao's avatar
dengyihao 已提交
749 750 751 752 753 754 755
  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 已提交
756
    taosArrayPush(pThrd->timerList, &conn->timer);
dengyihao's avatar
dengyihao 已提交
757 758
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
759

dengyihao's avatar
dengyihao 已提交
760
  if (clear) {
dengyihao's avatar
dengyihao 已提交
761
    if (!uv_is_closing((uv_handle_t*)conn->stream)) {
dengyihao's avatar
dengyihao 已提交
762
      uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
763 764
      uv_close((uv_handle_t*)conn->stream, cliDestroy);
    }
765
  }
dengyihao's avatar
dengyihao 已提交
766
}
U
ubuntu 已提交
767
static void cliDestroy(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
768 769 770
  if (uv_handle_get_type(handle) != UV_TCP || handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
771
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
772
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
773 774
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
dengyihao's avatar
dengyihao 已提交
775 776
    taosArrayPush(pThrd->timerList, &conn->timer);
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
777 778
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
779 780 781
  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 已提交
782

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

dengyihao's avatar
dengyihao 已提交
785
  transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
786
  transRemoveExHandle(transGetRefMgt(), conn->refId);
wafwerar's avatar
wafwerar 已提交
787 788
  taosMemoryFree(conn->ip);
  taosMemoryFree(conn->stream);
dengyihao's avatar
dengyihao 已提交
789 790 791

  cliDestroyConnMsgs(conn, true);

dengyihao's avatar
dengyihao 已提交
792
  tTrace("%s conn %p destroy successfully", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
793
  transReqQueueClear(&conn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
794
  transDestroyBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
795

wafwerar's avatar
wafwerar 已提交
796
  taosMemoryFree(conn);
dengyihao's avatar
dengyihao 已提交
797
}
dengyihao's avatar
dengyihao 已提交
798
static bool cliHandleNoResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
799 800
  bool res = false;
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
801
    SCliMsg* pMsg = transQueueGet(&conn->cliMsgs, 0);
dengyihao's avatar
dengyihao 已提交
802
    if (REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
803
      transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
804 805 806 807 808
      destroyCmsg(pMsg);
      res = true;
    }
    if (res == true) {
      if (cliMaySendCachedMsg(conn) == false) {
dengyihao's avatar
dengyihao 已提交
809
        SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
810
        addConnToPool(thrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
811 812 813
        res = false;
      } else {
        res = true;
dengyihao's avatar
dengyihao 已提交
814 815 816 817 818
      }
    }
  }
  return res;
}
U
ubuntu 已提交
819
static void cliSendCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
820 821
  SCliConn* pConn = transReqQueueRemove(req);
  if (pConn == NULL) return;
dengyihao's avatar
dengyihao 已提交
822

dengyihao's avatar
dengyihao 已提交
823 824 825
  SCliMsg* pMsg = !transQueueEmpty(&pConn->cliMsgs) ? transQueueGet(&pConn->cliMsgs, 0) : NULL;
  if (pMsg != NULL) {
    int64_t cost = taosGetTimestampUs() - pMsg->st;
dengyihao's avatar
dengyihao 已提交
826
    if (cost > 1000 * 20) {
dengyihao's avatar
dengyihao 已提交
827 828 829 830
      tWarn("%s conn %p send cost:%dus, send exception", CONN_GET_INST_LABEL(pConn), pConn, (int)cost);
    }
  }

dengyihao's avatar
dengyihao 已提交
831
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
832
    tTrace("%s conn %p data already was written out", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
833
  } else {
dengyihao's avatar
dengyihao 已提交
834 835 836 837
    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 已提交
838 839
    return;
  }
dengyihao's avatar
dengyihao 已提交
840
  if (cliHandleNoResp(pConn) == true) {
dengyihao's avatar
dengyihao 已提交
841
    tTrace("%s conn %p no resp required", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
842 843
    return;
  }
dengyihao's avatar
dengyihao 已提交
844
  uv_read_start((uv_stream_t*)pConn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
845
}
dengyihao's avatar
dengyihao 已提交
846 847 848 849
void cliSendBatch(SCliConn* pConn) {
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;

dengyihao's avatar
dengyihao 已提交
850 851 852 853 854
  SCliBatch*     pBatch = pConn->pBatch;
  SCliBatchList* pList = pBatch->pList;
  pList->connCnt += 1;

  int32_t wLen = pBatch->wLen;
dengyihao's avatar
dengyihao 已提交
855 856 857 858

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

dengyihao's avatar
dengyihao 已提交
859 860
  queue* h = NULL;
  QUEUE_FOREACH(h, &pBatch->wq) {
dengyihao's avatar
dengyihao 已提交
861 862 863 864 865 866 867 868 869
    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 已提交
870

dengyihao's avatar
dengyihao 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
    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 已提交
887 888 889 890 891 892 893 894
    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 已提交
895 896 897 898 899
    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 已提交
900
  tDebug("%s conn %p start to send batch msg, batch size:%d, msgLen:%d", CONN_GET_INST_LABEL(pConn), pConn,
dengyihao's avatar
dengyihao 已提交
901
         pBatch->wLen, pBatch->batchSize);
dengyihao's avatar
dengyihao 已提交
902 903 904
  uv_write(req, (uv_stream_t*)pConn->stream, wb, wLen, cliSendBatchCb);
  taosMemoryFree(wb);
}
U
ubuntu 已提交
905
void cliSend(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
906 907 908 909 910
  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 已提交
911
    cliHandleExcept(pConn);
dengyihao's avatar
dengyihao 已提交
912 913
    return;
  }
dengyihao's avatar
dengyihao 已提交
914 915

  SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
916
  CONN_GET_NEXT_SENDMSG(pConn);
dengyihao's avatar
dengyihao 已提交
917 918
  pCliMsg->sent = 1;

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

U
ubuntu 已提交
921
  STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
dengyihao's avatar
dengyihao 已提交
922 923 924 925
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
dengyihao's avatar
dengyihao 已提交
926

dengyihao's avatar
dengyihao 已提交
927
  int            msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
928
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
dengyihao's avatar
dengyihao 已提交
929

dengyihao's avatar
dengyihao 已提交
930 931 932 933 934 935 936 937 938 939 940
  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 已提交
941
  pHead->timestamp = taosHton64(taosGetTimestampUs());
dengyihao's avatar
dengyihao 已提交
942

dengyihao's avatar
dengyihao 已提交
943 944 945
  if (pHead->persist == 1) {
    CONN_SET_PERSIST_BY_APP(pConn);
  }
dengyihao's avatar
dengyihao 已提交
946

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

dengyihao's avatar
dengyihao 已提交
949
  if (pTransInst->startTimer != NULL && pTransInst->startTimer(0, pMsg->msgType)) {
dengyihao's avatar
dengyihao 已提交
950
    uv_timer_t* timer = taosArrayGetSize(pThrd->timerList) > 0 ? *(uv_timer_t**)taosArrayPop(pThrd->timerList) : NULL;
dengyihao's avatar
dengyihao 已提交
951 952
    if (timer == NULL) {
      timer = taosMemoryCalloc(1, sizeof(uv_timer_t));
dengyihao's avatar
dengyihao 已提交
953
      tDebug("no available timer, create a timer %p", timer);
dengyihao's avatar
dengyihao 已提交
954 955 956 957 958
      uv_timer_init(pThrd->loop, timer);
    }
    timer->data = pConn;
    pConn->timer = timer;

dengyihao's avatar
dengyihao 已提交
959 960 961
    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 已提交
962

dengyihao's avatar
dengyihao 已提交
963 964 965 966 967 968 969
  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 已提交
970
  }
dengyihao's avatar
dengyihao 已提交
971

dengyihao's avatar
dengyihao 已提交
972 973
  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 已提交
974

dengyihao's avatar
dengyihao 已提交
975
  uv_buf_t    wb = uv_buf_init((char*)pHead, msgLen);
dengyihao's avatar
dengyihao 已提交
976
  uv_write_t* req = transReqQueuePush(&pConn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
977 978 979

  int status = uv_write(req, (uv_stream_t*)pConn->stream, &wb, 1, cliSendCb);
  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
980
    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 已提交
981 982 983
            uv_err_name(status));
    cliHandleExcept(pConn);
  }
U
ubuntu 已提交
984 985
  return;
_RETURN:
dengyihao's avatar
dengyihao 已提交
986
  return;
dengyihao's avatar
dengyihao 已提交
987
}
dengyihao's avatar
dengyihao 已提交
988 989

static void cliDestroyBatch(SCliBatch* pBatch) {
dengyihao's avatar
dengyihao 已提交
990
  if (pBatch == NULL) return;
dengyihao's avatar
dengyihao 已提交
991
  while (!QUEUE_IS_EMPTY(&pBatch->wq)) {
dengyihao's avatar
dengyihao 已提交
992 993
    queue* h = QUEUE_HEAD(&pBatch->wq);
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
994

dengyihao's avatar
dengyihao 已提交
995
    SCliMsg* p = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
996 997
    destroyCmsg(p);
  }
dengyihao's avatar
dengyihao 已提交
998 999
  SCliBatchList* p = pBatch->pList;
  p->sending -= 1;
dengyihao's avatar
dengyihao 已提交
1000 1001
  taosMemoryFree(pBatch);
}
dengyihao's avatar
dengyihao 已提交
1002
static void cliHandleBatchReq(SCliBatch* pBatch, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1003 1004 1005 1006 1007
  if (pThrd->quit == true) {
    cliDestroyBatch(pBatch);
    return;
  }

dengyihao's avatar
dengyihao 已提交
1008
  if (pBatch == NULL || pBatch->wLen == 0 || QUEUE_IS_EMPTY(&pBatch->wq)) {
dengyihao's avatar
dengyihao 已提交
1009 1010
    return;
  }
dengyihao's avatar
dengyihao 已提交
1011 1012
  STrans*        pTransInst = pThrd->pTransInst;
  SCliBatchList* pList = pBatch->pList;
dengyihao's avatar
dengyihao 已提交
1013

dengyihao's avatar
dengyihao 已提交
1014
  SCliConn* conn = getConnFromPool(pThrd->pool, pList->ip, pList->port);
dengyihao's avatar
dengyihao 已提交
1015

dengyihao's avatar
dengyihao 已提交
1016 1017 1018 1019
  if (conn == NULL && 0 != cliPreCheckSessionLimit(pThrd, pList->ip, pList->port)) {
    tError("%s failed to send batch msg, batch size:%d, msgLen: %d", pTransInst->label, pBatch->wLen,
           pBatch->batchSize);
    cliDestroyBatch(pBatch);
dengyihao's avatar
dengyihao 已提交
1020 1021
    return;
  }
dengyihao's avatar
dengyihao 已提交
1022 1023
  if (conn == NULL) {
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
1024
    conn->pBatch = pBatch;
1025
    conn->ip = taosStrdup(pList->dst);
dengyihao's avatar
dengyihao 已提交
1026

dengyihao's avatar
dengyihao 已提交
1027
    uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, pList->ip);
dengyihao's avatar
dengyihao 已提交
1028 1029 1030 1031 1032 1033
    if (ipaddr == 0xffffffff) {
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

dengyihao's avatar
dengyihao 已提交
1034
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1035 1036 1037 1038 1039
      return;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = ipaddr;
dengyihao's avatar
dengyihao 已提交
1040
    addr.sin_port = (uint16_t)htons(pList->port);
dengyihao's avatar
dengyihao 已提交
1041

dengyihao's avatar
dengyihao 已提交
1042
    tTrace("%s conn %p try to connect to %s", pTransInst->label, conn, pList->dst);
dengyihao's avatar
dengyihao 已提交
1043 1044
    int32_t fd = taosCreateSocketWithTimeout(TRANS_CONN_TIMEOUT * 4);
    if (fd == -1) {
dengyihao's avatar
dengyihao 已提交
1045 1046 1047
      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 已提交
1048 1049 1050 1051
      return;
    }
    int ret = uv_tcp_open((uv_tcp_t*)conn->stream, fd);
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1052 1053
      tError("%s conn %p failed to set stream, reason:%s", transLabel(pTransInst), conn, uv_err_name(ret));
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1054 1055 1056 1057
      return;
    }
    ret = transSetConnOption((uv_tcp_t*)conn->stream);
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1058 1059
      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 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068
      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 已提交
1069
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1070 1071 1072 1073 1074 1075
      return;
    }
    uv_timer_start(conn->timer, cliConnTimeout, TRANS_CONN_TIMEOUT, 0);
    return;
  }

dengyihao's avatar
dengyihao 已提交
1076
  conn->pBatch = pBatch;
dengyihao's avatar
dengyihao 已提交
1077
  cliSendBatch(conn);
dengyihao's avatar
dengyihao 已提交
1078 1079
}
static void cliSendBatchCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
1080 1081 1082
  SCliConn*  conn = req->data;
  SCliThrd*  thrd = conn->hostThrd;
  SCliBatch* p = conn->pBatch;
dengyihao's avatar
dengyihao 已提交
1083

dengyihao's avatar
dengyihao 已提交
1084
  SCliBatchList* pBatchList = p->pList;
dengyihao's avatar
dengyihao 已提交
1085
  SCliBatch*     nxtBatch = cliGetHeadFromList(pBatchList);
dengyihao's avatar
dengyihao 已提交
1086 1087
  pBatchList->connCnt -= 1;

dengyihao's avatar
dengyihao 已提交
1088 1089 1090
  conn->pBatch = NULL;

  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
1091
    tDebug("%s conn %p failed to send batch msg, batch size:%d, msgLen:%d, reason:%s", CONN_GET_INST_LABEL(conn), conn,
dengyihao's avatar
dengyihao 已提交
1092
           p->wLen, p->batchSize, uv_err_name(status));
dengyihao's avatar
dengyihao 已提交
1093 1094 1095

    if (!uv_is_closing((uv_handle_t*)&conn->stream)) cliHandleExcept(conn);

dengyihao's avatar
dengyihao 已提交
1096
    cliHandleBatchReq(nxtBatch, thrd);
dengyihao's avatar
dengyihao 已提交
1097
  } else {
dengyihao's avatar
dengyihao 已提交
1098
    tDebug("%s conn %p succ to send batch msg, batch size:%d, msgLen:%d", CONN_GET_INST_LABEL(conn), conn, p->wLen,
dengyihao's avatar
dengyihao 已提交
1099
           p->batchSize);
dengyihao's avatar
dengyihao 已提交
1100
    if (!uv_is_closing((uv_handle_t*)&conn->stream)) {
dengyihao's avatar
dengyihao 已提交
1101 1102 1103 1104 1105 1106
      if (nxtBatch != NULL) {
        conn->pBatch = nxtBatch;
        cliSendBatch(conn);
      } else {
        addConnToPool(thrd->pool, conn);
      }
dengyihao's avatar
dengyihao 已提交
1107
    } else {
dengyihao's avatar
dengyihao 已提交
1108 1109
      cliDestroyBatch(nxtBatch);
      // conn release by other callback
dengyihao's avatar
dengyihao 已提交
1110
    }
dengyihao's avatar
dengyihao 已提交
1111
  }
dengyihao's avatar
dengyihao 已提交
1112 1113 1114

  cliDestroyBatch(p);
  taosMemoryFree(req);
dengyihao's avatar
dengyihao 已提交
1115
}
dengyihao's avatar
dengyihao 已提交
1116
static void cliHandleFastFail(SCliConn* pConn, int status) {
dengyihao's avatar
dengyihao 已提交
1117
  SCliThrd* pThrd = pConn->hostThrd;
dengyihao's avatar
dengyihao 已提交
1118
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1119 1120 1121

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

dengyihao's avatar
dengyihao 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
  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 已提交
1141
      } else {
dengyihao's avatar
dengyihao 已提交
1142 1143
        SFailFastItem item = {.count = 1, .timestamp = cTimestamp};
        taosHashPut(pThrd->failFastCache, pConn->ip, strlen(pConn->ip), &item, sizeof(SFailFastItem));
dengyihao's avatar
dengyihao 已提交
1144 1145
      }
    }
dengyihao's avatar
dengyihao 已提交
1146
  } else {
dengyihao's avatar
dengyihao 已提交
1147 1148
    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 已提交
1149 1150
    cliDestroyBatch(pConn->pBatch);
    pConn->pBatch = NULL;
dengyihao's avatar
dengyihao 已提交
1151 1152 1153
  }
  cliHandleExcept(pConn);
}
dengyihao's avatar
dengyihao 已提交
1154

dengyihao's avatar
dengyihao 已提交
1155 1156 1157
void cliConnCb(uv_connect_t* req, int status) {
  SCliConn* pConn = req->data;
  SCliThrd* pThrd = pConn->hostThrd;
dengyihao's avatar
dengyihao 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
  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 已提交
1168 1169

  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
1170 1171 1172 1173 1174
    if (timeout == false) {
      cliHandleFastFail(pConn, status);
    } else if (timeout == true) {
      // already deal by timeout
    }
1175
    return;
dengyihao's avatar
dengyihao 已提交
1176
  }
dengyihao's avatar
dengyihao 已提交
1177

dengyihao's avatar
dengyihao 已提交
1178
  int32_t* oVal = taosHashGet(pThrd->connLimitCache, pConn->ip, strlen(pConn->ip));
dengyihao's avatar
dengyihao 已提交
1179
  int32_t  nVal = oVal == NULL ? 0 : (*oVal) + 1;
dengyihao's avatar
dengyihao 已提交
1180
  taosHashPut(pThrd->connLimitCache, pConn->ip, strlen(pConn->ip), &nVal, sizeof(nVal));
dengyihao's avatar
dengyihao 已提交
1181 1182 1183

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

dengyihao's avatar
dengyihao 已提交
1187 1188
  addrlen = sizeof(sockname);
  uv_tcp_getsockname((uv_tcp_t*)pConn->stream, &sockname, &addrlen);
dengyihao's avatar
dengyihao 已提交
1189
  transSockInfo2Str(&sockname, pConn->src);
dengyihao's avatar
dengyihao 已提交
1190

dengyihao's avatar
dengyihao 已提交
1191
  tTrace("%s conn %p connect to server successfully", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1192 1193 1194 1195 1196
  if (pConn->pBatch != NULL) {
    cliSendBatch(pConn);
  } else {
    cliSend(pConn);
  }
dengyihao's avatar
dengyihao 已提交
1197 1198
}

dengyihao's avatar
dengyihao 已提交
1199
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1200 1201 1202 1203 1204
  if (!transAsyncPoolIsEmpty(pThrd->asyncPool)) {
    pThrd->stopMsg = pMsg;
    return;
  }
  pThrd->stopMsg = NULL;
dengyihao's avatar
dengyihao 已提交
1205
  pThrd->quit = true;
U
ubuntu 已提交
1206
  tDebug("cli work thread %p start to quit", pThrd);
dengyihao's avatar
dengyihao 已提交
1207
  destroyCmsg(pMsg);
dengyihao's avatar
fix bug  
dengyihao 已提交
1208
  destroyConnPool(pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1209
  uv_walk(pThrd->loop, cliWalkCb, NULL);
dengyihao's avatar
dengyihao 已提交
1210
}
dengyihao's avatar
dengyihao 已提交
1211
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1212
  int64_t    refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
1213
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1214
  if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
1215
    tDebug("%" PRId64 " already released", refId);
dengyihao's avatar
dengyihao 已提交
1216 1217
    destroyCmsg(pMsg);
    return;
dengyihao's avatar
dengyihao 已提交
1218 1219 1220
  }

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

dengyihao's avatar
dengyihao 已提交
1224 1225
  if (T_REF_VAL_GET(conn) == 2) {
    transUnrefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
1226 1227
    if (!transQueuePush(&conn->cliMsgs, pMsg)) {
      return;
dengyihao's avatar
dengyihao 已提交
1228 1229
    }
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
1230 1231 1232
  } else {
    tError("%s conn %p already released", CONN_GET_INST_LABEL(conn), conn);
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1233 1234
  }
}
dengyihao's avatar
dengyihao 已提交
1235
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1236
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1237
  pThrd->cvtAddr = pCtx->cvtAddr;
dengyihao's avatar
dengyihao 已提交
1238 1239
  destroyCmsg(pMsg);
}
U
ubuntu 已提交
1240

dengyihao's avatar
dengyihao 已提交
1241
SCliConn* cliGetConn(SCliMsg* pMsg, SCliThrd* pThrd, bool* ignore) {
dengyihao's avatar
dengyihao 已提交
1242 1243 1244 1245
  STransConnCtx* pCtx = pMsg->ctx;
  SCliConn*      conn = NULL;

  int64_t refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
1246
  if (refId != 0) {
dengyihao's avatar
dengyihao 已提交
1247
    SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1248
    if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
1249
      tError("failed to get conn, refId: %" PRId64 "", refId);
dengyihao's avatar
dengyihao 已提交
1250 1251
      *ignore = true;
      return NULL;
dengyihao's avatar
dengyihao 已提交
1252 1253
    } else {
      conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
1254 1255
      if (conn == NULL) {
        conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
dengyihao's avatar
dengyihao 已提交
1256
        if (conn != NULL) specifyConnRef(conn, true, refId);
dengyihao's avatar
dengyihao 已提交
1257
      }
dengyihao's avatar
dengyihao 已提交
1258
      transReleaseExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1259 1260 1261
    }
    return conn;
  };
dengyihao's avatar
dengyihao 已提交
1262 1263 1264

  conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
1265
    tTrace("%s conn %p get from conn pool:%p", CONN_GET_INST_LABEL(conn), conn, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1266
  } else {
dengyihao's avatar
dengyihao 已提交
1267
    tTrace("%s not found conn in conn pool:%p", ((STrans*)pThrd->pTransInst)->label, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1268
  }
dengyihao's avatar
dengyihao 已提交
1269 1270
  return conn;
}
dengyihao's avatar
dengyihao 已提交
1271
FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr) {
dengyihao's avatar
dengyihao 已提交
1272 1273 1274
  if (pCvtAddr->cvt == false) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1275 1276 1277
  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 已提交
1278 1279
  }
}
dengyihao's avatar
dengyihao 已提交
1280

dengyihao's avatar
dengyihao 已提交
1281
FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx) {
dengyihao's avatar
dengyihao 已提交
1282
  if (code != 0) return false;
dengyihao's avatar
dengyihao 已提交
1283
  // if (pCtx->retryCnt == 0) return false;
dengyihao's avatar
dengyihao 已提交
1284 1285 1286
  if (transEpSetIsEqual(&pCtx->epSet, &pCtx->origEpSet)) return false;
  return true;
}
dengyihao's avatar
dengyihao 已提交
1287
FORCE_INLINE int32_t cliBuildExceptResp(SCliMsg* pMsg, STransMsg* pResp) {
dengyihao's avatar
dengyihao 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  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 已提交
1299 1300 1301 1302 1303
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);
1304 1305 1306 1307
    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 已提交
1308 1309
    }

dengyihao's avatar
dengyihao 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    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 已提交
1320

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

dengyihao's avatar
dengyihao 已提交
1324 1325 1326
  // 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 已提交
1327 1328 1329 1330

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

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

dengyihao's avatar
dengyihao 已提交
1334
  if (*val >= pTransInst->connLimitNum) {
dengyihao's avatar
dengyihao 已提交
1335 1336 1337 1338
    return -1;
  }
  return 0;
}
dengyihao's avatar
dengyihao 已提交
1339
void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
formate  
dengyihao 已提交
1340
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1341
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1342

dengyihao's avatar
dengyihao 已提交
1343
  cliMayCvtFqdnToIp(&pCtx->epSet, &pThrd->cvtAddr);
1344
  STraceId* trace = &pMsg->msg.info.traceId;
dengyihao's avatar
dengyihao 已提交
1345 1346
  char*     ip = EPSET_GET_INUSE_IP(&pCtx->epSet);
  uint16_t  port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1347

dengyihao's avatar
dengyihao 已提交
1348
  if (!EPSET_IS_VALID(&pCtx->epSet)) {
1349
    tGError("%s, msg %s sent with invalid epset", pTransInst->label, TMSG_INFO(pMsg->msg.msgType));
dengyihao's avatar
dengyihao 已提交
1350
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1351 1352
    return;
  }
dengyihao's avatar
dengyihao 已提交
1353

dengyihao's avatar
dengyihao 已提交
1354
  if (REQUEST_NO_RESP(&pMsg->msg) && (pTransInst->failFastFp != NULL && pTransInst->failFastFp(pMsg->msg.msgType))) {
dengyihao's avatar
dengyihao 已提交
1355
    char key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
1356 1357 1358 1359
    CONN_CONSTRUCT_HASH_KEY(key, ip, port);

    SFailFastItem* item = taosHashGet(pThrd->failFastCache, key, strlen(key));
    if (item != NULL) {
dengyihao's avatar
dengyihao 已提交
1360 1361
      int32_t elapse = (int32_t)(taosGetTimestampMs() - item->timestamp);
      if (item->count >= pTransInst->failFastThreshold && (elapse >= 0 && elapse <= pTransInst->failFastInterval)) {
dengyihao's avatar
dengyihao 已提交
1362 1363
        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 已提交
1364 1365 1366 1367 1368 1369
        destroyCmsg(pMsg);
        return;
      }
    }
  }

dengyihao's avatar
dengyihao 已提交
1370 1371 1372
  bool      ignore = false;
  SCliConn* conn = cliGetConn(pMsg, pThrd, &ignore);
  if (ignore == true) {
dengyihao's avatar
dengyihao 已提交
1373
    // persist conn already release by server
dengyihao's avatar
dengyihao 已提交
1374 1375
    STransMsg resp;
    cliBuildExceptResp(pMsg, &resp);
dengyihao's avatar
dengyihao 已提交
1376 1377 1378
    if (pMsg->type != Release) {
      pTransInst->cfp(pTransInst->parent, &resp, NULL);
    }
dengyihao's avatar
dengyihao 已提交
1379
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1380 1381
    return;
  }
dengyihao's avatar
dengyihao 已提交
1382

dengyihao's avatar
dengyihao 已提交
1383
  if (conn == NULL && REQUEST_NO_RESP(&pMsg->msg) && 0 != cliPreCheckSessionLimit(pThrd, ip, port)) {
dengyihao's avatar
dengyihao 已提交
1384 1385 1386 1387 1388 1389
    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 已提交
1390
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
1391
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1392
    transQueuePush(&conn->cliMsgs, pMsg);
U
ubuntu 已提交
1393
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
1394
  } else {
U
ubuntu 已提交
1395
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
1396 1397 1398 1399

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

dengyihao's avatar
dengyihao 已提交
1400
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1401
    transQueuePush(&conn->cliMsgs, pMsg);
dengyihao's avatar
dengyihao 已提交
1402

dengyihao's avatar
dengyihao 已提交
1403
    char     key[TSDB_FQDN_LEN + 64] = {0};
dengyihao's avatar
dengyihao 已提交
1404
    char*    fqdn = EPSET_GET_INUSE_IP(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1405
    uint16_t port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1406
    CONN_CONSTRUCT_HASH_KEY(key, fqdn, port);
dengyihao's avatar
dengyihao 已提交
1407

1408
    conn->ip = taosStrdup(key);
dengyihao's avatar
dengyihao 已提交
1409

dengyihao's avatar
dengyihao 已提交
1410
    uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, fqdn);
1411 1412 1413 1414 1415 1416 1417 1418 1419
    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 已提交
1420

dengyihao's avatar
dengyihao 已提交
1421
    struct sockaddr_in addr;
1422
    addr.sin_family = AF_INET;
1423
    addr.sin_addr.s_addr = ipaddr;
dengyihao's avatar
dengyihao 已提交
1424
    addr.sin_port = (uint16_t)htons(port);
dengyihao's avatar
dengyihao 已提交
1425

dengyihao's avatar
dengyihao 已提交
1426
    tGTrace("%s conn %p try to connect to %s", pTransInst->label, conn, conn->ip);
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    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 已提交
1447

1448
    ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
dengyihao's avatar
dengyihao 已提交
1449
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1450 1451 1452 1453 1454
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

dengyihao's avatar
dengyihao 已提交
1455
      cliHandleFastFail(conn, ret);
dengyihao's avatar
dengyihao 已提交
1456 1457
      return;
    }
dengyihao's avatar
dengyihao 已提交
1458
    uv_timer_start(conn->timer, cliConnTimeout, TRANS_CONN_TIMEOUT, 0);
dengyihao's avatar
dengyihao 已提交
1459
  }
dengyihao's avatar
dengyihao 已提交
1460
  tGTrace("%s conn %p ready", pTransInst->label, conn);
dengyihao's avatar
dengyihao 已提交
1461
}
dengyihao's avatar
dengyihao 已提交
1462

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

dengyihao's avatar
dengyihao 已提交
1466 1467
  while (!QUEUE_IS_EMPTY(wq)) {
    queue* h = QUEUE_HEAD(wq);
dengyihao's avatar
dengyihao 已提交
1468 1469 1470
    QUEUE_REMOVE(h);

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1471 1472 1473 1474 1475

    if (pMsg->type == Quit) {
      pThrd->stopMsg = pMsg;
      continue;
    }
dengyihao's avatar
dengyihao 已提交
1476 1477 1478 1479 1480 1481 1482 1483
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);

    count++;
  }
  if (count >= 2) {
    tTrace("cli process batch size:%d", count);
  }
}
dengyihao's avatar
dengyihao 已提交
1484
SCliBatch* cliGetHeadFromList(SCliBatchList* pList) {
dengyihao's avatar
dengyihao 已提交
1485
  if (QUEUE_IS_EMPTY(&pList->wq) || pList->connCnt > pList->connMax || pList->sending > pList->connMax) {
dengyihao's avatar
dengyihao 已提交
1486 1487 1488 1489
    return NULL;
  }
  queue* hr = QUEUE_HEAD(&pList->wq);
  QUEUE_REMOVE(hr);
dengyihao's avatar
dengyihao 已提交
1490
  pList->sending += 1;
dengyihao's avatar
dengyihao 已提交
1491 1492 1493 1494 1495 1496

  pList->len -= 1;

  SCliBatch* batch = QUEUE_DATA(hr, SCliBatch, listq);
  return batch;
}
dengyihao's avatar
dengyihao 已提交
1497

dengyihao's avatar
dengyihao 已提交
1498
static void cliBatchDealReq(queue* wq, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1499 1500
  STrans* pInst = pThrd->pTransInst;

dengyihao's avatar
dengyihao 已提交
1501
  int count = 0;
dengyihao's avatar
dengyihao 已提交
1502 1503
  while (!QUEUE_IS_EMPTY(wq)) {
    queue* h = QUEUE_HEAD(wq);
dengyihao's avatar
dengyihao 已提交
1504
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
1505 1506

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1507 1508 1509 1510 1511 1512

    if (pMsg->type == Quit) {
      pThrd->stopMsg = pMsg;
      continue;
    }

dengyihao's avatar
dengyihao 已提交
1513
    if (pMsg->type == Normal && REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
1514 1515 1516 1517 1518 1519 1520
      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 已提交
1521 1522 1523 1524 1525
      // SCliBatch** ppBatch = taosHashGet(pThrd->batchCache, key, sizeof(key));
      SCliBatchList** ppBatchList = taosHashGet(pThrd->batchCache, key, sizeof(key));
      if (ppBatchList == NULL || *ppBatchList == NULL) {
        SCliBatchList* pBatchList = taosMemoryCalloc(1, sizeof(SCliBatchList));
        QUEUE_INIT(&pBatchList->wq);
dengyihao's avatar
dengyihao 已提交
1526
        pBatchList->connMax = pInst->connLimitNum;
dengyihao's avatar
dengyihao 已提交
1527
        pBatchList->connCnt = 0;
dengyihao's avatar
dengyihao 已提交
1528
        pBatchList->batchLenLimit = pInst->batchSize;
dengyihao's avatar
dengyihao 已提交
1529
        pBatchList->len += 1;
dengyihao's avatar
dengyihao 已提交
1530

1531 1532
        pBatchList->ip = taosStrdup(ip);
        pBatchList->dst = taosStrdup(key);
dengyihao's avatar
dengyihao 已提交
1533 1534
        pBatchList->port = port;

dengyihao's avatar
dengyihao 已提交
1535 1536
        SCliBatch* pBatch = taosMemoryCalloc(1, sizeof(SCliBatch));
        QUEUE_INIT(&pBatch->wq);
dengyihao's avatar
dengyihao 已提交
1537 1538
        QUEUE_INIT(&pBatch->listq);

dengyihao's avatar
dengyihao 已提交
1539 1540 1541
        QUEUE_PUSH(&pBatch->wq, h);
        pBatch->wLen += 1;
        pBatch->batchSize += pMsg->msg.contLen;
dengyihao's avatar
dengyihao 已提交
1542
        pBatch->pList = pBatchList;
dengyihao's avatar
dengyihao 已提交
1543

dengyihao's avatar
dengyihao 已提交
1544
        QUEUE_PUSH(&pBatchList->wq, &pBatch->listq);
dengyihao's avatar
dengyihao 已提交
1545

dengyihao's avatar
dengyihao 已提交
1546
        taosHashPut(pThrd->batchCache, key, sizeof(key), &pBatchList, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
1547
      } else {
dengyihao's avatar
dengyihao 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
        if (QUEUE_IS_EMPTY(&(*ppBatchList)->wq)) {
          SCliBatch* pBatch = taosMemoryCalloc(1, sizeof(SCliBatch));
          QUEUE_INIT(&pBatch->wq);
          QUEUE_INIT(&pBatch->listq);

          QUEUE_PUSH(&pBatch->wq, h);
          pBatch->wLen += 1;
          pBatch->batchSize = pMsg->msg.contLen;
          pBatch->pList = *ppBatchList;

          QUEUE_PUSH(&((*ppBatchList)->wq), &pBatch->listq);
          (*ppBatchList)->len += 1;

          continue;
        }

        queue*     hdr = QUEUE_TAIL(&((*ppBatchList)->wq));
        SCliBatch* pBatch = QUEUE_DATA(hdr, SCliBatch, listq);
        if ((pBatch->batchSize + pMsg->msg.contLen) < (*ppBatchList)->batchLenLimit) {
          QUEUE_PUSH(&pBatch->wq, h);
          pBatch->batchSize += pMsg->msg.contLen;
dengyihao's avatar
dengyihao 已提交
1569
          pBatch->wLen += 1;
dengyihao's avatar
dengyihao 已提交
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        } else {
          SCliBatch* pBatch = taosMemoryCalloc(1, sizeof(SCliBatch));
          QUEUE_INIT(&pBatch->wq);
          QUEUE_INIT(&pBatch->listq);

          QUEUE_PUSH(&pBatch->wq, h);
          pBatch->wLen += 1;
          pBatch->batchSize += pMsg->msg.contLen;
          pBatch->pList = *ppBatchList;

          QUEUE_PUSH(&((*ppBatchList)->wq), &pBatch->listq);
          (*ppBatchList)->len += 1;
        }
dengyihao's avatar
dengyihao 已提交
1583
      }
dengyihao's avatar
dengyihao 已提交
1584
      continue;
dengyihao's avatar
dengyihao 已提交
1585
    }
dengyihao's avatar
dengyihao 已提交
1586
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1587
    count++;
dengyihao's avatar
dengyihao 已提交
1588
  }
dengyihao's avatar
dengyihao 已提交
1589

dengyihao's avatar
dengyihao 已提交
1590
  void** pIter = taosHashIterate(pThrd->batchCache, NULL);
dengyihao's avatar
dengyihao 已提交
1591
  while (pIter != NULL) {
dengyihao's avatar
dengyihao 已提交
1592
    SCliBatchList* batchList = (SCliBatchList*)(*pIter);
dengyihao's avatar
dengyihao 已提交
1593 1594 1595
    SCliBatch*     batch = cliGetHeadFromList(batchList);
    if (batch != NULL) {
      cliHandleBatchReq(batch, pThrd);
dengyihao's avatar
dengyihao 已提交
1596
    }
dengyihao's avatar
dengyihao 已提交
1597
    pIter = (void**)taosHashIterate(pThrd->batchCache, pIter);
dengyihao's avatar
dengyihao 已提交
1598 1599
  }

dengyihao's avatar
dengyihao 已提交
1600
  if (count >= 2) {
S
Shengliang Guan 已提交
1601
    tTrace("cli process batch size:%d", count);
dengyihao's avatar
dengyihao 已提交
1602
  }
dengyihao's avatar
dengyihao 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
}

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

  // 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 已提交
1616
  int8_t supportBatch = pTransInst->supportBatch;
dengyihao's avatar
dengyihao 已提交
1617
  if (supportBatch == 0) {
dengyihao's avatar
dengyihao 已提交
1618
    cliNoBatchDealReq(&wq, pThrd);
dengyihao's avatar
dengyihao 已提交
1619
  } else if (supportBatch == 1) {
dengyihao's avatar
dengyihao 已提交
1620
    cliBatchDealReq(&wq, pThrd);
dengyihao's avatar
dengyihao 已提交
1621
  }
dengyihao's avatar
dengyihao 已提交
1622

dengyihao's avatar
dengyihao 已提交
1623
  if (pThrd->stopMsg != NULL) cliHandleQuit(pThrd->stopMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1624
}
dengyihao's avatar
dengyihao 已提交
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
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 已提交
1651
}
dengyihao's avatar
dengyihao 已提交
1652

dengyihao's avatar
dengyihao 已提交
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
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 已提交
1682 1683 1684
bool cliRecvReleaseReq(SCliConn* conn, STransMsgHead* pHead) {
  if (pHead->release == 1 && (pHead->msgLen) == sizeof(*pHead)) {
    uint64_t ahandle = pHead->ahandle;
dengyihao's avatar
dengyihao 已提交
1685
    tDebug("ahandle = %" PRIu64 "", ahandle);
dengyihao's avatar
dengyihao 已提交
1686 1687
    SCliMsg* pMsg = NULL;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
dengyihao's avatar
dengyihao 已提交
1688

dengyihao's avatar
dengyihao 已提交
1689 1690
    transClearBuffer(&conn->readBuf);
    transFreeMsg(transContFromHead((char*)pHead));
dengyihao's avatar
dengyihao 已提交
1691 1692 1693 1694

    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 已提交
1695
        ASSERTS(pMsg == NULL, "trans-cli recv invaid release-req");
dengyihao's avatar
dengyihao 已提交
1696 1697
        return true;
      }
dengyihao's avatar
dengyihao 已提交
1698
    }
dengyihao's avatar
dengyihao 已提交
1699 1700 1701

    cliIteraConnMsgs(conn);

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

dengyihao's avatar
dengyihao 已提交
1705 1706 1707 1708 1709 1710
    addConnToPool(((SCliThrd*)conn->hostThrd)->pool, conn);
    return true;
  }
  return false;
}

U
ubuntu 已提交
1711
static void* cliWorkThread(void* arg) {
dengyihao's avatar
dengyihao 已提交
1712
  SCliThrd* pThrd = (SCliThrd*)arg;
dengyihao's avatar
dengyihao 已提交
1713
  pThrd->pid = taosGetSelfPthreadId();
G
gccgdb1234 已提交
1714
  setThreadName("trans-cli-work");
dengyihao's avatar
dengyihao 已提交
1715
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
dengyihao's avatar
dengyihao 已提交
1716 1717

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

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

dengyihao's avatar
dengyihao 已提交
1724
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
1725
  memcpy(cli->label, label, TSDB_LABEL_LEN);
dengyihao's avatar
dengyihao 已提交
1726
  cli->numOfThreads = numOfThreads;
dengyihao's avatar
dengyihao 已提交
1727
  cli->pThreadObj = (SCliThrd**)taosMemoryCalloc(cli->numOfThreads, sizeof(SCliThrd*));
dengyihao's avatar
dengyihao 已提交
1728 1729

  for (int i = 0; i < cli->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
1730
    SCliThrd* pThrd = createThrdObj(shandle);
dengyihao's avatar
dengyihao 已提交
1731
    if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
1732
      goto _err;
dengyihao's avatar
dengyihao 已提交
1733 1734 1735
    }

    int err = taosThreadCreate(&pThrd->thread, NULL, cliWorkThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
1736 1737 1738
    if (err != 0) {
      goto _err;
    } else {
S
Shengliang Guan 已提交
1739
      tDebug("success to create tranport-cli thread:%d", i);
dengyihao's avatar
dengyihao 已提交
1740
    }
dengyihao's avatar
dengyihao 已提交
1741
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
1742 1743
  }
  return cli;
dengyihao's avatar
dengyihao 已提交
1744 1745 1746 1747 1748

_err:
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
  return NULL;
dengyihao's avatar
dengyihao 已提交
1749
}
dengyihao's avatar
dengyihao 已提交
1750

dengyihao's avatar
dengyihao 已提交
1751
static FORCE_INLINE void destroyUserdata(STransMsg* userdata) {
dengyihao's avatar
dengyihao 已提交
1752 1753 1754 1755 1756 1757
  if (userdata->pCont == NULL) {
    return;
  }
  transFreeMsg(userdata->pCont);
  userdata->pCont = NULL;
}
dengyihao's avatar
dengyihao 已提交
1758

dengyihao's avatar
dengyihao 已提交
1759
static FORCE_INLINE void destroyCmsg(void* arg) {
dengyihao's avatar
dengyihao 已提交
1760
  SCliMsg* pMsg = arg;
dengyihao's avatar
dengyihao 已提交
1761 1762 1763
  if (pMsg == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1764

dengyihao's avatar
dengyihao 已提交
1765 1766
  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
wafwerar's avatar
wafwerar 已提交
1767
  taosMemoryFree(pMsg);
dengyihao's avatar
dengyihao 已提交
1768
}
dengyihao's avatar
dengyihao 已提交
1769

dengyihao's avatar
dengyihao 已提交
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
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 已提交
1789 1790 1791
static SCliThrd* createThrdObj(void* trans) {
  STrans* pTransInst = trans;

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

dengyihao's avatar
dengyihao 已提交
1794
  QUEUE_INIT(&pThrd->msg);
wafwerar's avatar
wafwerar 已提交
1795
  taosThreadMutexInit(&pThrd->msgMtx, NULL);
dengyihao's avatar
dengyihao 已提交
1796

wafwerar's avatar
wafwerar 已提交
1797
  pThrd->loop = (uv_loop_t*)taosMemoryMalloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
1798 1799 1800 1801 1802 1803 1804 1805
  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 已提交
1806 1807 1808 1809 1810
  if (pTransInst->supportBatch) {
    pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 4, pThrd, cliAsyncCb);
  } else {
    pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 8, pThrd, cliAsyncCb);
  }
dengyihao's avatar
dengyihao 已提交
1811
  if (pThrd->asyncPool == NULL) {
dengyihao's avatar
ref log  
dengyihao 已提交
1812
    tError("failed to init async pool");
dengyihao's avatar
dengyihao 已提交
1813 1814 1815 1816 1817 1818
    uv_loop_close(pThrd->loop);
    taosMemoryFree(pThrd->loop);
    taosThreadMutexDestroy(&pThrd->msgMtx);
    taosMemoryFree(pThrd);
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1819 1820 1821 1822

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

dengyihao's avatar
dengyihao 已提交
1825
  int32_t timerSize = 64;
dengyihao's avatar
dengyihao 已提交
1826 1827 1828 1829 1830 1831 1832
  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 已提交
1833
  pThrd->pool = createConnPool(4);
dengyihao's avatar
dengyihao 已提交
1834
  transDQCreate(pThrd->loop, &pThrd->delayQueue);
dengyihao's avatar
dengyihao 已提交
1835

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

dengyihao's avatar
dengyihao 已提交
1838 1839 1840
  pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
  pThrd->pTransInst = trans;

dengyihao's avatar
dengyihao 已提交
1841
  pThrd->destroyAhandleFp = pTransInst->destroyFp;
dengyihao's avatar
dengyihao 已提交
1842
  pThrd->fqdn2ipCache = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1843
  pThrd->failFastCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1844 1845
  pThrd->connLimitCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true,
                                       pTransInst->connLimitLock == 0 ? HASH_NO_LOCK : HASH_ENTRY_LOCK);
dengyihao's avatar
dengyihao 已提交
1846

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

dengyihao's avatar
dengyihao 已提交
1849
  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
1850 1851
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1852
static void destroyThrdObj(SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1853 1854 1855
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1856

wafwerar's avatar
wafwerar 已提交
1857
  taosThreadJoin(pThrd->thread, NULL);
dengyihao's avatar
dengyihao 已提交
1858
  CLI_RELEASE_UV(pThrd->loop);
wafwerar's avatar
wafwerar 已提交
1859
  taosThreadMutexDestroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
1860
  TRANS_DESTROY_ASYNC_POOL_MSG(pThrd->asyncPool, SCliMsg, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1861
  transAsyncPoolDestroy(pThrd->asyncPool);
dengyihao's avatar
dengyihao 已提交
1862

dengyihao's avatar
dengyihao 已提交
1863
  transDQDestroy(pThrd->delayQueue, destroyCmsgAndAhandle);
dengyihao's avatar
dengyihao 已提交
1864
  transDQDestroy(pThrd->timeoutQueue, NULL);
dengyihao's avatar
dengyihao 已提交
1865

dengyihao's avatar
dengyihao 已提交
1866
  tDebug("thread destroy %" PRId64, pThrd->pid);
dengyihao's avatar
dengyihao 已提交
1867 1868 1869 1870 1871
  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 已提交
1872
  taosMemoryFree(pThrd->prepare);
wafwerar's avatar
wafwerar 已提交
1873
  taosMemoryFree(pThrd->loop);
dengyihao's avatar
dengyihao 已提交
1874
  taosHashCleanup(pThrd->fqdn2ipCache);
dengyihao's avatar
dengyihao 已提交
1875
  taosHashCleanup(pThrd->failFastCache);
dengyihao's avatar
dengyihao 已提交
1876
  taosHashCleanup(pThrd->connLimitCache);
dengyihao's avatar
dengyihao 已提交
1877 1878 1879

  void** pIter = taosHashIterate(pThrd->batchCache, NULL);
  while (pIter != NULL) {
dengyihao's avatar
dengyihao 已提交
1880 1881 1882 1883 1884 1885 1886 1887
    SCliBatchList* pBatchList = (SCliBatchList*)(*pIter);
    while (!QUEUE_IS_EMPTY(&pBatchList->wq)) {
      queue* h = QUEUE_HEAD(&pBatchList->wq);
      QUEUE_REMOVE(h);

      SCliBatch* pBatch = QUEUE_DATA(h, SCliBatch, listq);
      cliDestroyBatch(pBatch);
    }
dengyihao's avatar
dengyihao 已提交
1888 1889
    taosMemoryFree(pBatchList->ip);
    taosMemoryFree(pBatchList->dst);
dengyihao's avatar
dengyihao 已提交
1890
    taosMemoryFree(pBatchList);
dengyihao's avatar
dengyihao 已提交
1891

dengyihao's avatar
dengyihao 已提交
1892 1893
    pIter = (void**)taosHashIterate(pThrd->batchCache, pIter);
  }
dengyihao's avatar
dengyihao 已提交
1894
  taosHashCleanup(pThrd->batchCache);
wafwerar's avatar
wafwerar 已提交
1895
  taosMemoryFree(pThrd);
dengyihao's avatar
dengyihao 已提交
1896
}
dengyihao's avatar
dengyihao 已提交
1897

dengyihao's avatar
dengyihao 已提交
1898
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1899
  //
wafwerar's avatar
wafwerar 已提交
1900
  taosMemoryFree(ctx);
dengyihao's avatar
dengyihao 已提交
1901
}
dengyihao's avatar
dengyihao 已提交
1902

dengyihao's avatar
dengyihao 已提交
1903
void cliSendQuit(SCliThrd* thrd) {
dengyihao's avatar
dengyihao 已提交
1904
  // cli can stop gracefully
wafwerar's avatar
wafwerar 已提交
1905
  SCliMsg* msg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1906
  msg->type = Quit;
dengyihao's avatar
dengyihao 已提交
1907
  transAsyncSend(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
1908
  atomic_store_8(&thrd->asyncPool->stop, 1);
dengyihao's avatar
dengyihao 已提交
1909
}
dengyihao's avatar
dengyihao 已提交
1910 1911
void cliWalkCb(uv_handle_t* handle, void* arg) {
  if (!uv_is_closing(handle)) {
dengyihao's avatar
dengyihao 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
    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 已提交
1924
    uv_close(handle, cliDestroy);
dengyihao's avatar
dengyihao 已提交
1925 1926
  }
}
dengyihao's avatar
dengyihao 已提交
1927

dengyihao's avatar
dengyihao 已提交
1928
FORCE_INLINE int cliRBChoseIdx(STrans* pTransInst) {
dengyihao's avatar
dengyihao 已提交
1929
  int32_t index = pTransInst->index;
dengyihao's avatar
dengyihao 已提交
1930 1931 1932
  if (pTransInst->numOfThreads == 0) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1933 1934 1935 1936
  /*
   * no lock, and to avoid CPU load imbalance, set limit pTransInst->numOfThreads * 2000;
   */
  if (pTransInst->index++ >= pTransInst->numOfThreads * 2000) {
U
ubuntu 已提交
1937 1938 1939 1940
    pTransInst->index = 0;
  }
  return index % pTransInst->numOfThreads;
}
dengyihao's avatar
dengyihao 已提交
1941
static FORCE_INLINE void doDelayTask(void* param) {
dengyihao's avatar
dengyihao 已提交
1942
  STaskArg* arg = param;
dengyihao's avatar
dengyihao 已提交
1943
  cliHandleReq((SCliMsg*)arg->param1, (SCliThrd*)arg->param2);
dengyihao's avatar
dengyihao 已提交
1944 1945
  taosMemoryFree(arg);
}
dengyihao's avatar
dengyihao 已提交
1946

dengyihao's avatar
dengyihao 已提交
1947 1948 1949
static void doCloseIdleConn(void* param) {
  STaskArg* arg = param;
  SCliConn* conn = arg->param1;
dengyihao's avatar
dengyihao 已提交
1950
  tDebug("%s conn %p idle, close it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
1951
  conn->task = NULL;
dengyihao's avatar
dengyihao 已提交
1952 1953
  cliDestroyConn(conn, true);
  taosMemoryFree(arg);
dengyihao's avatar
dengyihao 已提交
1954 1955
}

dengyihao's avatar
dengyihao 已提交
1956
static void cliSchedMsgToNextNode(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1957
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1958 1959
  STransConnCtx* pCtx = pMsg->ctx;

dengyihao's avatar
dengyihao 已提交
1960 1961
  STraceId* trace = &pMsg->msg.info.traceId;
  char      tbuf[256] = {0};
dengyihao's avatar
dengyihao 已提交
1962
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1963 1964
  tGDebug("%s retry on next node,use:%s, step: %d,timeout:%" PRId64 "", transLabel(pThrd->pTransInst), tbuf,
          pCtx->retryStep, pCtx->retryNextInterval);
dengyihao's avatar
dengyihao 已提交
1965 1966 1967 1968

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

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

dengyihao's avatar
dengyihao 已提交
1973
FORCE_INLINE void cliCompareAndSwap(int8_t* val, int8_t exp, int8_t newVal) {
dengyihao's avatar
dengyihao 已提交
1974 1975 1976 1977
  if (*val != exp) {
    *val = newVal;
  }
}
dengyihao's avatar
dengyihao 已提交
1978

dengyihao's avatar
dengyihao 已提交
1979
FORCE_INLINE bool cliTryExtractEpSet(STransMsg* pResp, SEpSet* dst) {
dengyihao's avatar
dengyihao 已提交
1980 1981 1982 1983 1984 1985
  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 已提交
1986 1987 1988 1989
    return false;
  }
  int32_t tlen = tSerializeSEpSet(NULL, 0, dst);

dengyihao's avatar
dengyihao 已提交
1990 1991 1992 1993 1994 1995 1996
  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 已提交
1997 1998

  pResp->pCont = buf;
dengyihao's avatar
dengyihao 已提交
1999 2000 2001
  pResp->contLen = len;

  *dst = epset;
dengyihao's avatar
dengyihao 已提交
2002 2003
  return true;
}
dengyihao's avatar
dengyihao 已提交
2004
bool cliResetEpset(STransConnCtx* pCtx, STransMsg* pResp, bool hasEpSet) {
dengyihao's avatar
dengyihao 已提交
2005
  bool noDelay = true;
dengyihao's avatar
dengyihao 已提交
2006 2007 2008 2009 2010 2011 2012
  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 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
    } 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 已提交
2023
      } else {
dengyihao's avatar
dengyihao 已提交
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
        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 已提交
2036
      }
dengyihao's avatar
dengyihao 已提交
2037 2038
    }
  } else {
dengyihao's avatar
dengyihao 已提交
2039
    SEpSet  epSet;
dengyihao's avatar
dengyihao 已提交
2040 2041
    int32_t valid = tDeserializeSEpSet(pResp->pCont, pResp->contLen, &epSet);
    if (valid < 0) {
dengyihao's avatar
dengyihao 已提交
2042 2043 2044 2045 2046 2047
      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 已提交
2048
    } else {
dengyihao's avatar
dengyihao 已提交
2049 2050 2051
      if (!transEpSetIsEqual(&pCtx->epSet, &epSet)) {
        tDebug("epset not equal, retry new epset");
        pCtx->epSet = epSet;
dengyihao's avatar
dengyihao 已提交
2052
        noDelay = false;
dengyihao's avatar
dengyihao 已提交
2053
      } else {
dengyihao's avatar
dengyihao 已提交
2054 2055 2056 2057 2058 2059
        if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
          noDelay = false;
        } else {
          tDebug("epset equal, continue");
          EPSET_FORWARD_INUSE(&pCtx->epSet);
        }
dengyihao's avatar
dengyihao 已提交
2060
      }
dengyihao's avatar
dengyihao 已提交
2061 2062 2063 2064 2065
    }
  }
  return noDelay;
}
bool cliGenRetryRule(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
2066 2067
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
2068

dengyihao's avatar
dengyihao 已提交
2069 2070
  STransConnCtx* pCtx = pMsg->ctx;
  int32_t        code = pResp->code;
dengyihao's avatar
dengyihao 已提交
2071

dengyihao's avatar
dengyihao 已提交
2072
  bool retry = pTransInst->retry != NULL ? pTransInst->retry(code, pResp->msgType - 1) : false;
dengyihao's avatar
dengyihao 已提交
2073 2074 2075
  if (retry == false) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
2076 2077 2078 2079 2080 2081 2082 2083

  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 已提交
2084
    pCtx->retryStep = 0;
dengyihao's avatar
dengyihao 已提交
2085
    pCtx->retryInit = true;
dengyihao's avatar
dengyihao 已提交
2086
    pCtx->retryCode = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
2087 2088 2089

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

dengyihao's avatar
dengyihao 已提交
2092 2093
  if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
    return false;
dengyihao's avatar
dengyihao 已提交
2094
  }
dengyihao's avatar
dengyihao 已提交
2095

dengyihao's avatar
dengyihao 已提交
2096 2097 2098 2099 2100 2101
  // code, msgType

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

dengyihao's avatar
dengyihao 已提交
2102 2103
  bool noDelay = false;
  if (code == TSDB_CODE_RPC_BROKEN_LINK || code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
dengyihao's avatar
dengyihao 已提交
2104
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2105
    noDelay = cliResetEpset(pCtx, pResp, false);
dengyihao's avatar
dengyihao 已提交
2106 2107
    transFreeMsg(pResp->pCont);
    transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
2108
  } else if (code == TSDB_CODE_SYN_NOT_LEADER || code == TSDB_CODE_SYN_INTERNAL_ERROR ||
2109 2110
             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 已提交
2111
             code == TSDB_CODE_APP_IS_STOPPING || code == TSDB_CODE_VND_STOPPED) {
dengyihao's avatar
dengyihao 已提交
2112
    tTrace("code str %s, contlen:%d 1", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2113
    noDelay = cliResetEpset(pCtx, pResp, true);
dengyihao's avatar
dengyihao 已提交
2114 2115
    transFreeMsg(pResp->pCont);
    addConnToPool(pThrd->pool, pConn);
dengyihao's avatar
dengyihao 已提交
2116
  } else if (code == TSDB_CODE_SYN_RESTORING) {
dengyihao's avatar
dengyihao 已提交
2117
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2118
    noDelay = cliResetEpset(pCtx, pResp, true);
dengyihao's avatar
dengyihao 已提交
2119 2120
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
2121
  } else {
dengyihao's avatar
dengyihao 已提交
2122
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2123 2124 2125
    noDelay = cliResetEpset(pCtx, pResp, false);
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
2126
  }
dengyihao's avatar
dengyihao 已提交
2127 2128 2129 2130
  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 已提交
2131

dengyihao's avatar
dengyihao 已提交
2132 2133 2134
  if (noDelay == false) {
    pCtx->epsetRetryCnt = 1;
    pCtx->retryStep++;
dengyihao's avatar
dengyihao 已提交
2135

dengyihao's avatar
dengyihao 已提交
2136 2137 2138 2139 2140 2141
    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 已提交
2142 2143 2144
    // if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
    //   return false;
    // }
dengyihao's avatar
dengyihao 已提交
2145 2146 2147
  } else {
    pCtx->retryNextInterval = 0;
    pCtx->epsetRetryCnt++;
dengyihao's avatar
dengyihao 已提交
2148
  }
dengyihao's avatar
dengyihao 已提交
2149

dengyihao's avatar
dengyihao 已提交
2150
  pMsg->sent = 0;
dengyihao's avatar
dengyihao 已提交
2151
  cliSchedMsgToNextNode(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
2152
  return true;
dengyihao's avatar
dengyihao 已提交
2153
}
dengyihao's avatar
dengyihao 已提交
2154
int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
2155 2156
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
2157

dengyihao's avatar
dengyihao 已提交
2158
  if (pMsg == NULL || pMsg->ctx == NULL) {
dengyihao's avatar
dengyihao 已提交
2159
    tTrace("%s conn %p handle resp", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
2160 2161 2162
    pTransInst->cfp(pTransInst->parent, pResp, NULL);
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
2163

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

dengyihao's avatar
dengyihao 已提交
2166 2167 2168
  bool retry = cliGenRetryRule(pConn, pResp, pMsg);
  if (retry == true) {
    return -1;
dengyihao's avatar
dengyihao 已提交
2169
  }
dengyihao's avatar
dengyihao 已提交
2170

dengyihao's avatar
dengyihao 已提交
2171 2172 2173
  if (pCtx->retryCode != TSDB_CODE_SUCCESS) {
    int32_t code = pResp->code;
    // return internal code app
dengyihao's avatar
dengyihao 已提交
2174 2175
    if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK ||
        code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
dengyihao's avatar
dengyihao 已提交
2176 2177 2178 2179
      pResp->code = pCtx->retryCode;
    }
  }

2180
  // check whole vnodes is offline on this vgroup
2181 2182
  if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps || pCtx->retryStep > 0) {
    if (pResp->code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
A
Alex Duan 已提交
2183
      pResp->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
2184
    } else if (pResp->code == TSDB_CODE_RPC_BROKEN_LINK) {
A
Alex Duan 已提交
2185
      pResp->code = TSDB_CODE_RPC_SOMENODE_BROKEN_LINK;
2186 2187 2188
    }
  }

dengyihao's avatar
dengyihao 已提交
2189 2190
  STraceId* trace = &pResp->info.traceId;
  bool      hasEpSet = cliTryExtractEpSet(pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
2191
  if (hasEpSet) {
dengyihao's avatar
dengyihao 已提交
2192 2193
    char tbuf[256] = {0};
    EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
2194
    tGTrace("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
2195
  }
dengyihao's avatar
dengyihao 已提交
2196

dengyihao's avatar
dengyihao 已提交
2197
  if (pCtx->pSem != NULL) {
dengyihao's avatar
dengyihao 已提交
2198
    tGTrace("%s conn %p(sync) handle resp", CONN_GET_INST_LABEL(pConn), pConn);
2199
    if (pCtx->pRsp == NULL) {
dengyihao's avatar
dengyihao 已提交
2200
      tGTrace("%s conn %p(sync) failed to resp, ignore", CONN_GET_INST_LABEL(pConn), pConn);
2201 2202 2203
    } else {
      memcpy((char*)pCtx->pRsp, (char*)pResp, sizeof(*pResp));
    }
dengyihao's avatar
dengyihao 已提交
2204
    tsem_post(pCtx->pSem);
2205
    pCtx->pRsp = NULL;
dengyihao's avatar
dengyihao 已提交
2206
  } else {
dengyihao's avatar
dengyihao 已提交
2207
    tGTrace("%s conn %p handle resp", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
2208
    if (retry == false && hasEpSet == true) {
dengyihao's avatar
dengyihao 已提交
2209
      pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
2210
    } else {
dengyihao's avatar
dengyihao 已提交
2211
      if (!cliIsEpsetUpdated(pResp->code, pCtx)) {
dengyihao's avatar
dengyihao 已提交
2212 2213 2214 2215
        pTransInst->cfp(pTransInst->parent, pResp, NULL);
      } else {
        pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
2216
    }
dengyihao's avatar
dengyihao 已提交
2217
  }
dengyihao's avatar
dengyihao 已提交
2218
  return 0;
dengyihao's avatar
dengyihao 已提交
2219
}
U
ubuntu 已提交
2220 2221

void transCloseClient(void* arg) {
U
ubuntu 已提交
2222
  SCliObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
2223
  for (int i = 0; i < cli->numOfThreads; i++) {
U
ubuntu 已提交
2224
    cliSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
2225
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
2226
  }
wafwerar's avatar
wafwerar 已提交
2227 2228
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
dengyihao's avatar
dengyihao 已提交
2229
}
dengyihao's avatar
dengyihao 已提交
2230 2231 2232 2233 2234
void transRefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_INC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
2235
  tTrace("%s conn %p ref %d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
2236 2237 2238 2239 2240 2241 2242
  UNUSED(ref);
}
void transUnrefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_DEC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
2243
  tTrace("%s conn %p ref:%d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
2244
  if (ref == 0) {
U
ubuntu 已提交
2245
    cliDestroyConn((SCliConn*)handle, true);
dengyihao's avatar
dengyihao 已提交
2246 2247
  }
}
dengyihao's avatar
dengyihao 已提交
2248
static FORCE_INLINE SCliThrd* transGetWorkThrdFromHandle(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
2249
  SCliThrd*  pThrd = NULL;
dengyihao's avatar
dengyihao 已提交
2250
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
2251 2252 2253
  if (exh == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
2254

dengyihao's avatar
dengyihao 已提交
2255 2256 2257 2258 2259 2260
  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 已提交
2261
  pThrd = exh->pThrd;
dengyihao's avatar
dengyihao 已提交
2262
  transReleaseExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
2263 2264
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
2265
SCliThrd* transGetWorkThrd(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
2266
  if (handle == 0) {
dengyihao's avatar
dengyihao 已提交
2267
    int idx = cliRBChoseIdx(trans);
dengyihao's avatar
dengyihao 已提交
2268
    if (idx < 0) return NULL;
dengyihao's avatar
dengyihao 已提交
2269 2270
    return ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
dengyihao's avatar
dengyihao 已提交
2271
  SCliThrd* pThrd = transGetWorkThrdFromHandle(trans, handle);
D
dapan1121 已提交
2272
  return pThrd;
dengyihao's avatar
dengyihao 已提交
2273
}
dengyihao's avatar
dengyihao 已提交
2274
int transReleaseCliHandle(void* handle) {
dengyihao's avatar
dengyihao 已提交
2275 2276 2277
  int  idx = -1;
  bool valid = false;

dengyihao's avatar
dengyihao 已提交
2278
  SCliThrd* pThrd = transGetWorkThrdFromHandle(NULL, (int64_t)handle);
dengyihao's avatar
dengyihao 已提交
2279
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2280
    return -1;
dengyihao's avatar
dengyihao 已提交
2281
  }
dengyihao's avatar
dengyihao 已提交
2282

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

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

dengyihao's avatar
dengyihao 已提交
2289
  SCliMsg* cmsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2290
  cmsg->msg = tmsg;
dengyihao's avatar
dengyihao 已提交
2291
  cmsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2292
  cmsg->type = Release;
dengyihao's avatar
dengyihao 已提交
2293
  cmsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
2294

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

dengyihao's avatar
dengyihao 已提交
2298
  if (0 != transAsyncSend(pThrd->asyncPool, &cmsg->q)) {
dengyihao's avatar
dengyihao 已提交
2299
    destroyCmsg(cmsg);
dengyihao's avatar
dengyihao 已提交
2300 2301
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2302
  return 0;
dengyihao's avatar
dengyihao 已提交
2303
}
dengyihao's avatar
dengyihao 已提交
2304

dengyihao's avatar
dengyihao 已提交
2305
int transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
2306 2307 2308 2309 2310
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2311

dengyihao's avatar
dengyihao 已提交
2312
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
dengyihao's avatar
dengyihao 已提交
2313
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2314
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
2315
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2316
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
2317 2318
  }

dengyihao's avatar
dengyihao 已提交
2319
  TRACE_SET_MSGID(&pReq->info.traceId, tGenIdPI64());
wafwerar's avatar
wafwerar 已提交
2320
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2321
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
2322
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
2323
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
2324
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
2325

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

wafwerar's avatar
wafwerar 已提交
2328
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2329
  cliMsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
2330
  cliMsg->msg = *pReq;
dengyihao's avatar
dengyihao 已提交
2331
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2332
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
2333
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
2334

dengyihao's avatar
dengyihao 已提交
2335
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
2336 2337
  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 已提交
2338 2339
  if (0 != transAsyncSend(pThrd->asyncPool, &(cliMsg->q))) {
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2340
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2341 2342
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2343
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2344
  return 0;
dengyihao's avatar
dengyihao 已提交
2345
}
dengyihao's avatar
dengyihao 已提交
2346

dengyihao's avatar
dengyihao 已提交
2347
int transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMsg* pRsp) {
dengyihao's avatar
dengyihao 已提交
2348 2349 2350 2351 2352
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2353

dengyihao's avatar
dengyihao 已提交
2354 2355
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2356
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
2357
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2358
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
2359
  }
dengyihao's avatar
dengyihao 已提交
2360

dengyihao's avatar
dengyihao 已提交
2361 2362
  tsem_t* sem = taosMemoryCalloc(1, sizeof(tsem_t));
  tsem_init(sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
2363

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

wafwerar's avatar
wafwerar 已提交
2366
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2367
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
2368
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
2369
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
2370
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
2371
  pCtx->pSem = sem;
dengyihao's avatar
dengyihao 已提交
2372 2373
  pCtx->pRsp = pRsp;

wafwerar's avatar
wafwerar 已提交
2374
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2375 2376 2377
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pReq;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2378
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
2379
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
2380

dengyihao's avatar
dengyihao 已提交
2381
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
2382 2383
  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 已提交
2384

dengyihao's avatar
dengyihao 已提交
2385 2386
  int ret = transAsyncSend(pThrd->asyncPool, &cliMsg->q);
  if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
2387
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2388
    goto _RETURN;
dengyihao's avatar
dengyihao 已提交
2389
  }
dengyihao's avatar
dengyihao 已提交
2390
  tsem_wait(sem);
dengyihao's avatar
dengyihao 已提交
2391 2392

_RETURN:
dengyihao's avatar
dengyihao 已提交
2393 2394
  tsem_destroy(sem);
  taosMemoryFree(sem);
dengyihao's avatar
dengyihao 已提交
2395
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2396
  return ret;
dengyihao's avatar
dengyihao 已提交
2397
}
dengyihao's avatar
dengyihao 已提交
2398 2399 2400
/*
 *
 **/
dengyihao's avatar
dengyihao 已提交
2401
int transSetDefaultAddr(void* shandle, const char* ip, const char* fqdn) {
dengyihao's avatar
dengyihao 已提交
2402
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2403 2404 2405
  if (pTransInst == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2406 2407 2408

  SCvtAddr cvtAddr = {0};
  if (ip != NULL && fqdn != NULL) {
dengyihao's avatar
dengyihao 已提交
2409 2410
    tstrncpy(cvtAddr.ip, ip, sizeof(cvtAddr.ip));
    tstrncpy(cvtAddr.fqdn, fqdn, sizeof(cvtAddr.fqdn));
dengyihao's avatar
dengyihao 已提交
2411 2412
    cvtAddr.cvt = true;
  }
dengyihao's avatar
dengyihao 已提交
2413 2414
  for (int i = 0; i < pTransInst->numOfThreads; i++) {
    STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2415
    pCtx->cvtAddr = cvtAddr;
dengyihao's avatar
dengyihao 已提交
2416 2417 2418 2419

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

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

dengyihao's avatar
dengyihao 已提交
2425 2426
    if (transAsyncSend(thrd->asyncPool, &(cliMsg->q)) != 0) {
      destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2427
      transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2428 2429
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
2430
  }
dengyihao's avatar
dengyihao 已提交
2431
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2432
  return 0;
dengyihao's avatar
dengyihao 已提交
2433
}
dengyihao's avatar
dengyihao 已提交
2434 2435 2436 2437 2438

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

dengyihao's avatar
dengyihao 已提交
2440 2441
  return exh->refId;
}