transCli.c 18.1 KB
Newer Older
dengyihao's avatar
dengyihao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * 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"

20
#define CONN_PERSIST_TIME(para) (para * 1000 * 10)
dengyihao's avatar
dengyihao 已提交
21

dengyihao's avatar
dengyihao 已提交
22 23 24
typedef struct SCliConn {
  uv_connect_t connReq;
  uv_stream_t* stream;
dengyihao's avatar
dengyihao 已提交
25
  uv_write_t*  writeReq;
dengyihao's avatar
dengyihao 已提交
26
  void*        hostThrd;
dengyihao's avatar
dengyihao 已提交
27
  SConnBuffer  readBuf;
dengyihao's avatar
dengyihao 已提交
28 29
  void*        data;
  queue        conn;
dengyihao's avatar
dengyihao 已提交
30 31
  char         spi;
  char         secured;
dengyihao's avatar
dengyihao 已提交
32
  uint64_t     expireTime;
dengyihao's avatar
dengyihao 已提交
33
  int8_t       notifyCount;  // timers already notify to client
dengyihao's avatar
dengyihao 已提交
34
  int32_t      ref;
dengyihao's avatar
dengyihao 已提交
35
} SCliConn;
dengyihao's avatar
dengyihao 已提交
36

dengyihao's avatar
dengyihao 已提交
37
typedef struct SCliMsg {
dengyihao's avatar
dengyihao 已提交
38 39 40 41
  STransConnCtx* ctx;
  SRpcMsg        msg;
  queue          q;
  uint64_t       st;
dengyihao's avatar
dengyihao 已提交
42 43 44
} SCliMsg;

typedef struct SCliThrdObj {
dengyihao's avatar
dengyihao 已提交
45 46 47 48
  pthread_t  thread;
  uv_loop_t* loop;
  // uv_async_t*     cliAsync;  //
  SAsyncPool*     asyncPool;
dengyihao's avatar
dengyihao 已提交
49
  uv_timer_t*     timer;
dengyihao's avatar
dengyihao 已提交
50
  void*           pool;  // conn pool
dengyihao's avatar
dengyihao 已提交
51 52
  queue           msg;
  pthread_mutex_t msgMtx;
dengyihao's avatar
dengyihao 已提交
53
  uint64_t        nextTimeout;  // next timeout
dengyihao's avatar
dengyihao 已提交
54
  void*           pTransInst;   //
dengyihao's avatar
dengyihao 已提交
55
  bool            quit;
dengyihao's avatar
dengyihao 已提交
56 57 58 59 60 61 62 63 64
} SCliThrdObj;

typedef struct SClientObj {
  char          label[TSDB_LABEL_LEN];
  int32_t       index;
  int           numOfThreads;
  SCliThrdObj** pThreadObj;
} SClientObj;

dengyihao's avatar
dengyihao 已提交
65 66 67 68
typedef struct SConnList {
  queue conn;
} SConnList;

dengyihao's avatar
dengyihao 已提交
69
// conn pool
dengyihao's avatar
dengyihao 已提交
70
// add expire timeout and capacity limit
71 72
static void*     creatConnPool(int size);
static void*     destroyConnPool(void* pool);
dengyihao's avatar
dengyihao 已提交
73 74
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port);
static void      addConnToPool(void* pool, char* ip, uint32_t port, SCliConn* conn);
dengyihao's avatar
dengyihao 已提交
75

dengyihao's avatar
dengyihao 已提交
76 77
// register timer in each thread to clear expire conn
static void clientTimeoutCb(uv_timer_t* handle);
dengyihao's avatar
dengyihao 已提交
78 79 80
// check whether already read complete packet from server
static bool clientReadComplete(SConnBuffer* pBuf);
// alloc buf for read
dengyihao's avatar
dengyihao 已提交
81
static void clientAllocBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
82
// callback after read nbytes from socket
dengyihao's avatar
dengyihao 已提交
83
static void clientReadCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf);
dengyihao's avatar
dengyihao 已提交
84
// callback after write data to socket
dengyihao's avatar
dengyihao 已提交
85
static void clientWriteCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
86
// callback after conn  to server
dengyihao's avatar
dengyihao 已提交
87
static void clientConnCb(uv_connect_t* req, int status);
dengyihao's avatar
dengyihao 已提交
88
static void clientAsyncCb(uv_async_t* handle);
dengyihao's avatar
dengyihao 已提交
89
static void clientDestroy(uv_handle_t* handle);
90
static void clientConnDestroy(SCliConn* pConn, bool clear /*clear tcp handle or not*/);
dengyihao's avatar
dengyihao 已提交
91

