transSrv.c 18.8 KB
Newer Older
dengyihao's avatar
dengyihao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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

18
#include "transComm.h"
dengyihao's avatar
dengyihao 已提交
19

dengyihao's avatar
dengyihao 已提交
20 21 22 23 24 25 26 27
typedef struct SConn {
  uv_tcp_t*   pTcp;
  uv_write_t* pWriter;
  uv_timer_t* pTimer;

  uv_async_t* pWorkerAsync;
  queue       queue;
  int         ref;
dengyihao's avatar
dengyihao 已提交
28 29
  int         persist;  // persist connection or not
  SConnBuffer connBuf;  // read buf,
dengyihao's avatar
dengyihao 已提交
30
  int         count;
dengyihao's avatar
dengyihao 已提交
31 32 33
  int         inType;
  void*       pTransInst;  // rpc init
  void*       ahandle;     //
dengyihao's avatar
dengyihao 已提交
34
  void*       hostThrd;
dengyihao's avatar
dengyihao 已提交
35 36

  SRpcMsg sendMsg;
dengyihao's avatar
dengyihao 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  // del later
  char secured;
  int  spi;
  char info[64];
  char user[TSDB_UNI_LEN];  // user ID for the link
  char secret[TSDB_PASSWORD_LEN];
  char ckey[TSDB_PASSWORD_LEN];  // ciphering key
} SConn;

typedef struct SWorkThrdObj {
  pthread_t       thread;
  uv_pipe_t*      pipe;
  int             fd;
  uv_loop_t*      loop;
  uv_async_t*     workerAsync;  //
  queue           conn;
  pthread_mutex_t connMtx;
dengyihao's avatar
dengyihao 已提交
54
  void*           pTransInst;
dengyihao's avatar
dengyihao 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
} SWorkThrdObj;

typedef struct SServerObj {
  pthread_t      thread;
  uv_tcp_t       server;
  uv_loop_t*     loop;
  int            workerIdx;
  int            numOfThreads;
  SWorkThrdObj** pThreadObj;
  uv_pipe_t**    pipe;
  uint32_t       ip;
  uint32_t       port;
} SServerObj;

static const char* notify = "a";

// refactor later
dengyihao's avatar
dengyihao 已提交
72
static int transAddAuthPart(SConn* pConn, char* msg, int msgLen);
dengyihao's avatar
dengyihao 已提交
73 74 75 76 77 78 79 80

static int uvAuthMsg(SConn* pConn, char* msg, int msgLen);

static void uvAllocConnBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
static void uvAllocReadBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
static void uvOnReadCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf);
static void uvOnTimeoutCb(uv_timer_t* handle);
static void uvOnWriteCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
81
static void uvOnPipeWriteCb(uv_write_t* req, int status);
dengyihao's avatar
dengyihao 已提交
82 83 84 85
static void uvOnAcceptCb(uv_stream_t* stream, int status);
static void uvOnConnectionCb(uv_stream_t* q, ssize_t nread, const uv_buf_t* buf);
static void uvWorkerAsyncCb(uv_async_t* handle);

dengyihao's avatar
dengyihao 已提交
86 87
static void uvPrepareSendData(SConn* conn, uv_buf_t* wb);

88 89 90 91
// check whether already read complete packet
static bool   readComplete(SConnBuffer* buf);
static SConn* createConn();
static void   destroyConn(SConn* conn, bool clear /*clear handle or not*/);
dengyihao's avatar
dengyihao 已提交
92

93
static void uvDestroyConn(uv_handle_t* handle);
dengyihao's avatar
dengyihao 已提交
94

dengyihao's avatar
dengyihao 已提交
95
// server and worker thread
dengyihao's avatar
dengyihao 已提交
96 97 98
static void* workerThread(void* arg);
static void* acceptThread(void* arg);

dengyihao's avatar
dengyihao 已提交
99 100 101 102
// add handle loop
static bool addHandleToWorkloop(void* arg);
static bool addHandleToAcceptloop(void* arg);

