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 15 16
 *
 * 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/>.
 */

#include "transComm.h"

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

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

  int connMax;
  int connCnt;
  int batchLenLimit;
dengyihao's avatar
dengyihao 已提交
29
  int sending;
dengyihao's avatar
dengyihao 已提交
30

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

} SCliBatchList;

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

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

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

dengyihao's avatar
dengyihao 已提交
54 55 56 57
  void* hostThrd;

  SConnBuffer readBuf;
  STransQueue cliMsgs;
dengyihao's avatar
dengyihao 已提交
58 59 60

  queue      q;
  SConnList* list;
dengyihao's avatar
dengyihao 已提交
61 62

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

dengyihao's avatar
dengyihao 已提交
66 67
  SCliBatch* pBatch;

dengyihao's avatar
dengyihao 已提交
68 69
  int64_t refId;
  char*   ip;
dengyihao's avatar
dengyihao 已提交
70

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

dengyihao's avatar
dengyihao 已提交
73
  // debug and log info
dengyihao's avatar
dengyihao 已提交
74 75 76
  char src[32];
  char dst[32];

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

dengyihao's avatar
dengyihao 已提交
79 80 81 82
typedef struct {
  int32_t numOfConn;
  queue   msgQ;
} SMsgList;
dengyihao's avatar
dengyihao 已提交
83
typedef struct SCliMsg {
dengyihao's avatar
dengyihao 已提交
84
  STransConnCtx* ctx;
dengyihao's avatar
formate  
dengyihao 已提交
85
  STransMsg      msg;
dengyihao's avatar
dengyihao 已提交
86
  queue          q;
dengyihao's avatar
dengyihao 已提交
87
  STransMsgType  type;
dengyihao's avatar
dengyihao 已提交
88

dengyihao's avatar
dengyihao 已提交
89
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
90 91
  uint64_t st;
  int      sent;  //(0: no send, 1: alread sent)
dengyihao's avatar
dengyihao 已提交
92 93
} SCliMsg;

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

dengyihao's avatar
dengyihao 已提交
111
  int connCount;
dengyihao's avatar
dengyihao 已提交
112
  void (*destroyAhandleFp)(void* ahandle);
dengyihao's avatar
dengyihao 已提交
113 114
  SHashObj* fqdn2ipCache;
  SCvtAddr  cvtAddr;
dengyihao's avatar
dengyihao 已提交
115

dengyihao's avatar
dengyihao 已提交
116
  SHashObj* failFastCache;
dengyihao's avatar
dengyihao 已提交
117
  SHashObj* connLimitCache;
dengyihao's avatar
dengyihao 已提交
118
  SHashObj* batchCache;
dengyihao's avatar
dengyihao 已提交
119

dengyihao's avatar
dengyihao 已提交
120 121
  SCliMsg* stopMsg;

dengyihao's avatar
dengyihao 已提交
122
  bool quit;
dengyihao's avatar
dengyihao 已提交
123
} SCliThrd;
dengyihao's avatar
dengyihao 已提交
124

U
ubuntu 已提交
125
typedef struct SCliObj {
dengyihao's avatar
dengyihao 已提交
126 127 128 129
  char       label[TSDB_LABEL_LEN];
  int32_t    index;
  int        numOfThreads;
  SCliThrd** pThreadObj;
U
ubuntu 已提交
130
} SCliObj;
dengyihao's avatar
dengyihao 已提交
131

dengyihao's avatar
dengyihao 已提交
132 133 134 135 136 137 138
typedef struct {
  int32_t reinit;
  int64_t timestamp;
  int32_t count;
  int32_t threshold;
  int64_t interval;
} SFailFastItem;
dengyihao's avatar
dengyihao 已提交
139
// conn pool
dengyihao's avatar
dengyihao 已提交
140
// add expire timeout and capacity limit
dengyihao's avatar
dengyihao 已提交
141
static void*     createConnPool(int size);
142
static void*     destroyConnPool(void* pool);
dengyihao's avatar
dengyihao 已提交
143
static SCliConn* getConnFromPool(void* pool, char* addr);
dengyihao's avatar
dengyihao 已提交
144
static void      addConnToPool(void* pool, SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
145
static void      doCloseIdleConn(void* param);
dengyihao's avatar
dengyihao 已提交
146

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
183 184
static int32_t cliPreCheckSessionLimit(SCliThrd* pThrd, char* addr);
static int32_t cliPreCheckSessionLimitForMsg(SCliThrd* pThrd, char* addr, SCliMsg* pMsg);
dengyihao's avatar
dengyihao 已提交
185

dengyihao's avatar
dengyihao 已提交
186
// cli util func
dengyihao's avatar
dengyihao 已提交
187 188
static FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx);
static FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr);
dengyihao's avatar
dengyihao 已提交
189

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

dengyihao's avatar
dengyihao 已提交
192 193 194
static FORCE_INLINE uint32_t cliGetIpFromFqdnCache(SHashObj* cache, char* fqdn);
static FORCE_INLINE void     cliUpdateFqdnCache(SHashObj* cache, char* fqdn);

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

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

dengyihao's avatar
dengyihao 已提交
212 213
static FORCE_INLINE void destroyUserdata(STransMsg* userdata);
static FORCE_INLINE void destroyCmsg(void* cmsg);
dengyihao's avatar
dengyihao 已提交
214
static FORCE_INLINE void destroyCmsgAndAhandle(void* cmsg);
dengyihao's avatar
dengyihao 已提交
215
static FORCE_INLINE int  cliRBChoseIdx(STrans* pTransInst);
dengyihao's avatar
dengyihao 已提交
216
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx);
dengyihao's avatar
dengyihao 已提交
217

dengyihao's avatar
dengyihao 已提交
218
// thread obj
dengyihao's avatar
dengyihao 已提交
219
static SCliThrd* createThrdObj(void* trans);
dengyihao's avatar
dengyihao 已提交
220
static void      destroyThrdObj(SCliThrd* pThrd);
dengyihao's avatar
dengyihao 已提交
221

dengyihao's avatar
dengyihao 已提交
222 223 224 225 226 227 228 229 230
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 已提交
231 232 233 234 235 236
// snprintf may cause performance problem
#define CONN_CONSTRUCT_HASH_KEY(key, ip, port)          \
  do {                                                  \
    snprintf(key, sizeof(key), "%s:%d", ip, (int)port); \
  } while (0)

dengyihao's avatar
dengyihao 已提交
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 340 341 342 343
    if (pCliMsg == NULL)
      return false;
    else {
      cliSend(conn);
      return true;
    }
dengyihao's avatar
dengyihao 已提交
344
  }
dengyihao's avatar
dengyihao 已提交
345
  return false;
U
ubuntu 已提交
346 347
_RETURN:
  return false;
dengyihao's avatar
dengyihao 已提交
348
}
dengyihao's avatar
formate  
dengyihao 已提交
349
void cliHandleResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
350 351
  SCliThrd* pThrd = conn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
352

dengyihao's avatar
dengyihao 已提交
353 354 355 356 357 358
  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 已提交
359
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
360
    conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
361 362
  }

dengyihao's avatar
opt rpc  
dengyihao 已提交
363
  STransMsgHead* pHead = NULL;
dengyihao's avatar
dengyihao 已提交
364 365 366

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

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
444
  if (cliMaySendCachedMsg(conn) == true) {
dengyihao's avatar
dengyihao 已提交
445 446
    return;
  }
dengyihao's avatar
dengyihao 已提交
447

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

dengyihao's avatar
dengyihao 已提交
452
  uv_read_start((uv_stream_t*)conn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
453
}
U
ubuntu 已提交
454

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

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

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

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

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

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

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
564
static SCliConn* getConnFromPool(void* pool, char* key) {
dengyihao's avatar
dengyihao 已提交
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
  conn->status = ConnInPool;

dengyihao's avatar
dengyihao 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625
  SMsgList** msglist = taosHashGet(thrd->connLimitCache, conn->ip, strlen(conn->ip));
  if (msglist != NULL && *msglist != NULL) {
    if (!QUEUE_IS_EMPTY(&(*msglist)->msgQ)) {
      queue* h = QUEUE_HEAD(&(*msglist)->msgQ);
      QUEUE_REMOVE(h);

      SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
      transCtxMerge(&conn->ctx, &pMsg->ctx->appCtx);
      transQueuePush(&conn->cliMsgs, pMsg);
      cliSend(conn);
      return;
    }
  }

dengyihao's avatar
dengyihao 已提交
626 627
  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 已提交
628
    conn->list = taosHashGet((SHashObj*)pool, conn->ip, strlen(conn->ip));
dengyihao's avatar
dengyihao 已提交
629 630
  } 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 已提交
631
  }
dengyihao's avatar
dengyihao 已提交
632
  QUEUE_PUSH(&conn->list->conns, &conn->q);
dengyihao's avatar
dengyihao 已提交
633
  conn->list->size += 1;
dengyihao's avatar
dengyihao 已提交
634

dengyihao's avatar
dengyihao 已提交
635
  if (conn->list->size >= 250) {
dengyihao's avatar
dengyihao 已提交
636 637
    STaskArg* arg = taosMemoryCalloc(1, sizeof(STaskArg));
    arg->param1 = conn;
dengyihao's avatar
dengyihao 已提交
638
    arg->param2 = thrd;
dengyihao's avatar
dengyihao 已提交
639 640

    STrans* pTransInst = thrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
641 642
    conn->task = transDQSched(thrd->timeoutQueue, doCloseIdleConn, arg, CONN_PERSIST_TIME(pTransInst->idleTime));
  }
dengyihao's avatar
dengyihao 已提交
643
}
dengyihao's avatar
dengyihao 已提交
644
static int32_t allocConnRef(SCliConn* conn, bool update) {
dengyihao's avatar
dengyihao 已提交
645
  if (update) {
dengyihao's avatar
dengyihao 已提交
646
    transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
647
    transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
648
    conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
649 650 651 652
  }
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
653
  exh->refId = transAddExHandle(transGetRefMgt(), exh);
dengyihao's avatar
dengyihao 已提交
654
  conn->refId = exh->refId;
655 656 657 658

  if (conn->refId == -1) {
    taosMemoryFree(exh);
  }
dengyihao's avatar
dengyihao 已提交
659 660 661 662 663
  return 0;
}

