transCli.c 51.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 17
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef USE_UV
#include "transComm.h"

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

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

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

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

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

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
65
typedef struct SCliThrd {
dengyihao's avatar
dengyihao 已提交
66 67 68 69 70 71
  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 已提交
72

dengyihao's avatar
dengyihao 已提交
73 74
  SArray* timerList;

dengyihao's avatar
dengyihao 已提交
75
  // msg queue
dengyihao's avatar
dengyihao 已提交
76

dengyihao's avatar
dengyihao 已提交
77
  queue         msg;
wafwerar's avatar
wafwerar 已提交
78
  TdThreadMutex msgMtx;
dengyihao's avatar
dengyihao 已提交
79
  SDelayQueue*  delayQueue;
dengyihao's avatar
dengyihao 已提交
80
  SDelayQueue*  timeoutQueue;
dengyihao's avatar
dengyihao 已提交
81 82
  uint64_t      nextTimeout;  // next timeout
  void*         pTransInst;   //
dengyihao's avatar
dengyihao 已提交
83

dengyihao's avatar
dengyihao 已提交
84
  SCvtAddr cvtAddr;
dengyihao's avatar
dengyihao 已提交
85

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

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

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

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

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
140
// process data read from server, add decompress etc later
U
ubuntu 已提交
141
static void cliHandleResp(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
142
// handle except about conn
U
ubuntu 已提交
143
static void cliHandleExcept(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
144

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
190 191 192 193 194
#define CONN_HOST_THREAD_IDX1(idx, exh, refId, pThrd) \
  do {                                                \
    if (exh == NULL) {                                \
      idx = -1;                                       \
    } else {                                          \
dengyihao's avatar
dengyihao 已提交
195
      ASYNC_CHECK_HANDLE((exh), refId);               \
dengyihao's avatar
dengyihao 已提交
196
      pThrd = (SCliThrd*)(exh)->pThrd;                \
dengyihao's avatar
dengyihao 已提交
197 198
    }                                                 \
  } while (0)
dengyihao's avatar
dengyihao 已提交
199
#define CONN_PERSIST_TIME(para)    ((para) <= 90000 ? 90000 : (para))
dengyihao's avatar
dengyihao 已提交
200
#define CONN_GET_HOST_THREAD(conn) (conn ? ((SCliConn*)conn)->hostThrd : NULL)
dengyihao's avatar
dengyihao 已提交
201
#define CONN_GET_INST_LABEL(conn)  (((STrans*)(((SCliThrd*)(conn)->hostThrd)->pTransInst))->label)
dengyihao's avatar
dengyihao 已提交
202

dengyihao's avatar
dengyihao 已提交
203 204 205 206 207
#define CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle)                                         \
  do {                                                                                    \
    int i = 0, sz = transQueueSize(&conn->cliMsgs);                                       \
    for (; i < sz; i++) {                                                                 \
      pMsg = transQueueGet(&conn->cliMsgs, i);                                            \
S
Shengliang 已提交
208
      if (pMsg != NULL && pMsg->ctx != NULL && (uint64_t)pMsg->ctx->ahandle == ahandle) { \
dengyihao's avatar
dengyihao 已提交
209 210 211 212 213
        break;                                                                            \
      }                                                                                   \
    }                                                                                     \
    if (i == sz) {                                                                        \
      pMsg = NULL;                                                                        \
dengyihao's avatar
dengyihao 已提交
214
      tDebug("msg not found, %" PRIu64 "", ahandle);                                      \
dengyihao's avatar
dengyihao 已提交
215 216
    } else {                                                                              \
      pMsg = transQueueRm(&conn->cliMsgs, i);                                             \
dengyihao's avatar
dengyihao 已提交
217
      tDebug("msg found, %" PRIu64 "", ahandle);                                          \
dengyihao's avatar
dengyihao 已提交
218
    }                                                                                     \
dengyihao's avatar
dengyihao 已提交
219
  } while (0)
U
ubuntu 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232
#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 已提交
233

dengyihao's avatar
dengyihao 已提交
234 235 236 237 238
#define CONN_HANDLE_THREAD_QUIT(thrd) \
  do {                                \
    if (thrd->quit) {                 \
      return;                         \
    }                                 \
dengyihao's avatar
dengyihao 已提交
239 240 241 242 243
  } while (0)

#define CONN_HANDLE_BROKEN(conn) \
  do {                           \
    if (conn->broken) {          \
dengyihao's avatar
formate  
dengyihao 已提交
244
      cliHandleExcept(conn);     \
dengyihao's avatar
dengyihao 已提交
245
      return;                    \
dengyihao's avatar
dengyihao 已提交
246
    }                            \
dengyihao's avatar
dengyihao 已提交
247
  } while (0)
dengyihao's avatar
dengyihao 已提交
248

dengyihao's avatar
formate  
dengyihao 已提交
249 250
#define CONN_SET_PERSIST_BY_APP(conn) \
  do {                                \
dengyihao's avatar
dengyihao 已提交
251 252
    if (conn->status == ConnNormal) { \
      conn->status = ConnAcquire;     \
dengyihao's avatar
formate  
dengyihao 已提交
253 254 255
      transRefCliHandle(conn);        \
    }                                 \
  } while (0)
256

dengyihao's avatar
dengyihao 已提交
257 258 259 260
#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)
261

S
Shengliang Guan 已提交
262 263
#define REQUEST_NO_RESP(msg)         ((msg)->info.noResp == 1)
#define REQUEST_PERSIS_HANDLE(msg)   ((msg)->info.persistHandle == 1)
dengyihao's avatar
dengyihao 已提交
264
#define REQUEST_RELEASE_HANDLE(cmsg) ((cmsg)->type == Release)
dengyihao's avatar
dengyihao 已提交
265

dengyihao's avatar
dengyihao 已提交
266
#define EPSET_IS_VALID(epSet)       ((epSet) != NULL && (epSet)->numOfEps != 0)
dengyihao's avatar
dengyihao 已提交
267
#define EPSET_GET_SIZE(epSet)       (epSet)->numOfEps
dengyihao's avatar
dengyihao 已提交
268
#define EPSET_GET_INUSE_IP(epSet)   ((epSet)->eps[(epSet)->inUse].fqdn)
dengyihao's avatar
dengyihao 已提交
269
#define EPSET_GET_INUSE_PORT(epSet) ((epSet)->eps[(epSet)->inUse].port)
dengyihao's avatar
dengyihao 已提交
270 271 272 273 274
#define EPSET_FORWARD_INUSE(epSet)                                 \
  do {                                                             \
    if ((epSet)->numOfEps != 0) {                                  \
      (epSet)->inUse = (++((epSet)->inUse)) % ((epSet)->numOfEps); \
    }                                                              \
dengyihao's avatar
dengyihao 已提交
275
  } while (0)
dengyihao's avatar
dengyihao 已提交
276

dengyihao's avatar
dengyihao 已提交
277 278 279 280 281 282 283 284 285 286 287
#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 已提交
288
  } while (0);
dengyihao's avatar
dengyihao 已提交
289

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

dengyihao's avatar
dengyihao 已提交
292
bool cliMaySendCachedMsg(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
293
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
294
    SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
295
    CONN_GET_NEXT_SENDMSG(conn);
dengyihao's avatar
dengyihao 已提交
296 297
    cliSend(conn);
  }
dengyihao's avatar
dengyihao 已提交
298
  return false;
U
ubuntu 已提交
299 300
_RETURN:
  return false;
dengyihao's avatar
dengyihao 已提交
301
}
dengyihao's avatar
formate  
dengyihao 已提交
302
void cliHandleResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
303 304
  SCliThrd* pThrd = conn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
305

dengyihao's avatar
dengyihao 已提交
306 307 308 309 310 311
  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 已提交
312
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
313
    conn->timer = NULL;
dengyihao's avatar
dengyihao 已提交
314 315
  }

dengyihao's avatar
opt rpc  
dengyihao 已提交
316
  STransMsgHead* pHead = NULL;