dengyihao's avatar
dengyihao 已提交
103 104 105
void uvAllocReadBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
  /*
   * formate of data buffer:
dengyihao's avatar
dengyihao 已提交
106 107
   * |<--------------------------data from socket------------------------------->|
   * |<------STransMsgHead------->|<-------------------other data--------------->|
dengyihao's avatar
dengyihao 已提交
108 109 110 111 112 113
   */
  static const int CAPACITY = 1024;

  SConn*       conn = handle->data;
  SConnBuffer* pBuf = &conn->connBuf;
  if (pBuf->cap == 0) {
dengyihao's avatar
dengyihao 已提交
114
    pBuf->buf = (char*)calloc(CAPACITY, sizeof(char));
dengyihao's avatar
dengyihao 已提交
115 116 117 118
    pBuf->len = 0;
    pBuf->cap = CAPACITY;
    pBuf->left = -1;

dengyihao's avatar
dengyihao 已提交
119
    buf->base = pBuf->buf;
dengyihao's avatar
dengyihao 已提交
120 121 122 123 124
    buf->len = CAPACITY;
  } else {
    if (pBuf->len >= pBuf->cap) {
      if (pBuf->left == -1) {
        pBuf->cap *= 2;
dengyihao's avatar
dengyihao 已提交
125
        pBuf->buf = realloc(pBuf->buf, pBuf->cap);
dengyihao's avatar
dengyihao 已提交
126 127
      } else if (pBuf->len + pBuf->left > pBuf->cap) {
        pBuf->cap = pBuf->len + pBuf->left;
dengyihao's avatar
dengyihao 已提交
128
        pBuf->buf = realloc(pBuf->buf, pBuf->len + pBuf->left);
dengyihao's avatar
dengyihao 已提交
129 130
      }
    }
dengyihao's avatar
dengyihao 已提交
131
    buf->base = pBuf->buf + pBuf->len;
dengyihao's avatar
dengyihao 已提交
132 133 134 135 136 137 138 139
    buf->len = pBuf->cap - pBuf->len;
  }
}

// check data read from socket completely or not
//
static bool readComplete(SConnBuffer* data) {
  // TODO(yihao): handle pipeline later
dengyihao's avatar
dengyihao 已提交
140 141
  STransMsgHead head;
  int32_t       headLen = sizeof(head);
dengyihao's avatar
dengyihao 已提交
142
  if (data->len >= headLen) {
dengyihao's avatar
dengyihao 已提交
143 144
    memcpy((char*)&head, data->buf, headLen);
    int32_t msgLen = (int32_t)htonl((uint32_t)head.msgLen);
dengyihao's avatar
dengyihao 已提交
145 146 147
    if (msgLen > data->len) {
      data->left = msgLen - data->len;
      return false;
dengyihao's avatar
dengyihao 已提交
148
    } else if (msgLen == data->len) {
dengyihao's avatar
dengyihao 已提交
149
      return true;
dengyihao's avatar
dengyihao 已提交
150 151 152
    } else if (msgLen < data->len) {
      return false;
      // handle other packet later
dengyihao's avatar
dengyihao 已提交
153 154 155 156 157 158
    }
  } else {
    return false;
  }
}

dengyihao's avatar
dengyihao 已提交
159 160 161 162 163 164 165 166 167 168 169
// static void uvDoProcess(SRecvInfo* pRecv) {
//  // impl later
//  STransMsgHead* pHead = (STransMsgHead*)pRecv->msg;
//  SRpcInfo*      pRpc = (SRpcInfo*)pRecv->shandle;
//  SConn*         pConn = pRecv->thandle;
//  tDump(pRecv->msg, pRecv->msgLen);
//  terrno = 0;
//  // SRpcReqContext* pContest;
//
//  // do auth and check
//}
dengyihao's avatar
dengyihao 已提交
170 171