static int32_t specifyConnRef(SCliConn* conn, bool update, int64_t handle) {
  if (update) {
dengyihao's avatar
dengyihao 已提交
664
    transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677
    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 已提交
678
}
dengyihao's avatar
dengyihao 已提交
679

dengyihao's avatar
dengyihao 已提交
680
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
681
  SCliConn*    conn = handle->data;
dengyihao's avatar
dengyihao 已提交
682
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
683
  tDebug("%s conn %p alloc read buf", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
684
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
685
}
U
ubuntu 已提交
686
static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
687
  // impl later
dengyihao's avatar
dengyihao 已提交
688 689 690
  if (handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
691 692
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
693
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
694
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
695
    while (transReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
696
      tDebug("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
697 698 699 700 701 702
      if (pBuf->invalid) {
        cliHandleExcept(conn);
        break;
      } else {
        cliHandleResp(conn);
      }
dengyihao's avatar
dengyihao 已提交
703
    }
dengyihao's avatar
dengyihao 已提交
704 705
    return;
  }
dengyihao's avatar
dengyihao 已提交
706

707
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
708 709 710
    // 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 已提交
711
    tTrace("%s conn %p read empty", CONN_GET_INST_LABEL(conn), conn);
712 713
    return;
  }
dengyihao's avatar
fix bug  
dengyihao 已提交
714
  if (nread < 0) {
dengyihao's avatar
dengyihao 已提交
715
    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 已提交
716
    conn->broken = true;
U
ubuntu 已提交
717
    cliHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
718
  }
dengyihao's avatar
dengyihao 已提交
719
}
dengyihao's avatar
dengyihao 已提交
720

dengyihao's avatar
dengyihao 已提交
721
static SCliConn* cliCreateConn(SCliThrd* pThrd) {
wafwerar's avatar
wafwerar 已提交
722
  SCliConn* conn = taosMemoryCalloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
723
  // read/write stream handle
G
gccgdb1234 已提交
724
  conn->stream = (uv_stream_t*)taosMemoryMalloc(sizeof(uv_tcp_t));
dengyihao's avatar
dengyihao 已提交
725 726 727
  uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
  conn->stream->data = conn;

dengyihao's avatar
dengyihao 已提交
728 729 730 731 732 733 734 735
  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 已提交
736

dengyihao's avatar
dengyihao 已提交
737
  conn->connReq.data = conn;
dengyihao's avatar
dengyihao 已提交
738 739
  transReqQueueInit(&conn->wreqQueue);

dengyihao's avatar
dengyihao 已提交
740
  transQueueInit(&conn->cliMsgs, NULL);
dengyihao's avatar
opt rpc  
dengyihao 已提交
741 742

  transInitBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
743
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
744
  conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
745
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
746
  conn->broken = false;
dengyihao's avatar
dengyihao 已提交
747
  transRefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
748

dengyihao's avatar
dengyihao 已提交
749
  atomic_add_fetch_32(&pThrd->connCount, 1);
dengyihao's avatar
dengyihao 已提交
750
  allocConnRef(conn, false);
dengyihao's avatar
dengyihao 已提交
751

dengyihao's avatar
dengyihao 已提交
752 753
  return conn;
}
U
ubuntu 已提交
754
static void cliDestroyConn(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
755
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
756
  tTrace("%s conn %p remove from conn pool", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
757 758
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
759
  transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
760
  transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
opt rpc  
dengyihao 已提交
761
  conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
762

dengyihao's avatar
dengyihao 已提交
763 764 765 766 767 768 769
  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 已提交
770
    taosArrayPush(pThrd->timerList, &conn->timer);
dengyihao's avatar
dengyihao 已提交
771 772
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
773

dengyihao's avatar
dengyihao 已提交
774
  if (clear) {
dengyihao's avatar
dengyihao 已提交
775
    if (!uv_is_closing((uv_handle_t*)conn->stream)) {
dengyihao's avatar
dengyihao 已提交
776
      uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
777 778
      uv_close((uv_handle_t*)conn->stream, cliDestroy);
    }
779
  }
dengyihao's avatar
dengyihao 已提交
780
}
U
ubuntu 已提交
781
static void cliDestroy(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
782 783 784
  if (uv_handle_get_type(handle) != UV_TCP || handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
785
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
786
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
787 788
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
dengyihao's avatar
dengyihao 已提交
789 790
    taosArrayPush(pThrd->timerList, &conn->timer);
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
791 792
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
793 794 795 796
  SMsgList** list = taosHashGet(pThrd->connLimitCache, conn->ip, strlen(conn->ip));
  if (list != NULL && *list != NULL) {
    (*list)->numOfConn--;
  }
dengyihao's avatar
dengyihao 已提交
797

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

dengyihao's avatar
dengyihao 已提交
800
  transReleaseExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
801
  transRemoveExHandle(transGetRefMgt(), conn->refId);
wafwerar's avatar
wafwerar 已提交
802 803
  taosMemoryFree(conn->ip);
  taosMemoryFree(conn->stream);
dengyihao's avatar
dengyihao 已提交
804 805 806

  cliDestroyConnMsgs(conn, true);

dengyihao's avatar
dengyihao 已提交
807
  tTrace("%s conn %p destroy successfully", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
808
  transReqQueueClear(&conn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
809
  transDestroyBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
810

wafwerar's avatar
wafwerar 已提交
811
  taosMemoryFree(conn);
dengyihao's avatar
dengyihao 已提交
812
}
dengyihao's avatar
dengyihao 已提交
813
static bool cliHandleNoResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
814 815
  bool res = false;
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
816
    SCliMsg* pMsg = transQueueGet(&conn->cliMsgs, 0);
dengyihao's avatar
dengyihao 已提交
817
    if (REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
818
      transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
819 820 821 822 823
      destroyCmsg(pMsg);
      res = true;
    }
    if (res == true) {
      if (cliMaySendCachedMsg(conn) == false) {
dengyihao's avatar
dengyihao 已提交
824
        SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
825
        addConnToPool(thrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
826 827 828
        res = false;
      } else {
        res = true;
dengyihao's avatar
dengyihao 已提交
829 830 831 832 833
      }
    }
  }
  return res;
}
U
ubuntu 已提交
834
static void cliSendCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
835 836
  SCliConn* pConn = transReqQueueRemove(req);
  if (pConn == NULL) return;
dengyihao's avatar
dengyihao 已提交
837

dengyihao's avatar
dengyihao 已提交
838 839 840
  SCliMsg* pMsg = !transQueueEmpty(&pConn->cliMsgs) ? transQueueGet(&pConn->cliMsgs, 0) : NULL;
  if (pMsg != NULL) {
    int64_t cost = taosGetTimestampUs() - pMsg->st;
dengyihao's avatar
dengyihao 已提交
841
    if (cost > 1000 * 20) {
dengyihao's avatar
dengyihao 已提交
842 843 844 845
      tWarn("%s conn %p send cost:%dus, send exception", CONN_GET_INST_LABEL(pConn), pConn, (int)cost);
    }
  }

dengyihao's avatar
dengyihao 已提交
846
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
847
    tTrace("%s conn %p data already was written out", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
848
  } else {
dengyihao's avatar
dengyihao 已提交
849 850 851 852
    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 已提交
853 854
    return;
  }
dengyihao's avatar
dengyihao 已提交
855
  if (cliHandleNoResp(pConn) == true) {
dengyihao's avatar
dengyihao 已提交
856
    tTrace("%s conn %p no resp required", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
857 858
    return;
  }
dengyihao's avatar
dengyihao 已提交
859
  uv_read_start((uv_stream_t*)pConn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
860
}
dengyihao's avatar
dengyihao 已提交
861 862 863 864
void cliSendBatch(SCliConn* pConn) {
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;

dengyihao's avatar
dengyihao 已提交
865 866 867 868 869
  SCliBatch*     pBatch = pConn->pBatch;
  SCliBatchList* pList = pBatch->pList;
  pList->connCnt += 1;

  int32_t wLen = pBatch->wLen;
dengyihao's avatar
dengyihao 已提交
870 871 872 873

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

dengyihao's avatar
dengyihao 已提交
874 875
  queue* h = NULL;
  QUEUE_FOREACH(h, &pBatch->wq) {
dengyihao's avatar
dengyihao 已提交
876 877 878 879 880 881 882 883 884
    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 已提交
885

dengyihao's avatar
dengyihao 已提交
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    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 已提交
902 903 904 905 906 907 908 909
    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 已提交
910 911 912 913 914
    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 已提交
915
  tDebug("%s conn %p start to send batch msg, batch size:%d, msgLen:%d", CONN_GET_INST_LABEL(pConn), pConn,
dengyihao's avatar
dengyihao 已提交
916
         pBatch->wLen, pBatch->batchSize);
dengyihao's avatar
dengyihao 已提交
917 918 919
  uv_write(req, (uv_stream_t*)pConn->stream, wb, wLen, cliSendBatchCb);
  taosMemoryFree(wb);
}
U
ubuntu 已提交
920
void cliSend(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
921 922 923 924 925
  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 已提交
926
    cliHandleExcept(pConn);
dengyihao's avatar
dengyihao 已提交
927 928
    return;
  }
dengyihao's avatar
dengyihao 已提交
929 930

  SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
931
  CONN_GET_NEXT_SENDMSG(pConn);
dengyihao's avatar
dengyihao 已提交
932 933
  pCliMsg->sent = 1;

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

U
ubuntu 已提交
936
  STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
dengyihao's avatar
dengyihao 已提交
937 938 939 940
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
dengyihao's avatar
dengyihao 已提交
941

dengyihao's avatar
dengyihao 已提交
942
  int            msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
943
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
dengyihao's avatar
dengyihao 已提交
944

dengyihao's avatar
dengyihao 已提交
945 946 947 948 949 950 951 952 953 954 955
  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 已提交
956
  pHead->timestamp = taosHton64(taosGetTimestampUs());
dengyihao's avatar
dengyihao 已提交
957

dengyihao's avatar
dengyihao 已提交
958 959 960
  if (pHead->persist == 1) {
    CONN_SET_PERSIST_BY_APP(pConn);
  }
dengyihao's avatar
dengyihao 已提交
961

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

dengyihao's avatar
dengyihao 已提交
964
  if (pTransInst->startTimer != NULL && pTransInst->startTimer(0, pMsg->msgType)) {
dengyihao's avatar
dengyihao 已提交
965
    uv_timer_t* timer = taosArrayGetSize(pThrd->timerList) > 0 ? *(uv_timer_t**)taosArrayPop(pThrd->timerList) : NULL;
dengyihao's avatar
dengyihao 已提交
966 967
    if (timer == NULL) {
      timer = taosMemoryCalloc(1, sizeof(uv_timer_t));
dengyihao's avatar
dengyihao 已提交
968
      tDebug("no available timer, create a timer %p", timer);
dengyihao's avatar
dengyihao 已提交
969 970 971 972 973
      uv_timer_init(pThrd->loop, timer);
    }
    timer->data = pConn;
    pConn->timer = timer;

dengyihao's avatar
dengyihao 已提交
974 975 976
    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 已提交
977

dengyihao's avatar
dengyihao 已提交
978 979 980 981 982 983 984
  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 已提交
985
  }
dengyihao's avatar
dengyihao 已提交
986

dengyihao's avatar
dengyihao 已提交
987 988
  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 已提交
989

dengyihao's avatar
dengyihao 已提交
990
  uv_buf_t    wb = uv_buf_init((char*)pHead, msgLen);
dengyihao's avatar
dengyihao 已提交
991
  uv_write_t* req = transReqQueuePush(&pConn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
992 993 994

  int status = uv_write(req, (uv_stream_t*)pConn->stream, &wb, 1, cliSendCb);
  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
995
    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 已提交
996 997 998
            uv_err_name(status));
    cliHandleExcept(pConn);
  }
U
ubuntu 已提交
999 1000
  return;
_RETURN:
dengyihao's avatar
dengyihao 已提交
1001
  return;
dengyihao's avatar
dengyihao 已提交
1002
}
dengyihao's avatar
dengyihao 已提交
1003 1004

static void cliDestroyBatch(SCliBatch* pBatch) {
dengyihao's avatar
dengyihao 已提交
1005
  if (pBatch == NULL) return;
dengyihao's avatar
dengyihao 已提交
1006
  while (!QUEUE_IS_EMPTY(&pBatch->wq)) {
dengyihao's avatar
dengyihao 已提交
1007 1008
    queue* h = QUEUE_HEAD(&pBatch->wq);
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
1009

dengyihao's avatar
dengyihao 已提交
1010
    SCliMsg* p = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1011 1012
    destroyCmsg(p);
  }
dengyihao's avatar
dengyihao 已提交
1013 1014
  SCliBatchList* p = pBatch->pList;
  p->sending -= 1;
dengyihao's avatar
dengyihao 已提交
1015 1016
  taosMemoryFree(pBatch);
}
dengyihao's avatar
dengyihao 已提交
1017
static void cliHandleBatchReq(SCliBatch* pBatch, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1018 1019 1020 1021 1022
  if (pThrd->quit == true) {
    cliDestroyBatch(pBatch);
    return;
  }

dengyihao's avatar
dengyihao 已提交
1023
  if (pBatch == NULL || pBatch->wLen == 0 || QUEUE_IS_EMPTY(&pBatch->wq)) {
dengyihao's avatar
dengyihao 已提交
1024 1025
    return;
  }
dengyihao's avatar
dengyihao 已提交
1026 1027
  STrans*        pTransInst = pThrd->pTransInst;
  SCliBatchList* pList = pBatch->pList;
dengyihao's avatar
dengyihao 已提交
1028

dengyihao's avatar
dengyihao 已提交
1029 1030 1031 1032
  char key[TSDB_FQDN_LEN + 64] = {0};
  CONN_CONSTRUCT_HASH_KEY(key, pList->ip, pList->port);

  SCliConn* conn = getConnFromPool(pThrd->pool, key);
dengyihao's avatar
dengyihao 已提交
1033

dengyihao's avatar
dengyihao 已提交
1034
  if (conn == NULL && 0 != cliPreCheckSessionLimit(pThrd, key)) {
dengyihao's avatar
dengyihao 已提交
1035 1036 1037
    tError("%s failed to send batch msg, batch size:%d, msgLen: %d", pTransInst->label, pBatch->wLen,
           pBatch->batchSize);
    cliDestroyBatch(pBatch);
dengyihao's avatar
dengyihao 已提交
1038 1039
    return;
  }
dengyihao's avatar
dengyihao 已提交
1040 1041
  if (conn == NULL) {
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
1042 1043
    conn->pBatch = pBatch;
    conn->ip = strdup(pList->dst);
dengyihao's avatar
dengyihao 已提交
1044

dengyihao's avatar
dengyihao 已提交
1045
    uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, pList->ip);
dengyihao's avatar
dengyihao 已提交
1046 1047 1048 1049 1050 1051
    if (ipaddr == 0xffffffff) {
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

dengyihao's avatar
dengyihao 已提交
1052
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1053 1054 1055 1056 1057
      return;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = ipaddr;
dengyihao's avatar
dengyihao 已提交
1058
    addr.sin_port = (uint16_t)htons(pList->port);
dengyihao's avatar
dengyihao 已提交
1059

dengyihao's avatar
dengyihao 已提交
1060
    tTrace("%s conn %p try to connect to %s", pTransInst->label, conn, pList->dst);
dengyihao's avatar
dengyihao 已提交
1061 1062
    int32_t fd = taosCreateSocketWithTimeout(TRANS_CONN_TIMEOUT * 4);
    if (fd == -1) {
dengyihao's avatar
dengyihao 已提交
1063 1064 1065
      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 已提交
1066 1067 1068 1069
      return;
    }
    int ret = uv_tcp_open((uv_tcp_t*)conn->stream, fd);
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1070 1071
      tError("%s conn %p failed to set stream, reason:%s", transLabel(pTransInst), conn, uv_err_name(ret));
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1072 1073 1074 1075
      return;
    }
    ret = transSetConnOption((uv_tcp_t*)conn->stream);
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1076 1077
      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 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086
      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 已提交
1087
      cliHandleFastFail(conn, -1);
dengyihao's avatar
dengyihao 已提交
1088 1089
      return;
    }
dengyihao's avatar
dengyihao 已提交
1090 1091 1092 1093 1094 1095 1096 1097

    SMsgList** list = taosHashGet(pThrd->connLimitCache, conn->ip, strlen(conn->ip));
    if (list == NULL || *list == NULL) {
      SMsgList* nList = taosMemoryCalloc(1, sizeof(SMsgList));
      nList->numOfConn++;
      QUEUE_INIT(&nList->msgQ);
      taosHashPut(pThrd->connLimitCache, conn->ip, strlen(conn->ip), &nList, sizeof(void*));
    }
dengyihao's avatar
dengyihao 已提交
1098 1099 1100 1101
    uv_timer_start(conn->timer, cliConnTimeout, TRANS_CONN_TIMEOUT, 0);
    return;
  }

dengyihao's avatar
dengyihao 已提交
1102
  conn->pBatch = pBatch;
dengyihao's avatar
dengyihao 已提交
1103
  cliSendBatch(conn);
dengyihao's avatar
dengyihao 已提交
1104 1105
}
static void cliSendBatchCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
1106 1107 1108
  SCliConn*  conn = req->data;
  SCliThrd*  thrd = conn->hostThrd;
  SCliBatch* p = conn->pBatch;
dengyihao's avatar
dengyihao 已提交
1109

dengyihao's avatar
dengyihao 已提交
1110
  SCliBatchList* pBatchList = p->pList;
dengyihao's avatar
dengyihao 已提交
1111
  SCliBatch*     nxtBatch = cliGetHeadFromList(pBatchList);
dengyihao's avatar
dengyihao 已提交
1112 1113
  pBatchList->connCnt -= 1;

dengyihao's avatar
dengyihao 已提交
1114 1115 1116
  conn->pBatch = NULL;

  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
1117
    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 已提交
1118
           p->wLen, p->batchSize, uv_err_name(status));