dengyihao's avatar
dengyihao 已提交
92 93 94 95
// process data read from server, auth/decompress etc later
static void clientHandleResp(SCliConn* conn);
// handle except about conn
static void clientHandleExcept(SCliConn* conn);
96 97
// handle req from app
static void clientHandleReq(SCliMsg* pMsg, SCliThrdObj* pThrd);
dengyihao's avatar
dengyihao 已提交
98 99
static void clientHandleQuit(SCliMsg* pMsg, SCliThrdObj* pThrd);
static void clientSendQuit(SCliThrdObj* thrd);
dengyihao's avatar
dengyihao 已提交
100

dengyihao's avatar
dengyihao 已提交
101 102 103 104
static void destroyUserdata(SRpcMsg* userdata);

static void destroyCmsg(SCliMsg* cmsg);
static void transDestroyConnCtx(STransConnCtx* ctx);
dengyihao's avatar
dengyihao 已提交
105 106 107 108
// thread obj
static SCliThrdObj* createThrdObj();
static void         destroyThrdObj(SCliThrdObj* pThrd);
// thread
dengyihao's avatar
dengyihao 已提交
109 110
static void* clientThread(void* arg);

111
static void clientHandleResp(SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
112 113
  SCliMsg*       pMsg = conn->data;
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
114
  SRpcInfo*      pRpc = pCtx->pTransInst;
dengyihao's avatar
dengyihao 已提交
115

dengyihao's avatar
dengyihao 已提交
116 117 118 119
  STransMsgHead* pHead = (STransMsgHead*)(conn->readBuf.buf);
  pHead->code = htonl(pHead->code);
  pHead->msgLen = htonl(pHead->msgLen);

dengyihao's avatar
dengyihao 已提交
120
  SRpcMsg rpcMsg;
dengyihao's avatar
dengyihao 已提交
121
  rpcMsg.contLen = transContLenFromMsg(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
122
  rpcMsg.pCont = transContFromHead((char*)pHead);
dengyihao's avatar
dengyihao 已提交
123 124
  rpcMsg.code = pHead->code;
  rpcMsg.msgType = pHead->msgType;
dengyihao's avatar
dengyihao 已提交
125
  rpcMsg.ahandle = pCtx->ahandle;
dengyihao's avatar
dengyihao 已提交
126

dengyihao's avatar
dengyihao 已提交
127
  tDebug("conn %p handle resp", conn);
dengyihao's avatar
dengyihao 已提交
128
  (pRpc->cfp)(NULL, &rpcMsg, NULL);
dengyihao's avatar
dengyihao 已提交
129
  conn->notifyCount += 1;
dengyihao's avatar
dengyihao 已提交
130

dengyihao's avatar
dengyihao 已提交
131
  // buf's mem alread translated to rpcMsg.pCont
dengyihao's avatar
dengyihao 已提交
132 133
  transClearBuffer(&conn->readBuf);

dengyihao's avatar
dengyihao 已提交
134
  uv_read_start((uv_stream_t*)conn->stream, clientAllocBufferCb, clientReadCb);
dengyihao's avatar
dengyihao 已提交
135 136

  SCliThrdObj* pThrd = conn->hostThrd;
dengyihao's avatar
dengyihao 已提交
137
  addConnToPool(pThrd->pool, pCtx->ip, pCtx->port, conn);
dengyihao's avatar
dengyihao 已提交
138

dengyihao's avatar
dengyihao 已提交
139 140
  destroyCmsg(pMsg);
  conn->data = NULL;
dengyihao's avatar
dengyihao 已提交
141
  // start thread's timer of conn pool if not active
dengyihao's avatar
dengyihao 已提交
142 143
  if (!uv_is_active((uv_handle_t*)pThrd->timer) && pRpc->idleTime > 0) {
    uv_timer_start((uv_timer_t*)pThrd->timer, clientTimeoutCb, CONN_PERSIST_TIME(pRpc->idleTime) / 2, 0);
dengyihao's avatar
dengyihao 已提交
144
  }
dengyihao's avatar
dengyihao 已提交
145 146
}
static void clientHandleExcept(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
147
  if (pConn->data == NULL) {
dengyihao's avatar
dengyihao 已提交
148
    // handle conn except in conn pool
dengyihao's avatar
dengyihao 已提交
149 150 151
    clientConnDestroy(pConn, true);
    return;
  }
dengyihao's avatar
dengyihao 已提交
152
  tDebug("conn %p start to destroy", pConn);
dengyihao's avatar
dengyihao 已提交
153
  SCliMsg* pMsg = pConn->data;
dengyihao's avatar
dengyihao 已提交
154 155

  destroyUserdata(&pMsg->msg);
dengyihao's avatar
dengyihao 已提交
156 157 158

  STransConnCtx* pCtx = pMsg->ctx;

dengyihao's avatar
dengyihao 已提交
159
  SRpcMsg rpcMsg = {0};
dengyihao's avatar
dengyihao 已提交
160
  rpcMsg.ahandle = pCtx->ahandle;
dengyihao's avatar
dengyihao 已提交
161
  rpcMsg.code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
dengyihao's avatar
dengyihao 已提交
162
  // SRpcInfo* pRpc = pMsg->ctx->pRpc;
dengyihao's avatar
dengyihao 已提交
163
  (pCtx->pTransInst->cfp)(NULL, &rpcMsg, NULL);
dengyihao's avatar
dengyihao 已提交
164
  pConn->notifyCount += 1;
dengyihao's avatar
dengyihao 已提交
165 166 167 168

  destroyCmsg(pMsg);
  pConn->data = NULL;
  // transDestroyConnCtx(pCtx);
dengyihao's avatar
dengyihao 已提交
169
  clientConnDestroy(pConn, true);
dengyihao's avatar
dengyihao 已提交
170
}
dengyihao's avatar
dengyihao 已提交
171

dengyihao's avatar
dengyihao 已提交
172 173
static void clientTimeoutCb(uv_timer_t* handle) {
  SCliThrdObj* pThrd = handle->data;
dengyihao's avatar
dengyihao 已提交
174
  SRpcInfo*    pRpc = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
175
  int64_t      currentTime = pThrd->nextTimeout;
dengyihao's avatar
dengyihao 已提交
176
  tDebug("timeout, try to remove expire conn from conn pool");
dengyihao's avatar
dengyihao 已提交
177

dengyihao's avatar
dengyihao 已提交
178
  SConnList* p = taosHashIterate((SHashObj*)pThrd->pool, NULL);
dengyihao's avatar
dengyihao 已提交
179 180 181 182 183 184
  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);
185 186 187
        // uv_stream_t stm = *(c->stream);
        // uv_close((uv_handle_t*)&stm, clientDestroy);
        clientConnDestroy(c, true);
dengyihao's avatar
dengyihao 已提交
188 189 190 191
      } else {
        break;
      }
    }