static int uvAuthMsg(SConn* pConn, char* msg, int len) {
dengyihao's avatar
dengyihao 已提交
172 173 174
  STransMsgHead* pHead = (STransMsgHead*)msg;

  int code = 0;
dengyihao's avatar
dengyihao 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

  if ((pConn->secured && pHead->spi == 0) || (pHead->spi == 0 && pConn->spi == 0)) {
    // secured link, or no authentication
    pHead->msgLen = (int32_t)htonl((uint32_t)pHead->msgLen);
    // tTrace("%s, secured link, no auth is required", pConn->info);
    return 0;
  }

  if (!rpcIsReq(pHead->msgType)) {
    // for response, if code is auth failure, it shall bypass the auth process
    code = htonl(pHead->code);
    if (code == TSDB_CODE_RPC_INVALID_TIME_STAMP || code == TSDB_CODE_RPC_AUTH_FAILURE ||
        code == TSDB_CODE_RPC_INVALID_VERSION || code == TSDB_CODE_RPC_AUTH_REQUIRED ||
        code == TSDB_CODE_MND_USER_NOT_EXIST || code == TSDB_CODE_RPC_NOT_READY) {
      pHead->msgLen = (int32_t)htonl((uint32_t)pHead->msgLen);
      // tTrace("%s, dont check authentication since code is:0x%x", pConn->info, code);
      return 0;
    }
  }

  code = 0;
  if (pHead->spi == pConn->spi) {
    // authentication
    SRpcDigest* pDigest = (SRpcDigest*)((char*)pHead + len - sizeof(SRpcDigest));

    int32_t delta;
    delta = (int32_t)htonl(pDigest->timeStamp);
    delta -= (int32_t)taosGetTimestampSec();
    if (abs(delta) > 900) {
      tWarn("%s, time diff:%d is too big, msg discarded", pConn->info, delta);
      code = TSDB_CODE_RPC_INVALID_TIME_STAMP;
    } else {
      if (rpcAuthenticateMsg(pHead, len - TSDB_AUTH_LEN, pDigest->auth, pConn->secret) < 0) {
        // tDebug("%s, authentication failed, msg discarded", pConn->info);
        code = TSDB_CODE_RPC_AUTH_FAILURE;
      } else {
        pHead->msgLen = (int32_t)htonl((uint32_t)pHead->msgLen) - sizeof(SRpcDigest);
        if (!rpcIsReq(pHead->msgType)) pConn->secured = 1;  // link is secured for client
        // tTrace("%s, message is authenticated", pConn->info);
      }
    }
  } else {
    tDebug("%s, auth spi:%d not matched with received:%d", pConn->info, pConn->spi, pHead->spi);
    code = pHead->spi ? TSDB_CODE_RPC_AUTH_FAILURE : TSDB_CODE_RPC_AUTH_REQUIRED;
  }

  return code;
}

// refers specifically to query or insert timeout
static void uvHandleActivityTimeout(uv_timer_t* handle) {
  SConn* conn = handle->data;
dengyihao's avatar
dengyihao 已提交
227
  tDebug("%p timeout since no activity", conn);
dengyihao's avatar
dengyihao 已提交
228 229
}