dengyihao's avatar
dengyihao 已提交
1119 1120 1121

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

dengyihao's avatar
dengyihao 已提交
1122
    cliHandleBatchReq(nxtBatch, thrd);
dengyihao's avatar
dengyihao 已提交
1123
  } else {
dengyihao's avatar
dengyihao 已提交
1124
    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 已提交
1125
           p->batchSize);
dengyihao's avatar
dengyihao 已提交
1126
    if (!uv_is_closing((uv_handle_t*)&conn->stream)) {
dengyihao's avatar
dengyihao 已提交
1127 1128 1129 1130 1131 1132
      if (nxtBatch != NULL) {
        conn->pBatch = nxtBatch;
        cliSendBatch(conn);
      } else {
        addConnToPool(thrd->pool, conn);
      }
dengyihao's avatar
dengyihao 已提交
1133
    } else {
dengyihao's avatar
dengyihao 已提交
1134 1135
      cliDestroyBatch(nxtBatch);
      // conn release by other callback
dengyihao's avatar
dengyihao 已提交
1136
    }
dengyihao's avatar
dengyihao 已提交
1137
  }
dengyihao's avatar
dengyihao 已提交
1138 1139 1140

  cliDestroyBatch(p);
  taosMemoryFree(req);
dengyihao's avatar
dengyihao 已提交
1141
}
dengyihao's avatar
dengyihao 已提交
1142
static void cliHandleFastFail(SCliConn* pConn, int status) {
dengyihao's avatar
dengyihao 已提交
1143
  SCliThrd* pThrd = pConn->hostThrd;
dengyihao's avatar
dengyihao 已提交
1144
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1145 1146 1147

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

dengyihao's avatar
dengyihao 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  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 已提交
1167
      } else {
dengyihao's avatar
dengyihao 已提交
1168 1169
        SFailFastItem item = {.count = 1, .timestamp = cTimestamp};
        taosHashPut(pThrd->failFastCache, pConn->ip, strlen(pConn->ip), &item, sizeof(SFailFastItem));
dengyihao's avatar
dengyihao 已提交
1170 1171
      }
    }
dengyihao's avatar
dengyihao 已提交
1172
  } else {
dengyihao's avatar
dengyihao 已提交
1173 1174
    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 已提交
1175 1176
    cliDestroyBatch(pConn->pBatch);
    pConn->pBatch = NULL;
dengyihao's avatar
dengyihao 已提交
1177 1178 1179
  }
  cliHandleExcept(pConn);
}
dengyihao's avatar
dengyihao 已提交
1180

dengyihao's avatar
dengyihao 已提交
1181 1182 1183
void cliConnCb(uv_connect_t* req, int status) {
  SCliConn* pConn = req->data;
  SCliThrd* pThrd = pConn->hostThrd;
dengyihao's avatar
dengyihao 已提交
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
  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 已提交
1194 1195

  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
1196 1197 1198 1199 1200
    if (timeout == false) {
      cliHandleFastFail(pConn, status);
    } else if (timeout == true) {
      // already deal by timeout
    }
1201
    return;
dengyihao's avatar
dengyihao 已提交
1202
  }