dengyihao's avatar
dengyihao 已提交
317 318 319 320
  if (transDumpFromBuffer(&conn->readBuf, (char**)&pHead) <= 0) {
    tDebug("%s conn %p recv invalid packet ", CONN_GET_INST_LABEL(conn), conn);
    return;
  }
dengyihao's avatar
dengyihao 已提交
321 322
  pHead->code = htonl(pHead->code);
  pHead->msgLen = htonl(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
323

dengyihao's avatar
dengyihao 已提交
324 325 326 327
  if (cliRecvReleaseReq(conn, pHead)) {
    return;
  }

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

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

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

dengyihao's avatar
dengyihao 已提交
370
  STraceId* trace = &transMsg.info.traceId;
dengyihao's avatar
dengyihao 已提交
371
  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 已提交
372
          TMSG_INFO(pHead->msgType), conn->dst, conn->src, transMsg.contLen, tstrerror(transMsg.code));
dengyihao's avatar
dengyihao 已提交
373

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

dengyihao's avatar
dengyihao 已提交
383
  if (cliAppCb(conn, &transMsg, pMsg) != 0) {
dengyihao's avatar
dengyihao 已提交
384
    return;
dengyihao's avatar
dengyihao 已提交
385
  }
dengyihao's avatar
dengyihao 已提交
386 387
  destroyCmsg(pMsg);

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

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

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

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

dengyihao's avatar
dengyihao 已提交
417
    STransMsg transMsg = {0};
dengyihao's avatar
dengyihao 已提交
418
    transMsg.code = code == -1 ? (pConn->broken ? TSDB_CODE_RPC_BROKEN_LINK : TSDB_CODE_RPC_NETWORK_UNAVAIL) : code;
dengyihao's avatar
dengyihao 已提交
419
    transMsg.msgType = pMsg ? pMsg->msg.msgType + 1 : 0;
S
Shengliang Guan 已提交
420
    transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
421

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

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

dengyihao's avatar
dengyihao 已提交
454 455 456 457
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 已提交
458
  uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
459 460
  cliHandleExceptImpl(conn, TSDB_CODE_RPC_TIMEOUT);
}
U
ubuntu 已提交
461 462

void* createConnPool(int size) {
463 464
  // thread local, no lock
  return taosHashInit(size, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
465
}
U
ubuntu 已提交
466
void* destroyConnPool(void* pool) {
dengyihao's avatar
dengyihao 已提交
467
  SConnList* connList = taosHashIterate((SHashObj*)pool, NULL);
dengyihao's avatar
dengyihao 已提交
468
  while (connList != NULL) {
dengyihao's avatar
dengyihao 已提交
469 470
    while (!QUEUE_IS_EMPTY(&connList->conns)) {
      queue*    h = QUEUE_HEAD(&connList->conns);
dengyihao's avatar
dengyihao 已提交
471
      SCliConn* c = QUEUE_DATA(h, SCliConn, q);
U
ubuntu 已提交
472
      cliDestroyConn(c, true);
dengyihao's avatar
dengyihao 已提交
473
    }
dengyihao's avatar
dengyihao 已提交
474
    connList = taosHashIterate((SHashObj*)pool, connList);
dengyihao's avatar
dengyihao 已提交
475
  }
dengyihao's avatar
dengyihao 已提交
476
  taosHashCleanup(pool);
477
  return NULL;
dengyihao's avatar
dengyihao 已提交
478 479
}

dengyihao's avatar
dengyihao 已提交
480
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port) {
dengyihao's avatar
dengyihao 已提交
481
  char key[32] = {0};
dengyihao's avatar
dengyihao 已提交
482
  CONN_CONSTRUCT_HASH_KEY(key, ip, port);
dengyihao's avatar
dengyihao 已提交
483 484

  SConnList* plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
485
  if (plist == NULL) {
dengyihao's avatar
dengyihao 已提交
486
    SConnList list = {0};
dengyihao's avatar
dengyihao 已提交
487 488 489
    taosHashPut((SHashObj*)pool, key, strlen(key), (void*)&list, sizeof(list));
    plist = taosHashGet((SHashObj*)pool, key, strlen(key));
    QUEUE_INIT(&plist->conns);
dengyihao's avatar
dengyihao 已提交
490 491
  }

dengyihao's avatar
dengyihao 已提交
492
  if (QUEUE_IS_EMPTY(&plist->conns)) {
dengyihao's avatar
dengyihao 已提交
493 494
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
495 496

  plist->size -= 1;
dengyihao's avatar
dengyihao 已提交
497
  queue*    h = QUEUE_HEAD(&plist->conns);
dengyihao's avatar
dengyihao 已提交
498
  SCliConn* conn = QUEUE_DATA(h, SCliConn, q);
dengyihao's avatar
dengyihao 已提交
499
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
500 501
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
502

dengyihao's avatar
dengyihao 已提交
503 504 505 506
  if (conn->task != NULL) {
    transDQCancel(((SCliThrd*)conn->hostThrd)->timeoutQueue, conn->task);
    conn->task = NULL;
  }
dengyihao's avatar
dengyihao 已提交
507
  return conn;
dengyihao's avatar
dengyihao 已提交
508
}
dengyihao's avatar
dengyihao 已提交
509 510 511 512 513 514
static void addConnToPool(void* pool, SCliConn* conn) {
  if (conn->status == ConnInPool) {
    return;
  }
  allocConnRef(conn, true);

dengyihao's avatar
dengyihao 已提交
515
  SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
516 517 518 519 520 521
  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 已提交
522 523 524 525 526
  if (T_REF_VAL_GET(conn) > 1) {
    transUnrefCliHandle(conn);
  }

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

dengyihao's avatar
dengyihao 已提交
528 529 530 531 532 533 534
  conn->status = ConnInPool;

  if (conn->list == NULL) {
    char key[32] = {0};
    CONN_CONSTRUCT_HASH_KEY(key, conn->ip, conn->port);
    tTrace("%s conn %p added to conn pool, read buf cap:%d", CONN_GET_INST_LABEL(conn), conn, conn->readBuf.cap);
    conn->list = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
535 536
  } 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 已提交
537
  }
dengyihao's avatar
dengyihao 已提交
538
  QUEUE_PUSH(&conn->list->conns, &conn->q);
dengyihao's avatar
dengyihao 已提交
539
  conn->list->size += 1;
dengyihao's avatar
dengyihao 已提交
540

dengyihao's avatar
dengyihao 已提交
541
  if (conn->list->size >= 50) {
dengyihao's avatar
dengyihao 已提交
542 543 544
    STaskArg* arg = taosMemoryCalloc(1, sizeof(STaskArg));
    arg->param1 = conn;
    arg->param2 = thrd;
dengyihao's avatar
dengyihao 已提交
545 546

    STrans* pTransInst = thrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
547 548
    conn->task = transDQSched(thrd->timeoutQueue, doCloseIdleConn, arg, CONN_PERSIST_TIME(pTransInst->idleTime));
  }
dengyihao's avatar
dengyihao 已提交
549
}
dengyihao's avatar
dengyihao 已提交
550
static int32_t allocConnRef(SCliConn* conn, bool update) {
dengyihao's avatar
dengyihao 已提交
551
  if (update) {
dengyihao's avatar
dengyihao 已提交
552
    transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
dengyihao 已提交
553
    conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
554 555 556 557
  }
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
558
  exh->refId = transAddExHandle(transGetRefMgt(), exh);
dengyihao's avatar
dengyihao 已提交
559
  conn->refId = exh->refId;
dengyihao's avatar
dengyihao 已提交
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
  return 0;
}

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

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

dengyihao's avatar
dengyihao 已提交
580
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
581
  SCliConn*    conn = handle->data;
dengyihao's avatar
dengyihao 已提交
582
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
583
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
584
}
U
ubuntu 已提交
585
static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
586
  // impl later