dengyihao's avatar
dengyihao 已提交
230
static void uvHandleReq(SConn* pConn) {
dengyihao's avatar
dengyihao 已提交
231 232 233
  SRecvInfo    info;
  SRecvInfo*   p = &info;
  SConnBuffer* pBuf = &pConn->connBuf;
dengyihao's avatar
dengyihao 已提交
234
  p->msg = pBuf->buf;
dengyihao's avatar
dengyihao 已提交
235 236 237
  p->msgLen = pBuf->len;
  p->ip = 0;
  p->port = 0;
dengyihao's avatar
dengyihao 已提交
238
  p->shandle = pConn->pTransInst;  //
dengyihao's avatar
dengyihao 已提交
239 240 241
  p->thandle = pConn;
  p->chandle = NULL;

dengyihao's avatar
dengyihao 已提交
242
  STransMsgHead* pHead = (STransMsgHead*)p->msg;
dengyihao's avatar
dengyihao 已提交
243 244

  pConn->inType = pHead->msgType;
dengyihao's avatar
dengyihao 已提交
245
  assert(transIsReq(pHead->msgType));
dengyihao's avatar
dengyihao 已提交
246 247 248

  SRpcInfo* pRpc = (SRpcInfo*)p->shandle;
  // auth here
dengyihao's avatar
dengyihao 已提交
249
  // auth should not do in rpc thread
dengyihao's avatar
dengyihao 已提交
250

dengyihao's avatar
dengyihao 已提交
251 252 253 254 255
  // int8_t code = uvAuthMsg(pConn, (char*)pHead, p->msgLen);
  // if (code != 0) {
  //  terrno = code;
  //  return;
  //}
dengyihao's avatar
dengyihao 已提交
256 257
  pHead->code = htonl(pHead->code);

dengyihao's avatar
dengyihao 已提交
258
  int32_t dlen = 0;
dengyihao's avatar
dengyihao 已提交
259
  SRpcMsg rpcMsg;
dengyihao's avatar
dengyihao 已提交
260 261 262 263
  if (transDecompressMsg(NULL, 0, NULL)) {
    // add compress later
    // pHead = rpcDecompressRpcMsg(pHead);
  } else {
dengyihao's avatar
dengyihao 已提交
264
    pHead->msgLen = htonl(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
265
    // impl later
dengyihao's avatar
dengyihao 已提交
266
    //
dengyihao's avatar
dengyihao 已提交
267
  }
dengyihao's avatar
dengyihao 已提交
268
  rpcMsg.contLen = transContLenFromMsg(pHead->msgLen);
dengyihao's avatar
dengyihao 已提交
269 270 271
  rpcMsg.pCont = pHead->content;
  rpcMsg.msgType = pHead->msgType;
  rpcMsg.code = pHead->code;
dengyihao's avatar
dengyihao 已提交
272
  rpcMsg.ahandle = NULL;
dengyihao's avatar
dengyihao 已提交
273 274 275
  rpcMsg.handle = pConn;

  (*(pRpc->cfp))(pRpc->parent, &rpcMsg, NULL);
dengyihao's avatar
dengyihao 已提交
276
  // uv_timer_start(pConn->pTimer, uvHandleActivityTimeout, pRpc->idleTime * 10000, 0);
dengyihao's avatar
dengyihao 已提交
277 278 279 280 281 282
  // auth
  // validate msg type
}

void uvOnReadCb(uv_stream_t* cli, ssize_t nread, const uv_buf_t* buf) {
  // opt
dengyihao's avatar
dengyihao 已提交
283 284
  SConn*       conn = cli->data;
  SConnBuffer* pBuf = &conn->connBuf;
dengyihao's avatar
dengyihao 已提交
285 286
  if (nread > 0) {
    pBuf->len += nread;
dengyihao's avatar
dengyihao 已提交
287
    tDebug("conn %p read summroy, total read: %d, current read: %d", conn, pBuf->len, (int)nread);
dengyihao's avatar
dengyihao 已提交
288
    if (readComplete(pBuf)) {
dengyihao's avatar
dengyihao 已提交
289 290
      tDebug("conn %p alread read complete packet", conn);
      uvHandleReq(conn);
dengyihao's avatar
dengyihao 已提交
291
    } else {
dengyihao's avatar
dengyihao 已提交
292
      tDebug("conn %p read partial packet, continue to read", conn);
dengyihao's avatar
dengyihao 已提交
293 294 295
    }
    return;
  }
296
  if (nread == 0) {
dengyihao's avatar
dengyihao 已提交
297 298
    tDebug("conn %p except read", conn);
    // destroyConn(conn, true);
299 300
    return;
  }
dengyihao's avatar
dengyihao 已提交
301
  if (nread != UV_EOF) {
dengyihao's avatar
dengyihao 已提交
302 303
    tDebug("conn %p read error: %s", conn, uv_err_name(nread));
    destroyConn(conn, true);
dengyihao's avatar
dengyihao 已提交
304 305 306 307 308 309 310 311 312
  }
}
void uvAllocConnBufferCb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
  buf->base = malloc(sizeof(char));
  buf->len = 2;
}

void uvOnTimeoutCb(uv_timer_t* handle) {
  // opt
dengyihao's avatar
dengyihao 已提交
313 314
  SConn* pConn = handle->data;
  tDebug("conn %p time out", pConn);
dengyihao's avatar
dengyihao 已提交
315 316 317 318
}

void uvOnWriteCb(uv_write_t* req, int status) {
  SConn* conn = req->data;
dengyihao's avatar
dengyihao 已提交
319 320 321 322 323

  SConnBuffer* buf = &conn->connBuf;
  buf->len = 0;
  memset(buf->buf, 0, buf->cap);
  buf->left = -1;
dengyihao's avatar
dengyihao 已提交
324
  if (status == 0) {
dengyihao's avatar
dengyihao 已提交
325
    tDebug("conn %p data already was written on stream", conn);
dengyihao's avatar
dengyihao 已提交
326
  } else {
dengyihao's avatar
dengyihao 已提交
327
    tDebug("conn %p failed to write data, %s", conn, uv_err_name(status));
328
    destroyConn(conn, true);
dengyihao's avatar
dengyihao 已提交
329 330 331
  }
  // opt
}
dengyihao's avatar
dengyihao 已提交
332 333 334 335 336 337 338
static void uvOnPipeWriteCb(uv_write_t* req, int status) {
  if (status == 0) {
    tDebug("success to dispatch conn to work thread");
  } else {
    tError("fail to dispatch conn to work thread");
  }
}
dengyihao's avatar
dengyihao 已提交
339