dengyihao's avatar
dengyihao 已提交
1203

dengyihao's avatar
dengyihao 已提交
1204 1205
  struct sockaddr peername, sockname;
  int             addrlen = sizeof(peername);
dengyihao's avatar
dengyihao 已提交
1206
  uv_tcp_getpeername((uv_tcp_t*)pConn->stream, &peername, &addrlen);
dengyihao's avatar
dengyihao 已提交
1207
  transSockInfo2Str(&peername, pConn->dst);
dengyihao's avatar
dengyihao 已提交
1208

dengyihao's avatar
dengyihao 已提交
1209 1210
  addrlen = sizeof(sockname);
  uv_tcp_getsockname((uv_tcp_t*)pConn->stream, &sockname, &addrlen);
dengyihao's avatar
dengyihao 已提交
1211
  transSockInfo2Str(&sockname, pConn->src);
dengyihao's avatar
dengyihao 已提交
1212

dengyihao's avatar
dengyihao 已提交
1213
  tTrace("%s conn %p connect to server successfully", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1214 1215 1216 1217 1218
  if (pConn->pBatch != NULL) {
    cliSendBatch(pConn);
  } else {
    cliSend(pConn);
  }
dengyihao's avatar
dengyihao 已提交
1219 1220
}

dengyihao's avatar
dengyihao 已提交
1221
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1222 1223 1224 1225 1226
  if (!transAsyncPoolIsEmpty(pThrd->asyncPool)) {
    pThrd->stopMsg = pMsg;
    return;
  }
  pThrd->stopMsg = NULL;
dengyihao's avatar
dengyihao 已提交
1227
  pThrd->quit = true;
U
ubuntu 已提交
1228
  tDebug("cli work thread %p start to quit", pThrd);
dengyihao's avatar
dengyihao 已提交
1229
  destroyCmsg(pMsg);
dengyihao's avatar
fix bug  
dengyihao 已提交
1230
  destroyConnPool(pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1231
  uv_walk(pThrd->loop, cliWalkCb, NULL);
dengyihao's avatar
dengyihao 已提交
1232
}
dengyihao's avatar
dengyihao 已提交
1233
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1234
  int64_t    refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
1235
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1236
  if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
1237
    tDebug("%" PRId64 " already released", refId);
dengyihao's avatar
dengyihao 已提交
1238 1239
    destroyCmsg(pMsg);
    return;
dengyihao's avatar
dengyihao 已提交
1240 1241 1242
  }

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

dengyihao's avatar
dengyihao 已提交
1246 1247
  if (T_REF_VAL_GET(conn) == 2) {
    transUnrefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
1248 1249
    if (!transQueuePush(&conn->cliMsgs, pMsg)) {
      return;
dengyihao's avatar
dengyihao 已提交
1250 1251
    }
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
1252 1253 1254
  } else {
    tError("%s conn %p already released", CONN_GET_INST_LABEL(conn), conn);
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1255 1256
  }
}
dengyihao's avatar
dengyihao 已提交
1257
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1258
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1259
  pThrd->cvtAddr = pCtx->cvtAddr;
dengyihao's avatar
dengyihao 已提交
1260 1261
  destroyCmsg(pMsg);
}
U
ubuntu 已提交
1262

dengyihao's avatar
dengyihao 已提交
1263
SCliConn* cliGetConn(SCliMsg* pMsg, SCliThrd* pThrd, bool* ignore, char* addr) {
dengyihao's avatar
dengyihao 已提交
1264 1265 1266 1267
  STransConnCtx* pCtx = pMsg->ctx;
  SCliConn*      conn = NULL;

  int64_t refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
1268
  if (refId != 0) {
dengyihao's avatar
dengyihao 已提交
1269
    SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1270
    if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
1271
      tError("failed to get conn, refId: %" PRId64 "", refId);
dengyihao's avatar
dengyihao 已提交
1272 1273
      *ignore = true;
      return NULL;
dengyihao's avatar
dengyihao 已提交
1274 1275
    } else {
      conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
1276
      if (conn == NULL) {
dengyihao's avatar
dengyihao 已提交
1277
        conn = getConnFromPool(pThrd->pool, addr);
dengyihao's avatar
dengyihao 已提交
1278
        if (conn != NULL) specifyConnRef(conn, true, refId);
dengyihao's avatar
dengyihao 已提交
1279
      }
dengyihao's avatar
dengyihao 已提交
1280
      transReleaseExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
1281 1282 1283
    }
    return conn;
  };
dengyihao's avatar
dengyihao 已提交
1284

dengyihao's avatar
dengyihao 已提交
1285
  conn = getConnFromPool(pThrd->pool, addr);
dengyihao's avatar
dengyihao 已提交
1286
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
1287
    tTrace("%s conn %p get from conn pool:%p", CONN_GET_INST_LABEL(conn), conn, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1288
  } else {
dengyihao's avatar
dengyihao 已提交
1289
    tTrace("%s not found conn in conn pool:%p", ((STrans*)pThrd->pTransInst)->label, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
1290
  }
dengyihao's avatar
dengyihao 已提交
1291 1292
  return conn;
}
dengyihao's avatar
dengyihao 已提交
1293
FORCE_INLINE void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr) {
dengyihao's avatar
dengyihao 已提交
1294 1295 1296
  if (pCvtAddr->cvt == false) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1297 1298 1299
  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 已提交
1300 1301
  }
}
dengyihao's avatar
dengyihao 已提交
1302

dengyihao's avatar
dengyihao 已提交
1303
FORCE_INLINE bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx) {
dengyihao's avatar
dengyihao 已提交
1304
  if (code != 0) return false;
dengyihao's avatar
dengyihao 已提交
1305
  // if (pCtx->retryCnt == 0) return false;
dengyihao's avatar
dengyihao 已提交
1306 1307 1308
  if (transEpSetIsEqual(&pCtx->epSet, &pCtx->origEpSet)) return false;
  return true;
}
dengyihao's avatar
dengyihao 已提交
1309
FORCE_INLINE int32_t cliBuildExceptResp(SCliMsg* pMsg, STransMsg* pResp) {
dengyihao's avatar
dengyihao 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
  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 已提交
1321 1322 1323 1324 1325
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);
1326 1327 1328 1329
    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 已提交
1330 1331
    }

dengyihao's avatar
dengyihao 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    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 已提交
1342

dengyihao's avatar
dengyihao 已提交
1343
static int32_t cliPreCheckSessionLimit(SCliThrd* pThrd, char* addr) {
dengyihao's avatar
dengyihao 已提交
1344 1345
  STrans* pTransInst = pThrd->pTransInst;

dengyihao's avatar
dengyihao 已提交
1346 1347 1348 1349
  SMsgList** list = taosHashGet(pThrd->connLimitCache, addr, strlen(addr));
  if (list == NULL || *list == NULL) {
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
1350

dengyihao's avatar
dengyihao 已提交
1351 1352 1353 1354 1355
  if ((*list)->numOfConn >= pTransInst->connLimitNum) {
    return -1;
  }
  return 0;
}
dengyihao's avatar
dengyihao 已提交
1356

dengyihao's avatar
dengyihao 已提交
1357 1358 1359 1360 1361 1362 1363
static int32_t cliPreCheckSessionLimitForMsg(SCliThrd* pThrd, char* addr, SCliMsg* pMsg) {
  STrans* pTransInst = pThrd->pTransInst;

  SMsgList** list = taosHashGet(pThrd->connLimitCache, addr, strlen(addr));
  if (list == NULL || *list == NULL) {
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
1364

dengyihao's avatar
dengyihao 已提交
1365 1366
  if ((*list)->numOfConn >= pTransInst->connLimitNum) {
    QUEUE_PUSH(&(*list)->msgQ, &pMsg->q);
dengyihao's avatar
dengyihao 已提交
1367 1368 1369 1370
    return -1;
  }
  return 0;
}
dengyihao's avatar
dengyihao 已提交
1371
void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
formate  
dengyihao 已提交
1372
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1373
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
1374
  STraceId*      trace = &pMsg->msg.info.traceId;
dengyihao's avatar
dengyihao 已提交
1375

dengyihao's avatar
dengyihao 已提交
1376
  cliMayCvtFqdnToIp(&pCtx->epSet, &pThrd->cvtAddr);
dengyihao's avatar
dengyihao 已提交
1377
  if (!EPSET_IS_VALID(&pCtx->epSet)) {
1378
    tGError("%s, msg %s sent with invalid epset", pTransInst->label, TMSG_INFO(pMsg->msg.msgType));
dengyihao's avatar
dengyihao 已提交
1379
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1380 1381
    return;
  }
dengyihao's avatar
dengyihao 已提交
1382

dengyihao's avatar
dengyihao 已提交
1383 1384 1385 1386
  char*    fqdn = EPSET_GET_INUSE_IP(&pCtx->epSet);
  uint16_t port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
  char     addr[TSDB_FQDN_LEN + 64] = {0};
  CONN_CONSTRUCT_HASH_KEY(addr, fqdn, port);
dengyihao's avatar
dengyihao 已提交
1387

dengyihao's avatar
dengyihao 已提交
1388
  bool      ignore = false;
dengyihao's avatar
dengyihao 已提交
1389
  SCliConn* conn = cliGetConn(pMsg, pThrd, &ignore, addr);
dengyihao's avatar
dengyihao 已提交
1390
  if (ignore == true) {
dengyihao's avatar
dengyihao 已提交
1391
    // persist conn already release by server
dengyihao's avatar
dengyihao 已提交
1392 1393
    STransMsg resp;
    cliBuildExceptResp(pMsg, &resp);
dengyihao's avatar
dengyihao 已提交
1394 1395 1396
    if (pMsg->type != Release) {
      pTransInst->cfp(pTransInst->parent, &resp, NULL);
    }
dengyihao's avatar
dengyihao 已提交
1397
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
1398 1399
    return;
  }
dengyihao's avatar
dengyihao 已提交
1400
  if (conn == NULL && cliPreCheckSessionLimitForMsg(pThrd, addr, pMsg) != 0) {
dengyihao's avatar
dengyihao 已提交
1401 1402 1403
    return;
  }

dengyihao's avatar
dengyihao 已提交
1404
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
1405
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1406
    transQueuePush(&conn->cliMsgs, pMsg);
U
ubuntu 已提交
1407
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
1408
  } else {
U
ubuntu 已提交
1409
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
1410 1411 1412 1413

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

dengyihao's avatar
dengyihao 已提交
1414
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
1415
    transQueuePush(&conn->cliMsgs, pMsg);
dengyihao's avatar
dengyihao 已提交
1416

dengyihao's avatar
dengyihao 已提交
1417
    conn->ip = strdup(addr);
dengyihao's avatar
dengyihao 已提交
1418
    uint32_t ipaddr = cliGetIpFromFqdnCache(pThrd->fqdn2ipCache, fqdn);
1419 1420 1421 1422 1423 1424 1425 1426 1427
    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 已提交
1428

dengyihao's avatar
dengyihao 已提交
1429
    struct sockaddr_in addr;
1430
    addr.sin_family = AF_INET;
1431
    addr.sin_addr.s_addr = ipaddr;
dengyihao's avatar
dengyihao 已提交
1432
    addr.sin_port = (uint16_t)htons(port);
dengyihao's avatar
dengyihao 已提交
1433

dengyihao's avatar
dengyihao 已提交
1434
    tGTrace("%s conn %p try to connect to %s", pTransInst->label, conn, conn->ip);
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    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 已提交
1455

1456
    ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
dengyihao's avatar
dengyihao 已提交
1457
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1458 1459 1460 1461 1462
      uv_timer_stop(conn->timer);
      conn->timer->data = NULL;
      taosArrayPush(pThrd->timerList, &conn->timer);
      conn->timer = NULL;

dengyihao's avatar
dengyihao 已提交
1463
      cliHandleFastFail(conn, ret);
dengyihao's avatar
dengyihao 已提交
1464 1465
      return;
    }
dengyihao's avatar
dengyihao 已提交
1466 1467 1468 1469 1470 1471 1472 1473 1474

    SMsgList** list = taosHashGet(pThrd->connLimitCache, conn->ip, strlen(conn->ip));
    if (list == NULL || *list == NULL) {
      SMsgList* nList = taosMemoryCalloc(1, sizeof(SMsgList));
      nList->numOfConn++;
      QUEUE_INIT(&nList->msgQ);
      taosHashPut(pThrd->connLimitCache, conn->ip, strlen(conn->ip), &nList, sizeof(void*));
    }

dengyihao's avatar
dengyihao 已提交
1475
    uv_timer_start(conn->timer, cliConnTimeout, TRANS_CONN_TIMEOUT, 0);
dengyihao's avatar
dengyihao 已提交
1476
  }