dengyihao's avatar
dengyihao 已提交
192
    p = taosHashIterate((SHashObj*)pThrd->pool, p);
dengyihao's avatar
dengyihao 已提交
193 194
  }

dengyihao's avatar
dengyihao 已提交
195 196
  pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pRpc->idleTime);
  uv_timer_start(handle, clientTimeoutCb, CONN_PERSIST_TIME(pRpc->idleTime) / 2, 0);
dengyihao's avatar
dengyihao 已提交
197
}
198 199 200
static void* creatConnPool(int size) {
  // thread local, no lock
  return taosHashInit(size, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
dengyihao's avatar
dengyihao 已提交
201
}
202
static void* destroyConnPool(void* pool) {
dengyihao's avatar
dengyihao 已提交
203
  SConnList* connList = taosHashIterate((SHashObj*)pool, NULL);
dengyihao's avatar
dengyihao 已提交
204 205 206 207 208
  while (connList != NULL) {
    while (!QUEUE_IS_EMPTY(&connList->conn)) {
      queue* h = QUEUE_HEAD(&connList->conn);
      QUEUE_REMOVE(h);
      SCliConn* c = QUEUE_DATA(h, SCliConn, conn);
209
      clientConnDestroy(c, true);
dengyihao's avatar
dengyihao 已提交
210
    }
dengyihao's avatar
dengyihao 已提交
211
    connList = taosHashIterate((SHashObj*)pool, connList);
dengyihao's avatar
dengyihao 已提交
212
  }
dengyihao's avatar
dengyihao 已提交
213
  taosHashClear(pool);
dengyihao's avatar
dengyihao 已提交
214 215
}

dengyihao's avatar
dengyihao 已提交
216
static SCliConn* getConnFromPool(void* pool, char* ip, uint32_t port) {
dengyihao's avatar
dengyihao 已提交
217 218 219 220
  char key[128] = {0};
  tstrncpy(key, ip, strlen(ip));
  tstrncpy(key + strlen(key), (char*)(&port), sizeof(port));

dengyihao's avatar
dengyihao 已提交
221 222
  SHashObj*  pPool = pool;
  SConnList* plist = taosHashGet(pPool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
223 224
  if (plist == NULL) {
    SConnList list;
dengyihao's avatar
dengyihao 已提交
225 226
    taosHashPut(pPool, key, strlen(key), (void*)&list, sizeof(list));
    plist = taosHashGet(pPool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
227
    QUEUE_INIT(&plist->conn);
dengyihao's avatar
dengyihao 已提交
228 229 230 231 232 233 234
  }

  if (QUEUE_IS_EMPTY(&plist->conn)) {
    return NULL;
  }
  queue* h = QUEUE_HEAD(&plist->conn);
  QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
235 236 237 238

  SCliConn* conn = QUEUE_DATA(h, SCliConn, conn);
  QUEUE_INIT(&conn->conn);
  return conn;
dengyihao's avatar
dengyihao 已提交
239
}
dengyihao's avatar
dengyihao 已提交
240
static void addConnToPool(void* pool, char* ip, uint32_t port, SCliConn* conn) {
dengyihao's avatar
dengyihao 已提交
241
  char key[128] = {0};
dengyihao's avatar
dengyihao 已提交
242

dengyihao's avatar
dengyihao 已提交
243 244
  tstrncpy(key, ip, strlen(ip));
  tstrncpy(key + strlen(key), (char*)(&port), sizeof(port));
dengyihao's avatar
dengyihao 已提交
245
  tDebug("conn %p added to conn pool, read buf cap: %d", conn, conn->readBuf.cap);
dengyihao's avatar
dengyihao 已提交
246

dengyihao's avatar
dengyihao 已提交
247
  SRpcInfo* pRpc = ((SCliThrdObj*)conn->hostThrd)->pTransInst;
dengyihao's avatar
dengyihao 已提交
248

dengyihao's avatar
dengyihao 已提交
249
  conn->expireTime = taosGetTimestampMs() + CONN_PERSIST_TIME(pRpc->idleTime);
dengyihao's avatar
dengyihao 已提交
250
  SConnList* plist = taosHashGet((SHashObj*)pool, key, strlen(key));
dengyihao's avatar
dengyihao 已提交
251
  conn->notifyCount = 0;
dengyihao's avatar
dengyihao 已提交
252 253 254 255
  // list already create before
  assert(plist != NULL);
  QUEUE_PUSH(&plist->conn, &conn->conn);
}
dengyihao's avatar
dengyihao 已提交
256 257 258 259 260 261 262 263 264
static bool clientReadComplete(SConnBuffer* data) {
  STransMsgHead head;
  int32_t       headLen = sizeof(head);
  if (data->len >= headLen) {
    memcpy((char*)&head, data->buf, headLen);
    int32_t msgLen = (int32_t)htonl((uint32_t)head.msgLen);
    if (msgLen > data->len) {
      data->left = msgLen - data->len;
      return false;
dengyihao's avatar
dengyihao 已提交
265 266
    } else if (msgLen == data->len) {
      data->left = 0;
dengyihao's avatar
dengyihao 已提交
267 268 269 270 271 272
      return true;
    }
  } else {
    return false;
  }
}
dengyihao's avatar
dengyihao 已提交
273
static void clientAllocBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
274 275
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
276
  transAllocBuffer(pBuf, buf);
dengyihao's avatar
dengyihao 已提交
277 278
}
static void clientReadCb(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
dengyihao's avatar
dengyihao 已提交
279
  // impl later
dengyihao's avatar
dengyihao 已提交
280 281
  SCliConn*    conn = handle->data;
  SConnBuffer* pBuf = &conn->readBuf;
dengyihao's avatar
dengyihao 已提交
282
  if (nread > 0) {
dengyihao's avatar
dengyihao 已提交
283 284
    pBuf->len += nread;
    if (clientReadComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
285
      uv_read_stop((uv_stream_t*)conn->stream);
286
      tDebug("conn %p read complete", conn);
287
      clientHandleResp(conn);
dengyihao's avatar
dengyihao 已提交
288
    } else {
289
      tDebug("conn %p read partial packet, continue to read", conn);
dengyihao's avatar
dengyihao 已提交
290
    }
dengyihao's avatar
dengyihao 已提交
291 292
    return;
  }
293 294
  assert(nread <= 0);
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
295 296 297
    // 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).
298 299
    return;
  }
dengyihao's avatar
dengyihao 已提交
300
  if (nread < 0 || nread == UV_EOF) {
301
    tError("conn %p read error: %s", conn, uv_err_name(nread));
dengyihao's avatar
dengyihao 已提交
302
    clientHandleExcept(conn);
dengyihao's avatar
dengyihao 已提交
303
  }
304 305
  // tDebug("Read error %s\n", uv_err_name(nread));
  // uv_close((uv_handle_t*)handle, clientDestroy);
dengyihao's avatar
dengyihao 已提交
306
}
dengyihao's avatar
dengyihao 已提交
307

308
static void clientConnDestroy(SCliConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
309
  //
dengyihao's avatar
dengyihao 已提交
310 311 312 313 314 315 316 317
  conn->ref--;
  if (conn->ref == 0) {
    tDebug("conn %p remove from conn pool", conn);
    QUEUE_REMOVE(&conn->conn);
    tDebug("conn %p remove from conn pool successfully", conn);
    if (clear) {
      uv_close((uv_handle_t*)conn->stream, clientDestroy);
    }
318
  }
dengyihao's avatar
dengyihao 已提交
319
}
dengyihao's avatar
dengyihao 已提交
320 321
static void clientDestroy(uv_handle_t* handle) {
  SCliConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
322
  // transDestroyBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
323 324 325 326 327 328 329

  free(conn->stream);
  free(conn->writeReq);
  tDebug("conn %p destroy successfully", conn);
  free(conn);

  // clientConnDestroy(conn, false);
dengyihao's avatar
dengyihao 已提交
330 331 332 333 334
}

static void clientWriteCb(uv_write_t* req, int status) {
  SCliConn* pConn = req->data;
  if (status == 0) {
335
    tDebug("conn %p data already was written out", pConn);
dengyihao's avatar
dengyihao 已提交
336
    SCliMsg* pMsg = pConn->data;
dengyihao's avatar
dengyihao 已提交
337
    if (pMsg == NULL) {
dengyihao's avatar
dengyihao 已提交
338 339
      // handle
      return;
dengyihao's avatar
dengyihao 已提交
340
    }
dengyihao's avatar
dengyihao 已提交
341
    destroyUserdata(&pMsg->msg);
dengyihao's avatar
dengyihao 已提交
342
  } else {
343
    tError("conn %p failed to write: %s", pConn, uv_err_name(status));
dengyihao's avatar
dengyihao 已提交
344
    clientHandleExcept(pConn);
dengyihao's avatar
dengyihao 已提交
345 346
    return;
  }
dengyihao's avatar
dengyihao 已提交
347
  SCliThrdObj* pThrd = pConn->hostThrd;
dengyihao's avatar
dengyihao 已提交
348
  uv_read_start((uv_stream_t*)pConn->stream, clientAllocBufferCb, clientReadCb);
dengyihao's avatar
dengyihao 已提交
349
}
dengyihao's avatar
dengyihao 已提交
350 351

static void clientWrite(SCliConn* pConn) {
dengyihao's avatar
dengyihao 已提交
352 353 354 355
  SCliMsg*       pCliMsg = pConn->data;
  SRpcMsg*       pMsg = (SRpcMsg*)(&pCliMsg->msg);
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);

dengyihao's avatar
dengyihao 已提交
356
  int msgLen = transMsgLenFromCont(pMsg->contLen);
dengyihao's avatar
dengyihao 已提交
357

dengyihao's avatar
dengyihao 已提交
358 359 360 361
  pHead->msgType = pMsg->msgType;
  pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);

  uv_buf_t wb = uv_buf_init((char*)pHead, msgLen);