dengyihao's avatar
dengyihao 已提交
340
static void uvPrepareSendData(SConn* conn, uv_buf_t* wb) {
341
  // impl later;
dengyihao's avatar
dengyihao 已提交
342
  tDebug("conn %p prepare to send resp", conn);
dengyihao's avatar
dengyihao 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  SRpcMsg* pMsg = &conn->sendMsg;
  if (pMsg->pCont == 0) {
    pMsg->pCont = (void*)rpcMallocCont(0);
    pMsg->contLen = 0;
  }
  STransMsgHead* pHead = transHeadFromCont(pMsg->pCont);
  pHead->msgType = conn->inType + 1;
  // add more info
  char*   msg = (char*)pHead;
  int32_t len = transMsgLenFromCont(pMsg->contLen);
  if (transCompressMsg(msg, len, NULL)) {
    // impl later
  }
  pHead->msgLen = htonl(len);
  wb->base = msg;
  wb->len = len;
}
dengyihao's avatar
dengyihao 已提交
360
void uvWorkerAsyncCb(uv_async_t* handle) {
dengyihao's avatar
dengyihao 已提交
361
  SWorkThrdObj* pThrd = handle->data;
dengyihao's avatar
dengyihao 已提交
362
  SConn*        conn = NULL;
dengyihao's avatar
dengyihao 已提交
363 364
  queue         wq;
  // batch process to avoid to lock/unlock frequently
dengyihao's avatar
dengyihao 已提交
365
  pthread_mutex_lock(&pThrd->connMtx);
dengyihao's avatar
dengyihao 已提交
366
  QUEUE_MOVE(&pThrd->conn, &wq);
dengyihao's avatar
dengyihao 已提交
367
  pthread_mutex_unlock(&pThrd->connMtx);
dengyihao's avatar
dengyihao 已提交
368 369 370 371 372 373 374 375 376

  while (!QUEUE_IS_EMPTY(&wq)) {
    queue* head = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(head);
    SConn* conn = QUEUE_DATA(head, SConn, queue);
    if (conn == NULL) {
      tError("except occurred, do nothing");
      return;
    }
dengyihao's avatar
dengyihao 已提交
377 378
    uv_buf_t wb;
    uvPrepareSendData(conn, &wb);
dengyihao's avatar
dengyihao 已提交
379 380
    uv_timer_stop(conn->pTimer);

dengyihao's avatar
dengyihao 已提交
381
    uv_write(conn->pWriter, (uv_stream_t*)conn->pTcp, &wb, 1, uvOnWriteCb);
dengyihao's avatar
dengyihao 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  }
}