dengyihao's avatar
dengyihao 已提交
1477
  tGTrace("%s conn %p ready", pTransInst->label, conn);
dengyihao's avatar
dengyihao 已提交
1478
}
dengyihao's avatar
dengyihao 已提交
1479

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

dengyihao's avatar
dengyihao 已提交
1483 1484
  while (!QUEUE_IS_EMPTY(wq)) {
    queue* h = QUEUE_HEAD(wq);
dengyihao's avatar
dengyihao 已提交
1485 1486 1487
    QUEUE_REMOVE(h);

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1488 1489 1490 1491 1492

    if (pMsg->type == Quit) {
      pThrd->stopMsg = pMsg;
      continue;
    }
dengyihao's avatar
dengyihao 已提交
1493 1494 1495 1496 1497 1498 1499 1500
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);

    count++;
  }
  if (count >= 2) {
    tTrace("cli process batch size:%d", count);
  }
}
dengyihao's avatar
dengyihao 已提交
1501
SCliBatch* cliGetHeadFromList(SCliBatchList* pList) {
dengyihao's avatar
dengyihao 已提交
1502
  if (QUEUE_IS_EMPTY(&pList->wq) || pList->connCnt > pList->connMax || pList->sending > pList->connMax) {
dengyihao's avatar
dengyihao 已提交
1503 1504 1505 1506
    return NULL;
  }
  queue* hr = QUEUE_HEAD(&pList->wq);
  QUEUE_REMOVE(hr);
dengyihao's avatar
dengyihao 已提交
1507
  pList->sending += 1;
dengyihao's avatar
dengyihao 已提交
1508 1509 1510 1511 1512 1513

  pList->len -= 1;

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

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

dengyihao's avatar
dengyihao 已提交
1518
  int count = 0;
dengyihao's avatar
dengyihao 已提交
1519 1520
  while (!QUEUE_IS_EMPTY(wq)) {
    queue* h = QUEUE_HEAD(wq);
dengyihao's avatar
dengyihao 已提交
1521
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
1522 1523

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1524 1525 1526 1527 1528 1529

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

dengyihao's avatar
dengyihao 已提交
1530
    if (pMsg->type == Normal && REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
1531 1532 1533 1534 1535 1536 1537
      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 已提交
1538 1539 1540 1541 1542
      // 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 已提交
1543
        pBatchList->connMax = pInst->connLimitNum;
dengyihao's avatar
dengyihao 已提交
1544
        pBatchList->connCnt = 0;
dengyihao's avatar
dengyihao 已提交
1545
        pBatchList->batchLenLimit = pInst->batchSize;
dengyihao's avatar
dengyihao 已提交
1546
        pBatchList->len += 1;
dengyihao's avatar
dengyihao 已提交
1547

dengyihao's avatar
dengyihao 已提交
1548 1549 1550 1551
        pBatchList->ip = strdup(ip);
        pBatchList->dst = strdup(key);
        pBatchList->port = port;

dengyihao's avatar
dengyihao 已提交
1552 1553
        SCliBatch* pBatch = taosMemoryCalloc(1, sizeof(SCliBatch));
        QUEUE_INIT(&pBatch->wq);
dengyihao's avatar
dengyihao 已提交
1554 1555
        QUEUE_INIT(&pBatch->listq);

dengyihao's avatar
dengyihao 已提交
1556 1557 1558
        QUEUE_PUSH(&pBatch->wq, h);
        pBatch->wLen += 1;
        pBatch->batchSize += pMsg->msg.contLen;
dengyihao's avatar
dengyihao 已提交
1559
        pBatch->pList = pBatchList;
dengyihao's avatar
dengyihao 已提交
1560

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

dengyihao's avatar
dengyihao 已提交
1563
        taosHashPut(pThrd->batchCache, key, sizeof(key), &pBatchList, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
1564
      } else {
dengyihao's avatar
dengyihao 已提交
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
        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 已提交
1586
          pBatch->wLen += 1;
dengyihao's avatar
dengyihao 已提交
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
        } 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 已提交
1600
      }
dengyihao's avatar
dengyihao 已提交
1601
      continue;
dengyihao's avatar
dengyihao 已提交
1602
    }
dengyihao's avatar
dengyihao 已提交
1603
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1604
    count++;
dengyihao's avatar
dengyihao 已提交
1605
  }
dengyihao's avatar
dengyihao 已提交
1606

dengyihao's avatar
dengyihao 已提交
1607
  void** pIter = taosHashIterate(pThrd->batchCache, NULL);
dengyihao's avatar
dengyihao 已提交
1608
  while (pIter != NULL) {
dengyihao's avatar
dengyihao 已提交
1609
    SCliBatchList* batchList = (SCliBatchList*)(*pIter);
dengyihao's avatar
dengyihao 已提交
1610 1611 1612
    SCliBatch*     batch = cliGetHeadFromList(batchList);
    if (batch != NULL) {
      cliHandleBatchReq(batch, pThrd);
dengyihao's avatar
dengyihao 已提交
1613
    }
dengyihao's avatar
dengyihao 已提交
1614
    pIter = (void**)taosHashIterate(pThrd->batchCache, pIter);
dengyihao's avatar
dengyihao 已提交
1615 1616
  }

dengyihao's avatar
dengyihao 已提交
1617
  if (count >= 2) {
S
Shengliang Guan 已提交
1618
    tTrace("cli process batch size:%d", count);
dengyihao's avatar
dengyihao 已提交
1619
  }
dengyihao's avatar
dengyihao 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
}

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 已提交
1633
  int8_t supportBatch = pTransInst->supportBatch;
dengyihao's avatar
dengyihao 已提交
1634
  if (supportBatch == 0) {
dengyihao's avatar
dengyihao 已提交
1635
    cliNoBatchDealReq(&wq, pThrd);
dengyihao's avatar
dengyihao 已提交
1636
  } else if (supportBatch == 1) {
dengyihao's avatar
dengyihao 已提交
1637
    cliBatchDealReq(&wq, pThrd);
dengyihao's avatar
dengyihao 已提交
1638
  }
dengyihao's avatar
dengyihao 已提交
1639

dengyihao's avatar
dengyihao 已提交
1640
  if (pThrd->stopMsg != NULL) cliHandleQuit(pThrd->stopMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1641
}
dengyihao's avatar
dengyihao 已提交
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
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 已提交
1668
}
dengyihao's avatar
dengyihao 已提交
1669

dengyihao's avatar
dengyihao 已提交
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
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 已提交
1699 1700 1701
bool cliRecvReleaseReq(SCliConn* conn, STransMsgHead* pHead) {
  if (pHead->release == 1 && (pHead->msgLen) == sizeof(*pHead)) {
    uint64_t ahandle = pHead->ahandle;
dengyihao's avatar
dengyihao 已提交
1702
    tDebug("ahandle = %" PRIu64 "", ahandle);
dengyihao's avatar
dengyihao 已提交
1703 1704
    SCliMsg* pMsg = NULL;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
dengyihao's avatar
dengyihao 已提交
1705

dengyihao's avatar
dengyihao 已提交
1706 1707
    transClearBuffer(&conn->readBuf);
    transFreeMsg(transContFromHead((char*)pHead));
dengyihao's avatar
dengyihao 已提交
1708 1709 1710 1711

    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 已提交
1712
        ASSERTS(pMsg == NULL, "trans-cli recv invaid release-req");
dengyihao's avatar
dengyihao 已提交
1713 1714
        return true;
      }
dengyihao's avatar
dengyihao 已提交
1715
    }
dengyihao's avatar
dengyihao 已提交
1716 1717 1718

    cliIteraConnMsgs(conn);

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

dengyihao's avatar
dengyihao 已提交
1722 1723 1724 1725 1726 1727
    addConnToPool(((SCliThrd*)conn->hostThrd)->pool, conn);
    return true;
  }
  return false;
}