362
  tDebug("conn %p data write out, msgType : %d, len: %d", pConn, pHead->msgType, msgLen);
dengyihao's avatar
dengyihao 已提交
363 364
  uv_write(pConn->writeReq, (uv_stream_t*)pConn->stream, &wb, 1, clientWriteCb);
}
dengyihao's avatar
dengyihao 已提交
365 366
static void clientConnCb(uv_connect_t* req, int status) {
  // impl later
dengyihao's avatar
dengyihao 已提交
367 368
  SCliConn* pConn = req->data;
  if (status != 0) {
dengyihao's avatar
dengyihao 已提交
369
    // tError("failed to connect server(%s, %d), errmsg: %s", pCtx->ip, pCtx->port, uv_strerror(status));
370
    tError("conn %p failed to connect server: %s", pConn, uv_strerror(status));
dengyihao's avatar
dengyihao 已提交
371
    clientHandleExcept(pConn);
372
    return;
dengyihao's avatar
dengyihao 已提交
373
  }
374
  tDebug("conn %p create", pConn);
dengyihao's avatar
dengyihao 已提交
375

dengyihao's avatar
dengyihao 已提交
376
  assert(pConn->stream == req->handle);
dengyihao's avatar
dengyihao 已提交
377
  clientWrite(pConn);
dengyihao's avatar
dengyihao 已提交
378 379
}