dengyihao's avatar
dengyihao 已提交
587 588 589
  if (handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
590 591
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
592
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
593
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
594
    while (transReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
595
      tTrace("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
596 597 598 599 600 601
      if (pBuf->invalid) {
        cliHandleExcept(conn);
        break;
      } else {
        cliHandleResp(conn);
      }
dengyihao's avatar
dengyihao 已提交
602
    }
dengyihao's avatar
dengyihao 已提交
603 604
    return;
  }
dengyihao's avatar
dengyihao 已提交
605

606 607
  assert(nread <= 0);
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
608 609 610
    // 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 已提交
611
    tTrace("%s conn %p read empty", CONN_GET_INST_LABEL(conn), conn);
612 613
    return;
  }
dengyihao's avatar
fix bug  
dengyihao 已提交
614
  if (nread < 0) {
dengyihao's avatar
dengyihao 已提交
615
    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 已提交
616
    conn->broken = true;
U
ubuntu 已提交
617
    cliHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
618
  }
dengyihao's avatar
dengyihao 已提交
619
}
dengyihao's avatar
dengyihao 已提交
620

dengyihao's avatar
dengyihao 已提交
621
static SCliConn* cliCreateConn(SCliThrd* pThrd) {
wafwerar's avatar
wafwerar 已提交
622
  SCliConn* conn = taosMemoryCalloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
623
  // read/write stream handle
wafwerar's avatar
wafwerar 已提交
624
  conn->stream = (uv_stream_t*)taosMemoryMalloc(sizeof(uv_tcp_t));
dengyihao's avatar
dengyihao 已提交
625 626 627 628
  uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
  conn->stream->data = conn;

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

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

dengyihao's avatar
dengyihao 已提交
632
  transQueueInit(&conn->cliMsgs, NULL);
dengyihao's avatar
opt rpc  
dengyihao 已提交
633 634

  transInitBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
635
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
636
  conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
637 638
  conn->status = ConnNormal;
  conn->broken = 0;
dengyihao's avatar
dengyihao 已提交
639
  transRefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
640

dengyihao's avatar
dengyihao 已提交
641
  allocConnRef(conn, false);
dengyihao's avatar
dengyihao 已提交
642

dengyihao's avatar
dengyihao 已提交
643 644
  return conn;
}
U
ubuntu 已提交
645
static void cliDestroyConn(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
646
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
647
  tTrace("%s conn %p remove from conn pool", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
648 649
  QUEUE_REMOVE(&conn->q);
  QUEUE_INIT(&conn->q);
dengyihao's avatar
dengyihao 已提交
650
  transRemoveExHandle(transGetRefMgt(), conn->refId);
dengyihao's avatar
opt rpc  
dengyihao 已提交
651
  conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
652

dengyihao's avatar
dengyihao 已提交
653 654 655 656 657 658 659 660 661 662
  if (conn->task != NULL) {
    transDQCancel(pThrd->timeoutQueue, conn->task);
    conn->task = NULL;
  }
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
    taosArrayPush(pThrd->timerList, &conn->timer);
    conn->timer->data = NULL;
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
663

dengyihao's avatar
dengyihao 已提交
664
  if (clear) {
dengyihao's avatar
dengyihao 已提交
665
    if (!uv_is_closing((uv_handle_t*)conn->stream)) {
dengyihao's avatar
dengyihao 已提交
666
      uv_read_stop(conn->stream);
dengyihao's avatar
dengyihao 已提交
667 668
      uv_close((uv_handle_t*)conn->stream, cliDestroy);
    }
669
  }
dengyihao's avatar
dengyihao 已提交
670
}
U
ubuntu 已提交
671
static void cliDestroy(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
672 673 674
  if (uv_handle_get_type(handle) != UV_TCP || handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
675
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
676
  SCliThrd* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
677 678
  if (conn->timer != NULL) {
    uv_timer_stop(conn->timer);
dengyihao's avatar
dengyihao 已提交
679 680
    taosArrayPush(pThrd->timerList, &conn->timer);
    conn->timer->data = NULL;
dengyihao's avatar
dengyihao 已提交
681 682
    conn->timer = NULL;
  }
dengyihao's avatar
dengyihao 已提交
683

dengyihao's avatar
dengyihao 已提交
684
  transRemoveExHandle(transGetRefMgt(), conn->refId);
wafwerar's avatar
wafwerar 已提交
685 686
  taosMemoryFree(conn->ip);
  taosMemoryFree(conn->stream);
dengyihao's avatar
dengyihao 已提交
687 688 689

  cliDestroyConnMsgs(conn, true);

dengyihao's avatar
dengyihao 已提交
690
  tTrace("%s conn %p destroy successfully", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
691
  transReqQueueClear(&conn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
692
  transDestroyBuffer(&conn->readBuf);
wafwerar's avatar
wafwerar 已提交
693
  taosMemoryFree(conn);
dengyihao's avatar
dengyihao 已提交
694
}
dengyihao's avatar
dengyihao 已提交
695
static bool cliHandleNoResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
696 697
  bool res = false;
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
698
    SCliMsg* pMsg = transQueueGet(&conn->cliMsgs, 0);
dengyihao's avatar
dengyihao 已提交
699
    if (REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
700
      transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
701 702 703 704 705
      destroyCmsg(pMsg);
      res = true;
    }
    if (res == true) {
      if (cliMaySendCachedMsg(conn) == false) {
dengyihao's avatar
dengyihao 已提交
706
        SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
707
        addConnToPool(thrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
708 709 710 711 712
      }
    }
  }
  return res;
}
U
ubuntu 已提交
713
static void cliSendCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
714 715
  SCliConn* pConn = transReqQueueRemove(req);
  if (pConn == NULL) return;
dengyihao's avatar
dengyihao 已提交
716

dengyihao's avatar
dengyihao 已提交
717
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
718
    tTrace("%s conn %p data already was written out", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
719
  } else {
S
Shengliang Guan 已提交
720
    tError("%s conn %p failed to write:%s", CONN_GET_INST_LABEL(pConn), pConn, uv_err_name(status));
U
ubuntu 已提交
721
    cliHandleExcept(pConn);
dengyihao's avatar
dengyihao 已提交
722 723
    return;
  }
dengyihao's avatar
dengyihao 已提交
724
  if (cliHandleNoResp(pConn) == true) {
dengyihao's avatar
dengyihao 已提交
725
    tTrace("%s conn %p no resp required", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
726 727
    return;
  }
dengyihao's avatar
dengyihao 已提交
728
  uv_read_start((uv_stream_t*)pConn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
729
}
dengyihao's avatar
dengyihao 已提交
730

U
ubuntu 已提交
731
void cliSend(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
732
  assert(!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
733 734

  SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
735
  CONN_GET_NEXT_SENDMSG(pConn);
dengyihao's avatar
dengyihao 已提交
736 737
  pCliMsg->sent = 1;

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

dengyihao's avatar
dengyihao 已提交
740 741
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
742

U
ubuntu 已提交
743
  STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
dengyihao's avatar
dengyihao 已提交
744 745 746 747
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
dengyihao's avatar
dengyihao 已提交
748

dengyihao's avatar
dengyihao 已提交
749
  int            msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
750 751
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
  pHead->ahandle = pCtx != NULL ? (uint64_t)pCtx->ahandle : 0;
dengyihao's avatar
dengyihao 已提交
752 753
  pHead->noResp = REQUEST_NO_RESP(pMsg) ? 1 : 0;
  pHead->persist = REQUEST_PERSIS_HANDLE(pMsg) ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
754 755
  pHead->msgType = pMsg->msgType;
  pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);
dengyihao's avatar
dengyihao 已提交
756
  pHead->release = REQUEST_RELEASE_HANDLE(pCliMsg) ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
757
  memcpy(pHead->user, pTransInst->user, strlen(pTransInst->user));
dengyihao's avatar
dengyihao 已提交
758
  pHead->traceId = pMsg->info.traceId;
dengyihao's avatar
dengyihao 已提交
759
  pHead->magicNum = htonl(TRANS_MAGIC_NUM);
dengyihao's avatar
dengyihao 已提交
760

dengyihao's avatar
dengyihao 已提交
761
  STraceId* trace = &pMsg->info.traceId;
dengyihao's avatar
dengyihao 已提交
762
  tGDebug("%s conn %p %s is sent to %s, local info %s, len:%d", CONN_GET_INST_LABEL(pConn), pConn,
dengyihao's avatar
dengyihao 已提交
763
          TMSG_INFO(pHead->msgType), pConn->dst, pConn->src, pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
764

dengyihao's avatar
dengyihao 已提交
765 766 767
  if (pHead->persist == 1) {
    CONN_SET_PERSIST_BY_APP(pConn);
  }
dengyihao's avatar
dengyihao 已提交
768

dengyihao's avatar
dengyihao 已提交
769
  if (pTransInst->startTimer != NULL && pTransInst->startTimer(0, pMsg->msgType)) {
dengyihao's avatar
dengyihao 已提交
770
    uv_timer_t* timer = taosArrayGetSize(pThrd->timerList) > 0 ? *(uv_timer_t**)taosArrayPop(pThrd->timerList) : NULL;
dengyihao's avatar
dengyihao 已提交
771 772 773 774 775 776 777 778
    if (timer == NULL) {
      tDebug("no avaiable timer, create");
      timer = taosMemoryCalloc(1, sizeof(uv_timer_t));
      uv_timer_init(pThrd->loop, timer);
    }
    timer->data = pConn;
    pConn->timer = timer;

dengyihao's avatar
dengyihao 已提交
779 780 781
    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 已提交
782 783

  uv_buf_t    wb = uv_buf_init((char*)pHead, msgLen);
dengyihao's avatar
dengyihao 已提交
784
  uv_write_t* req = transReqQueuePush(&pConn->wreqQueue);
dengyihao's avatar
dengyihao 已提交
785
  uv_write(req, (uv_stream_t*)pConn->stream, &wb, 1, cliSendCb);
U
ubuntu 已提交
786 787
  return;
_RETURN:
dengyihao's avatar
dengyihao 已提交
788
  return;
dengyihao's avatar
dengyihao 已提交
789
}
U
ubuntu 已提交
790 791

void cliConnCb(uv_connect_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
792
  // impl later
dengyihao's avatar
dengyihao 已提交
793 794
  SCliConn* pConn = req->data;
  if (status != 0) {
S
Shengliang Guan 已提交
795
    tError("%s conn %p failed to connect server:%s", CONN_GET_INST_LABEL(pConn), pConn, uv_strerror(status));
U
ubuntu 已提交
796
    cliHandleExcept(pConn);
797
    return;
dengyihao's avatar
dengyihao 已提交
798
  }
dengyihao's avatar
dengyihao 已提交
799 800
  struct sockaddr peername, sockname;

dengyihao's avatar
dengyihao 已提交
801
  int addrlen = sizeof(peername);
dengyihao's avatar
dengyihao 已提交
802
  uv_tcp_getpeername((uv_tcp_t*)pConn->stream, &peername, &addrlen);
dengyihao's avatar
dengyihao 已提交
803
  transSockInfo2Str(&peername, pConn->dst);
dengyihao's avatar
dengyihao 已提交
804

dengyihao's avatar
dengyihao 已提交
805 806
  addrlen = sizeof(sockname);
  uv_tcp_getsockname((uv_tcp_t*)pConn->stream, &sockname, &addrlen);
dengyihao's avatar
dengyihao 已提交
807
  transSockInfo2Str(&sockname, pConn->src);
dengyihao's avatar
dengyihao 已提交
808

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

U
ubuntu 已提交
812
  cliSend(pConn);
dengyihao's avatar
dengyihao 已提交
813 814
}

dengyihao's avatar
dengyihao 已提交
815
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
816 817 818 819 820
  if (!transAsyncPoolIsEmpty(pThrd->asyncPool)) {
    pThrd->stopMsg = pMsg;
    return;
  }
  pThrd->stopMsg = NULL;
dengyihao's avatar
dengyihao 已提交
821
  pThrd->quit = true;
U
ubuntu 已提交
822
  tDebug("cli work thread %p start to quit", pThrd);
dengyihao's avatar
dengyihao 已提交
823
  destroyCmsg(pMsg);
dengyihao's avatar
fix bug  
dengyihao 已提交
824
  destroyConnPool(pThrd->pool);
dengyihao's avatar
dengyihao 已提交
825
  uv_walk(pThrd->loop, cliWalkCb, NULL);
dengyihao's avatar
dengyihao 已提交
826
}
dengyihao's avatar
dengyihao 已提交
827
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
828
  int64_t    refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
829
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
830
  if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
831
    tDebug("%" PRId64 " already released", refId);
dengyihao's avatar
dengyihao 已提交
832 833
    destroyCmsg(pMsg);
    return;
dengyihao's avatar
dengyihao 已提交
834 835 836
  }

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

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

dengyihao's avatar
dengyihao 已提交
841 842
  if (T_REF_VAL_GET(conn) == 2) {
    transUnrefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
843 844
    if (!transQueuePush(&conn->cliMsgs, pMsg)) {
      return;
dengyihao's avatar
dengyihao 已提交
845 846
    }
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
847 848 849
  } else {
    tError("%s conn %p already released", CONN_GET_INST_LABEL(conn), conn);
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
850 851
  }
}
dengyihao's avatar
dengyihao 已提交
852
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
853
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
854
  pThrd->cvtAddr = pCtx->cvtAddr;
dengyihao's avatar
dengyihao 已提交
855 856
  destroyCmsg(pMsg);
}
U
ubuntu 已提交
857

dengyihao's avatar
dengyihao 已提交
858
SCliConn* cliGetConn(SCliMsg* pMsg, SCliThrd* pThrd, bool* ignore) {
dengyihao's avatar
dengyihao 已提交
859 860 861 862
  STransConnCtx* pCtx = pMsg->ctx;
  SCliConn*      conn = NULL;

  int64_t refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
863
  if (refId != 0) {
dengyihao's avatar
dengyihao 已提交
864
    SExHandle* exh = transAcquireExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
865
    if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
866
      tError("failed to get conn, refId: %" PRId64 "", refId);
dengyihao's avatar
dengyihao 已提交
867 868
      *ignore = true;
      return NULL;
dengyihao's avatar
dengyihao 已提交
869 870
    } else {
      conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
871 872
      if (conn == NULL) {
        conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
dengyihao's avatar
dengyihao 已提交
873
        if (conn != NULL) specifyConnRef(conn, true, refId);
dengyihao's avatar
dengyihao 已提交
874
      }
dengyihao's avatar
dengyihao 已提交
875
      transReleaseExHandle(transGetRefMgt(), refId);
dengyihao's avatar
dengyihao 已提交
876 877 878
    }
    return conn;
  };
dengyihao's avatar
dengyihao 已提交
879 880 881

  conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
882
    tTrace("%s conn %p get from conn pool:%p", CONN_GET_INST_LABEL(conn), conn, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
883
  } else {
dengyihao's avatar
dengyihao 已提交
884
    tTrace("%s not found conn in conn pool:%p", ((STrans*)pThrd->pTransInst)->label, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
885
  }
dengyihao's avatar
dengyihao 已提交
886 887
  return conn;
}
dengyihao's avatar
dengyihao 已提交
888 889 890 891 892 893 894 895 896 897 898
void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr) {
  if (pCvtAddr->cvt == false) {
    return;
  }
  for (int i = 0; i < pEpSet->numOfEps && pEpSet->numOfEps == 1; i++) {
    if (strncmp(pEpSet->eps[i].fqdn, pCvtAddr->fqdn, TSDB_FQDN_LEN) == 0) {
      memset(pEpSet->eps[i].fqdn, 0, TSDB_FQDN_LEN);
      memcpy(pEpSet->eps[i].fqdn, pCvtAddr->ip, TSDB_FQDN_LEN);
    }
  }
}
dengyihao's avatar
dengyihao 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

bool cliIsEpsetUpdated(int32_t code, STransConnCtx* pCtx) {
  if (code != 0) return false;
  if (pCtx->retryCnt == 0) return false;
  if (transEpSetIsEqual(&pCtx->epSet, &pCtx->origEpSet)) return false;
  return true;
}

int32_t cliBuildExceptResp(SCliMsg* pMsg, STransMsg* pResp) {
  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 已提交
920
void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
formate  
dengyihao 已提交
921
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
922
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
923

dengyihao's avatar
dengyihao 已提交
924
  cliMayCvtFqdnToIp(&pCtx->epSet, &pThrd->cvtAddr);
dengyihao's avatar
dengyihao 已提交
925 926 927 928 929
  if (!EPSET_IS_VALID(&pCtx->epSet)) {
    destroyCmsg(pMsg);
    tError("invalid epset");
    return;
  }
dengyihao's avatar
dengyihao 已提交
930

dengyihao's avatar
dengyihao 已提交
931 932 933
  bool      ignore = false;
  SCliConn* conn = cliGetConn(pMsg, pThrd, &ignore);
  if (ignore == true) {
dengyihao's avatar
dengyihao 已提交
934
    // persist conn already release by server
dengyihao's avatar
dengyihao 已提交
935 936
    STransMsg resp;
    cliBuildExceptResp(pMsg, &resp);
dengyihao's avatar
dengyihao 已提交
937 938
    pTransInst->cfp(pTransInst->parent, &resp, NULL);
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
939 940
    return;
  }
dengyihao's avatar
dengyihao 已提交
941

dengyihao's avatar
dengyihao 已提交
942
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
943
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
944
    transQueuePush(&conn->cliMsgs, pMsg);
U
ubuntu 已提交
945
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
946
  } else {
U
ubuntu 已提交
947
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
948 949 950 951

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

dengyihao's avatar
dengyihao 已提交
952
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
953
    transQueuePush(&conn->cliMsgs, pMsg);
dengyihao's avatar
dengyihao 已提交
954

dengyihao's avatar
dengyihao 已提交
955 956
    conn->ip = strdup(EPSET_GET_INUSE_IP(&pCtx->epSet));
    conn->port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
957

dengyihao's avatar
dengyihao 已提交
958 959
    int ret = transSetConnOption((uv_tcp_t*)conn->stream);
    if (ret) {
dengyihao's avatar
dengyihao 已提交
960
      tError("%s conn %p failed to set conn option, errmsg %s", transLabel(pTransInst), conn, uv_err_name(ret));
dengyihao's avatar
dengyihao 已提交
961
    }
dengyihao's avatar
dengyihao 已提交
962
    int32_t fd = taosCreateSocketWithTimeout(TRANS_CONN_TIMEOUT);
dengyihao's avatar
dengyihao 已提交
963
    if (fd == -1) {
dengyihao's avatar
dengyihao 已提交
964
      tTrace("%s conn %p failed to create socket", transLabel(pTransInst), conn);
dengyihao's avatar
dengyihao 已提交
965 966 967 968
      cliHandleExcept(conn);
      return;
    }
    uv_tcp_open((uv_tcp_t*)conn->stream, fd);
969

dengyihao's avatar
dengyihao 已提交
970
    struct sockaddr_in addr;
971 972 973
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = taosGetIpv4FromFqdn(conn->ip);
    addr.sin_port = (uint16_t)htons((uint16_t)conn->port);
dengyihao's avatar
dengyihao 已提交
974
    tTrace("%s conn %p try to connect to %s:%d", pTransInst->label, conn, conn->ip, conn->port);
dengyihao's avatar
dengyihao 已提交
975 976
    ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
    if (ret != 0) {
S
Shengliang Guan 已提交
977
      tTrace("%s conn %p failed to connect to %s:%d, reason:%s", pTransInst->label, conn, conn->ip, conn->port,
dengyihao's avatar
dengyihao 已提交
978 979 980 981
             uv_err_name(ret));
      cliHandleExcept(conn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
982 983
  }
}
U
ubuntu 已提交
984
static void cliAsyncCb(uv_async_t* handle) {
dengyihao's avatar
dengyihao 已提交
985 986 987
  SAsyncItem* item = handle->data;
  SCliThrd*   pThrd = item->pThrd;
  SCliMsg*    pMsg = NULL;
dengyihao's avatar
dengyihao 已提交
988

dengyihao's avatar
dengyihao 已提交
989
  // batch process to avoid to lock/unlock frequently
dengyihao's avatar
formate  
dengyihao 已提交
990
  queue wq;
wafwerar's avatar
wafwerar 已提交
991
  taosThreadMutexLock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
992
  QUEUE_MOVE(&item->qmsg, &wq);
wafwerar's avatar
wafwerar 已提交
993
  taosThreadMutexUnlock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
994

dengyihao's avatar
dengyihao 已提交
995 996 997 998
  int count = 0;
  while (!QUEUE_IS_EMPTY(&wq)) {
    queue* h = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
999 1000

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
1001
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1002
    count++;
dengyihao's avatar
dengyihao 已提交
1003 1004
  }
  if (count >= 2) {
S
Shengliang Guan 已提交
1005
    tTrace("cli process batch size:%d", count);
dengyihao's avatar
dengyihao 已提交
1006
  }
dengyihao's avatar
dengyihao 已提交
1007
  // if (!uv_is_active((uv_handle_t*)pThrd->prepare)) uv_prepare_start(pThrd->prepare, cliPrepareCb);
dengyihao's avatar
dengyihao 已提交
1008

dengyihao's avatar
dengyihao 已提交
1009
  if (pThrd->stopMsg != NULL) cliHandleQuit(pThrd->stopMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1010
}
dengyihao's avatar
dengyihao 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
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);
      if (pMsg == NULL) {
        continue;
      }
      (*cliAsyncHandle[pMsg->type])(pMsg, thrd);
      count++;
    }
  }
  tTrace("prepare work end");
  if (thrd->stopMsg != NULL) cliHandleQuit(thrd->stopMsg, thrd);