U
ubuntu 已提交
1728
static void* cliWorkThread(void* arg) {
dengyihao's avatar
dengyihao 已提交
1729
  SCliThrd* pThrd = (SCliThrd*)arg;
dengyihao's avatar
dengyihao 已提交
1730
  pThrd->pid = taosGetSelfPthreadId();
G
gccgdb1234 已提交
1731
  setThreadName("trans-cli-work");
dengyihao's avatar
dengyihao 已提交
1732
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
dengyihao's avatar
dengyihao 已提交
1733 1734

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

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

dengyihao's avatar
dengyihao 已提交
1741
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
1742
  memcpy(cli->label, label, TSDB_LABEL_LEN);
dengyihao's avatar
dengyihao 已提交
1743
  cli->numOfThreads = numOfThreads;
dengyihao's avatar
dengyihao 已提交
1744
  cli->pThreadObj = (SCliThrd**)taosMemoryCalloc(cli->numOfThreads, sizeof(SCliThrd*));
dengyihao's avatar
dengyihao 已提交
1745 1746

  for (int i = 0; i < cli->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
1747
    SCliThrd* pThrd = createThrdObj(shandle);
dengyihao's avatar
dengyihao 已提交
1748 1749 1750 1751 1752
    if (pThrd == NULL) {
      return NULL;
    }

    int err = taosThreadCreate(&pThrd->thread, NULL, cliWorkThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
1753
    if (err == 0) {
S
Shengliang Guan 已提交
1754
      tDebug("success to create tranport-cli thread:%d", i);
dengyihao's avatar
dengyihao 已提交
1755
    }
dengyihao's avatar
dengyihao 已提交
1756
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
1757
  }
dengyihao's avatar
dengyihao 已提交
1758

dengyihao's avatar
dengyihao 已提交
1759 1760
  return cli;
}
dengyihao's avatar
dengyihao 已提交
1761

dengyihao's avatar
dengyihao 已提交
1762
static FORCE_INLINE void destroyUserdata(STransMsg* userdata) {
dengyihao's avatar
dengyihao 已提交
1763 1764 1765 1766 1767 1768
  if (userdata->pCont == NULL) {
    return;
  }
  transFreeMsg(userdata->pCont);
  userdata->pCont = NULL;
}
dengyihao's avatar
dengyihao 已提交
1769

dengyihao's avatar
dengyihao 已提交
1770
static FORCE_INLINE void destroyCmsg(void* arg) {
dengyihao's avatar
dengyihao 已提交
1771
  SCliMsg* pMsg = arg;
dengyihao's avatar
dengyihao 已提交
1772 1773 1774
  if (pMsg == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1775

dengyihao's avatar
dengyihao 已提交
1776 1777
  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
wafwerar's avatar
wafwerar 已提交
1778
  taosMemoryFree(pMsg);
dengyihao's avatar
dengyihao 已提交
1779
}
dengyihao's avatar
dengyihao 已提交
1780

dengyihao's avatar
dengyihao 已提交
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
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 已提交
1800 1801 1802
static SCliThrd* createThrdObj(void* trans) {
  STrans* pTransInst = trans;

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

dengyihao's avatar
dengyihao 已提交
1805
  QUEUE_INIT(&pThrd->msg);
wafwerar's avatar
wafwerar 已提交
1806
  taosThreadMutexInit(&pThrd->msgMtx, NULL);
dengyihao's avatar
dengyihao 已提交
1807

wafwerar's avatar
wafwerar 已提交
1808
  pThrd->loop = (uv_loop_t*)taosMemoryMalloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
1809 1810 1811 1812 1813 1814 1815 1816
  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 已提交
1817 1818 1819 1820 1821
  if (pTransInst->supportBatch) {
    pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 4, pThrd, cliAsyncCb);
  } else {
    pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 8, pThrd, cliAsyncCb);
  }
dengyihao's avatar
dengyihao 已提交
1822
  if (pThrd->asyncPool == NULL) {
dengyihao's avatar
ref log  
dengyihao 已提交
1823
    tError("failed to init async pool");
dengyihao's avatar
dengyihao 已提交
1824 1825 1826 1827 1828 1829
    uv_loop_close(pThrd->loop);
    taosMemoryFree(pThrd->loop);
    taosThreadMutexDestroy(&pThrd->msgMtx);
    taosMemoryFree(pThrd);
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1830 1831 1832 1833

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

dengyihao's avatar
dengyihao 已提交
1836
  int32_t timerSize = 64;
dengyihao's avatar
dengyihao 已提交
1837 1838 1839 1840 1841 1842 1843
  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 已提交
1844
  pThrd->pool = createConnPool(4);
dengyihao's avatar
dengyihao 已提交
1845
  transDQCreate(pThrd->loop, &pThrd->delayQueue);
dengyihao's avatar
dengyihao 已提交
1846

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

dengyihao's avatar
dengyihao 已提交
1849 1850 1851
  pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
  pThrd->pTransInst = trans;

dengyihao's avatar
dengyihao 已提交
1852
  pThrd->destroyAhandleFp = pTransInst->destroyFp;
dengyihao's avatar
dengyihao 已提交
1853
  pThrd->fqdn2ipCache = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1854
  pThrd->failFastCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1855
  pThrd->connLimitCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
1856

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

dengyihao's avatar
dengyihao 已提交
1859
  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
1860 1861
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1862
static void destroyThrdObj(SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1863 1864 1865
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1866

wafwerar's avatar
wafwerar 已提交
1867
  taosThreadJoin(pThrd->thread, NULL);
dengyihao's avatar
dengyihao 已提交
1868
  CLI_RELEASE_UV(pThrd->loop);
wafwerar's avatar
wafwerar 已提交
1869
  taosThreadMutexDestroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
1870
  TRANS_DESTROY_ASYNC_POOL_MSG(pThrd->asyncPool, SCliMsg, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1871
  transAsyncPoolDestroy(pThrd->asyncPool);
dengyihao's avatar
dengyihao 已提交
1872

dengyihao's avatar
dengyihao 已提交
1873
  transDQDestroy(pThrd->delayQueue, destroyCmsgAndAhandle);
dengyihao's avatar
dengyihao 已提交
1874
  transDQDestroy(pThrd->timeoutQueue, NULL);
dengyihao's avatar
dengyihao 已提交
1875

dengyihao's avatar
dengyihao 已提交
1876
  tDebug("thread destroy %" PRId64, pThrd->pid);
dengyihao's avatar
dengyihao 已提交
1877 1878 1879 1880 1881
  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 已提交
1882
  taosMemoryFree(pThrd->prepare);
wafwerar's avatar
wafwerar 已提交
1883
  taosMemoryFree(pThrd->loop);
dengyihao's avatar
dengyihao 已提交
1884
  taosHashCleanup(pThrd->fqdn2ipCache);
dengyihao's avatar
dengyihao 已提交
1885
  taosHashCleanup(pThrd->failFastCache);
dengyihao's avatar
dengyihao 已提交
1886 1887 1888

  void** pIter = taosHashIterate(pThrd->batchCache, NULL);
  while (pIter != NULL) {
dengyihao's avatar
dengyihao 已提交
1889 1890 1891 1892 1893 1894 1895 1896
    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 已提交
1897 1898
    taosMemoryFree(pBatchList->ip);
    taosMemoryFree(pBatchList->dst);
dengyihao's avatar
dengyihao 已提交
1899
    taosMemoryFree(pBatchList);
dengyihao's avatar
dengyihao 已提交
1900

dengyihao's avatar
dengyihao 已提交
1901 1902
    pIter = (void**)taosHashIterate(pThrd->batchCache, pIter);
  }
dengyihao's avatar
dengyihao 已提交
1903
  taosHashCleanup(pThrd->batchCache);
dengyihao's avatar
dengyihao 已提交
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920

  pIter = taosHashIterate(pThrd->connLimitCache, NULL);
  while (pIter != NULL) {
    SMsgList* list = (SMsgList*)(*pIter);
    while (!QUEUE_IS_EMPTY(&list->msgQ)) {
      queue* h = QUEUE_HEAD(&list->msgQ);
      QUEUE_REMOVE(h);

      SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
      destroyCmsg(pMsg);
    }
    taosMemoryFree(list);

    pIter = (void**)taosHashIterate(pThrd->connLimitCache, pIter);
  }
  taosHashCleanup(pThrd->connLimitCache);

wafwerar's avatar
wafwerar 已提交
1921
  taosMemoryFree(pThrd);
dengyihao's avatar
dengyihao 已提交
1922
}
dengyihao's avatar
dengyihao 已提交
1923

dengyihao's avatar
dengyihao 已提交
1924
static FORCE_INLINE void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1925
  //
wafwerar's avatar
wafwerar 已提交
1926
  taosMemoryFree(ctx);
dengyihao's avatar
dengyihao 已提交
1927
}
dengyihao's avatar
dengyihao 已提交
1928

dengyihao's avatar
dengyihao 已提交
1929
void cliSendQuit(SCliThrd* thrd) {
dengyihao's avatar
dengyihao 已提交
1930
  // cli can stop gracefully
wafwerar's avatar
wafwerar 已提交
1931
  SCliMsg* msg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1932
  msg->type = Quit;
dengyihao's avatar
dengyihao 已提交
1933
  transAsyncSend(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
1934
  atomic_store_8(&thrd->asyncPool->stop, 1);
dengyihao's avatar
dengyihao 已提交
1935
}
dengyihao's avatar
dengyihao 已提交
1936 1937
void cliWalkCb(uv_handle_t* handle, void* arg) {
  if (!uv_is_closing(handle)) {
dengyihao's avatar
dengyihao 已提交
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
    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 已提交
1950
    uv_close(handle, cliDestroy);
dengyihao's avatar
dengyihao 已提交
1951 1952
  }
}
dengyihao's avatar
dengyihao 已提交
1953

dengyihao's avatar
dengyihao 已提交
1954
FORCE_INLINE int cliRBChoseIdx(STrans* pTransInst) {
dengyihao's avatar
dengyihao 已提交
1955
  int32_t index = pTransInst->index;
dengyihao's avatar
dengyihao 已提交
1956 1957 1958
  if (pTransInst->numOfThreads == 0) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1959 1960 1961 1962
  /*
   * no lock, and to avoid CPU load imbalance, set limit pTransInst->numOfThreads * 2000;
   */
  if (pTransInst->index++ >= pTransInst->numOfThreads * 2000) {
U
ubuntu 已提交
1963 1964 1965 1966
    pTransInst->index = 0;
  }
  return index % pTransInst->numOfThreads;
}
dengyihao's avatar
dengyihao 已提交
1967
static FORCE_INLINE void doDelayTask(void* param) {
dengyihao's avatar
dengyihao 已提交
1968
  STaskArg* arg = param;
dengyihao's avatar
dengyihao 已提交
1969
  cliHandleReq((SCliMsg*)arg->param1, (SCliThrd*)arg->param2);
dengyihao's avatar
dengyihao 已提交
1970 1971
  taosMemoryFree(arg);
}
dengyihao's avatar
dengyihao 已提交
1972

dengyihao's avatar
dengyihao 已提交
1973 1974 1975
static void doCloseIdleConn(void* param) {
  STaskArg* arg = param;
  SCliConn* conn = arg->param1;
dengyihao's avatar
dengyihao 已提交
1976
  tDebug("%s conn %p idle, close it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
1977
  conn->task = NULL;
dengyihao's avatar
dengyihao 已提交
1978 1979
  cliDestroyConn(conn, true);
  taosMemoryFree(arg);
dengyihao's avatar
dengyihao 已提交
1980 1981
}

dengyihao's avatar
dengyihao 已提交
1982
static void cliSchedMsgToNextNode(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1983
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1984 1985
  STransConnCtx* pCtx = pMsg->ctx;

dengyihao's avatar
dengyihao 已提交
1986 1987
  STraceId* trace = &pMsg->msg.info.traceId;
  char      tbuf[256] = {0};
dengyihao's avatar
dengyihao 已提交
1988
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1989 1990
  tGDebug("%s retry on next node,use:%s, step: %d,timeout:%" PRId64 "", transLabel(pThrd->pTransInst), tbuf,
          pCtx->retryStep, pCtx->retryNextInterval);
dengyihao's avatar
dengyihao 已提交
1991 1992 1993 1994

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

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

dengyihao's avatar
dengyihao 已提交
1999
FORCE_INLINE void cliCompareAndSwap(int8_t* val, int8_t exp, int8_t newVal) {
dengyihao's avatar
dengyihao 已提交
2000 2001 2002 2003
  if (*val != exp) {
    *val = newVal;
  }
}
dengyihao's avatar
dengyihao 已提交
2004

dengyihao's avatar
dengyihao 已提交
2005
FORCE_INLINE bool cliTryExtractEpSet(STransMsg* pResp, SEpSet* dst) {
dengyihao's avatar
dengyihao 已提交
2006 2007 2008 2009 2010 2011
  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 已提交
2012 2013 2014 2015
    return false;
  }
  int32_t tlen = tSerializeSEpSet(NULL, 0, dst);

dengyihao's avatar
dengyihao 已提交
2016 2017 2018 2019 2020 2021 2022
  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 已提交
2023 2024

  pResp->pCont = buf;
dengyihao's avatar
dengyihao 已提交
2025 2026 2027
  pResp->contLen = len;

  *dst = epset;
dengyihao's avatar
dengyihao 已提交
2028 2029
  return true;
}
dengyihao's avatar
dengyihao 已提交
2030
bool cliResetEpset(STransConnCtx* pCtx, STransMsg* pResp, bool hasEpSet) {
dengyihao's avatar
dengyihao 已提交
2031
  bool noDelay = true;
dengyihao's avatar
dengyihao 已提交
2032 2033 2034 2035 2036 2037 2038
  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 已提交
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
    } 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 已提交
2049
      } else {
dengyihao's avatar
dengyihao 已提交
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
        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 已提交
2062
      }
dengyihao's avatar
dengyihao 已提交
2063 2064
    }
  } else {
dengyihao's avatar
dengyihao 已提交
2065
    SEpSet  epSet;
dengyihao's avatar
dengyihao 已提交
2066 2067
    int32_t valid = tDeserializeSEpSet(pResp->pCont, pResp->contLen, &epSet);
    if (valid < 0) {
dengyihao's avatar
dengyihao 已提交
2068 2069 2070 2071 2072 2073
      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 已提交
2074
    } else {
dengyihao's avatar
dengyihao 已提交
2075 2076 2077
      if (!transEpSetIsEqual(&pCtx->epSet, &epSet)) {
        tDebug("epset not equal, retry new epset");
        pCtx->epSet = epSet;
dengyihao's avatar
dengyihao 已提交
2078
        noDelay = false;
dengyihao's avatar
dengyihao 已提交
2079
      } else {
dengyihao's avatar
dengyihao 已提交
2080 2081 2082 2083 2084 2085
        if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps) {
          noDelay = false;
        } else {
          tDebug("epset equal, continue");
          EPSET_FORWARD_INUSE(&pCtx->epSet);
        }
dengyihao's avatar
dengyihao 已提交
2086
      }
dengyihao's avatar
dengyihao 已提交
2087 2088 2089 2090 2091
    }
  }
  return noDelay;
}
bool cliGenRetryRule(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
2092 2093
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
2094

dengyihao's avatar
dengyihao 已提交
2095 2096
  STransConnCtx* pCtx = pMsg->ctx;
  int32_t        code = pResp->code;
dengyihao's avatar
dengyihao 已提交
2097

dengyihao's avatar
dengyihao 已提交
2098
  bool retry = pTransInst->retry != NULL ? pTransInst->retry(code, pResp->msgType - 1) : false;
dengyihao's avatar
dengyihao 已提交
2099 2100 2101
  if (retry == false) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
2102 2103 2104 2105 2106 2107 2108 2109

  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 已提交
2110
    pCtx->retryStep = 0;
dengyihao's avatar
dengyihao 已提交
2111
    pCtx->retryInit = true;
dengyihao's avatar
dengyihao 已提交
2112
    pCtx->retryCode = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
2113 2114 2115

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

dengyihao's avatar
dengyihao 已提交
2118 2119
  if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
    return false;
dengyihao's avatar
dengyihao 已提交
2120
  }