void uvOnAcceptCb(uv_stream_t* stream, int status) {
  if (status == -1) {
    return;
  }
  SServerObj* pObj = container_of(stream, SServerObj, server);

  uv_tcp_t* cli = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
  uv_tcp_init(pObj->loop, cli);

  if (uv_accept(stream, (uv_stream_t*)cli) == 0) {
    uv_write_t* wr = (uv_write_t*)malloc(sizeof(uv_write_t));

    uv_buf_t buf = uv_buf_init((char*)notify, strlen(notify));

    pObj->workerIdx = (pObj->workerIdx + 1) % pObj->numOfThreads;
dengyihao's avatar
dengyihao 已提交
400

dengyihao's avatar
dengyihao 已提交
401
    tDebug("new conntion accepted by main server, dispatch to %dth worker-thread", pObj->workerIdx);
dengyihao's avatar
dengyihao 已提交
402
    uv_write2(wr, (uv_stream_t*)&(pObj->pipe[pObj->workerIdx][0]), &buf, 1, (uv_stream_t*)cli, uvOnPipeWriteCb);
dengyihao's avatar
dengyihao 已提交
403 404
  } else {
    uv_close((uv_handle_t*)cli, NULL);
405
    free(cli);
dengyihao's avatar
dengyihao 已提交
406 407 408 409 410 411 412 413 414
  }
}
void uvOnConnectionCb(uv_stream_t* q, ssize_t nread, const uv_buf_t* buf) {
  tDebug("connection coming");
  if (nread < 0) {
    if (nread != UV_EOF) {
      tError("read error %s", uv_err_name(nread));
    }
    // TODO(log other failure reason)
415
    // uv_close((uv_handle_t*)q, NULL);
dengyihao's avatar
dengyihao 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    return;
  }
  // free memory allocated by
  assert(nread == strlen(notify));
  assert(buf->base[0] == notify[0]);
  free(buf->base);

  SWorkThrdObj* pThrd = q->data;

  uv_pipe_t* pipe = (uv_pipe_t*)q;
  if (!uv_pipe_pending_count(pipe)) {
    tError("No pending count");
    return;
  }

  uv_handle_type pending = uv_pipe_pending_type(pipe);
  assert(pending == UV_TCP);

434
  SConn* pConn = createConn();
dengyihao's avatar
dengyihao 已提交
435
  pConn->pTransInst = pThrd->pTransInst;
dengyihao's avatar
dengyihao 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  /* init conn timer*/
  pConn->pTimer = malloc(sizeof(uv_timer_t));
  uv_timer_init(pThrd->loop, pConn->pTimer);
  pConn->pTimer->data = pConn;

  pConn->hostThrd = pThrd;
  pConn->pWorkerAsync = pThrd->workerAsync;  // thread safty

  // init client handle
  pConn->pTcp = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
  uv_tcp_init(pThrd->loop, pConn->pTcp);
  pConn->pTcp->data = pConn;

  // init write request, just
  pConn->pWriter = calloc(1, sizeof(uv_write_t));
  pConn->pWriter->data = pConn;

  if (uv_accept(q, (uv_stream_t*)(pConn->pTcp)) == 0) {
    uv_os_fd_t fd;
    uv_fileno((const uv_handle_t*)pConn->pTcp, &fd);
dengyihao's avatar
dengyihao 已提交
456
    tDebug("conn %p created, fd: %d", pConn, fd);
dengyihao's avatar
dengyihao 已提交
457 458
    uv_read_start((uv_stream_t*)(pConn->pTcp), uvAllocReadBufferCb, uvOnReadCb);
  } else {
dengyihao's avatar
dengyihao 已提交
459
    tDebug("failed to create new connection");
460
    destroyConn(pConn, true);
dengyihao's avatar
dengyihao 已提交
461 462 463 464 465 466 467 468
  }
}

void* acceptThread(void* arg) {
  // opt
  SServerObj* srv = (SServerObj*)arg;
  uv_run(srv->loop, UV_RUN_DEFAULT);
}
dengyihao's avatar
dengyihao 已提交
469 470
static bool addHandleToWorkloop(void* arg) {
  SWorkThrdObj* pThrd = arg;
dengyihao's avatar
dengyihao 已提交
471
  pThrd->loop = (uv_loop_t*)malloc(sizeof(uv_loop_t));
dengyihao's avatar
dengyihao 已提交
472 473 474
  if (0 != uv_loop_init(pThrd->loop)) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
475 476

  // SRpcInfo* pRpc = pThrd->shandle;
dengyihao's avatar
dengyihao 已提交
477
  uv_pipe_init(pThrd->loop, pThrd->pipe, 1);
dengyihao's avatar
dengyihao 已提交
478 479 480 481 482 483 484 485 486
  uv_pipe_open(pThrd->pipe, pThrd->fd);

  pThrd->pipe->data = pThrd;

  QUEUE_INIT(&pThrd->conn);
  pthread_mutex_init(&pThrd->connMtx, NULL);

  pThrd->workerAsync = malloc(sizeof(uv_async_t));
  uv_async_init(pThrd->loop, pThrd->workerAsync, uvWorkerAsyncCb);
dengyihao's avatar
dengyihao 已提交
487
  pThrd->workerAsync->data = pThrd;
dengyihao's avatar
dengyihao 已提交
488 489

  uv_read_start((uv_stream_t*)pThrd->pipe, uvAllocConnBufferCb, uvOnConnectionCb);
dengyihao's avatar
dengyihao 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
  return true;
}