dengyihao's avatar
dengyihao 已提交
380 381 382
static void clientHandleQuit(SCliMsg* pMsg, SCliThrdObj* pThrd) {
  tDebug("thread %p start to quit", pThrd);
  destroyCmsg(pMsg);
dengyihao's avatar
dengyihao 已提交
383
  // transDestroyAsyncPool(pThr) uv_close((uv_handle_t*)pThrd->cliAsync, NULL);
dengyihao's avatar
dengyihao 已提交
384 385 386 387 388
  uv_timer_stop(pThrd->timer);
  pThrd->quit = true;
  // uv__async_stop(pThrd->cliAsync);
  uv_stop(pThrd->loop);
}
dengyihao's avatar
dengyihao 已提交
389
static void clientHandleReq(SCliMsg* pMsg, SCliThrdObj* pThrd) {
dengyihao's avatar
dengyihao 已提交
390 391
  uint64_t et = taosGetTimestampUs();
  uint64_t el = et - pMsg->st;
dengyihao's avatar
dengyihao 已提交
392
  tDebug("msg tran time cost: %" PRIu64 "", el);
dengyihao's avatar
dengyihao 已提交
393
  et = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
394

dengyihao's avatar
dengyihao 已提交
395
  STransConnCtx* pCtx = pMsg->ctx;
dengyihao's avatar
dengyihao 已提交
396
  SCliConn*      conn = getConnFromPool(pThrd->pool, pCtx->ip, pCtx->port);
dengyihao's avatar
dengyihao 已提交
397
  if (conn != NULL) {
dengyihao's avatar
dengyihao 已提交
398
    // impl later
399
    tDebug("conn %p get from conn pool", conn);
dengyihao's avatar
dengyihao 已提交
400 401
    conn->data = pMsg;
    conn->writeReq->data = conn;
dengyihao's avatar
dengyihao 已提交
402
    transDestroyBuffer(&conn->readBuf);
dengyihao's avatar
dengyihao 已提交
403 404 405 406 407

    if (pThrd->quit) {
      clientHandleExcept(conn);
      return;
    }
dengyihao's avatar
dengyihao 已提交
408
    clientWrite(conn);
dengyihao's avatar
dengyihao 已提交
409

dengyihao's avatar
dengyihao 已提交
410
  } else {
dengyihao's avatar
dengyihao 已提交
411
    SCliConn* conn = calloc(1, sizeof(SCliConn));
dengyihao's avatar
dengyihao 已提交
412
    conn->ref++;
dengyihao's avatar
dengyihao 已提交
413
    // read/write stream handle
dengyihao's avatar
dengyihao 已提交
414 415
    conn->stream = (uv_stream_t*)malloc(sizeof(uv_tcp_t));
    uv_tcp_init(pThrd->loop, (uv_tcp_t*)(conn->stream));
dengyihao's avatar
dengyihao 已提交
416 417 418
    conn->stream->data = conn;

    // write req handle
dengyihao's avatar
dengyihao 已提交
419
    conn->writeReq = malloc(sizeof(uv_write_t));
dengyihao's avatar
dengyihao 已提交
420
    conn->writeReq->data = conn;
dengyihao's avatar
dengyihao 已提交
421

dengyihao's avatar
dengyihao 已提交
422
    QUEUE_INIT(&conn->conn);
dengyihao's avatar
dengyihao 已提交
423 424 425

    conn->connReq.data = conn;
    conn->data = pMsg;
dengyihao's avatar
dengyihao 已提交
426
    conn->hostThrd = pThrd;
dengyihao's avatar
dengyihao 已提交
427

dengyihao's avatar
dengyihao 已提交
428
    struct sockaddr_in addr;
dengyihao's avatar
dengyihao 已提交
429
    uv_ip4_addr(pMsg->ctx->ip, pMsg->ctx->port, &addr);
dengyihao's avatar
dengyihao 已提交
430
    // handle error in callback if fail to connect
dengyihao's avatar
dengyihao 已提交
431
    uv_tcp_connect(&conn->connReq, (uv_tcp_t*)(conn->stream), (const struct sockaddr*)&addr, clientConnCb);
dengyihao's avatar
dengyihao 已提交
432 433 434
  }
}
static void clientAsyncCb(uv_async_t* handle) {
dengyihao's avatar
dengyihao 已提交
435 436
  SAsyncItem*  item = handle->data;
  SCliThrdObj* pThrd = item->pThrd;
dengyihao's avatar
dengyihao 已提交
437 438
  SCliMsg*     pMsg = NULL;
  queue        wq;
dengyihao's avatar
dengyihao 已提交
439

dengyihao's avatar
dengyihao 已提交
440
  // batch process to avoid to lock/unlock frequently
dengyihao's avatar
dengyihao 已提交
441 442 443
  pthread_mutex_lock(&item->mtx);
  QUEUE_MOVE(&item->qmsg, &wq);
  pthread_mutex_unlock(&item->mtx);
dengyihao's avatar
dengyihao 已提交
444

dengyihao's avatar
dengyihao 已提交
445 446 447 448
  int count = 0;
  while (!QUEUE_IS_EMPTY(&wq)) {
    queue* h = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(h);
dengyihao's avatar
dengyihao 已提交
449 450

    SCliMsg* pMsg = QUEUE_DATA(h, SCliMsg, q);
dengyihao's avatar
dengyihao 已提交
451 452 453 454 455 456
    if (pMsg->ctx == NULL) {
      clientHandleQuit(pMsg, pThrd);
    } else {
      clientHandleReq(pMsg, pThrd);
    }
    // clientHandleReq(pMsg, pThrd);
dengyihao's avatar
dengyihao 已提交
457
    count++;
dengyihao's avatar
dengyihao 已提交
458 459 460
  }
  if (count >= 2) {
    tDebug("already process batch size: %d", count);
dengyihao's avatar
dengyihao 已提交
461
  }
dengyihao's avatar
dengyihao 已提交
462 463 464 465 466 467 468 469 470
}