dengyihao's avatar
dengyihao 已提交
2121

dengyihao's avatar
dengyihao 已提交
2122 2123 2124 2125 2126 2127
  // code, msgType

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

dengyihao's avatar
dengyihao 已提交
2128 2129
  bool noDelay = false;
  if (code == TSDB_CODE_RPC_BROKEN_LINK || code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
dengyihao's avatar
dengyihao 已提交
2130
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2131
    noDelay = cliResetEpset(pCtx, pResp, false);
dengyihao's avatar
dengyihao 已提交
2132 2133
    transFreeMsg(pResp->pCont);
    transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
2134
  } else if (code == TSDB_CODE_SYN_NOT_LEADER || code == TSDB_CODE_SYN_INTERNAL_ERROR ||
2135 2136
             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 已提交
2137
             code == TSDB_CODE_APP_IS_STOPPING || code == TSDB_CODE_VND_STOPPED) {
dengyihao's avatar
dengyihao 已提交
2138
    tTrace("code str %s, contlen:%d 1", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2139
    noDelay = cliResetEpset(pCtx, pResp, true);
dengyihao's avatar
dengyihao 已提交
2140 2141
    transFreeMsg(pResp->pCont);
    addConnToPool(pThrd->pool, pConn);
dengyihao's avatar
dengyihao 已提交
2142
  } else if (code == TSDB_CODE_SYN_RESTORING) {
dengyihao's avatar
dengyihao 已提交
2143
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2144
    noDelay = cliResetEpset(pCtx, pResp, true);
dengyihao's avatar
dengyihao 已提交
2145 2146
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
2147
  } else {
dengyihao's avatar
dengyihao 已提交
2148
    tTrace("code str %s, contlen:%d 0", tstrerror(code), pResp->contLen);
dengyihao's avatar
dengyihao 已提交
2149 2150 2151
    noDelay = cliResetEpset(pCtx, pResp, false);
    addConnToPool(pThrd->pool, pConn);
    transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
2152
  }
dengyihao's avatar
dengyihao 已提交
2153 2154 2155 2156
  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 已提交
2157

dengyihao's avatar
dengyihao 已提交
2158 2159 2160
  if (noDelay == false) {
    pCtx->epsetRetryCnt = 1;
    pCtx->retryStep++;
dengyihao's avatar
dengyihao 已提交
2161

dengyihao's avatar
dengyihao 已提交
2162 2163 2164 2165 2166 2167
    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 已提交
2168 2169 2170
    // if (-1 != pCtx->retryMaxTimeout && taosGetTimestampMs() - pCtx->retryInitTimestamp >= pCtx->retryMaxTimeout) {
    //   return false;
    // }
dengyihao's avatar
dengyihao 已提交
2171 2172 2173
  } else {
    pCtx->retryNextInterval = 0;
    pCtx->epsetRetryCnt++;
dengyihao's avatar
dengyihao 已提交
2174
  }
dengyihao's avatar
dengyihao 已提交
2175

dengyihao's avatar
dengyihao 已提交
2176
  pMsg->sent = 0;
dengyihao's avatar
dengyihao 已提交
2177
  cliSchedMsgToNextNode(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
2178
  return true;
dengyihao's avatar
dengyihao 已提交
2179
}
dengyihao's avatar
dengyihao 已提交
2180
int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
2181 2182
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
2183

dengyihao's avatar
dengyihao 已提交
2184
  if (pMsg == NULL || pMsg->ctx == NULL) {
dengyihao's avatar
dengyihao 已提交
2185
    tTrace("%s conn %p handle resp", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
2186 2187 2188
    pTransInst->cfp(pTransInst->parent, pResp, NULL);
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
2189

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

dengyihao's avatar
dengyihao 已提交
2192 2193 2194
  bool retry = cliGenRetryRule(pConn, pResp, pMsg);
  if (retry == true) {
    return -1;
dengyihao's avatar
dengyihao 已提交
2195
  }
dengyihao's avatar
dengyihao 已提交
2196

dengyihao's avatar
dengyihao 已提交
2197 2198 2199
  if (pCtx->retryCode != TSDB_CODE_SUCCESS) {
    int32_t code = pResp->code;
    // return internal code app
dengyihao's avatar
dengyihao 已提交
2200 2201
    if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK ||
        code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED) {
dengyihao's avatar
dengyihao 已提交
2202 2203 2204 2205
      pResp->code = pCtx->retryCode;
    }
  }

2206
  // check whole vnodes is offline on this vgroup
2207 2208
  if (pCtx->epsetRetryCnt >= pCtx->epSet.numOfEps || pCtx->retryStep > 0) {
    if (pResp->code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
A
Alex Duan 已提交
2209
      pResp->code = TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED;
2210
    } else if (pResp->code == TSDB_CODE_RPC_BROKEN_LINK) {
A
Alex Duan 已提交
2211
      pResp->code = TSDB_CODE_RPC_SOMENODE_BROKEN_LINK;
2212 2213 2214
    }
  }

dengyihao's avatar
dengyihao 已提交
2215 2216
  STraceId* trace = &pResp->info.traceId;
  bool      hasEpSet = cliTryExtractEpSet(pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
2217
  if (hasEpSet) {
dengyihao's avatar
dengyihao 已提交
2218 2219
    char tbuf[256] = {0};
    EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
2220
    tGTrace("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
2221
  }
dengyihao's avatar
dengyihao 已提交
2222

dengyihao's avatar
dengyihao 已提交
2223
  if (pCtx->pSem != NULL) {
dengyihao's avatar
dengyihao 已提交
2224
    tGTrace("%s conn %p(sync) handle resp", CONN_GET_INST_LABEL(pConn), pConn);
2225
    if (pCtx->pRsp == NULL) {
dengyihao's avatar
dengyihao 已提交
2226
      tGTrace("%s conn %p(sync) failed to resp, ignore", CONN_GET_INST_LABEL(pConn), pConn);
2227 2228 2229
    } else {
      memcpy((char*)pCtx->pRsp, (char*)pResp, sizeof(*pResp));
    }
dengyihao's avatar
dengyihao 已提交
2230
    tsem_post(pCtx->pSem);
2231
    pCtx->pRsp = NULL;
dengyihao's avatar
dengyihao 已提交
2232
  } else {
dengyihao's avatar
dengyihao 已提交
2233
    tGTrace("%s conn %p handle resp", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
2234
    if (retry == false && hasEpSet == true) {
dengyihao's avatar
dengyihao 已提交
2235
      pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
2236
    } else {
dengyihao's avatar
dengyihao 已提交
2237
      if (!cliIsEpsetUpdated(pResp->code, pCtx)) {
dengyihao's avatar
dengyihao 已提交
2238 2239 2240 2241
        pTransInst->cfp(pTransInst->parent, pResp, NULL);
      } else {
        pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
2242
    }
dengyihao's avatar
dengyihao 已提交
2243
  }
dengyihao's avatar
dengyihao 已提交
2244
  return 0;
dengyihao's avatar
dengyihao 已提交
2245
}
U
ubuntu 已提交
2246 2247

void transCloseClient(void* arg) {
U
ubuntu 已提交
2248
  SCliObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
2249
  for (int i = 0; i < cli->numOfThreads; i++) {
U
ubuntu 已提交
2250
    cliSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
2251
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
2252
  }
wafwerar's avatar
wafwerar 已提交
2253 2254
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
dengyihao's avatar
dengyihao 已提交
2255
}
dengyihao's avatar
dengyihao 已提交
2256 2257 2258 2259 2260
void transRefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_INC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
2261
  tTrace("%s conn %p ref %d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
2262 2263 2264 2265 2266 2267 2268
  UNUSED(ref);
}
void transUnrefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_DEC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
2269
  tTrace("%s conn %p ref:%d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
2270
  if (ref == 0) {
U
ubuntu 已提交
2271
    cliDestroyConn((SCliConn*)handle, true);
dengyihao's avatar
dengyihao 已提交
2272 2273
  }
}
dengyihao's avatar
dengyihao 已提交
2274
static FORCE_INLINE SCliThrd* transGetWorkThrdFromHandle(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
2275
  SCliThrd*  pThrd = NULL;
dengyihao's avatar
dengyihao 已提交
2276
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
2277 2278 2279
  if (exh == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
2280

dengyihao's avatar
dengyihao 已提交
2281 2282 2283 2284 2285 2286
  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 已提交
2287
  pThrd = exh->pThrd;
dengyihao's avatar
dengyihao 已提交
2288
  transReleaseExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
2289 2290
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
2291
SCliThrd* transGetWorkThrd(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
2292
  if (handle == 0) {
dengyihao's avatar
dengyihao 已提交
2293
    int idx = cliRBChoseIdx(trans);
dengyihao's avatar
dengyihao 已提交
2294
    if (idx < 0) return NULL;
dengyihao's avatar
dengyihao 已提交
2295 2296
    return ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
dengyihao's avatar
dengyihao 已提交
2297
  SCliThrd* pThrd = transGetWorkThrdFromHandle(trans, handle);
D
dapan1121 已提交
2298
  return pThrd;
dengyihao's avatar
dengyihao 已提交
2299
}
dengyihao's avatar
dengyihao 已提交
2300
int transReleaseCliHandle(void* handle) {
dengyihao's avatar
dengyihao 已提交
2301 2302 2303
  int  idx = -1;
  bool valid = false;

dengyihao's avatar
dengyihao 已提交
2304
  SCliThrd* pThrd = transGetWorkThrdFromHandle(NULL, (int64_t)handle);
dengyihao's avatar
dengyihao 已提交
2305
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2306
    return -1;
dengyihao's avatar
dengyihao 已提交
2307
  }
dengyihao's avatar
dengyihao 已提交
2308

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

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

dengyihao's avatar
dengyihao 已提交
2315
  SCliMsg* cmsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2316
  cmsg->msg = tmsg;
dengyihao's avatar
dengyihao 已提交
2317
  cmsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2318
  cmsg->type = Release;
dengyihao's avatar
dengyihao 已提交
2319
  cmsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
2320

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

dengyihao's avatar
dengyihao 已提交
2324
  if (0 != transAsyncSend(pThrd->asyncPool, &cmsg->q)) {
dengyihao's avatar
dengyihao 已提交
2325
    destroyCmsg(cmsg);
dengyihao's avatar
dengyihao 已提交
2326 2327
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2328
  return 0;
dengyihao's avatar
dengyihao 已提交
2329
}
dengyihao's avatar
dengyihao 已提交
2330

dengyihao's avatar
dengyihao 已提交
2331
int transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
2332 2333 2334 2335 2336
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2337

dengyihao's avatar
dengyihao 已提交
2338
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
dengyihao's avatar
dengyihao 已提交
2339
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2340
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
2341
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2342
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
2343 2344
  }

dengyihao's avatar
dengyihao 已提交
2345
  TRACE_SET_MSGID(&pReq->info.traceId, tGenIdPI64());
wafwerar's avatar
wafwerar 已提交
2346
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2347
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
2348
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
2349
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
2350
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
2351

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

wafwerar's avatar
wafwerar 已提交
2354
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2355
  cliMsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
2356
  cliMsg->msg = *pReq;
dengyihao's avatar
dengyihao 已提交
2357
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2358
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
2359
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
2360

dengyihao's avatar
dengyihao 已提交
2361
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
2362 2363
  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 已提交
2364 2365
  if (0 != transAsyncSend(pThrd->asyncPool, &(cliMsg->q))) {
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2366
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2367 2368
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2369
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2370
  return 0;
dengyihao's avatar
dengyihao 已提交
2371
}
dengyihao's avatar
dengyihao 已提交
2372

dengyihao's avatar
dengyihao 已提交
2373
int transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMsg* pRsp) {
dengyihao's avatar
dengyihao 已提交
2374 2375 2376 2377 2378
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2379

dengyihao's avatar
dengyihao 已提交
2380 2381
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
2382
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
2383
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2384
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
2385
  }
dengyihao's avatar
dengyihao 已提交
2386

dengyihao's avatar
dengyihao 已提交
2387 2388
  tsem_t* sem = taosMemoryCalloc(1, sizeof(tsem_t));
  tsem_init(sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
2389

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

wafwerar's avatar
wafwerar 已提交
2392
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2393
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
2394
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
2395
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
2396
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
2397
  pCtx->pSem = sem;
dengyihao's avatar
dengyihao 已提交
2398 2399
  pCtx->pRsp = pRsp;

wafwerar's avatar
wafwerar 已提交
2400
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
2401 2402 2403
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pReq;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
2404
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
2405
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
2406

dengyihao's avatar
dengyihao 已提交
2407
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
2408 2409
  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 已提交
2410

dengyihao's avatar
dengyihao 已提交
2411 2412
  int ret = transAsyncSend(pThrd->asyncPool, &cliMsg->q);
  if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
2413
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2414
    goto _RETURN;
dengyihao's avatar
dengyihao 已提交
2415
  }
dengyihao's avatar
dengyihao 已提交
2416
  tsem_wait(sem);
dengyihao's avatar
dengyihao 已提交
2417 2418

_RETURN:
dengyihao's avatar
dengyihao 已提交
2419 2420
  tsem_destroy(sem);
  taosMemoryFree(sem);
dengyihao's avatar
dengyihao 已提交
2421
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2422
  return ret;
dengyihao's avatar
dengyihao 已提交
2423
}
dengyihao's avatar
dengyihao 已提交
2424 2425 2426
/*
 *
 **/
dengyihao's avatar
dengyihao 已提交
2427
int transSetDefaultAddr(void* shandle, const char* ip, const char* fqdn) {
dengyihao's avatar
dengyihao 已提交
2428
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2429 2430 2431
  if (pTransInst == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
2432 2433 2434

  SCvtAddr cvtAddr = {0};
  if (ip != NULL && fqdn != NULL) {
dengyihao's avatar
dengyihao 已提交
2435 2436
    tstrncpy(cvtAddr.ip, ip, sizeof(cvtAddr.ip));
    tstrncpy(cvtAddr.fqdn, fqdn, sizeof(cvtAddr.fqdn));
dengyihao's avatar
dengyihao 已提交
2437 2438
    cvtAddr.cvt = true;
  }
dengyihao's avatar
dengyihao 已提交
2439 2440
  for (int i = 0; i < pTransInst->numOfThreads; i++) {
    STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
2441
    pCtx->cvtAddr = cvtAddr;
dengyihao's avatar
dengyihao 已提交
2442 2443 2444 2445

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

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

dengyihao's avatar
dengyihao 已提交
2451 2452
    if (transAsyncSend(thrd->asyncPool, &(cliMsg->q)) != 0) {
      destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
2453
      transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2454 2455
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
2456
  }
dengyihao's avatar
dengyihao 已提交
2457
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
2458
  return 0;
dengyihao's avatar
dengyihao 已提交
2459
}
dengyihao's avatar
dengyihao 已提交
2460 2461 2462 2463 2464

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

dengyihao's avatar
dengyihao 已提交
2466 2467
  return exh->refId;
}