static bool addHandleToAcceptloop(void* arg) {
  // impl later
  SServerObj* srv = arg;

  int err = 0;
  if ((err = uv_tcp_init(srv->loop, &srv->server)) != 0) {
    tError("failed to init accept server: %s", uv_err_name(err));
    return false;
  }

  struct sockaddr_in bind_addr;

  uv_ip4_addr("0.0.0.0", srv->port, &bind_addr);
  if ((err = uv_tcp_bind(&srv->server, (const struct sockaddr*)&bind_addr, 0)) != 0) {
    tError("failed to bind: %s", uv_err_name(err));
    return false;
  }
  if ((err = uv_listen((uv_stream_t*)&srv->server, 128, uvOnAcceptCb)) != 0) {
    tError("failed to listen: %s", uv_err_name(err));
    return false;
  }
  return true;
dengyihao's avatar
dengyihao 已提交
515 516 517
}
void* workerThread(void* arg) {
  SWorkThrdObj* pThrd = (SWorkThrdObj*)arg;
dengyihao's avatar
dengyihao 已提交
518 519 520
  uv_run(pThrd->loop, UV_RUN_DEFAULT);
}

521
static SConn* createConn() {
dengyihao's avatar
dengyihao 已提交
522 523 524
  SConn* pConn = (SConn*)calloc(1, sizeof(SConn));
  return pConn;
}
dengyihao's avatar
dengyihao 已提交
525

526
static void destroyConn(SConn* conn, bool clear) {
dengyihao's avatar
dengyihao 已提交
527 528 529
  if (conn == NULL) {
    return;
  }
530
  if (clear) {
dengyihao's avatar
dengyihao 已提交
531
    uv_close((uv_handle_t*)conn->pTcp, NULL);
532
  }
dengyihao's avatar
dengyihao 已提交
533 534 535
  uv_timer_stop(conn->pTimer);
  free(conn->pTimer);
  free(conn->pTcp);
dengyihao's avatar
dengyihao 已提交
536
  free(conn->connBuf.buf);
dengyihao's avatar
dengyihao 已提交
537
  free(conn->pWriter);
538
  free(conn);
dengyihao's avatar
dengyihao 已提交
539
}
540
static void uvDestroyConn(uv_handle_t* handle) {
dengyihao's avatar
dengyihao 已提交
541
  SConn* conn = handle->data;
542
  destroyConn(conn, false);
dengyihao's avatar
dengyihao 已提交
543
}
dengyihao's avatar
dengyihao 已提交
544 545
static int transAddAuthPart(SConn* pConn, char* msg, int msgLen) {
  STransMsgHead* pHead = (STransMsgHead*)msg;
dengyihao's avatar
dengyihao 已提交
546 547 548 549

  if (pConn->spi && pConn->secured == 0) {
    // add auth part
    pHead->spi = pConn->spi;
dengyihao's avatar
dengyihao 已提交
550
    STransDigestMsg* pDigest = (STransDigestMsg*)(msg + msgLen);
dengyihao's avatar
dengyihao 已提交
551 552 553
    pDigest->timeStamp = htonl(taosGetTimestampSec());
    msgLen += sizeof(SRpcDigest);
    pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);
dengyihao's avatar
dengyihao 已提交
554 555
    // transBuildAuthHead(pHead, msgLen - TSDB_AUTH_LEN, pDigest->auth, pConn->secret);
    // transBuildAuthHead(pHead, msgLen - TSDB_AUTH_LEN, pDigest->auth, pConn->secret);
dengyihao's avatar
dengyihao 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  } else {
    pHead->spi = 0;
    pHead->msgLen = (int32_t)htonl((uint32_t)msgLen);
  }

  return msgLen;
}