static void* clientThread(void* arg) {
  SCliThrdObj* pThrd = (SCliThrdObj*)arg;
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
}

void* taosInitClient(uint32_t ip, uint32_t port, char* label, int numOfThreads, void* fp, void* shandle) {
  SClientObj* cli = calloc(1, sizeof(SClientObj));
dengyihao's avatar
dengyihao 已提交
471

dengyihao's avatar
dengyihao 已提交
472
  SRpcInfo* pRpc = shandle;
dengyihao's avatar
dengyihao 已提交
473 474 475 476 477
  memcpy(cli->label, label, strlen(label));
  cli->numOfThreads = numOfThreads;
  cli->pThreadObj = (SCliThrdObj**)calloc(cli->numOfThreads, sizeof(SCliThrdObj*));

  for (int i = 0; i < cli->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
478
    SCliThrdObj* pThrd = createThrdObj();
dengyihao's avatar
dengyihao 已提交
479
    pThrd->nextTimeout = taosGetTimestampMs() + CONN_PERSIST_TIME(pRpc->idleTime);
dengyihao's avatar
dengyihao 已提交
480
    pThrd->pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
481

dengyihao's avatar
dengyihao 已提交
482
    int err = pthread_create(&pThrd->thread, NULL, clientThread, (void*)(pThrd));
dengyihao's avatar
dengyihao 已提交
483
    if (err == 0) {
dengyihao's avatar
dengyihao 已提交
484
      tDebug("success to create tranport-client thread %d", i);
dengyihao's avatar
dengyihao 已提交
485
    }
dengyihao's avatar
dengyihao 已提交
486
    cli->pThreadObj[i] = pThrd;
dengyihao's avatar
dengyihao 已提交
487 488 489
  }
  return cli;
}
dengyihao's avatar
dengyihao 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503