dengyihao's avatar
dengyihao 已提交
1040
}
dengyihao's avatar
dengyihao 已提交
1041

dengyihao's avatar
dengyihao 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
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 已提交
1071 1072 1073
bool cliRecvReleaseReq(SCliConn* conn, STransMsgHead* pHead) {
  if (pHead->release == 1 && (pHead->msgLen) == sizeof(*pHead)) {
    uint64_t ahandle = pHead->ahandle;
dengyihao's avatar
dengyihao 已提交
1074
    tDebug("ahandle = %" PRIu64 "", ahandle);
dengyihao's avatar
dengyihao 已提交
1075 1076
    SCliMsg* pMsg = NULL;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
dengyihao's avatar
dengyihao 已提交
1077

dengyihao's avatar
dengyihao 已提交
1078 1079
    transClearBuffer(&conn->readBuf);
    transFreeMsg(transContFromHead((char*)pHead));
dengyihao's avatar
dengyihao 已提交
1080 1081 1082 1083 1084 1085 1086

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

    cliIteraConnMsgs(conn);

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

dengyihao's avatar
dengyihao 已提交
1094 1095 1096 1097 1098 1099
    addConnToPool(((SCliThrd*)conn->hostThrd)->pool, conn);
    return true;
  }
  return false;
}