void* taosInitServer(uint32_t ip, uint32_t port, char* label, int numOfThreads, void* fp, void* shandle) {
  SServerObj* srv = calloc(1, sizeof(SServerObj));
  srv->loop = (uv_loop_t*)malloc(sizeof(uv_loop_t));
  srv->numOfThreads = numOfThreads;
  srv->workerIdx = 0;
  srv->pThreadObj = (SWorkThrdObj**)calloc(srv->numOfThreads, sizeof(SWorkThrdObj*));
  srv->pipe = (uv_pipe_t**)calloc(srv->numOfThreads, sizeof(uv_pipe_t*));
  srv->ip = ip;
  srv->port = port;
  uv_loop_init(srv->loop);

  for (int i = 0; i < srv->numOfThreads; i++) {
    SWorkThrdObj* thrd = (SWorkThrdObj*)calloc(1, sizeof(SWorkThrdObj));
dengyihao's avatar
dengyihao 已提交
577
    srv->pThreadObj[i] = thrd;
dengyihao's avatar
dengyihao 已提交
578

dengyihao's avatar
dengyihao 已提交
579 580 581
    srv->pipe[i] = (uv_pipe_t*)calloc(2, sizeof(uv_pipe_t));
    int fds[2];
    if (uv_socketpair(AF_UNIX, SOCK_STREAM, fds, UV_NONBLOCK_PIPE, UV_NONBLOCK_PIPE) != 0) {
dengyihao's avatar
dengyihao 已提交
582
      goto End;
dengyihao's avatar
dengyihao 已提交
583 584 585 586
    }
    uv_pipe_init(srv->loop, &(srv->pipe[i][0]), 1);
    uv_pipe_open(&(srv->pipe[i][0]), fds[1]);  // init write

dengyihao's avatar
dengyihao 已提交
587
    thrd->pTransInst = shandle;
dengyihao's avatar
dengyihao 已提交
588 589
    thrd->fd = fds[0];
    thrd->pipe = &(srv->pipe[i][1]);  // init read
dengyihao's avatar
dengyihao 已提交
590

dengyihao's avatar
dengyihao 已提交
591 592 593
    if (false == addHandleToWorkloop(thrd)) {
      goto End;
    }
dengyihao's avatar
dengyihao 已提交
594 595 596 597 598 599 600 601 602
    int err = pthread_create(&(thrd->thread), NULL, workerThread, (void*)(thrd));
    if (err == 0) {
      tDebug("sucess to create worker-thread %d", i);
      // printf("thread %d create\n", i);
    } else {
      // TODO: clear all other resource later
      tError("failed to create worker-thread %d", i);
    }
  }
dengyihao's avatar
dengyihao 已提交
603 604 605
  if (false == addHandleToAcceptloop(srv)) {
    goto End;
  }
dengyihao's avatar
dengyihao 已提交
606 607 608 609 610 611 612 613
  int err = pthread_create(&srv->thread, NULL, acceptThread, (void*)srv);
  if (err == 0) {
    tDebug("success to create accept-thread");
  } else {
    // clear all resource later
  }

  return srv;
dengyihao's avatar
dengyihao 已提交
614 615 616 617 618 619 620 621 622 623 624 625 626
End:
  taosCloseServer(srv);
  return NULL;
}

void destroyWorkThrd(SWorkThrdObj* pThrd) {
  if (pThrd == NULL) {
    return;
  }
  pthread_join(pThrd->thread, NULL);
  // free(srv->pipe[i]);
  free(pThrd->loop);
  free(pThrd);
dengyihao's avatar
dengyihao 已提交
627
}
dengyihao's avatar
dengyihao 已提交
628 629 630
void taosCloseServer(void* arg) {
  // impl later
  SServerObj* srv = arg;
dengyihao's avatar
dengyihao 已提交
631
  for (int i = 0; i < srv->numOfThreads; i++) {
dengyihao's avatar
dengyihao 已提交
632
    destroyWorkThrd(srv->pThreadObj[i]);
dengyihao's avatar
dengyihao 已提交
633 634 635 636 637
  }
  free(srv->loop);
  free(srv->pipe);
  free(srv->pThreadObj);
  pthread_join(srv->thread, NULL);
dengyihao's avatar
dengyihao 已提交
638
  free(srv);
dengyihao's avatar
dengyihao 已提交
639
}
dengyihao's avatar
dengyihao 已提交
640 641 642 643 644 645

void rpcSendResponse(const SRpcMsg* pMsg) {
  SConn*        pConn = pMsg->handle;
  SWorkThrdObj* pThrd = pConn->hostThrd;

  // opt later
dengyihao's avatar
dengyihao 已提交
646
  pConn->sendMsg = *pMsg;
dengyihao's avatar
dengyihao 已提交
647 648 649
  pthread_mutex_lock(&pThrd->connMtx);
  QUEUE_PUSH(&pThrd->conn, &pConn->queue);
  pthread_mutex_unlock(&pThrd->connMtx);
dengyihao's avatar
dengyihao 已提交
650
  tDebug("conn %p start to send resp", pConn);
dengyihao's avatar
dengyihao 已提交
651 652 653 654 655

  uv_async_send(pConn->pWorkerAsync);
}

#endif