transCli.c 43.4 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 18
 *
 * 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"

typedef struct SCliConn {
dengyihao's avatar
dengyihao 已提交
19
  T_REF_DECLARE()
dengyihao's avatar
dengyihao 已提交
20 21
  uv_connect_t connReq;
  uv_stream_t* stream;
dengyihao's avatar
dengyihao 已提交
22
  uv_write_t   writeReq;
dengyihao's avatar
dengyihao 已提交
23

dengyihao's avatar
dengyihao 已提交
24 25 26 27 28 29 30 31
  void* hostThrd;

  SConnBuffer readBuf;
  STransQueue cliMsgs;
  queue       conn;
  uint64_t    expireTime;

  STransCtx  ctx;
dengyihao's avatar
dengyihao 已提交
32 33
  bool       broken;  // link broken or not
  ConnStatus status;  //
dengyihao's avatar
dengyihao 已提交
34

dengyihao's avatar
dengyihao 已提交
35
  int64_t  refId;
dengyihao's avatar
dengyihao 已提交
36 37 38
  char*    ip;
  uint32_t port;

dengyihao's avatar
dengyihao 已提交
39
  // debug and log info
dengyihao's avatar
dengyihao 已提交
40
  struct sockaddr_in addr;
dengyihao's avatar
dengyihao 已提交
41
  struct sockaddr_in localAddr;
dengyihao's avatar
dengyihao 已提交
42
} SCliConn;
dengyihao's avatar
dengyihao 已提交
43

dengyihao's avatar
dengyihao 已提交
44
typedef struct SCliMsg {
dengyihao's avatar
dengyihao 已提交
45
  STransConnCtx* ctx;
dengyihao's avatar
formate  
dengyihao 已提交
46
  STransMsg      msg;
dengyihao's avatar
dengyihao 已提交
47
  queue          q;
dengyihao's avatar
dengyihao 已提交
48
  STransMsgType  type;
dengyihao's avatar
dengyihao 已提交
49 50 51

  uint64_t st;
  int      sent;  //(0: no send, 1: alread sent)
dengyihao's avatar
dengyihao 已提交
52 53
} SCliMsg;

dengyihao's avatar
dengyihao 已提交
54
typedef struct SCliThrd {
dengyihao's avatar
dengyihao 已提交
55 56
  TdThread    thread;  // tid
  int64_t     pid;     // pid
dengyihao's avatar
dengyihao 已提交
57
  uv_loop_t*  loop;
dengyihao's avatar
dengyihao 已提交
58
  SAsyncPool* asyncPool;
dengyihao's avatar
dengyihao 已提交
59
  uv_timer_t  timer;
dengyihao's avatar
dengyihao 已提交
60 61 62
  void*       pool;  // conn pool

  // msg queue
dengyihao's avatar
dengyihao 已提交
63
  queue         msg;
wafwerar's avatar
wafwerar 已提交
64
  TdThreadMutex msgMtx;
dengyihao's avatar
dengyihao 已提交
65 66 67
  SDelayQueue*  delayQueue;
  uint64_t      nextTimeout;  // next timeout
  void*         pTransInst;   //
dengyihao's avatar
dengyihao 已提交
68

dengyihao's avatar
dengyihao 已提交
69
  SCvtAddr cvtAddr;
dengyihao's avatar
dengyihao 已提交
70 71

  bool quit;
dengyihao's avatar
dengyihao 已提交
72
} SCliThrd;
dengyihao's avatar
dengyihao 已提交
73

U
ubuntu 已提交
74
typedef struct SCliObj {
dengyihao's avatar
dengyihao 已提交
75 76 77 78
  char       label[TSDB_LABEL_LEN];
  int32_t    index;
  int        numOfThreads;
  SCliThrd** pThreadObj;
U
ubuntu 已提交
79
} SCliObj;
dengyihao's avatar
dengyihao 已提交
80

dengyihao's avatar
dengyihao 已提交
81 82 83 84
typedef struct SConnList {
  queue conn;
} SConnList;

dengyihao's avatar
dengyihao 已提交
85
// conn pool
dengyihao's avatar
dengyihao 已提交
86
// add expire timeout and capacity limit
dengyihao's avatar
dengyihao 已提交
87
static void*     createConnPool(int size);
88
static void*     destroyConnPool(void* pool);
dengyihao's avatar
dengyihao 已提交
89
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port);
dengyihao's avatar
dengyihao 已提交
90
static void      addConnToPool(void* pool, SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
91

dengyihao's avatar
dengyihao 已提交
92
// register timer in each thread to clear expire conn
U
ubuntu 已提交
93 94
static void cliTimeoutCb(uv_timer_t* handle);
// alloc buf for recv
dengyihao's avatar
dengyihao 已提交
95
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
U
ubuntu 已提交
96 97
// callback after  read nbytes from socket
static void cliRecvCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
98
// callback after write data to socket
U
ubuntu 已提交
99
static void cliSendCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
100
// callback after conn  to server
U
ubuntu 已提交
101 102
static void cliConnCb(uv_connect_t* req, int status);
static void cliAsyncCb(uv_async_t* handle);
dengyihao's avatar
dengyihao 已提交
103

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

dengyihao's avatar
dengyihao 已提交
106
static SCliConn* cliCreateConn(SCliThrd* thrd);
U
ubuntu 已提交
107 108
static void      cliDestroyConn(SCliConn* pConn, bool clear /*clear tcp handle or not*/);
static void      cliDestroy(uv_handle_t* handle);
dengyihao's avatar
dengyihao 已提交
109
static void      cliSend(SCliConn* pConn);
dengyihao's avatar
dengyihao 已提交
110

dengyihao's avatar
dengyihao 已提交
111 112 113 114 115 116 117
static 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;
}

dengyihao's avatar
dengyihao 已提交
118
void cliMayCvtFqdnToIp(SEpSet* pEpSet, SCvtAddr* pCvtAddr);
dengyihao's avatar
dengyihao 已提交
119 120 121 122
/*
 * set TCP connection timeout per-socket level
 */
static int cliCreateSocket();
dengyihao's avatar
dengyihao 已提交
123
// process data read from server, add decompress etc later
U
ubuntu 已提交
124
static void cliHandleResp(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
125
// handle except about conn
U
ubuntu 已提交
126
static void cliHandleExcept(SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
127

128
// handle req from app
dengyihao's avatar
dengyihao 已提交
129 130 131 132 133 134 135 136
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 已提交
137
static void destroyUserdata(STransMsg* userdata);
dengyihao's avatar
dengyihao 已提交
138

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

dengyihao's avatar
dengyihao 已提交
141 142
static void destroyCmsg(SCliMsg* cmsg);
static void transDestroyConnCtx(STransConnCtx* ctx);
dengyihao's avatar
dengyihao 已提交
143
// thread obj
dengyihao's avatar
dengyihao 已提交
144 145
static SCliThrd* createThrdObj();
static void      destroyThrdObj(SCliThrd* pThrd);
dengyihao's avatar
dengyihao 已提交
146

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

dengyihao's avatar
dengyihao 已提交
149 150 151 152 153 154 155 156 157 158 159 160
static void cliReleaseUnfinishedMsg(SCliConn* conn) {
  SCliMsg* pMsg = NULL;
  for (int i = 0; i < transQueueSize(&conn->cliMsgs); i++) {
    pMsg = transQueueGet(&conn->cliMsgs, i);
    if (pMsg != NULL && pMsg->ctx != NULL) {
      if (conn->ctx.freeFunc != NULL) {
        conn->ctx.freeFunc(pMsg->ctx->ahandle);
      }
    }
    destroyCmsg(pMsg);
  }
}
dengyihao's avatar
dengyihao 已提交
161 162 163 164 165 166 167
#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 已提交
168 169 170 171 172 173
// 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 已提交
174 175 176 177 178
#define CONN_HOST_THREAD_IDX1(idx, exh, refId, pThrd) \
  do {                                                \
    if (exh == NULL) {                                \
      idx = -1;                                       \
    } else {                                          \
dengyihao's avatar
dengyihao 已提交
179
      ASYNC_CHECK_HANDLE((exh), refId);               \
dengyihao's avatar
dengyihao 已提交
180
      pThrd = (SCliThrd*)(exh)->pThrd;                \
dengyihao's avatar
dengyihao 已提交
181 182
    }                                                 \
  } while (0)
dengyihao's avatar
dengyihao 已提交
183 184
#define CONN_PERSIST_TIME(para)    (para * 1000 * 10)
#define CONN_GET_HOST_THREAD(conn) (conn ? ((SCliConn*)conn)->hostThrd : NULL)
dengyihao's avatar
dengyihao 已提交
185
#define CONN_GET_INST_LABEL(conn)  (((STrans*)(((SCliThrd*)(conn)->hostThrd)->pTransInst))->label)
dengyihao's avatar
dengyihao 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198
#define CONN_SHOULD_RELEASE(conn, head)                                                                            \
  do {                                                                                                             \
    if ((head)->release == 1 && (head->msgLen) == sizeof(*head)) {                                                 \
      uint64_t ahandle = head->ahandle;                                                                            \
      CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);                                                                   \
      transClearBuffer(&conn->readBuf);                                                                            \
      transFreeMsg(transContFromHead((char*)head));                                                                \
      tDebug("%s conn %p receive release request, ref: %d", CONN_GET_INST_LABEL(conn), conn, T_REF_VAL_GET(conn)); \
      if (T_REF_VAL_GET(conn) > 1) {                                                                               \
        transUnrefCliHandle(conn);                                                                                 \
      }                                                                                                            \
      destroyCmsg(pMsg);                                                                                           \
      cliReleaseUnfinishedMsg(conn);                                                                               \
dengyihao's avatar
dengyihao 已提交
199
      addConnToPool(((SCliThrd*)conn->hostThrd)->pool, conn);                                                      \
dengyihao's avatar
dengyihao 已提交
200 201
      return;                                                                                                      \
    }                                                                                                              \
dengyihao's avatar
dengyihao 已提交
202 203
  } while (0)

dengyihao's avatar
dengyihao 已提交
204 205 206 207 208
#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 已提交
209
      if (pMsg != NULL && pMsg->ctx != NULL && (uint64_t)pMsg->ctx->ahandle == ahandle) { \
dengyihao's avatar
dengyihao 已提交
210 211 212 213 214 215 216 217
        break;                                                                            \
      }                                                                                   \
    }                                                                                     \
    if (i == sz) {                                                                        \
      pMsg = NULL;                                                                        \
    } else {                                                                              \
      pMsg = transQueueRm(&conn->cliMsgs, i);                                             \
    }                                                                                     \