U
ubuntu 已提交
1100
static void* cliWorkThread(void* arg) {
dengyihao's avatar
dengyihao 已提交
1101
  SCliThrd* pThrd = (SCliThrd*)arg;
dengyihao's avatar
dengyihao 已提交
1102
  pThrd->pid = taosGetSelfPthreadId();
U
ubuntu 已提交
1103
  setThreadName("trans-cli-work");
dengyihao's avatar
dengyihao 已提交
1104
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
1105
  return NULL;
dengyihao's avatar
dengyihao 已提交
1106 1107
}

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

dengyihao's avatar
dengyihao 已提交
1111
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
1112 1113
  memcpy(cli->label, label, strlen(label));
  cli->numOfThreads = numOfThreads;
dengyihao's avatar
dengyihao 已提交
1114
  cli->pThreadObj = (SCliThrd**)taosMemoryCalloc(cli->numOfThreads, sizeof(SCliThrd*));
dengyihao's avatar
dengyihao 已提交
1115 1116

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

wafwerar's avatar
wafwerar 已提交
1121
    int err = taosThreadCreate(&pThrd->thread, NULL, cliWorkThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
1122
    if (err == 0) {
S
Shengliang Guan 已提交
1123
      tDebug("success to create tranport-cli thread:%d", i);
dengyihao's avatar
dengyihao 已提交
1124
    }
dengyihao's avatar
dengyihao 已提交
1125
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
1126
  }