static void destroyUserdata(SRpcMsg* userdata) {
  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);
dengyihao's avatar
dengyihao 已提交
504 505
  free(pMsg);
}
dengyihao's avatar
dengyihao 已提交
506

dengyihao's avatar
dengyihao 已提交
507 508 509 510 511 512 513 514
static SCliThrdObj* createThrdObj() {
  SCliThrdObj* pThrd = (SCliThrdObj*)calloc(1, sizeof(SCliThrdObj));
  QUEUE_INIT(&pThrd->msg);
  pthread_mutex_init(&pThrd->msgMtx, NULL);

  pThrd->loop = (uv_loop_t*)malloc(sizeof(uv_loop_t));
  uv_loop_init(pThrd->loop);

dengyihao's avatar
dengyihao 已提交
515
  pThrd->asyncPool = transCreateAsyncPool(pThrd->loop, pThrd, clientAsyncCb);
dengyihao's avatar
dengyihao 已提交
516

dengyihao's avatar
dengyihao 已提交
517 518 519
  pThrd->timer = malloc(sizeof(uv_timer_t));
  uv_timer_init(pThrd->loop, pThrd->timer);
  pThrd->timer->data = pThrd;
dengyihao's avatar
dengyihao 已提交
520

521
  pThrd->pool = creatConnPool(1);
dengyihao's avatar
dengyihao 已提交
522 523

  pThrd->quit = false;
dengyihao's avatar
dengyihao 已提交
524 525
  return pThrd;
}
dengyihao's avatar
dengyihao 已提交
526
static void destroyThrdObj(SCliThrdObj* pThrd) {
dengyihao's avatar
dengyihao 已提交
527 528 529
  if (pThrd == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
530
  uv_stop(pThrd->loop);
dengyihao's avatar
dengyihao 已提交
531 532
  pthread_join(pThrd->thread, NULL);
  pthread_mutex_destroy(&pThrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
533 534
  transDestroyAsyncPool(pThrd->asyncPool);
  // free(pThrd->cliAsync);
dengyihao's avatar
dengyihao 已提交
535
  free(pThrd->timer);
dengyihao's avatar
dengyihao 已提交
536 537 538
  free(pThrd->loop);
  free(pThrd);
}
dengyihao's avatar
dengyihao 已提交
539

dengyihao's avatar
dengyihao 已提交
540
static void transDestroyConnCtx(STransConnCtx* ctx) {
dengyihao's avatar
dengyihao 已提交
541 542 543 544 545
  if (ctx != NULL) {
    free(ctx->ip);
  }
  free(ctx);
}
dengyihao's avatar
dengyihao 已提交
546
//
dengyihao's avatar
dengyihao 已提交
547 548 549 550 551
static void clientSendQuit(SCliThrdObj* thrd) {
  // cli can stop gracefully
  SCliMsg* msg = calloc(1, sizeof(SCliMsg));
  msg->ctx = NULL;  //

dengyihao's avatar
dengyihao 已提交
552 553 554
  // pthread_mutex_lock(&thrd->msgMtx);
  // QUEUE_PUSH(&thrd->msg, &msg->q);
  // pthread_mutex_unlock(&thrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
555

dengyihao's avatar
dengyihao 已提交
556
  transSendAsync(thrd->asyncPool, &msg->q);
dengyihao's avatar
dengyihao 已提交
557
  // uv_async_send(thrd->cliAsync);
dengyihao's avatar
dengyihao 已提交
558
}
dengyihao's avatar
dengyihao 已提交
559 560 561
void taosCloseClient(void* arg) {
  // impl later
  SClientObj* cli = arg;
dengyihao's avatar
dengyihao 已提交
562
  for (int i = 0; i < cli->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
563
    clientSendQuit(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
564
    destroyThrdObj(cli->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
565 566 567
  }
  free(cli->pThreadObj);
  free(cli);
dengyihao's avatar
dengyihao 已提交
568
}
dengyihao's avatar
dengyihao 已提交
569 570
void rpcSendRequest(void* shandle, const SEpSet* pEpSet, SRpcMsg* pMsg, int64_t* pRid) {
  // impl later
dengyihao's avatar
dengyihao 已提交
571 572 573
  char*    ip = (char*)(pEpSet->fqdn[pEpSet->inUse]);
  uint32_t port = pEpSet->port[pEpSet->inUse];

dengyihao's avatar
dengyihao 已提交
574 575
  SRpcInfo* pRpc = (SRpcInfo*)shandle;

dengyihao's avatar
dengyihao 已提交
576 577 578 579
  int32_t flen = 0;
  if (transCompressMsg(pMsg->pCont, pMsg->contLen, &flen)) {
    // imp later
  }
dengyihao's avatar
dengyihao 已提交
580

dengyihao's avatar
dengyihao 已提交
581 582
  STransConnCtx* pCtx = calloc(1, sizeof(STransConnCtx));

dengyihao's avatar
dengyihao 已提交
583
  pCtx->pTransInst = (SRpcInfo*)shandle;
dengyihao's avatar
dengyihao 已提交
584 585 586 587
  pCtx->ahandle = pMsg->ahandle;
  pCtx->msgType = pMsg->msgType;
  pCtx->ip = strdup(ip);
  pCtx->port = port;
dengyihao's avatar
dengyihao 已提交
588 589 590 591 592 593 594

  assert(pRpc->connType == TAOS_CONN_CLIENT);
  // atomic or not
  int64_t index = pRpc->index;
  if (pRpc->index++ >= pRpc->numOfThreads) {
    pRpc->index = 0;
  }
dengyihao's avatar
dengyihao 已提交
595 596 597 598
  SCliMsg* cliMsg = malloc(sizeof(SCliMsg));
  cliMsg->ctx = pCtx;
  cliMsg->msg = *pMsg;
  cliMsg->st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
599 600 601

  SCliThrdObj* thrd = ((SClientObj*)pRpc->tcphandle)->pThreadObj[index % pRpc->numOfThreads];

dengyihao's avatar
dengyihao 已提交
602 603 604
  // pthread_mutex_lock(&thrd->msgMtx);
  // QUEUE_PUSH(&thrd->msg, &cliMsg->q);
  // pthread_mutex_unlock(&thrd->msgMtx);
dengyihao's avatar
dengyihao 已提交
605

dengyihao's avatar
dengyihao 已提交
606 607
  // int start = taosGetTimestampUs();
  transSendAsync(thrd->asyncPool, &(cliMsg->q));
dengyihao's avatar
dengyihao 已提交
608
  // uv_async_send(thrd->cliAsync);
dengyihao's avatar
dengyihao 已提交
609
  // int end = taosGetTimestampUs() - start;
dengyihao's avatar
dengyihao 已提交
610
  // tError("client sent to rpc, time cost: %d", (int)end);
dengyihao's avatar
dengyihao 已提交
611 612
}
#endif