dengyihao's avatar
dengyihao 已提交
218
  } while (0)
U
ubuntu 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231
#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 已提交
232

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

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

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
305 306 307
  STransMsgHead* pHead = (STransMsgHead*)(conn->readBuf.buf);
  pHead->code = htonl(pHead->code);
  pHead->msgLen = htonl(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
308

dengyihao's avatar
dengyihao 已提交
309 310 311 312 313
  STransMsg transMsg = {0};
  transMsg.contLen = transContLenFromMsg(pHead->msgLen);
  transMsg.pCont = transContFromHead((char*)pHead);
  transMsg.code = pHead->code;
  transMsg.msgType = pHead->msgType;
S
Shengliang Guan 已提交
314
  transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
315
  transMsg.info.traceId = pHead->traceId;
dengyihao's avatar
dengyihao 已提交
316
  transMsg.info.hasEpSet = pHead->hasEpSet;
dengyihao's avatar
dengyihao 已提交
317

dengyihao's avatar
dengyihao 已提交
318 319
  SCliMsg*       pMsg = NULL;
  STransConnCtx* pCtx = NULL;
dengyihao's avatar
dengyihao 已提交
320
  CONN_SHOULD_RELEASE(conn, pHead);
dengyihao's avatar
dengyihao 已提交
321

dengyihao's avatar
dengyihao 已提交
322 323
  if (CONN_NO_PERSIST_BY_APP(conn)) {
    pMsg = transQueuePop(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
324 325 326

    pCtx = pMsg ? pMsg->ctx : NULL;
    transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
327
    tDebug("%s conn %p get ahandle %p, persist: 0", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
U
ubuntu 已提交
328
  } else {
dengyihao's avatar
dengyihao 已提交
329 330 331
    uint64_t ahandle = (uint64_t)pHead->ahandle;
    CONN_GET_MSGCTX_BY_AHANDLE(conn, ahandle);
    if (pMsg == NULL) {
S
Shengliang Guan 已提交
332
      transMsg.info.ahandle = transCtxDumpVal(&conn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
333 334
      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 已提交
335
      if (!CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
D
dapan1121 已提交
336
        transMsg.code = TSDB_CODE_RPC_BROKEN_LINK;
S
Shengliang Guan 已提交
337
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&conn->ctx, (int32_t*)&(transMsg.msgType));
dengyihao's avatar
dengyihao 已提交
338 339
        tDebug("%s conn %p construct ahandle %p due brokenlink, persist: 1", CONN_GET_INST_LABEL(conn), conn,
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
340 341 342
      }
    } else {
      pCtx = pMsg ? pMsg->ctx : NULL;
S
Shengliang Guan 已提交
343
      transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
344
      tDebug("%s conn %p get ahandle %p, persist: 1", CONN_GET_INST_LABEL(conn), conn, transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
345
    }
U
ubuntu 已提交
346
  }
dengyihao's avatar
dengyihao 已提交
347 348
  // buf's mem alread translated to transMsg.pCont
  transClearBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
349
  if (!CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
350
    transMsg.info.handle = (void*)conn->refId;
dengyihao's avatar
dengyihao 已提交
351
    tDebug("%s conn %p ref by app", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
352
  }
dengyihao's avatar
dengyihao 已提交
353

dengyihao's avatar
dengyihao 已提交
354
  STraceId* trace = &transMsg.info.traceId;
dengyihao's avatar
dengyihao 已提交
355 356 357
  tGTrace("%s conn %p %s received from %s:%d, local info: %s:%d, msg size: %d, code: %d", CONN_GET_INST_LABEL(conn),
          conn, TMSG_INFO(pHead->msgType), taosInetNtoa(conn->addr.sin_addr), ntohs(conn->addr.sin_port),
          taosInetNtoa(conn->localAddr.sin_addr), ntohs(conn->localAddr.sin_port), transMsg.contLen, transMsg.code);
dengyihao's avatar
dengyihao 已提交
358

dengyihao's avatar
dengyihao 已提交
359
  if (pCtx == NULL && CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
360
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
361 362
    return;
  }
S
Shengliang Guan 已提交
363
  if (CONN_RELEASE_BY_SERVER(conn) && transMsg.info.ahandle == NULL) {
dengyihao's avatar
dengyihao 已提交
364
    tDebug("%s except, conn %p read while cli ignore it", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
365 366
    return;
  }
dengyihao's avatar
dengyihao 已提交
367

dengyihao's avatar
dengyihao 已提交
368
  if (cliAppCb(conn, &transMsg, pMsg) != 0) {
dengyihao's avatar
dengyihao 已提交
369
    return;
dengyihao's avatar
dengyihao 已提交
370
  }
dengyihao's avatar
dengyihao 已提交
371 372
  destroyCmsg(pMsg);

dengyihao's avatar
dengyihao 已提交
373
  if (cliMaySendCachedMsg(conn) == true) {
dengyihao's avatar
dengyihao 已提交
374 375
    return;
  }
dengyihao's avatar
dengyihao 已提交
376

U
ubuntu 已提交
377
  if (CONN_NO_PERSIST_BY_APP(conn)) {
dengyihao's avatar
dengyihao 已提交
378
    addConnToPool(pThrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
379
  }
dengyihao's avatar
test  
dengyihao 已提交
380

dengyihao's avatar
dengyihao 已提交
381
  uv_read_start((uv_stream_t*)conn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
382
  // start thread's timer of conn pool if not active
dengyihao's avatar
dengyihao 已提交
383
  if (!uv_is_active((uv_handle_t*)&pThrd->timer) && pTransInst->idleTime > 0) {
U
ubuntu 已提交
384
    // uv_timer_start((uv_timer_t*)&pThrd->timer, cliTimeoutCb, CONN_PERSIST_TIME(pRpc->idleTime) / 2, 0);
dengyihao's avatar
dengyihao 已提交
385
  }
dengyihao's avatar
dengyihao 已提交
386
}
U
ubuntu 已提交
387 388

void cliHandleExcept(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
389
  if (transQueueEmpty(&pConn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
390
    if (pConn->broken == true && CONN_NO_PERSIST_BY_APP(pConn)) {
dengyihao's avatar
dengyihao 已提交
391
      tTrace("%s conn %p handle except, persist:0", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
formate  
dengyihao 已提交
392 393 394
      transUnrefCliHandle(pConn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
395
  }
dengyihao's avatar
dengyihao 已提交
396 397 398
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
  bool      once = false;
D
dapan1121 已提交
399
  do {
dengyihao's avatar
dengyihao 已提交
400
    SCliMsg* pMsg = transQueuePop(&pConn->cliMsgs);
D
dapan1121 已提交
401 402
    if (pMsg == NULL && once) {
      break;
dengyihao's avatar
dengyihao 已提交
403
    }
dengyihao's avatar
dengyihao 已提交
404
    STransConnCtx* pCtx = pMsg ? pMsg->ctx : NULL;
U
ubuntu 已提交
405

dengyihao's avatar
dengyihao 已提交
406
    STransMsg transMsg = {0};
dengyihao's avatar
dengyihao 已提交
407
    transMsg.code = pConn->broken ? TSDB_CODE_RPC_BROKEN_LINK : TSDB_CODE_RPC_NETWORK_UNAVAIL;
dengyihao's avatar
dengyihao 已提交
408
    transMsg.msgType = pMsg ? pMsg->msg.msgType + 1 : 0;
S
Shengliang Guan 已提交
409
    transMsg.info.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
410

dengyihao's avatar
dengyihao 已提交
411
    if (pMsg == NULL && !CONN_NO_PERSIST_BY_APP(pConn)) {
S
Shengliang Guan 已提交
412
      transMsg.info.ahandle = transCtxDumpVal(&pConn->ctx, transMsg.msgType);
dengyihao's avatar
dengyihao 已提交
413
      tDebug("%s conn %p construct ahandle %p by %s", CONN_GET_INST_LABEL(pConn), pConn, transMsg.info.ahandle,
dengyihao's avatar
dengyihao 已提交
414
             TMSG_INFO(transMsg.msgType));
S
Shengliang Guan 已提交
415 416
      if (transMsg.info.ahandle == NULL) {
        transMsg.info.ahandle = transCtxDumpBrokenlinkVal(&pConn->ctx, (int32_t*)&(transMsg.msgType));
dengyihao's avatar
dengyihao 已提交
417
        tDebug("%s conn %p construct ahandle %p due to brokenlink", CONN_GET_INST_LABEL(pConn), pConn,
S
Shengliang Guan 已提交
418
               transMsg.info.ahandle);
dengyihao's avatar
dengyihao 已提交
419
      }
dengyihao's avatar
dengyihao 已提交
420
    } else {
S
Shengliang Guan 已提交
421
      transMsg.info.ahandle = pCtx ? pCtx->ahandle : NULL;
dengyihao's avatar
dengyihao 已提交
422 423 424
    }

    if (pCtx == NULL || pCtx->pSem == NULL) {
S
Shengliang Guan 已提交
425
      if (transMsg.info.ahandle == NULL) {
D
dapan1121 已提交
426
        once = true;
U
ubuntu 已提交
427 428
        continue;
      }
dengyihao's avatar
dengyihao 已提交
429
    }
dengyihao's avatar
dengyihao 已提交
430
    if (cliAppCb(pConn, &transMsg, pMsg) != 0) {
dengyihao's avatar
dengyihao 已提交
431
      return;
dengyihao's avatar
dengyihao 已提交
432 433
    }
    destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
434
    tTrace("%s conn %p start to destroy, ref:%d", CONN_GET_INST_LABEL(pConn), pConn, T_REF_VAL_GET(pConn));
D
dapan1121 已提交
435
  } while (!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
436
  transUnrefCliHandle(pConn);
dengyihao's avatar
dengyihao 已提交
437
}
dengyihao's avatar
dengyihao 已提交
438

U
ubuntu 已提交
439
void cliTimeoutCb(uv_timer_t* handle) {
dengyihao's avatar
dengyihao 已提交
440 441 442
  SCliThrd* pThrd = handle->data;
  STrans*   pTransInst = pThrd->pTransInst;
  int64_t   currentTime = pThrd->nextTimeout;
dengyihao's avatar
dengyihao 已提交
443
  tTrace("%s conn timeout, try to remove expire conn from conn pool", pTransInst->label);
dengyihao's avatar
dengyihao 已提交
444

dengyihao's avatar
dengyihao 已提交
445
  SConnList* p = taosHashIterate((SHashObj*)pThrd->pool, NULL);
dengyihao's avatar
dengyihao 已提交
446 447 448 449 450 451
  while (p != NULL) {
    while (!QUEUE_IS_EMPTY(&p->conn)) {
      queue*    h = QUEUE_HEAD(&p->conn);
      SCliConn* c = QUEUE_DATA(h, SCliConn, conn);
      if (c->expireTime < currentTime) {
        QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
452
        transUnrefCliHandle(c);
dengyihao's avatar
dengyihao 已提交
453 454 455 456
      } else {
        break;
      }
    }
dengyihao's avatar
dengyihao 已提交
457
    p = taosHashIterate((SHashObj*)pThrd->pool, p);
dengyihao's avatar
dengyihao 已提交
458 459
  }

dengyihao's avatar
dengyihao 已提交
460 461
  pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
  uv_timer_start(handle, cliTimeoutCb, CONN_PERSIST_TIME(pTransInst->idleTime) / 2, 0);
dengyihao's avatar
dengyihao 已提交
462
}
U
ubuntu 已提交
463 464

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

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

dengyihao's avatar
dengyihao 已提交
486 487
  SHashObj*  pPool = pool;
  SConnList* plist = taosHashGet(pPool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
488 489
  if (plist == NULL) {
    SConnList list;
dengyihao's avatar
dengyihao 已提交
490 491
    taosHashPut(pPool, key, strlen(key), (void*)&list, sizeof(list));
    plist = taosHashGet(pPool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
492
    QUEUE_INIT(&plist->conn);
dengyihao's avatar
dengyihao 已提交
493 494 495 496 497
  }

  if (QUEUE_IS_EMPTY(&plist->conn)) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
498
  queue*    h = QUEUE_HEAD(&plist->conn);
dengyihao's avatar
dengyihao 已提交
499
  SCliConn* conn = QUEUE_DATA(h, SCliConn, conn);
dengyihao's avatar
dengyihao 已提交
500
  conn->status = ConnNormal;
dengyihao's avatar
dengyihao 已提交
501
  QUEUE_REMOVE(&conn->conn);
dengyihao's avatar
dengyihao 已提交
502
  QUEUE_INIT(&conn->conn);
503
  assert(h == &conn->conn);
dengyihao's avatar
dengyihao 已提交
504
  return conn;
dengyihao's avatar
dengyihao 已提交
505
}
dengyihao's avatar
dengyihao 已提交
506 507
static void allocConnRef(SCliConn* conn, bool update) {
  if (update) {
dengyihao's avatar
dengyihao 已提交
508
    transRemoveExHandle(conn->refId);
dengyihao's avatar
dengyihao 已提交
509
    conn->refId = -1;
dengyihao's avatar
dengyihao 已提交
510 511 512 513
  }
  SExHandle* exh = taosMemoryCalloc(1, sizeof(SExHandle));
  exh->handle = conn;
  exh->pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
514
  exh->refId = transAddExHandle(exh);
dengyihao's avatar
dengyihao 已提交
515 516
  conn->refId = exh->refId;
}
dengyihao's avatar
dengyihao 已提交
517
static void addConnToPool(void* pool, SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
518 519 520
  if (conn->status == ConnInPool) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
521
  SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
522 523
  CONN_HANDLE_THREAD_QUIT(thrd);

dengyihao's avatar
dengyihao 已提交
524 525
  allocConnRef(conn, true);

dengyihao's avatar
dengyihao 已提交
526
  STrans* pTransInst = thrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
527 528
  conn->expireTime = taosGetTimestampMs() + CONN_PERSIST_TIME(pTransInst->idleTime);
  transQueueClear(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
529
  transCtxCleanup(&conn->ctx);
dengyihao's avatar
dengyihao 已提交
530
  conn->status = ConnInPool;
dengyihao's avatar
dengyihao 已提交
531

dengyihao's avatar
dengyihao 已提交
532
  char key[128] = {0};
dengyihao's avatar
dengyihao 已提交
533
  CONN_CONSTRUCT_HASH_KEY(key, conn->ip, conn->port);
dengyihao's avatar
dengyihao 已提交
534
  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 已提交
535

dengyihao's avatar
dengyihao 已提交
536
  SConnList* plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
537 538
  // list already create before
  assert(plist != NULL);
dengyihao's avatar
dengyihao 已提交
539
  QUEUE_INIT(&conn->conn);
dengyihao's avatar
dengyihao 已提交
540
  QUEUE_PUSH(&plist->conn, &conn->conn);
dengyihao's avatar
dengyihao 已提交
541
  assert(!QUEUE_IS_EMPTY(&plist->conn));
dengyihao's avatar
dengyihao 已提交
542
}
dengyihao's avatar
dengyihao 已提交
543
static void cliAllocRecvBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
544
  SCliConn*    conn = handle->data;
dengyihao's avatar
dengyihao 已提交
545
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
546
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
547
}
U
ubuntu 已提交
548
static void cliRecvCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
549
  // impl later
dengyihao's avatar
dengyihao 已提交
550 551 552
  if (handle->data == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
553 554
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
555
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
556
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
557
    if (transReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
558
      tTrace("%s conn %p read complete", CONN_GET_INST_LABEL(conn), conn);
U
ubuntu 已提交
559
      cliHandleResp(conn);
dengyihao's avatar
dengyihao 已提交
560
    } else {
dengyihao's avatar
dengyihao 已提交
561
      tTrace("%s conn %p read partial packet, continue to read", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
562
    }
dengyihao's avatar
dengyihao 已提交
563 564
    return;
  }
dengyihao's avatar
dengyihao 已提交
565

566 567
  assert(nread <= 0);
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
568 569 570
    // 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 已提交
571
    tTrace("%s conn %p read empty", CONN_GET_INST_LABEL(conn), conn);
572 573
    return;
  }
dengyihao's avatar
fix bug  
dengyihao 已提交
574
  if (nread < 0) {
dengyihao's avatar
dengyihao 已提交
575 576
    tError("%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 已提交
577
    conn->broken = true;
U
ubuntu 已提交
578
    cliHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
579
  }
dengyihao's avatar
dengyihao 已提交
580
}
dengyihao's avatar
dengyihao 已提交
581

dengyihao's avatar
dengyihao 已提交
582
static SCliConn* cliCreateConn(SCliThrd* pThrd) {
wafwerar's avatar
wafwerar 已提交
583
  SCliConn* conn = taosMemoryCalloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
584
  // read/write stream handle
wafwerar's avatar
wafwerar 已提交
585
  conn->stream = (uv_stream_t*)taosMemoryMalloc(sizeof(uv_tcp_t));
dengyihao's avatar
dengyihao 已提交
586 587 588 589 590
  uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
  conn->stream->data = conn;

  conn->writeReq.data = conn;
  conn->connReq.data = conn;
dengyihao's avatar
dengyihao 已提交
591 592

  transQueueInit(&conn->cliMsgs, NULL);
dengyihao's avatar
dengyihao 已提交
593 594
  QUEUE_INIT(&conn->conn);
  conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
595 596
  conn->status = ConnNormal;
  conn->broken = 0;
dengyihao's avatar
dengyihao 已提交
597
  transRefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
598

dengyihao's avatar
dengyihao 已提交
599
  allocConnRef(conn, false);
dengyihao's avatar
dengyihao 已提交
600

dengyihao's avatar
dengyihao 已提交
601 602
  return conn;
}
U
ubuntu 已提交
603
static void cliDestroyConn(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
604
  tTrace("%s conn %p remove from conn pool", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
605
  QUEUE_REMOVE(&conn->conn);
dengyihao's avatar
dengyihao 已提交
606
  QUEUE_INIT(&conn->conn);
dengyihao's avatar
dengyihao 已提交
607
  transRemoveExHandle(conn->refId);
dengyihao's avatar
dengyihao 已提交
608 609
  conn->refId = -1;

dengyihao's avatar
dengyihao 已提交
610
  if (clear) {
dengyihao's avatar
dengyihao 已提交
611
    if (!uv_is_closing((uv_handle_t*)conn->stream)) {
dengyihao's avatar
dengyihao 已提交
612 613
      uv_close((uv_handle_t*)conn->stream, cliDestroy);
    }
dengyihao's avatar
dengyihao 已提交
614 615 616
    //} else {
    //  cliDestroy((uv_handle_t*)conn->stream);
    //}
617
  }
dengyihao's avatar
dengyihao 已提交
618
}
U
ubuntu 已提交
619
static void cliDestroy(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
620 621 622 623
  if (uv_handle_get_type(handle) != UV_TCP || handle->data == NULL) {
    return;
  }

dengyihao's avatar
dengyihao 已提交
624
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
625
  transRemoveExHandle(conn->refId);
wafwerar's avatar
wafwerar 已提交
626
  taosMemoryFree(conn->ip);
dengyihao's avatar
dengyihao 已提交
627
  conn->stream->data = NULL;
wafwerar's avatar
wafwerar 已提交
628
  taosMemoryFree(conn->stream);
dengyihao's avatar
dengyihao 已提交
629 630
  transCtxCleanup(&conn->ctx);
  transQueueDestroy(&conn->cliMsgs);
dengyihao's avatar
dengyihao 已提交
631
  tTrace("%s conn %p destroy successfully", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
632
  transDestroyBuffer(&conn->readBuf);
wafwerar's avatar
wafwerar 已提交
633
  taosMemoryFree(conn);
dengyihao's avatar
dengyihao 已提交
634
}
dengyihao's avatar
dengyihao 已提交
635
static bool cliHandleNoResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
636 637
  bool res = false;
  if (!transQueueEmpty(&conn->cliMsgs)) {
dengyihao's avatar
dengyihao 已提交
638
    SCliMsg* pMsg = transQueueGet(&conn->cliMsgs, 0);
dengyihao's avatar
dengyihao 已提交
639
    if (REQUEST_NO_RESP(&pMsg->msg)) {
dengyihao's avatar
dengyihao 已提交
640 641
      transQueuePop(&conn->cliMsgs);
      // taosArrayRemove(msgs, 0);
dengyihao's avatar
dengyihao 已提交
642 643 644 645 646
      destroyCmsg(pMsg);
      res = true;
    }
    if (res == true) {
      if (cliMaySendCachedMsg(conn) == false) {
dengyihao's avatar
dengyihao 已提交
647
        SCliThrd* thrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
648
        addConnToPool(thrd->pool, conn);
dengyihao's avatar
dengyihao 已提交
649 650 651 652 653
      }
    }
  }
  return res;
}
U
ubuntu 已提交
654
static void cliSendCb(uv_write_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
655
  SCliConn* pConn = req->data;
dengyihao's avatar
dengyihao 已提交
656

dengyihao's avatar
dengyihao 已提交
657
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
658
    tTrace("%s conn %p data already was written out", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
659
  } else {
dengyihao's avatar
dengyihao 已提交
660
    tError("%s conn %p failed to write: %s", CONN_GET_INST_LABEL(pConn), pConn, uv_err_name(status));
U
ubuntu 已提交
661
    cliHandleExcept(pConn);
dengyihao's avatar
dengyihao 已提交
662 663
    return;
  }
dengyihao's avatar
dengyihao 已提交
664
  if (cliHandleNoResp(pConn) == true) {
dengyihao's avatar
dengyihao 已提交
665
    tTrace("%s conn %p no resp required", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
666 667
    return;
  }
dengyihao's avatar
dengyihao 已提交
668
  uv_read_start((uv_stream_t*)pConn->stream, cliAllocRecvBufferCb, cliRecvCb);
dengyihao's avatar
dengyihao 已提交
669
}
dengyihao's avatar
dengyihao 已提交
670

U
ubuntu 已提交
671
void cliSend(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
672 673
  CONN_HANDLE_BROKEN(pConn);

dengyihao's avatar
dengyihao 已提交
674
  assert(!transQueueEmpty(&pConn->cliMsgs));
dengyihao's avatar
dengyihao 已提交
675 676

  SCliMsg* pCliMsg = NULL;
U
ubuntu 已提交
677
  CONN_GET_NEXT_SENDMSG(pConn);
dengyihao's avatar
dengyihao 已提交
678 679
  pCliMsg->sent = 1;

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

dengyihao's avatar
dengyihao 已提交
682 683
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
684

U
ubuntu 已提交
685
  STransMsg* pMsg = (STransMsg*)(&pCliMsg->msg);
dengyihao's avatar
dengyihao 已提交
686 687 688 689
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
dengyihao's avatar
dengyihao 已提交
690
  int msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
691

dengyihao's avatar
dengyihao 已提交
692 693
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
  pHead->ahandle = pCtx != NULL ? (uint64_t)pCtx->ahandle : 0;
dengyihao's avatar
dengyihao 已提交
694 695
  pHead->noResp = REQUEST_NO_RESP(pMsg) ? 1 : 0;
  pHead->persist = REQUEST_PERSIS_HANDLE(pMsg) ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
696 697
  pHead->msgType = pMsg->msgType;
  pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);
dengyihao's avatar
dengyihao 已提交
698
  pHead->release = REQUEST_RELEASE_HANDLE(pCliMsg) ? 1 : 0;
dengyihao's avatar
dengyihao 已提交
699
  memcpy(pHead->user, pTransInst->user, strlen(pTransInst->user));
dengyihao's avatar
dengyihao 已提交
700
  pHead->traceId = pMsg->info.traceId;
dengyihao's avatar
dengyihao 已提交
701 702

  uv_buf_t wb = uv_buf_init((char*)pHead, msgLen);
dengyihao's avatar
dengyihao 已提交
703 704

  STraceId* trace = &pMsg->info.traceId;
dengyihao's avatar
dengyihao 已提交
705 706 707
  tGTrace("%s conn %p %s is sent to %s:%d, local info %s:%d", CONN_GET_INST_LABEL(pConn), pConn,
          TMSG_INFO(pHead->msgType), taosInetNtoa(pConn->addr.sin_addr), ntohs(pConn->addr.sin_port),
          taosInetNtoa(pConn->localAddr.sin_addr), ntohs(pConn->localAddr.sin_port));
dengyihao's avatar
dengyihao 已提交
708

dengyihao's avatar
dengyihao 已提交
709 710 711
  if (pHead->persist == 1) {
    CONN_SET_PERSIST_BY_APP(pConn);
  }
dengyihao's avatar
dengyihao 已提交
712

dengyihao's avatar
dengyihao 已提交
713
  pConn->writeReq.data = pConn;
U
ubuntu 已提交
714
  uv_write(&pConn->writeReq, (uv_stream_t*)pConn->stream, &wb, 1, cliSendCb);
U
ubuntu 已提交
715 716
  return;
_RETURN:
dengyihao's avatar
dengyihao 已提交
717
  return;
dengyihao's avatar
dengyihao 已提交
718
}
U
ubuntu 已提交
719 720

void cliConnCb(uv_connect_t* req, int status) {
dengyihao's avatar
dengyihao 已提交
721
  // impl later
dengyihao's avatar
dengyihao 已提交
722 723
  SCliConn* pConn = req->data;
  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
724
    tError("%s conn %p failed to connect server: %s", CONN_GET_INST_LABEL(pConn), pConn, uv_strerror(status));
U
ubuntu 已提交
725
    cliHandleExcept(pConn);
726
    return;
dengyihao's avatar
dengyihao 已提交
727
  }
dengyihao's avatar
dengyihao 已提交
728 729 730
  int addrlen = sizeof(pConn->addr);
  uv_tcp_getpeername((uv_tcp_t*)pConn->stream, (struct sockaddr*)&pConn->addr, &addrlen);

dengyihao's avatar
dengyihao 已提交
731 732
  addrlen = sizeof(pConn->localAddr);
  uv_tcp_getsockname((uv_tcp_t*)pConn->stream, (struct sockaddr*)&pConn->localAddr, &addrlen);
dengyihao's avatar
dengyihao 已提交
733

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

U
ubuntu 已提交
737
  cliSend(pConn);
dengyihao's avatar
dengyihao 已提交
738 739
}

dengyihao's avatar
dengyihao 已提交
740
static void cliHandleQuit(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
741
  pThrd->quit = true;
U
ubuntu 已提交
742
  tDebug("cli work thread %p start to quit", pThrd);
dengyihao's avatar
dengyihao 已提交
743
  destroyCmsg(pMsg);
dengyihao's avatar
fix bug  
dengyihao 已提交
744
  destroyConnPool(pThrd->pool);
dengyihao's avatar
dengyihao 已提交
745
  uv_timer_stop(&pThrd->timer);
dengyihao's avatar
dengyihao 已提交
746 747 748
  uv_walk(pThrd->loop, cliWalkCb, NULL);

  // uv_stop(pThrd->loop);
dengyihao's avatar
dengyihao 已提交
749
}
dengyihao's avatar
dengyihao 已提交
750
static void cliHandleRelease(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
751
  int64_t    refId = (int64_t)(pMsg->msg.info.handle);
dengyihao's avatar
dengyihao 已提交
752
  SExHandle* exh = transAcquireExHandle(refId);
dengyihao's avatar
dengyihao 已提交
753
  if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
754
    tDebug("%" PRId64 " already release", refId);
dengyihao's avatar
dengyihao 已提交
755 756 757
  }

  SCliConn* conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
758
  tDebug("%s conn %p start to release to inst", CONN_GET_INST_LABEL(conn), conn);
dengyihao's avatar
dengyihao 已提交
759

dengyihao's avatar
dengyihao 已提交
760 761
  if (T_REF_VAL_GET(conn) == 2) {
    transUnrefCliHandle(conn);
dengyihao's avatar
dengyihao 已提交
762 763
    if (!transQueuePush(&conn->cliMsgs, pMsg)) {
      return;
dengyihao's avatar
dengyihao 已提交
764 765
    }
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
766 767
  }
}
dengyihao's avatar
dengyihao 已提交
768
static void cliHandleUpdate(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
769
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
770
  pThrd->cvtAddr = pCtx->cvtAddr;
dengyihao's avatar
dengyihao 已提交
771 772
  destroyCmsg(pMsg);
}
U
ubuntu 已提交
773

dengyihao's avatar
dengyihao 已提交
774
SCliConn* cliGetConn(SCliMsg* pMsg, SCliThrd* pThrd, bool* ignore) {
dengyihao's avatar
dengyihao 已提交
775
  SCliConn* conn = NULL;
dengyihao's avatar
dengyihao 已提交
776 777
  int64_t   refId = (int64_t)(pMsg->msg.info.handle);
  if (refId != 0) {
dengyihao's avatar
dengyihao 已提交
778
    SExHandle* exh = transAcquireExHandle(refId);
dengyihao's avatar
dengyihao 已提交
779
    if (exh == NULL) {
dengyihao's avatar
dengyihao 已提交
780 781 782
      *ignore = true;
      destroyCmsg(pMsg);
      return NULL;
dengyihao's avatar
dengyihao 已提交
783 784
    } else {
      conn = exh->handle;
dengyihao's avatar
dengyihao 已提交
785
      transReleaseExHandle(refId);
dengyihao's avatar
dengyihao 已提交
786 787 788
    }
    return conn;
  };
dengyihao's avatar
dengyihao 已提交
789 790 791 792

  STransConnCtx* pCtx = pMsg->ctx;
  conn = getConnFromPool(pThrd->pool, EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet));
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
793
    tTrace("%s conn %p get from conn pool:%p", CONN_GET_INST_LABEL(conn), conn, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
794
  } else {
dengyihao's avatar
dengyihao 已提交
795
    tTrace("%s not found conn in conn pool:%p", ((STrans*)pThrd->pTransInst)->label, pThrd->pool);
dengyihao's avatar
dengyihao 已提交
796
  }
dengyihao's avatar
dengyihao 已提交
797 798
  return conn;
}
dengyihao's avatar
dengyihao 已提交
799 800 801 802 803 804 805 806 807 808 809
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 已提交
810
void cliHandleReq(SCliMsg* pMsg, SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
811
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
formate  
dengyihao 已提交
812
  STrans*        pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
813

dengyihao's avatar
dengyihao 已提交
814
  cliMayCvtFqdnToIp(&pCtx->epSet, &pThrd->cvtAddr);
dengyihao's avatar
dengyihao 已提交
815 816 817 818 819
  if (!EPSET_IS_VALID(&pCtx->epSet)) {
    destroyCmsg(pMsg);
    tError("invalid epset");
    return;
  }
dengyihao's avatar
dengyihao 已提交
820

dengyihao's avatar
dengyihao 已提交
821 822 823 824 825
  bool      ignore = false;
  SCliConn* conn = cliGetConn(pMsg, pThrd, &ignore);
  if (ignore == true) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
826
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
827
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
828
    transQueuePush(&conn->cliMsgs, pMsg);
U
ubuntu 已提交
829
    cliSend(conn);
dengyihao's avatar
dengyihao 已提交
830
  } else {
U
ubuntu 已提交
831
    conn = cliCreateConn(pThrd);
dengyihao's avatar
dengyihao 已提交
832
    transCtxMerge(&conn->ctx, &pCtx->appCtx);
dengyihao's avatar
dengyihao 已提交
833
    transQueuePush(&conn->cliMsgs, pMsg);
dengyihao's avatar
dengyihao 已提交
834

dengyihao's avatar
dengyihao 已提交
835 836
    conn->ip = strdup(EPSET_GET_INUSE_IP(&pCtx->epSet));
    conn->port = EPSET_GET_INUSE_PORT(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
837

dengyihao's avatar
dengyihao 已提交
838 839
    int ret = transSetConnOption((uv_tcp_t*)conn->stream);
    if (ret) {
dengyihao's avatar
dengyihao 已提交
840
      tError("%s conn %p failed to set conn option, errmsg %s", transLabel(pTransInst), conn, uv_err_name(ret));
dengyihao's avatar
dengyihao 已提交
841
    }
dengyihao's avatar
dengyihao 已提交
842
    int32_t fd = taosCreateSocketWithTimeout(TRANS_CONN_TIMEOUT);
dengyihao's avatar
dengyihao 已提交
843
    if (fd == -1) {
dengyihao's avatar
dengyihao 已提交
844
      tTrace("%s conn %p failed to create socket", transLabel(pTransInst), conn);
dengyihao's avatar
dengyihao 已提交
845 846 847 848
      cliHandleExcept(conn);
      return;
    }
    uv_tcp_open((uv_tcp_t*)conn->stream, fd);
849

dengyihao's avatar
dengyihao 已提交
850
    struct sockaddr_in addr;
851 852 853
    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 已提交
854
    tTrace("%s conn %p try to connect to %s:%d", pTransInst->label, conn, conn->ip, conn->port);
dengyihao's avatar
dengyihao 已提交
855 856
    ret = uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, cliConnCb);
    if (ret != 0) {
dengyihao's avatar
dengyihao 已提交
857
      tTrace("%s conn %p failed to connect to %s:%d, reason: %s", pTransInst->label, conn, conn->ip, conn->port,
dengyihao's avatar
dengyihao 已提交
858 859 860 861
             uv_err_name(ret));
      cliHandleExcept(conn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
862 863
  }
}
U
ubuntu 已提交
864
static void cliAsyncCb(uv_async_t* handle) {
dengyihao's avatar
dengyihao 已提交
865 866 867
  SAsyncItem* item = handle->data;
  SCliThrd*   pThrd = item->pThrd;
  SCliMsg*    pMsg = NULL;
dengyihao's avatar
dengyihao 已提交
868

dengyihao's avatar
dengyihao 已提交
869
  // batch process to avoid to lock/unlock frequently
dengyihao's avatar
formate  
dengyihao 已提交
870
  queue wq;
wafwerar's avatar
wafwerar 已提交
871
  taosThreadMutexLock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
872
  QUEUE_MOVE(&item->qmsg, &wq);
wafwerar's avatar
wafwerar 已提交
873
  taosThreadMutexUnlock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
874

dengyihao's avatar
dengyihao 已提交
875 876 877 878
  int count = 0;
  while (!QUEUE_IS_EMPTY(&wq)) {
    queue* h = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
879 880

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
881 882
    if (pMsg == NULL) {
      continue;
dengyihao's avatar
dengyihao 已提交
883
    }
dengyihao's avatar
dengyihao 已提交
884
    (*cliAsyncHandle[pMsg->type])(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
885
    count++;
dengyihao's avatar
dengyihao 已提交
886 887
  }
  if (count >= 2) {
U
ubuntu 已提交
888
    tTrace("cli process batch size: %d", count);
dengyihao's avatar
dengyihao 已提交
889
  }
dengyihao's avatar
dengyihao 已提交
890 891
}

U
ubuntu 已提交
892
static void* cliWorkThread(void* arg) {
dengyihao's avatar
dengyihao 已提交
893
  SCliThrd* pThrd = (SCliThrd*)arg;
dengyihao's avatar
dengyihao 已提交
894
  pThrd->pid = taosGetSelfPthreadId();
U
ubuntu 已提交
895
  setThreadName("trans-cli-work");
dengyihao's avatar
dengyihao 已提交
896
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
897
  return NULL;
dengyihao's avatar
dengyihao 已提交
898 899
}

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

dengyihao's avatar
dengyihao 已提交
903
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
904 905
  memcpy(cli->label, label, strlen(label));
  cli->numOfThreads = numOfThreads;
dengyihao's avatar
dengyihao 已提交
906
  cli->pThreadObj = (SCliThrd**)taosMemoryCalloc(cli->numOfThreads, sizeof(SCliThrd*));
dengyihao's avatar
dengyihao 已提交
907 908

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

wafwerar's avatar
wafwerar 已提交
913
    int err = taosThreadCreate(&pThrd->thread, NULL, cliWorkThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
914
    if (err == 0) {
U
ubuntu 已提交
915
      tDebug("success to create tranport-cli thread %d", i);
dengyihao's avatar
dengyihao 已提交
916
    }
dengyihao's avatar
dengyihao 已提交
917
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
918
  }
dengyihao's avatar
dengyihao 已提交
919

dengyihao's avatar
dengyihao 已提交
920 921
  return cli;
}
dengyihao's avatar
dengyihao 已提交
922

U
ubuntu 已提交
923
static void destroyUserdata(STransMsg* userdata) {
dengyihao's avatar
dengyihao 已提交
924 925 926 927 928 929 930 931 932 933 934 935
  if (userdata->pCont == NULL) {
    return;
  }
  transFreeMsg(userdata->pCont);
  userdata->pCont = NULL;
}
static void destroyCmsg(SCliMsg* pMsg) {
  if (pMsg == NULL) {
    return;
  }
  transDestroyConnCtx(pMsg->ctx);
  destroyUserdata(&pMsg->msg);
wafwerar's avatar
wafwerar 已提交
936
  taosMemoryFree(pMsg);
dengyihao's avatar
dengyihao 已提交
937
}
dengyihao's avatar
dengyihao 已提交
938

dengyihao's avatar
dengyihao 已提交
939 940
static SCliThrd* createThrdObj() {
  SCliThrd* pThrd = (SCliThrd*)taosMemoryCalloc(1, sizeof(SCliThrd));
U
ubuntu 已提交
941

dengyihao's avatar
dengyihao 已提交
942
  QUEUE_INIT(&pThrd->msg);
wafwerar's avatar
wafwerar 已提交
943
  taosThreadMutexInit(&pThrd->msgMtx, NULL);
dengyihao's avatar
dengyihao 已提交
944

wafwerar's avatar
wafwerar 已提交
945
  pThrd->loop = (uv_loop_t*)taosMemoryMalloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
946 947
  uv_loop_init(pThrd->loop);

U
ubuntu 已提交
948
  pThrd->asyncPool = transCreateAsyncPool(pThrd->loop, 5, pThrd, cliAsyncCb);
dengyihao's avatar
dengyihao 已提交
949 950
  uv_timer_init(pThrd->loop, &pThrd->timer);
  pThrd->timer.data = pThrd;
dengyihao's avatar
dengyihao 已提交
951

dengyihao's avatar
dengyihao 已提交
952
  pThrd->pool = createConnPool(4);
dengyihao's avatar
dengyihao 已提交
953
  transDQCreate(pThrd->loop, &pThrd->delayQueue);
dengyihao's avatar
dengyihao 已提交
954

dengyihao's avatar
dengyihao 已提交
955
  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
956 957
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
958
static void destroyThrdObj(SCliThrd* pThrd) {
dengyihao's avatar
dengyihao 已提交
959 960 961
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
962

wafwerar's avatar
wafwerar 已提交
963
  taosThreadJoin(pThrd->thread, NULL);
dengyihao's avatar
dengyihao 已提交
964
  CLI_RELEASE_UV(pThrd->loop);
wafwerar's avatar
wafwerar 已提交
965
  taosThreadMutexDestroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
966
  TRANS_DESTROY_ASYNC_POOL_MSG(pThrd->asyncPool, SCliMsg, destroyCmsg);
dengyihao's avatar
dengyihao 已提交
967
  transDestroyAsyncPool(pThrd->asyncPool);
dengyihao's avatar
dengyihao 已提交
968

dengyihao's avatar
dengyihao 已提交
969
  transDQDestroy(pThrd->delayQueue);
wafwerar's avatar
wafwerar 已提交
970 971
  taosMemoryFree(pThrd->loop);
  taosMemoryFree(pThrd);
dengyihao's avatar
dengyihao 已提交
972
}
dengyihao's avatar
dengyihao 已提交
973

dengyihao's avatar
dengyihao 已提交
974
static void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
975
  //
wafwerar's avatar
wafwerar 已提交
976
  taosMemoryFree(ctx);
dengyihao's avatar
dengyihao 已提交
977
}
dengyihao's avatar
dengyihao 已提交
978

dengyihao's avatar
dengyihao 已提交
979
void cliSendQuit(SCliThrd* thrd) {
dengyihao's avatar
dengyihao 已提交
980
  // cli can stop gracefully
wafwerar's avatar
wafwerar 已提交
981
  SCliMsg* msg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
982
  msg->type = Quit;
dengyihao's avatar
dengyihao 已提交
983
  transAsyncSend(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
984
}
dengyihao's avatar
dengyihao 已提交
985 986
void cliWalkCb(uv_handle_t* handle, void* arg) {
  if (!uv_is_closing(handle)) {
dengyihao's avatar
dengyihao 已提交
987
    uv_close(handle, cliDestroy);
dengyihao's avatar
dengyihao 已提交
988 989
  }
}
dengyihao's avatar
dengyihao 已提交
990

U
ubuntu 已提交
991
int cliRBChoseIdx(STrans* pTransInst) {
dengyihao's avatar
dengyihao 已提交
992 993 994 995
  int8_t index = pTransInst->index;
  if (pTransInst->numOfThreads == 0) {
    return -1;
  }
U
ubuntu 已提交
996 997 998 999 1000
  if (pTransInst->index++ >= pTransInst->numOfThreads) {
    pTransInst->index = 0;
  }
  return index % pTransInst->numOfThreads;
}
dengyihao's avatar
dengyihao 已提交
1001 1002
static void doDelayTask(void* param) {
  STaskArg* arg = param;
dengyihao's avatar
dengyihao 已提交
1003 1004
  SCliMsg*  pMsg = arg->param1;
  SCliThrd* pThrd = arg->param2;
dengyihao's avatar
dengyihao 已提交
1005 1006
  taosMemoryFree(arg);

dengyihao's avatar
dengyihao 已提交
1007
  cliHandleReq(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
1008
}
dengyihao's avatar
dengyihao 已提交
1009

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

dengyihao's avatar
dengyihao 已提交
1013 1014
  STraceId* trace = &pMsg->msg.info.traceId;
  char      tbuf[256] = {0};
dengyihao's avatar
dengyihao 已提交
1015
  EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
dengyihao's avatar
dengyihao 已提交
1016 1017
  tGTrace("%s retry on next node, use %s, retryCnt:%d, limit:%d", transLabel(pThrd->pTransInst), tbuf,
          pCtx->retryCnt + 1, pCtx->retryLimit);
dengyihao's avatar
dengyihao 已提交
1018 1019 1020 1021 1022

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

dengyihao's avatar
dengyihao 已提交
1025
void cliCompareAndSwap(int8_t* val, int8_t exp, int8_t newVal) {
dengyihao's avatar
dengyihao 已提交
1026 1027 1028 1029
  if (*val != exp) {
    *val = newVal;
  }
}
dengyihao's avatar
dengyihao 已提交
1030 1031

bool cliTryToExtractEpSet(STransMsg* pResp, SEpSet* dst) {
dengyihao's avatar
dengyihao 已提交
1032 1033 1034 1035 1036 1037
  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 已提交
1038 1039 1040 1041
    return false;
  }
  int32_t tlen = tSerializeSEpSet(NULL, 0, dst);

dengyihao's avatar
dengyihao 已提交
1042 1043 1044 1045 1046 1047 1048
  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 已提交
1049 1050

  pResp->pCont = buf;
dengyihao's avatar
dengyihao 已提交
1051 1052 1053
  pResp->contLen = len;

  *dst = epset;
dengyihao's avatar
dengyihao 已提交
1054 1055
  return true;
}
dengyihao's avatar
dengyihao 已提交
1056
int cliAppCb(SCliConn* pConn, STransMsg* pResp, SCliMsg* pMsg) {
dengyihao's avatar
dengyihao 已提交
1057 1058
  SCliThrd* pThrd = pConn->hostThrd;
  STrans*   pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
1059

dengyihao's avatar
dengyihao 已提交
1060
  if (pMsg == NULL || pMsg->ctx == NULL) {
dengyihao's avatar
dengyihao 已提交
1061
    tTrace("%s conn %p handle resp", pTransInst->label, pConn);
dengyihao's avatar
dengyihao 已提交
1062 1063 1064
    pTransInst->cfp(pTransInst->parent, pResp, NULL);
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
1065
  /*
dengyihao's avatar
dengyihao 已提交
1066 1067 1068
   *  no retry
   *  1. query conn
   *  2. rpc thread already receive quit msg
dengyihao's avatar
dengyihao 已提交
1069
   */
dengyihao's avatar
dengyihao 已提交
1070 1071
  STransConnCtx* pCtx = pMsg->ctx;
  int32_t        code = pResp->code;
dengyihao's avatar
dengyihao 已提交
1072 1073
  bool           retry = (pTransInst->retry != NULL && pTransInst->retry(code, pResp->msgType - 1)) ? true : false;
  if (retry) {
dengyihao's avatar
dengyihao 已提交
1074 1075 1076
    pMsg->sent = 0;
    pCtx->retryCnt += 1;
    if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
dengyihao's avatar
dengyihao 已提交
1077
      cliCompareAndSwap(&pCtx->retryLimit, TRANS_RETRY_COUNT_LIMIT, EPSET_GET_SIZE(&pCtx->epSet) * 3);
dengyihao's avatar
dengyihao 已提交
1078 1079 1080 1081 1082 1083 1084
      if (pCtx->retryCnt < pCtx->retryLimit) {
        transUnrefCliHandle(pConn);
        EPSET_FORWARD_INUSE(&pCtx->epSet);
        cliSchedMsgToNextNode(pMsg, pThrd);
        return -1;
      }
    } else {
dengyihao's avatar
dengyihao 已提交
1085
      cliCompareAndSwap(&pCtx->retryLimit, TRANS_RETRY_COUNT_LIMIT, TRANS_RETRY_COUNT_LIMIT);
dengyihao's avatar
dengyihao 已提交
1086 1087
      if (pCtx->retryCnt < pCtx->retryLimit) {
        if (pResp->contLen == 0) {
dengyihao's avatar
dengyihao 已提交
1088
          EPSET_FORWARD_INUSE(&pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1089
        } else {
dengyihao's avatar
dengyihao 已提交
1090 1091 1092
          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 已提交
1093
        }
dengyihao's avatar
dengyihao 已提交
1094
        addConnToPool(pThrd->pool, pConn);
dengyihao's avatar
dengyihao 已提交
1095 1096 1097
        transFreeMsg(pResp->pCont);
        cliSchedMsgToNextNode(pMsg, pThrd);
        return -1;
dengyihao's avatar
dengyihao 已提交
1098
      }
dengyihao's avatar
dengyihao 已提交
1099 1100
    }
  }
dengyihao's avatar
dengyihao 已提交
1101

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

dengyihao's avatar
dengyihao 已提交
1104 1105
  bool hasEpSet = cliTryToExtractEpSet(pResp, &pCtx->epSet);
  if (hasEpSet) {
dengyihao's avatar
dengyihao 已提交
1106 1107 1108 1109
    char tbuf[256] = {0};
    EPSET_DEBUG_STR(&pCtx->epSet, tbuf);
    tGTrace("%s conn %p extract epset from msg", CONN_GET_INST_LABEL(pConn), pConn);
  }
dengyihao's avatar
dengyihao 已提交
1110

dengyihao's avatar
dengyihao 已提交
1111
  if (pCtx->pSem != NULL) {
dengyihao's avatar
dengyihao 已提交
1112
    tGTrace("%s conn %p(sync) handle resp", CONN_GET_INST_LABEL(pConn), pConn);
1113
    if (pCtx->pRsp == NULL) {
dengyihao's avatar
dengyihao 已提交
1114
      tGTrace("%s conn %p(sync) failed to resp, ignore", CONN_GET_INST_LABEL(pConn), pConn);
1115 1116 1117
    } else {
      memcpy((char*)pCtx->pRsp, (char*)pResp, sizeof(*pResp));
    }
dengyihao's avatar
dengyihao 已提交
1118
    tsem_post(pCtx->pSem);
1119
    pCtx->pRsp = NULL;
dengyihao's avatar
dengyihao 已提交
1120
  } else {
dengyihao's avatar
dengyihao 已提交
1121
    tGTrace("%s conn %p handle resp", CONN_GET_INST_LABEL(pConn), pConn);
dengyihao's avatar
dengyihao 已提交
1122
    if (retry == false && hasEpSet == true) {
dengyihao's avatar
dengyihao 已提交
1123
      pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
dengyihao's avatar
dengyihao 已提交
1124 1125 1126 1127 1128 1129
    } else {
      if (!cliIsEpsetUpdated(code, pCtx)) {
        pTransInst->cfp(pTransInst->parent, pResp, NULL);
      } else {
        pTransInst->cfp(pTransInst->parent, pResp, &pCtx->epSet);
      }
dengyihao's avatar
dengyihao 已提交
1130
    }
dengyihao's avatar
dengyihao 已提交
1131
  }
dengyihao's avatar
dengyihao 已提交
1132
  return 0;
dengyihao's avatar
dengyihao 已提交
1133
}
U
ubuntu 已提交
1134 1135

void transCloseClient(void* arg) {
U
ubuntu 已提交
1136
  SCliObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
1137
  for (int i = 0; i < cli->numOfThreads; i++) {
U
ubuntu 已提交
1138
    cliSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1139
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
1140
  }
wafwerar's avatar
wafwerar 已提交
1141 1142
  taosMemoryFree(cli->pThreadObj);
  taosMemoryFree(cli);
dengyihao's avatar
dengyihao 已提交
1143
}
dengyihao's avatar
dengyihao 已提交
1144 1145 1146 1147 1148
void transRefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_INC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1149
  tTrace("%s conn %p ref %d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1150 1151 1152 1153 1154 1155 1156
  UNUSED(ref);
}
void transUnrefCliHandle(void* handle) {
  if (handle == NULL) {
    return;
  }
  int ref = T_REF_DEC((SCliConn*)handle);
dengyihao's avatar
dengyihao 已提交
1157
  tTrace("%s conn %p ref:%d", CONN_GET_INST_LABEL((SCliConn*)handle), handle, ref);
dengyihao's avatar
dengyihao 已提交
1158
  if (ref == 0) {
U
ubuntu 已提交
1159
    cliDestroyConn((SCliConn*)handle, true);
dengyihao's avatar
dengyihao 已提交
1160 1161
  }
}
dengyihao's avatar
dengyihao 已提交
1162 1163
SCliThrd* transGetWorkThrdFromHandle(int64_t handle) {
  SCliThrd*  pThrd = NULL;
dengyihao's avatar
dengyihao 已提交
1164
  SExHandle* exh = transAcquireExHandle(handle);
dengyihao's avatar
dengyihao 已提交
1165 1166 1167 1168
  if (exh == NULL) {
    return NULL;
  }
  pThrd = exh->pThrd;
dengyihao's avatar
dengyihao 已提交
1169
  transReleaseExHandle(handle);
dengyihao's avatar
dengyihao 已提交
1170 1171
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
1172
SCliThrd* transGetWorkThrd(STrans* trans, int64_t handle) {
dengyihao's avatar
dengyihao 已提交
1173
  if (handle == 0) {
dengyihao's avatar
dengyihao 已提交
1174
    int idx = cliRBChoseIdx(trans);
dengyihao's avatar
dengyihao 已提交
1175
    if (idx < 0) return NULL;
dengyihao's avatar
dengyihao 已提交
1176 1177 1178 1179
    return ((SCliObj*)trans->tcphandle)->pThreadObj[idx];
  }
  return transGetWorkThrdFromHandle(handle);
}
dengyihao's avatar
dengyihao 已提交
1180
void transReleaseCliHandle(void* handle) {
dengyihao's avatar
dengyihao 已提交
1181 1182
  int       idx = -1;
  SCliThrd* pThrd = transGetWorkThrdFromHandle((int64_t)handle);
dengyihao's avatar
dengyihao 已提交
1183
  if (pThrd == NULL) {
dengyihao's avatar
dengyihao 已提交
1184 1185
    return;
  }
S
Shengliang Guan 已提交
1186
  STransMsg tmsg = {.info.handle = handle};
wafwerar's avatar
wafwerar 已提交
1187
  SCliMsg*  cmsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1188
  cmsg->msg = tmsg;
dengyihao's avatar
dengyihao 已提交
1189
  cmsg->type = Release;
dengyihao's avatar
dengyihao 已提交
1190

dengyihao's avatar
dengyihao 已提交
1191
  transAsyncSend(pThrd->asyncPool, &cmsg->q);
dengyihao's avatar
dengyihao 已提交
1192
  return;
dengyihao's avatar
dengyihao 已提交
1193
}
dengyihao's avatar
dengyihao 已提交
1194

dengyihao's avatar
dengyihao 已提交
1195
void transSendRequest(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
1196 1197
  STrans*   pTransInst = (STrans*)shandle;
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
dengyihao's avatar
dengyihao 已提交
1198 1199 1200
  if (pThrd == NULL) {
    transFreeMsg(pReq->pCont);
    return;
dengyihao's avatar
dengyihao 已提交
1201 1202
  }

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

wafwerar's avatar
wafwerar 已提交
1205
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1206
  pCtx->epSet = *pEpSet;
S
Shengliang Guan 已提交
1207
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1208
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1209 1210 1211 1212

  if (ctx != NULL) {
    pCtx->appCtx = *ctx;
  }
dengyihao's avatar
dengyihao 已提交
1213
  assert(pTransInst->connType == TAOS_CONN_CLIENT);
dengyihao's avatar
dengyihao 已提交
1214

wafwerar's avatar
wafwerar 已提交
1215
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1216
  cliMsg->ctx = pCtx;
dengyihao's avatar
dengyihao 已提交
1217
  cliMsg->msg = *pReq;
dengyihao's avatar
dengyihao 已提交
1218
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1219
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1220

dengyihao's avatar
dengyihao 已提交
1221
  STraceId* trace = &pReq->info.traceId;
dengyihao's avatar
dengyihao 已提交
1222
  tGTrace("%s send request at thread:%08" PRId64 ", dst: %s:%d, app:%p", transLabel(pTransInst), pThrd->pid,
dengyihao's avatar
dengyihao 已提交
1223
          EPSET_GET_INUSE_IP(&pCtx->epSet), EPSET_GET_INUSE_PORT(&pCtx->epSet), pReq->info.ahandle);
dengyihao's avatar
dengyihao 已提交
1224
  ASSERT(transAsyncSend(pThrd->asyncPool, &(cliMsg->q)) == 0);
dengyihao's avatar
dengyihao 已提交
1225
  return;
dengyihao's avatar
dengyihao 已提交
1226
}
dengyihao's avatar
dengyihao 已提交
1227

dengyihao's avatar
dengyihao 已提交
1228
void transSendRecv(void* shandle, const SEpSet* pEpSet, STransMsg* pReq, STransMsg* pRsp) {
dengyihao's avatar
dengyihao 已提交
1229 1230
  STrans*   pTransInst = (STrans*)shandle;
  SCliThrd* pThrd = transGetWorkThrd(pTransInst, (int64_t)pReq->info.handle);
dengyihao's avatar
dengyihao 已提交
1231 1232 1233
  if (pThrd == NULL) {
    transFreeMsg(pReq->pCont);
    return;
dengyihao's avatar
dengyihao 已提交
1234
  }
dengyihao's avatar
dengyihao 已提交
1235 1236
  tsem_t* sem = taosMemoryCalloc(1, sizeof(tsem_t));
  tsem_init(sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
1237

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

wafwerar's avatar
wafwerar 已提交
1240
  STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1241
  pCtx->epSet = *pEpSet;
dengyihao's avatar
dengyihao 已提交
1242
  pCtx->origEpSet = *pEpSet;
S
Shengliang Guan 已提交
1243
  pCtx->ahandle = pReq->info.ahandle;
dengyihao's avatar
dengyihao 已提交
1244
  pCtx->msgType = pReq->msgType;
dengyihao's avatar
dengyihao 已提交
1245
  pCtx->pSem = sem;
dengyihao's avatar
dengyihao 已提交
1246 1247
  pCtx->pRsp = pRsp;

wafwerar's avatar
wafwerar 已提交
1248
  SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
dengyihao's avatar
dengyihao 已提交
1249 1250 1251
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pReq;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
1252
  cliMsg->type = Normal;
dengyihao's avatar
dengyihao 已提交
1253

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

dengyihao's avatar
dengyihao 已提交
1258
  transAsyncSend(pThrd->asyncPool, &(cliMsg->q));
dengyihao's avatar
dengyihao 已提交
1259 1260 1261
  tsem_wait(sem);
  tsem_destroy(sem);
  taosMemoryFree(sem);
dengyihao's avatar
dengyihao 已提交
1262
  return;
dengyihao's avatar
dengyihao 已提交
1263
}
dengyihao's avatar
dengyihao 已提交
1264 1265 1266
/*
 *
 **/
dengyihao's avatar
dengyihao 已提交
1267 1268
void transSetDefaultAddr(void* shandle, const char* ip, const char* fqdn) {
  STrans* pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
1269 1270 1271 1272 1273 1274 1275

  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 已提交
1276 1277
  for (int i = 0; i < pTransInst->numOfThreads; i++) {
    STransConnCtx* pCtx = taosMemoryCalloc(1, sizeof(STransConnCtx));
dengyihao's avatar
dengyihao 已提交
1278
    pCtx->cvtAddr = cvtAddr;
dengyihao's avatar
dengyihao 已提交
1279 1280 1281 1282 1283

    SCliMsg* cliMsg = taosMemoryCalloc(1, sizeof(SCliMsg));
    cliMsg->ctx = pCtx;
    cliMsg->type = Update;

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

dengyihao's avatar
dengyihao 已提交
1287
    transAsyncSend(thrd->asyncPool, &(cliMsg->q));
dengyihao's avatar
dengyihao 已提交
1288 1289
  }
}
dengyihao's avatar
dengyihao 已提交
1290
#endif