dengyihao's avatar
dengyihao 已提交
1127

dengyihao's avatar
dengyihao 已提交
1128 1129
  return cli;
}
dengyihao's avatar
dengyihao 已提交
1130

U
ubuntu 已提交
1131
static void destroyUserdata(STransMsg* userdata) {
dengyihao's avatar
dengyihao 已提交
1132 1133 1134 1135 1136 1137
  if (userdata->pCont == NULL) {
    return;
  }
  transFreeMsg(userdata->pCont);
  userdata->pCont = NULL;
}
dengyihao's avatar
dengyihao 已提交
1138 1139
static void destroyCmsg(void* arg) {
  SCliMsg* pMsg = arg;
dengyihao's avatar
dengyihao 已提交
1140 1141 1142 1143 1144
  if (pMsg == NULL) {
    return;
  }
  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
wafwerar's avatar
wafwerar 已提交
1145
  taosMemoryFree(pMsg);
dengyihao's avatar
dengyihao 已提交
1146
}
dengyihao's avatar
dengyihao 已提交
1147

dengyihao's avatar
dengyihao 已提交
1148 1149
static SCliThrd* createThrdObj() {
  SCliThrd* pThrd = (SCliThrd*)taosMemoryCalloc(1, sizeof(SCliThrd));
U
ubuntu 已提交
1150

dengyihao's avatar
dengyihao 已提交
1151
  QUEUE_INIT(&pThrd->msg);
wafwerar's avatar
wafwerar 已提交
1152
  taosThreadMutexInit(&pThrd->msgMtx, NULL);
dengyihao's avatar
dengyihao 已提交
1153

wafwerar's avatar
wafwerar 已提交
1154
  pThrd->loop = (uv_loop_t*)taosMemoryMalloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
1155 1156
  uv_loop_init(pThrd->loop);

dengyihao's avatar
dengyihao 已提交
1157
  pThrd->asyncPool = transAsyncPoolCreate(pThrd->loop, 5, pThrd, cliAsyncCb);
dengyihao's avatar
dengyihao 已提交
1158 1159 1160 1161

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

dengyihao's avatar
dengyihao 已提交
1164 1165 1166 1167 1168 1169 1170 1171
  int32_t timerSize = 512;
  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 已提交
1172
  pThrd->pool = createConnPool(4);
dengyihao's avatar
dengyihao 已提交
1173
  transDQCreate(pThrd->loop, &pThrd->delayQueue);
dengyihao's avatar
dengyihao 已提交
1174

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

dengyihao's avatar
dengyihao 已提交
1177
  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
1178 1179
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1180
static void destroyThrdObj(SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
1181 1182 1183
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
1184

wafwerar's avatar
wafwerar 已提交
1185
  taosThreadJoin(pThrd->thread, NULL);
dengyihao's avatar
dengyihao 已提交
1186
  CLI_RELEASE_UV(pThrd->loop);
wafwerar's avatar
wafwerar 已提交
1187
  taosThreadMutexDestroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
1188
  TRANS_DESTROY_ASYNC_POOL_MSG(pThrd->asyncPool, SCliMsg, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1189
  transAsyncPoolDestroy(pThrd->asyncPool);
dengyihao's avatar
dengyihao 已提交
1190

dengyihao's avatar
dengyihao 已提交
1191
  transDQDestroy(pThrd->delayQueue, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
1192
  transDQDestroy(pThrd->timeoutQueue, NULL);
dengyihao's avatar
dengyihao 已提交
1193

dengyihao's avatar
dengyihao 已提交
1194 1195 1196 1197 1198
  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 已提交
1199
  taosMemoryFree(pThrd->prepare);
wafwerar's avatar
wafwerar 已提交
1200 1201
  taosMemoryFree(pThrd->loop);
  taosMemoryFree(pThrd);
dengyihao's avatar
dengyihao 已提交
1202
}
dengyihao's avatar
dengyihao 已提交
1203

dengyihao's avatar
dengyihao 已提交
1204
static void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1205
  //
wafwerar's avatar
wafwerar 已提交
1206
  taosMemoryFree(ctx);
dengyihao's avatar
dengyihao 已提交
1207
}
dengyihao's avatar
dengyihao 已提交
1208

dengyihao's avatar
dengyihao 已提交
1209
void cliSendQuit(SCliThrd* thrd) {
dengyihao's avatar
dengyihao 已提交
1210
  // cli can stop gracefully
wafwerar's avatar
wafwerar 已提交
1211
  SCliMsg* msg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1212
  msg->type = Quit;
dengyihao's avatar
dengyihao 已提交
1213
  transAsyncSend(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
1214
  atomic_store_8(&thrd->asyncPool->stop, 1);
dengyihao's avatar
dengyihao 已提交
1215
}
dengyihao's avatar
dengyihao 已提交
1216 1217
void cliWalkCb(uv_handle_t* handle, void* arg) {
  if (!uv_is_closing(handle)) {
dengyihao's avatar
dengyihao 已提交
1218
    uv_read_stop((uv_stream_t*)handle);
dengyihao's avatar
dengyihao 已提交
1219
    uv_close(handle, cliDestroy);
dengyihao's avatar
dengyihao 已提交
1220 1221
  }
}
dengyihao's avatar
dengyihao 已提交
1222

U
ubuntu 已提交
1223
int cliRBChoseIdx(STrans* pTransInst) {
dengyihao's avatar
dengyihao 已提交
1224 1225 1226 1227
  int8_t index = pTransInst->index;
  if (pTransInst->numOfThreads == 0) {
    return -1;
  }
U
ubuntu 已提交
1228 1229 1230 1231 1232
  if (pTransInst->index++ >= pTransInst->numOfThreads) {
    pTransInst->index = 0;
  }
  return index % pTransInst->numOfThreads;
}
dengyihao's avatar
dengyihao 已提交
1233 1234
static void doDelayTask(void* param) {
  STaskArg* arg = param;
dengyihao's avatar
dengyihao 已提交
1235 1236
  SCliMsg*  pMsg = arg->param1;
  SCliThrd* pThrd = arg->param2;
dengyihao's avatar
dengyihao 已提交
1237 1238
  taosMemoryFree(arg);

dengyihao's avatar
dengyihao 已提交
1239
  cliHandleReq(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1240
}
dengyihao's avatar
dengyihao 已提交
1241

dengyihao's avatar
dengyihao 已提交
1242 1243 1244 1245
static void doCloseIdleConn(void* param) {
  STaskArg* arg = param;
  SCliConn* conn = arg->param1;
  SCliThrd* pThrd = arg->param2;
dengyihao's avatar
dengyihao 已提交
1246 1247
  tTrace("%s conn %p idle, close it", CONN_GET_INST_LABEL(conn), conn);
  conn->task = NULL;
dengyihao's avatar
dengyihao 已提交
1248 1249
  cliDestroyConn(conn, true);
  taosMemoryFree(arg);
dengyihao's avatar
dengyihao 已提交
1250 1251
}

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

dengyihao's avatar
dengyihao 已提交
1255 1256
  STraceId* trace = &pMsg->msg.info.traceId;
  char      tbuf[256] = {0};
dengyihao's avatar
dengyihao 已提交
1257
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1258
  tGDebug("%s retry on next node, use %s, retryCnt:%d, limit:%d", transLabel(pThrd->pTransInst), tbuf,
dengyihao's avatar
dengyihao 已提交
1259
          pCtx->retryCnt + 1, pCtx->retryLimit);
dengyihao's avatar
dengyihao 已提交
1260 1261 1262 1263 1264

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

dengyihao's avatar
dengyihao 已提交
1267
void cliCompareAndSwap(int8_t* val, int8_t exp, int8_t newVal) {
dengyihao's avatar
dengyihao 已提交
1268 1269 1270 1271
  if (*val != exp) {
    *val = newVal;
  }
}
dengyihao's avatar
dengyihao 已提交
1272

dengyihao's avatar
dengyihao 已提交
1273
bool cliTryExtractEpSet(STransMsg* pResp, SEpSet* dst) {
dengyihao's avatar
dengyihao 已提交
1274 1275 1276 1277 1278 1279
  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 已提交
1280 1281 1282 1283
    return false;
  }
  int32_t tlen = tSerializeSEpSet(NULL, 0, dst);

dengyihao's avatar
dengyihao 已提交
1284 1285 1286 1287 1288 1289 1290
  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 已提交
1291 1292

  pResp->pCont = buf;
dengyihao's avatar
dengyihao 已提交
1293 1294 1295
  pResp->contLen = len;

  *dst = epset;
dengyihao's avatar
dengyihao 已提交
1296 1297
  return true;
}
dengyihao's avatar
dengyihao 已提交
1298
int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
1299 1300
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1301

dengyihao's avatar
dengyihao 已提交
1302
  if (pMsg == NULL || pMsg->ctx == NULL) {
dengyihao's avatar
dengyihao 已提交
1303
    tTrace("%s conn %p handle resp", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
1304 1305 1306
    pTransInst->cfp(pTransInst->parent, pResp, NULL);
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
1307

dengyihao's avatar
dengyihao 已提交
1308 1309
  STransConnCtx* pCtx = pMsg->ctx;
  int32_t        code = pResp->code;
dengyihao's avatar
dengyihao 已提交
1310 1311

  bool retry = (pTransInst->retry != NULL && pTransInst->retry(code, pResp->msgType - 1)) ? true : false;
dengyihao's avatar
dengyihao 已提交
1312
  if (retry) {
dengyihao's avatar
dengyihao 已提交
1313 1314
    pMsg->sent = 0;
    pCtx->retryCnt += 1;
dengyihao's avatar
dengyihao 已提交
1315
    if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK) {
dengyihao's avatar
dengyihao 已提交
1316
      cliCompareAndSwap(&pCtx->retryLimit, TRANS_RETRY_COUNT_LIMIT, EPSET_GET_SIZE(&pCtx->epSet) * 3);
dengyihao's avatar
dengyihao 已提交
1317 1318 1319
      if (pCtx->retryCnt < pCtx->retryLimit) {
        transUnrefCliHandle(pConn);
        EPSET_FORWARD_INUSE(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1320
        transFreeMsg(pResp->pCont);
dengyihao's avatar
dengyihao 已提交
1321 1322 1323 1324
        cliSchedMsgToNextNode(pMsg, pThrd);
        return -1;
      }
    } else {
dengyihao's avatar
dengyihao 已提交
1325
      cliCompareAndSwap(&pCtx->retryLimit, TRANS_RETRY_COUNT_LIMIT, TRANS_RETRY_COUNT_LIMIT);
dengyihao's avatar
dengyihao 已提交
1326 1327
      if (pCtx->retryCnt < pCtx->retryLimit) {
        if (pResp->contLen == 0) {
dengyihao's avatar
dengyihao 已提交
1328
          EPSET_FORWARD_INUSE(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1329
        } else {
dengyihao's avatar
dengyihao 已提交
1330 1331 1332
          if (tDeserializeSEpSet(pResp->pCont, pResp->contLen, &pCtx->epSet) < 0) {
            tError("%s conn %p failed to deserialize epset", CONN_GET_INST_LABEL(pConn));
          }
dengyihao's avatar
dengyihao 已提交
1333
        }
dengyihao's avatar
dengyihao 已提交
1334
        addConnToPool(pThrd->pool, pConn);
dengyihao's avatar
dengyihao 已提交
1335 1336 1337
        transFreeMsg(pResp->pCont);
        cliSchedMsgToNextNode(pMsg, pThrd);
        return -1;
dengyihao's avatar
dengyihao 已提交
1338
      } else {
dengyihao's avatar
dengyihao 已提交
1339 1340
        // change error code for taos client driver if retryCnt exceeds limit
        if (0 == strncmp(pTransInst->label, "TSC", strlen("TSC"))) pResp->code = TSDB_CODE_APP_NOT_READY;
dengyihao's avatar
dengyihao 已提交
1341
      }
dengyihao's avatar
dengyihao 已提交
1342 1343
    }
  }
dengyihao's avatar
dengyihao 已提交
1344

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

dengyihao's avatar
dengyihao 已提交
1347
  bool hasEpSet = cliTryExtractEpSet(pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1348
  if (hasEpSet) {
dengyihao's avatar
dengyihao 已提交
1349 1350
    char tbuf[256] = {0};
    EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1351
    tGDebug("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1352
  }
dengyihao's avatar
dengyihao 已提交
1353

dengyihao's avatar
dengyihao 已提交
1354
  if (pCtx->pSem != NULL) {
dengyihao's avatar
dengyihao 已提交
1355
    tGDebug("%s conn %p(sync) handle resp", CONN_GET_INST_LABEL(pConn), pConn);
1356
    if (pCtx->pRsp == NULL) {
dengyihao's avatar
dengyihao 已提交
1357
      tGTrace("%s conn %p(sync) failed to resp, ignore", CONN_GET_INST_LABEL(pConn), pConn);
1358 1359 1360
    } else {
      memcpy((char*)pCtx->pRsp, (char*)pResp, sizeof(*pResp));
    }
dengyihao's avatar
dengyihao 已提交
1361
    tsem_post(pCtx->pSem);
1362
    pCtx->pRsp = NULL;
dengyihao's avatar
dengyihao 已提交
1363
  } else {
dengyihao's avatar
dengyihao 已提交
1364
    tGDebug("%s conn %p handle resp", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1365
    if (retry == false && hasEpSet == true) {
dengyihao's avatar
dengyihao 已提交
1366
      pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1367 1368 1369 1370 1371 1372
    } else {
      if (!cliIsEpsetUpdated(code, pCtx)) {
        pTransInst->cfp(pTransInst->parent, pResp, NULL);
      } else {
        pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1373
    }
dengyihao's avatar
dengyihao 已提交
1374
  }
dengyihao's avatar
dengyihao 已提交
1375
  return 0;
dengyihao's avatar
dengyihao 已提交
1376
}
U
ubuntu 已提交
1377 1378

void transCloseClient(void* arg) {
U
ubuntu 已提交
1379
  SCliObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
1380
  for (int i = 0; i < cli->numOfThreads; i++) {
U
ubuntu 已提交
1381
    cliSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1382
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1383
  }
wafwerar's avatar
wafwerar 已提交
1384 1385
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
dengyihao's avatar
dengyihao 已提交
1386
}
dengyihao's avatar
dengyihao 已提交
1387 1388 1389 1390 1391
void transRefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_INC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1392
  tTrace("%s conn %p ref %d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1393 1394 1395 1396 1397 1398 1399
  UNUSED(ref);
}
void transUnrefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_DEC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1400
  tTrace("%s conn %p ref:%d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1401
  if (ref == 0) {
U
ubuntu 已提交
1402
    cliDestroyConn((SCliConn*)handle, true);
dengyihao's avatar
dengyihao 已提交
1403 1404
  }
}
dengyihao's avatar
dengyihao 已提交
1405
SCliThrd* transGetWorkThrdFromHandle(int64_t handle, bool* validHandle) {
dengyihao's avatar
dengyihao 已提交
1406
  SCliThrd*  pThrd = NULL;
dengyihao's avatar
dengyihao 已提交
1407
  SExHandle* exh = transAcquireExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
1408 1409 1410
  if (exh == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
1411 1412

  *validHandle = true;
dengyihao's avatar
dengyihao 已提交
1413
  pThrd = exh->pThrd;
dengyihao's avatar
dengyihao 已提交
1414
  transReleaseExHandle(transGetRefMgt(), handle);
dengyihao's avatar
dengyihao 已提交
1415 1416
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1417
SCliThrd* transGetWorkThrd(STrans* trans, int64_t handle, bool* validHandle) {
dengyihao's avatar
dengyihao 已提交
1418
  if (handle == 0) {
dengyihao's avatar
dengyihao 已提交
1419
    int idx = cliRBChoseIdx(trans);
dengyihao's avatar
dengyihao 已提交
1420
    if (idx < 0) return NULL;
dengyihao's avatar
dengyihao 已提交
1421 1422
    return ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
D
dapan1121 已提交
1423 1424 1425 1426 1427 1428 1429
  SCliThrd* pThrd = transGetWorkThrdFromHandle(handle, validHandle);
  if (*validHandle == true && pThrd == NULL) {
    int idx = cliRBChoseIdx(trans);
    if (idx < 0) return NULL;
    pThrd = ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
  return pThrd;
dengyihao's avatar
dengyihao 已提交
1430
}
dengyihao's avatar
dengyihao 已提交
1431
int transReleaseCliHandle(void* handle) {
dengyihao's avatar
dengyihao 已提交
1432 1433 1434 1435
  int  idx = -1;
  bool valid = false;

  SCliThrd* pThrd = transGetWorkThrdFromHandle((int64_t)handle, &valid);
dengyihao's avatar
dengyihao 已提交
1436
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
1437
    return -1;
dengyihao's avatar
dengyihao 已提交
1438
  }
dengyihao's avatar
dengyihao 已提交
1439

S
Shengliang Guan 已提交
1440
  STransMsg tmsg = {.info.handle = handle};
dengyihao's avatar
rm code  
dengyihao 已提交
1441
  TRACE_SET_MSGID(&tmsg.info.traceId, tGenIdPI64());
dengyihao's avatar
dengyihao 已提交
1442 1443

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

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

dengyihao's avatar
dengyihao 已提交
1450
  if (0 != transAsyncSend(pThrd->asyncPool, &cmsg->q)) {
dengyihao's avatar
dengyihao 已提交
1451
    taosMemoryFree(cmsg);
dengyihao's avatar
dengyihao 已提交
1452 1453
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1454
  return 0;
dengyihao's avatar
dengyihao 已提交
1455
}
dengyihao's avatar
dengyihao 已提交
1456

dengyihao's avatar
dengyihao 已提交
1457
int transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1458 1459 1460 1461 1462
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1463

dengyihao's avatar
dengyihao 已提交
1464 1465 1466
  bool      valid = false;
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle, &valid);
  if (pThrd == NULL && valid == false) {
dengyihao's avatar
dengyihao 已提交
1467
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1468
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1469
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
1470 1471
  }

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

wafwerar's avatar
wafwerar 已提交
1474
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1475
  pCtx->epSet = *pEpSet;
S
Shengliang Guan 已提交
1476
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1477
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1478 1479 1480 1481

  if (ctx != NULL) {
    pCtx->appCtx = *ctx;
  }
dengyihao's avatar
dengyihao 已提交
1482

wafwerar's avatar
wafwerar 已提交
1483
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1484
  cliMsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
1485
  cliMsg->msg = *pReq;
dengyihao's avatar
dengyihao 已提交
1486
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1487
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1488
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
1489

dengyihao's avatar
dengyihao 已提交
1490
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
1491
  tGDebug("%s send request at thread:%08" PRId64 ", dst:%s:%d, app:%p", transLabel(pTransInst), pThrd->pid,
dengyihao's avatar
dengyihao 已提交
1492
          EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet), pReq->info.ahandle);
dengyihao's avatar
dengyihao 已提交
1493 1494
  if (0 != transAsyncSend(pThrd->asyncPool, &(cliMsg->q))) {
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1495
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1496 1497
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1498
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1499
  return 0;
dengyihao's avatar
dengyihao 已提交
1500
}
dengyihao's avatar
dengyihao 已提交
1501

dengyihao's avatar
dengyihao 已提交
1502
int transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMsg* pRsp) {
dengyihao's avatar
dengyihao 已提交
1503 1504 1505 1506 1507
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
  if (pTransInst == NULL) {
    transFreeMsg(pReq->pCont);
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1508

dengyihao's avatar
dengyihao 已提交
1509 1510 1511
  bool      valid = false;
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle, &valid);
  if (pThrd == NULL && valid == false) {
dengyihao's avatar
dengyihao 已提交
1512
    transFreeMsg(pReq->pCont);
dengyihao's avatar
dengyihao 已提交
1513
    transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1514
    return TSDB_CODE_RPC_BROKEN_LINK;
dengyihao's avatar
dengyihao 已提交
1515
  }
dengyihao's avatar
dengyihao 已提交
1516

dengyihao's avatar
dengyihao 已提交
1517 1518
  tsem_t* sem = taosMemoryCalloc(1, sizeof(tsem_t));
  tsem_init(sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
1519

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

wafwerar's avatar
wafwerar 已提交
1522
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1523
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
1524
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
1525
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1526
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1527
  pCtx->pSem = sem;
dengyihao's avatar
dengyihao 已提交
1528 1529
  pCtx->pRsp = pRsp;

wafwerar's avatar
wafwerar 已提交
1530
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1531 1532 1533
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pReq;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1534
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1535
  cliMsg->refId = (int64_t)shandle;
dengyihao's avatar
dengyihao 已提交
1536

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

dengyihao's avatar
dengyihao 已提交
1541 1542
  int ret = transAsyncSend(pThrd->asyncPool, &cliMsg->q);
  if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
1543
    destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1544
    goto _RETURN;
dengyihao's avatar
dengyihao 已提交
1545
  }
dengyihao's avatar
dengyihao 已提交
1546
  tsem_wait(sem);
dengyihao's avatar
dengyihao 已提交
1547 1548

_RETURN:
dengyihao's avatar
dengyihao 已提交
1549 1550
  tsem_destroy(sem);
  taosMemoryFree(sem);
dengyihao's avatar
dengyihao 已提交
1551
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1552
  return ret;
dengyihao's avatar
dengyihao 已提交
1553
}
dengyihao's avatar
dengyihao 已提交
1554 1555 1556
/*
 *
 **/
dengyihao's avatar
dengyihao 已提交
1557
int transSetDefaultAddr(void* shandle, const char* ip, const char* fqdn) {
dengyihao's avatar
dengyihao 已提交
1558
  STrans* pTransInst = (STrans*)transAcquireExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1559 1560 1561
  if (pTransInst == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
1562 1563 1564 1565 1566 1567 1568

  SCvtAddr cvtAddr = {0};
  if (ip != NULL && fqdn != NULL) {
    memcpy(cvtAddr.ip, ip, strlen(ip));
    memcpy(cvtAddr.fqdn, fqdn, strlen(fqdn));
    cvtAddr.cvt = true;
  }
dengyihao's avatar
dengyihao 已提交
1569 1570
  for (int i = 0; i < pTransInst->numOfThreads; i++) {
    STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1571
    pCtx->cvtAddr = cvtAddr;
dengyihao's avatar
dengyihao 已提交
1572 1573 1574 1575

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

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

dengyihao's avatar
dengyihao 已提交
1581 1582
    if (transAsyncSend(thrd->asyncPool, &(cliMsg->q)) != 0) {
      destroyCmsg(cliMsg);
dengyihao's avatar
dengyihao 已提交
1583
      transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1584 1585
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
1586
  }
dengyihao's avatar
dengyihao 已提交
1587
  transReleaseExHandle(transGetInstMgt(), (int64_t)shandle);
dengyihao's avatar
dengyihao 已提交
1588
  return 0;
dengyihao's avatar
dengyihao 已提交
1589
}
dengyihao's avatar
dengyihao 已提交
1590 1591 1592 1593 1594 1595 1596

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