udfd.c 25.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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/>.
 */
#include "uv.h"
#include "os.h"
S
slzhou 已提交
17 18
#include "fnLog.h"
#include "thash.h"
S
shenglian zhou 已提交
19

20 21 22
#include "tudf.h"
#include "tudfInt.h"

23
#include "tdatablock.h"
24 25 26 27
#include "tdataformat.h"
#include "tglobal.h"
#include "tmsg.h"
#include "trpc.h"
28

S
slzhou 已提交
29
typedef struct SUdfdContext {
dengyihao's avatar
dengyihao 已提交
30
  uv_loop_t * loop;
S
slzhou 已提交
31
  uv_pipe_t   ctrlPipe;
32
  uv_signal_t intrSignal;
33
  char        listenPipeName[PATH_MAX + UDF_LISTEN_PIPE_NAME_LEN + 2];
S
slzhou 已提交
34
  uv_pipe_t   listeningPipe;
S
slzhou 已提交
35

dengyihao's avatar
dengyihao 已提交
36
  void *     clientRpc;
37
  SCorEpSet  mgmtEp;
S
slzhou 已提交
38
  uv_mutex_t udfsMutex;
dengyihao's avatar
dengyihao 已提交
39
  SHashObj * udfsHash;
S
slzhou 已提交
40 41 42 43 44

  bool printVersion;
} SUdfdContext;

SUdfdContext global;
45 46

typedef struct SUdfdUvConn {
S
slzhou 已提交
47
  uv_stream_t *client;
dengyihao's avatar
dengyihao 已提交
48
  char *       inputBuf;
S
slzhou 已提交
49 50 51
  int32_t      inputLen;
  int32_t      inputCap;
  int32_t      inputTotal;
52 53 54
} SUdfdUvConn;

typedef struct SUvUdfWork {
S
slzhou 已提交
55 56 57
  uv_stream_t *client;
  uv_buf_t     input;
  uv_buf_t     output;
58 59
} SUvUdfWork;

S
slzhou 已提交
60
typedef enum { UDF_STATE_INIT = 0, UDF_STATE_LOADING, UDF_STATE_READY, UDF_STATE_UNLOADING } EUdfState;
61

S
slzhou 已提交
62
typedef struct SUdf {
S
slzhou 已提交
63 64
  int32_t    refCount;
  EUdfState  state;
S
slzhou 已提交
65
  uv_mutex_t lock;
S
slzhou 已提交
66
  uv_cond_t  condReady;
S
slzhou 已提交
67

dengyihao's avatar
dengyihao 已提交
68 69 70 71
  char    name[TSDB_FUNC_NAME_LEN];
  int8_t  funcType;
  int8_t  scriptType;
  int8_t  outputType;
S
slzhou 已提交
72 73 74
  int32_t outputLen;
  int32_t bufSize;

dengyihao's avatar
dengyihao 已提交
75
  char path[PATH_MAX];
S
slzhou 已提交
76

dengyihao's avatar
dengyihao 已提交
77
  uv_lib_t lib;
S
shenglian zhou 已提交
78

dengyihao's avatar
dengyihao 已提交
79
  TUdfScalarProcFunc scalarProcFunc;
80

dengyihao's avatar
dengyihao 已提交
81 82 83
  TUdfAggStartFunc   aggStartFunc;
  TUdfAggProcessFunc aggProcFunc;
  TUdfAggFinishFunc  aggFinishFunc;
84

dengyihao's avatar
dengyihao 已提交
85 86
  TUdfInitFunc    initFunc;
  TUdfDestroyFunc destroyFunc;
87 88
} SUdf;

S
slzhou 已提交
89
// TODO: add private udf structure.
90
typedef struct SUdfcFuncHandle {
S
slzhou 已提交
91
  SUdf *udf;
92
} SUdfcFuncHandle;
93

94 95 96 97 98 99 100
typedef enum EUdfdRpcReqRspType {
  UDFD_RPC_MNODE_CONNECT = 0,
  UDFD_RPC_RETRIVE_FUNC,
} EUdfdRpcReqRspType;

typedef struct SUdfdRpcSendRecvInfo {
  EUdfdRpcReqRspType rpcType;
dengyihao's avatar
dengyihao 已提交
101 102 103
  int32_t            code;
  void *             param;
  uv_sem_t           resultSem;
104 105 106
} SUdfdRpcSendRecvInfo;

void udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet) {
107 108
  SUdfdRpcSendRecvInfo *msgInfo = (SUdfdRpcSendRecvInfo *)pMsg->info.ahandle;
  ASSERT(pMsg->info.ahandle != NULL);
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

  if (pEpSet) {
    if (!isEpsetEqual(&global.mgmtEp.epSet, pEpSet)) {
      updateEpSet_s(&global.mgmtEp, pEpSet);
    }
  }

  if (pMsg->code != TSDB_CODE_SUCCESS) {
    fnError("udfd rpc error. code: %s", tstrerror(pMsg->code));
    msgInfo->code = pMsg->code;
    goto _return;
  }

  if (msgInfo->rpcType == UDFD_RPC_MNODE_CONNECT) {
    SConnectRsp connectRsp = {0};
    tDeserializeSConnectRsp(pMsg->pCont, pMsg->contLen, &connectRsp);
    if (connectRsp.epSet.numOfEps == 0) {
      msgInfo->code = TSDB_CODE_MND_APP_ERROR;
      goto _return;
    }

    if (connectRsp.dnodeNum > 1 && !isEpsetEqual(&global.mgmtEp.epSet, &connectRsp.epSet)) {
      updateEpSet_s(&global.mgmtEp, &connectRsp.epSet);
    }
    msgInfo->code = 0;
  } else if (msgInfo->rpcType == UDFD_RPC_RETRIVE_FUNC) {
    SRetrieveFuncRsp retrieveRsp = {0};
    tDeserializeSRetrieveFuncRsp(pMsg->pCont, pMsg->contLen, &retrieveRsp);

    SFuncInfo *pFuncInfo = (SFuncInfo *)taosArrayGet(retrieveRsp.pFuncInfos, 0);
dengyihao's avatar
dengyihao 已提交
139
    SUdf *     udf = msgInfo->param;
140 141
    udf->funcType = pFuncInfo->funcType;
    udf->scriptType = pFuncInfo->scriptType;
142
    udf->outputType = pFuncInfo->outputType;
143 144 145 146 147
    udf->outputLen = pFuncInfo->outputLen;
    udf->bufSize = pFuncInfo->bufSize;

    char path[PATH_MAX] = {0};
    snprintf(path, sizeof(path), "%s/lib%s.so", "/tmp", pFuncInfo->name);
dengyihao's avatar
dengyihao 已提交
148 149
    TdFilePtr file =
        taosOpenFile(path, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_READ | TD_FILE_TRUNC | TD_FILE_AUTO_DEL);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    // TODO check for failure of flush to disk
    taosWriteFile(file, pFuncInfo->pCode, pFuncInfo->codeSize);
    taosCloseFile(&file);
    strncpy(udf->path, path, strlen(path));
    tFreeSFuncInfo(pFuncInfo);
    taosArrayDestroy(retrieveRsp.pFuncInfos);
    msgInfo->code = 0;
  }

_return:
  rpcFreeCont(pMsg->pCont);
  uv_sem_post(&msgInfo->resultSem);
  return;
}

int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf) {
  SRetrieveFuncReq retrieveReq = {0};
  retrieveReq.numOfFuncs = 1;
  retrieveReq.pFuncNames = taosArrayInit(1, TSDB_FUNC_NAME_LEN);
  taosArrayPush(retrieveReq.pFuncNames, udfName);

  int32_t contLen = tSerializeSRetrieveFuncReq(NULL, 0, &retrieveReq);
dengyihao's avatar
dengyihao 已提交
172
  void *  pReq = rpcMallocCont(contLen);
173 174 175
  tSerializeSRetrieveFuncReq(pReq, contLen, &retrieveReq);
  taosArrayDestroy(retrieveReq.pFuncNames);

dengyihao's avatar
dengyihao 已提交
176
  SUdfdRpcSendRecvInfo *msgInfo = taosMemoryCalloc(1, sizeof(SUdfdRpcSendRecvInfo));
177 178 179 180 181 182 183 184
  msgInfo->rpcType = UDFD_RPC_RETRIVE_FUNC;
  msgInfo->param = udf;
  uv_sem_init(&msgInfo->resultSem, 0);

  SRpcMsg rpcMsg = {0};
  rpcMsg.pCont = pReq;
  rpcMsg.contLen = contLen;
  rpcMsg.msgType = TDMT_MND_RETRIEVE_FUNC;
185
  rpcMsg.info.ahandle = msgInfo;
186 187 188 189 190 191 192 193 194 195 196 197
  rpcSendRequest(clientRpc, &global.mgmtEp.epSet, &rpcMsg, NULL);

  uv_sem_wait(&msgInfo->resultSem);
  uv_sem_destroy(&msgInfo->resultSem);
  int32_t code = msgInfo->code;
  taosMemoryFree(msgInfo);
  return code;
}

int32_t udfdConnectToMnode() {
  SConnectReq connReq = {0};
  connReq.connType = CONN_TYPE__UDFD;
dengyihao's avatar
dengyihao 已提交
198
  tstrncpy(connReq.app, "udfd", sizeof(connReq.app));
199 200 201 202 203 204 205 206
  tstrncpy(connReq.user, TSDB_DEFAULT_USER, sizeof(connReq.user));
  char pass[TSDB_PASSWORD_LEN + 1] = {0};
  taosEncryptPass_c((uint8_t *)(TSDB_DEFAULT_PASS), strlen(TSDB_DEFAULT_PASS), pass);
  tstrncpy(connReq.passwd, pass, sizeof(connReq.passwd));
  connReq.pid = htonl(taosGetPId());
  connReq.startTime = htobe64(taosGetTimestampMs());

  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connReq);
dengyihao's avatar
dengyihao 已提交
207
  void *  pReq = rpcMallocCont(contLen);
208 209 210 211 212 213 214 215 216 217
  tSerializeSConnectReq(pReq, contLen, &connReq);

  SUdfdRpcSendRecvInfo *msgInfo = taosMemoryCalloc(1, sizeof(SUdfdRpcSendRecvInfo));
  msgInfo->rpcType = UDFD_RPC_MNODE_CONNECT;
  uv_sem_init(&msgInfo->resultSem, 0);

  SRpcMsg rpcMsg = {0};
  rpcMsg.msgType = TDMT_MND_CONNECT;
  rpcMsg.pCont = pReq;
  rpcMsg.contLen = contLen;
218
  rpcMsg.info.ahandle = msgInfo;
219 220 221 222 223 224 225 226
  rpcSendRequest(global.clientRpc, &global.mgmtEp.epSet, &rpcMsg, NULL);

  uv_sem_wait(&msgInfo->resultSem);
  int32_t code = msgInfo->code;
  uv_sem_destroy(&msgInfo->resultSem);
  taosMemoryFree(msgInfo);
  return code;
}
227

228
int32_t udfdLoadUdf(char *udfName, SUdf *udf) {
S
slzhou 已提交
229
  strcpy(udf->name, udfName);
S
slzhou 已提交
230
  int32_t err = 0;
231

S
slzhou 已提交
232 233 234 235 236
  err = udfdFillUdfInfoFromMNode(global.clientRpc, udf->name, udf);
  if (err != 0) {
    fnError("can not retrieve udf from mnode. udf name %s", udfName);
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
  }
S
slzhou 已提交
237

S
slzhou 已提交
238
  err = uv_dlopen(udf->path, &udf->lib);
S
slzhou 已提交
239 240
  if (err != 0) {
    fnError("can not load library %s. error: %s", udf->path, uv_strerror(err));
241
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
S
slzhou 已提交
242
  }
243

dengyihao's avatar
dengyihao 已提交
244
  char  initFuncName[TSDB_FUNC_NAME_LEN + 5] = {0};
245 246 247
  char *initSuffix = "_init";
  strcpy(initFuncName, udfName);
  strncat(initFuncName, initSuffix, strlen(initSuffix));
dengyihao's avatar
dengyihao 已提交
248
  uv_dlsym(&udf->lib, initFuncName, (void **)(&udf->initFunc));
249

dengyihao's avatar
dengyihao 已提交
250
  char  destroyFuncName[TSDB_FUNC_NAME_LEN + 5] = {0};
251 252 253
  char *destroySuffix = "_destroy";
  strcpy(destroyFuncName, udfName);
  strncat(destroyFuncName, destroySuffix, strlen(destroySuffix));
dengyihao's avatar
dengyihao 已提交
254
  uv_dlsym(&udf->lib, destroyFuncName, (void **)(&udf->destroyFunc));
255

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  if (udf->funcType == TSDB_FUNC_TYPE_SCALAR) {
    char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
    strcpy(processFuncName, udfName);
    uv_dlsym(&udf->lib, processFuncName, (void **)(&udf->scalarProcFunc));
  } else if (udf->funcType == TSDB_FUNC_TYPE_AGGREGATE) {
    char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
    strcpy(processFuncName, udfName);
    uv_dlsym(&udf->lib, processFuncName, (void **)(&udf->aggProcFunc));
    char  startFuncName[TSDB_FUNC_NAME_LEN + 6] = {0};
    char *startSuffix = "_start";
    strncpy(startFuncName, processFuncName, strlen(processFuncName));
    strncat(startFuncName, startSuffix, strlen(startSuffix));
    uv_dlsym(&udf->lib, startFuncName, (void **)(&udf->aggStartFunc));
    char  finishFuncName[TSDB_FUNC_NAME_LEN + 7] = {0};
    char *finishSuffix = "_finish";
    strncpy(finishFuncName, processFuncName, strlen(processFuncName));
    strncat(finishFuncName, finishSuffix, strlen(finishSuffix));
S
slzhou 已提交
273
    uv_dlsym(&udf->lib, finishFuncName, (void **)(&udf->aggFinishFunc));
dengyihao's avatar
dengyihao 已提交
274
    // TODO: merge
275
  }
S
slzhou 已提交
276
  return 0;
S
slzhou 已提交
277
}
278

dengyihao's avatar
dengyihao 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
  // TODO: tracable id from client. connect, setup, call, teardown
  fnInfo("setup request. seq num: %" PRId64 ", udf name: %s", request->seqNum, request->setup.udfName);
  SUdfSetupRequest *setup = &request->setup;
  int32_t           code = TSDB_CODE_SUCCESS;
  SUdf *            udf = NULL;
  uv_mutex_lock(&global.udfsMutex);
  SUdf **udfInHash = taosHashGet(global.udfsHash, request->setup.udfName, strlen(request->setup.udfName));
  if (udfInHash) {
    ++(*udfInHash)->refCount;
    udf = *udfInHash;
    uv_mutex_unlock(&global.udfsMutex);
  } else {
    SUdf *udfNew = taosMemoryCalloc(1, sizeof(SUdf));
    udfNew->refCount = 1;
    udfNew->state = UDF_STATE_INIT;

    uv_mutex_init(&udfNew->lock);
    uv_cond_init(&udfNew->condReady);
    udf = udfNew;
    taosHashPut(global.udfsHash, request->setup.udfName, strlen(request->setup.udfName), &udfNew, sizeof(&udfNew));
    uv_mutex_unlock(&global.udfsMutex);
  }

  uv_mutex_lock(&udf->lock);
  if (udf->state == UDF_STATE_INIT) {
    udf->state = UDF_STATE_LOADING;
    code = udfdLoadUdf(setup->udfName, udf);
    if (udf->initFunc) {
      udf->initFunc();
309
    }
dengyihao's avatar
dengyihao 已提交
310 311 312 313 314 315
    udf->state = UDF_STATE_READY;
    uv_cond_broadcast(&udf->condReady);
    uv_mutex_unlock(&udf->lock);
  } else {
    while (udf->state != UDF_STATE_READY) {
      uv_cond_wait(&udf->condReady, &udf->lock);
316
    }
dengyihao's avatar
dengyihao 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    uv_mutex_unlock(&udf->lock);
  }
  SUdfcFuncHandle *handle = taosMemoryMalloc(sizeof(SUdfcFuncHandle));
  handle->udf = udf;

  SUdfResponse rsp;
  rsp.seqNum = request->seqNum;
  rsp.type = request->type;
  rsp.code = code;
  rsp.setupRsp.udfHandle = (int64_t)(handle);
  rsp.setupRsp.outputType = udf->outputType;
  rsp.setupRsp.outputLen = udf->outputLen;
  rsp.setupRsp.bufSize = udf->bufSize;

  int32_t len = encodeUdfResponse(NULL, &rsp);
  rsp.msgLen = len;
  void *bufBegin = taosMemoryMalloc(len);
  void *buf = bufBegin;
  encodeUdfResponse(&buf, &rsp);

  uvUdf->output = uv_buf_init(bufBegin, len);

  taosMemoryFree(uvUdf->input.base);
  return;
341 342 343 344
}

void udfdProcessCallRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
  SUdfCallRequest *call = &request->call;
dengyihao's avatar
dengyihao 已提交
345 346 347 348 349
  fnDebug("%" PRId64 "call request. call type %d, handle: %" PRIx64, request->seqNum, call->callType, call->udfHandle);
  SUdfcFuncHandle * handle = (SUdfcFuncHandle *)(call->udfHandle);
  SUdf *            udf = handle->udf;
  SUdfResponse      response = {0};
  SUdfResponse *    rsp = &response;
350 351 352
  SUdfCallResponse *subRsp = &rsp->callRsp;

  int32_t code = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
353
  switch (call->callType) {
354 355 356 357 358 359
    case TSDB_UDF_CALL_SCALA_PROC: {
      SUdfColumn output = {0};

      SUdfDataBlock input = {0};
      convertDataBlockToUdfDataBlock(&call->block, &input);
      code = udf->scalarProcFunc(&input, &output);
S
slzhou 已提交
360
      freeUdfDataDataBlock(&input);
361 362 363 364 365
      convertUdfColumnToDataBlock(&output, &response.callRsp.resultData);
      freeUdfColumn(&output);
      break;
    }
    case TSDB_UDF_CALL_AGG_INIT: {
dengyihao's avatar
dengyihao 已提交
366
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
367 368 369 370 371 372 373
      udf->aggStartFunc(&outBuf);
      subRsp->resultBuf = outBuf;
      break;
    }
    case TSDB_UDF_CALL_AGG_PROC: {
      SUdfDataBlock input = {0};
      convertDataBlockToUdfDataBlock(&call->block, &input);
dengyihao's avatar
dengyihao 已提交
374
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
375
      code = udf->aggProcFunc(&input, &call->interBuf, &outBuf);
S
slzhou 已提交
376 377
      freeUdfInterBuf(&call->interBuf);
      freeUdfDataDataBlock(&input);
378 379 380 381 382
      subRsp->resultBuf = outBuf;

      break;
    }
    case TSDB_UDF_CALL_AGG_FIN: {
dengyihao's avatar
dengyihao 已提交
383
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
384
      code = udf->aggFinishFunc(&call->interBuf, &outBuf);
S
slzhou 已提交
385
      freeUdfInterBuf(&call->interBuf);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
      subRsp->resultBuf = outBuf;
      break;
    }
    default:
      break;
  }

  rsp->seqNum = request->seqNum;
  rsp->type = request->type;
  rsp->code = code;
  subRsp->callType = call->callType;

  int32_t len = encodeUdfResponse(NULL, rsp);
  rsp->msgLen = len;
  void *bufBegin = taosMemoryMalloc(len);
  void *buf = bufBegin;
  encodeUdfResponse(&buf, rsp);
  uvUdf->output = uv_buf_init(bufBegin, len);

S
slzhou 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
  switch (call->callType) {
    case TSDB_UDF_CALL_SCALA_PROC: {
      tDeleteSSDataBlock(&call->block);
      tDeleteSSDataBlock(&subRsp->resultData);
      break;
    }
    case TSDB_UDF_CALL_AGG_INIT: {
      freeUdfInterBuf(&subRsp->resultBuf);
      break;
    }
    case TSDB_UDF_CALL_AGG_PROC: {
      tDeleteSSDataBlock(&call->block);
      freeUdfInterBuf(&subRsp->resultBuf);
      break;
    }
    case TSDB_UDF_CALL_AGG_FIN: {
      freeUdfInterBuf(&subRsp->resultBuf);
      break;
    }
    default:
      break;
  }

428 429 430 431
  taosMemoryFree(uvUdf->input.base);
  return;
}

dengyihao's avatar
dengyihao 已提交
432
void udfdProcessTeardownRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
433
  SUdfTeardownRequest *teardown = &request->teardown;
S
slzhou 已提交
434
  fnInfo("teardown. seq number: %" PRId64 ", handle:%" PRIx64, request->seqNum, teardown->udfHandle);
435
  SUdfcFuncHandle *handle = (SUdfcFuncHandle *)(teardown->udfHandle);
dengyihao's avatar
dengyihao 已提交
436 437 438
  SUdf *           udf = handle->udf;
  bool             unloadUdf = false;
  int32_t          code = TSDB_CODE_SUCCESS;
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

  uv_mutex_lock(&global.udfsMutex);
  udf->refCount--;
  if (udf->refCount == 0) {
    unloadUdf = true;
    taosHashRemove(global.udfsHash, udf->name, strlen(udf->name));
  }
  uv_mutex_unlock(&global.udfsMutex);
  if (unloadUdf) {
    uv_cond_destroy(&udf->condReady);
    uv_mutex_destroy(&udf->lock);
    if (udf->destroyFunc) {
      (udf->destroyFunc)();
    }
    uv_dlclose(&udf->lib);
    taosMemoryFree(udf);
  }
  taosMemoryFree(handle);

  SUdfResponse  response;
  SUdfResponse *rsp = &response;
  rsp->seqNum = request->seqNum;
  rsp->type = request->type;
  rsp->code = code;
  int32_t len = encodeUdfResponse(NULL, rsp);
  rsp->msgLen = len;
  void *bufBegin = taosMemoryMalloc(len);
  void *buf = bufBegin;
  encodeUdfResponse(&buf, rsp);
  uvUdf->output = uv_buf_init(bufBegin, len);

  taosMemoryFree(uvUdf->input.base);
  return;
}

S
slzhou 已提交
474 475 476 477 478 479 480
void udfdProcessRequest(uv_work_t *req) {
  SUvUdfWork *uvUdf = (SUvUdfWork *)(req->data);
  SUdfRequest request = {0};
  decodeUdfRequest(uvUdf->input.base, &request);

  switch (request.type) {
    case UDF_TASK_SETUP: {
481
      udfdProcessSetupRequest(uvUdf, &request);
S
slzhou 已提交
482
      break;
483 484
    }

S
slzhou 已提交
485
    case UDF_TASK_CALL: {
486
      udfdProcessCallRequest(uvUdf, &request);
S
slzhou 已提交
487 488 489
      break;
    }
    case UDF_TASK_TEARDOWN: {
490
      udfdProcessTeardownRequest(uvUdf, &request);
S
slzhou 已提交
491 492 493 494 495 496
      break;
    }
    default: {
      break;
    }
  }
497 498 499
}

void udfdOnWrite(uv_write_t *req, int status) {
S
slzhou 已提交
500 501
  SUvUdfWork *work = (SUvUdfWork *)req->data;
  if (status < 0) {
S
slzhou 已提交
502
    fnError("udfd send response error, length: %zu code: %s", work->output.len, uv_err_name(status));
S
slzhou 已提交
503 504 505 506
  }
  taosMemoryFree(work->output.base);
  taosMemoryFree(work);
  taosMemoryFree(req);
507 508 509
}

void udfdSendResponse(uv_work_t *work, int status) {
S
slzhou 已提交
510
  SUvUdfWork *udfWork = (SUvUdfWork *)(work->data);
511

S
slzhou 已提交
512 513 514
  uv_write_t *write_req = taosMemoryMalloc(sizeof(uv_write_t));
  write_req->data = udfWork;
  uv_write(write_req, udfWork->client, &udfWork->output, 1, udfdOnWrite);
515

S
slzhou 已提交
516
  taosMemoryFree(work);
517 518 519
}

void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
S
slzhou 已提交
520 521 522 523 524 525 526 527 528 529 530
  SUdfdUvConn *ctx = handle->data;
  int32_t      msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
  if (ctx->inputCap == 0) {
    ctx->inputBuf = taosMemoryMalloc(msgHeadSize);
    if (ctx->inputBuf) {
      ctx->inputLen = 0;
      ctx->inputCap = msgHeadSize;
      ctx->inputTotal = -1;

      buf->base = ctx->inputBuf;
      buf->len = ctx->inputCap;
531
    } else {
S
slzhou 已提交
532 533 534
      // TODO: log error
      buf->base = NULL;
      buf->len = 0;
535
    }
S
slzhou 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549
  } else {
    ctx->inputCap = ctx->inputTotal > ctx->inputCap ? ctx->inputTotal : ctx->inputCap;
    void *inputBuf = taosMemoryRealloc(ctx->inputBuf, ctx->inputCap);
    if (inputBuf) {
      ctx->inputBuf = inputBuf;
      buf->base = ctx->inputBuf + ctx->inputLen;
      buf->len = ctx->inputCap - ctx->inputLen;
    } else {
      // TODO: log error
      buf->base = NULL;
      buf->len = 0;
    }
  }
  fnDebug("allocate buf. input buf cap - len - total : %d - %d - %d", ctx->inputCap, ctx->inputLen, ctx->inputTotal);
550 551 552
}

bool isUdfdUvMsgComplete(SUdfdUvConn *pipe) {
S
slzhou 已提交
553 554 555 556 557 558 559 560
  if (pipe->inputTotal == -1 && pipe->inputLen >= sizeof(int32_t)) {
    pipe->inputTotal = *(int32_t *)(pipe->inputBuf);
  }
  if (pipe->inputLen == pipe->inputCap && pipe->inputTotal == pipe->inputCap) {
    fnDebug("receive request complete. length %d", pipe->inputLen);
    return true;
  }
  return false;
561 562 563
}

void udfdHandleRequest(SUdfdUvConn *conn) {
dengyihao's avatar
dengyihao 已提交
564
  uv_work_t * work = taosMemoryMalloc(sizeof(uv_work_t));
S
slzhou 已提交
565 566 567 568 569 570 571 572 573
  SUvUdfWork *udfWork = taosMemoryMalloc(sizeof(SUvUdfWork));
  udfWork->client = conn->client;
  udfWork->input = uv_buf_init(conn->inputBuf, conn->inputLen);
  conn->inputBuf = NULL;
  conn->inputLen = 0;
  conn->inputCap = 0;
  conn->inputTotal = -1;
  work->data = udfWork;
  uv_queue_work(global.loop, work, udfdProcessRequest, udfdSendResponse);
574 575 576
}

void udfdPipeCloseCb(uv_handle_t *pipe) {
S
slzhou 已提交
577 578 579 580
  SUdfdUvConn *conn = pipe->data;
  taosMemoryFree(conn->client);
  taosMemoryFree(conn->inputBuf);
  taosMemoryFree(conn);
581 582
}

S
slzhou 已提交
583
void udfdUvHandleError(SUdfdUvConn *conn) { uv_close((uv_handle_t *)conn->client, udfdPipeCloseCb); }
584 585

void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
586
  fnDebug("udf read %zd bytes from client", nread);
S
slzhou 已提交
587
  if (nread == 0) return;
588

S
slzhou 已提交
589
  SUdfdUvConn *conn = client->data;
590

S
slzhou 已提交
591 592 593 594 595 596
  if (nread > 0) {
    conn->inputLen += nread;
    if (isUdfdUvMsgComplete(conn)) {
      udfdHandleRequest(conn);
    } else {
      // log error or continue;
597
    }
S
slzhou 已提交
598 599
    return;
  }
600

S
slzhou 已提交
601 602 603 604 605
  if (nread < 0) {
    fnDebug("Receive error %s", uv_err_name(nread));
    if (nread == UV_EOF) {
      // TODO check more when close
    } else {
606
    }
S
slzhou 已提交
607 608
    udfdUvHandleError(conn);
  }
609 610 611
}

void udfdOnNewConnection(uv_stream_t *server, int status) {
S
slzhou 已提交
612
  if (status < 0) {
S
slzhou 已提交
613
    fnError("udfd new connection error. code: %s", uv_strerror(status));
S
slzhou 已提交
614 615
    return;
  }
616

S
slzhou 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630
  uv_pipe_t *client = (uv_pipe_t *)taosMemoryMalloc(sizeof(uv_pipe_t));
  uv_pipe_init(global.loop, client, 0);
  if (uv_accept(server, (uv_stream_t *)client) == 0) {
    SUdfdUvConn *ctx = taosMemoryMalloc(sizeof(SUdfdUvConn));
    ctx->client = (uv_stream_t *)client;
    ctx->inputBuf = 0;
    ctx->inputLen = 0;
    ctx->inputCap = 0;
    client->data = ctx;
    ctx->client = (uv_stream_t *)client;
    uv_read_start((uv_stream_t *)client, udfdAllocBuffer, udfdPipeRead);
  } else {
    uv_close((uv_handle_t *)client, NULL);
  }
631 632
}

633 634
void udfdIntrSignalHandler(uv_signal_t *handle, int signum) {
  fnInfo("udfd signal received: %d\n", signum);
S
slzhou 已提交
635
  uv_fs_t req;
636 637 638
  uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
  uv_signal_stop(handle);
  uv_stop(global.loop);
639 640
}

641 642 643 644 645 646 647
static bool udfdRpcRfp(int32_t code) {
  if (code == TSDB_CODE_RPC_REDIRECT) {
    return true;
  } else {
    return false;
  }
}
648

dengyihao's avatar
dengyihao 已提交
649
int initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet) {
650 651 652
  pEpSet->version = 0;

  // init mnode ip set
dengyihao's avatar
dengyihao 已提交
653
  SEpSet *mgmtEpSet = &(pEpSet->epSet);
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
  mgmtEpSet->numOfEps = 0;
  mgmtEpSet->inUse = 0;

  if (firstEp && firstEp[0] != 0) {
    if (strlen(firstEp) >= TSDB_EP_LEN) {
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
      return -1;
    }

    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[0]);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
      return terrno;
    }

    mgmtEpSet->numOfEps++;
  }

  if (secondEp && secondEp[0] != 0) {
    if (strlen(secondEp) >= TSDB_EP_LEN) {
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
      return -1;
    }

    taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
    mgmtEpSet->numOfEps++;
  }

  if (mgmtEpSet->numOfEps == 0) {
    terrno = TSDB_CODE_TSC_INVALID_FQDN;
    return -1;
  }

  return 0;
}

S
slzhou 已提交
690
int32_t udfdOpenClientRpc() {
691
  SRpcInit rpcInit = {0};
692
  rpcInit.label = "UDFD";
693
  rpcInit.numOfThreads = 1;
694
  rpcInit.cfp = (RpcCfp)udfdProcessRpcRsp;
695 696
  rpcInit.sessions = 1024;
  rpcInit.connType = TAOS_CONN_CLIENT;
697
  rpcInit.idleTime = tsShellActivityTimer * 1000;
698
  rpcInit.user = TSDB_DEFAULT_USER;
S
slzhou 已提交
699
  rpcInit.parent = &global;
700
  rpcInit.rfp = udfdRpcRfp;
701

S
slzhou 已提交
702
  global.clientRpc = rpcOpen(&rpcInit);
703 704 705 706
  if (global.clientRpc == NULL) {
    fnError("failed to init dnode rpc client");
    return -1;
  }
S
slzhou 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
  return 0;
}

int32_t udfdCloseClientRpc() {
  rpcClose(global.clientRpc);
  return 0;
}

static void udfdPrintVersion() {
#ifdef TD_ENTERPRISE
  char *releaseName = "enterprise";
#else
  char *releaseName = "community";
#endif
  printf("%s version: %s compatible_version: %s\n", releaseName, version, compatible_version);
  printf("gitinfo: %s\n", gitinfo);
  printf("buildInfo: %s\n", buildinfo);
}

static int32_t udfdParseArgs(int32_t argc, char *argv[]) {
  for (int32_t i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "-c") == 0) {
      if (i < argc - 1) {
        if (strlen(argv[++i]) >= PATH_MAX) {
          printf("config file path overflow");
          return -1;
        }
        tstrncpy(configDir, argv[i], PATH_MAX);
      } else {
        printf("'-c' requires a parameter, default is %s\n", configDir);
        return -1;
      }
    } else if (strcmp(argv[i], "-V") == 0) {
      global.printVersion = true;
    } else {
    }
  }
744 745 746 747

  return 0;
}

S
slzhou 已提交
748 749 750
static int32_t udfdInitLog() {
  char logName[12] = {0};
  snprintf(logName, sizeof(logName), "%slog", "udfd");
wafwerar's avatar
wafwerar 已提交
751
  return taosCreateLog(logName, 1, configDir, NULL, NULL, NULL, NULL, 0);
S
slzhou 已提交
752
}
753

754 755 756 757 758 759 760 761
void udfdCtrlAllocBufCb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
  buf->base = taosMemoryMalloc(suggested_size);
  buf->len = suggested_size;
}

void udfdCtrlReadCb(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) {
  if (nread < 0) {
    fnError("udfd ctrl pipe read error. %s", uv_err_name(nread));
S
slzhou 已提交
762
    uv_close((uv_handle_t *)q, NULL);
763 764 765 766 767 768 769 770 771
    uv_stop(global.loop);
    return;
  }
  fnError("udfd ctrl pipe read %zu bytes", nread);
  taosMemoryFree(buf->base);
}

static int32_t removeListeningPipe() {
  uv_fs_t req;
S
slzhou 已提交
772
  int     err = uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
773 774 775 776
  uv_fs_req_cleanup(&req);
  return err;
}

S
slzhou 已提交
777
static int32_t udfdUvInit() {
S
slzhou 已提交
778
  uv_loop_t *loop = taosMemoryMalloc(sizeof(uv_loop_t));
S
slzhou 已提交
779 780 781 782
  if (loop) {
    uv_loop_init(loop);
  }
  global.loop = loop;
783 784 785

  uv_pipe_init(global.loop, &global.ctrlPipe, 1);
  uv_pipe_open(&global.ctrlPipe, 0);
S
slzhou 已提交
786
  uv_read_start((uv_stream_t *)&global.ctrlPipe, udfdCtrlAllocBufCb, udfdCtrlReadCb);
787

788
  getUdfdPipeName(global.listenPipeName, sizeof(global.listenPipeName));
S
slzhou 已提交
789

790
  removeListeningPipe();
S
slzhou 已提交
791

792
  uv_pipe_init(global.loop, &global.listeningPipe, 0);
S
slzhou 已提交
793

794 795
  uv_signal_init(global.loop, &global.intrSignal);
  uv_signal_start(&global.intrSignal, udfdIntrSignalHandler, SIGINT);
S
slzhou 已提交
796 797 798

  int r;
  fnInfo("bind to pipe %s", global.listenPipeName);
799
  if ((r = uv_pipe_bind(&global.listeningPipe, global.listenPipeName))) {
S
slzhou 已提交
800
    fnError("Bind error %s", uv_err_name(r));
801
    removeListeningPipe();
S
slzhou 已提交
802 803
    return -1;
  }
804
  if ((r = uv_listen((uv_stream_t *)&global.listeningPipe, 128, udfdOnNewConnection))) {
S
slzhou 已提交
805
    fnError("Listen error %s", uv_err_name(r));
806
    removeListeningPipe();
S
slzhou 已提交
807 808
    return -2;
  }
809 810
  return 0;
}
811

dengyihao's avatar
dengyihao 已提交
812
static void udfdCloseWalkCb(uv_handle_t *handle, void *arg) {
S
slzhou 已提交
813 814 815 816 817
  if (!uv_is_closing(handle)) {
    uv_close(handle, NULL);
  }
}

S
slzhou 已提交
818 819 820
static int32_t udfdRun() {
  global.udfsHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  uv_mutex_init(&global.udfsMutex);
821

S
slzhou 已提交
822 823 824 825 826 827 828 829 830 831
  fnInfo("start udfd event loop");
  uv_run(global.loop, UV_RUN_DEFAULT);
  fnInfo("udfd event loop stopped.");

  uv_loop_close(global.loop);

  uv_walk(global.loop, udfdCloseWalkCb, NULL);
  uv_run(global.loop, UV_RUN_DEFAULT);
  uv_loop_close(global.loop);

S
slzhou 已提交
832 833
  uv_mutex_destroy(&global.udfsMutex);
  taosHashCleanup(global.udfsHash);
S
slzhou 已提交
834
  return 0;
S
slzhou 已提交
835
}
836

S
slzhou 已提交
837
int main(int argc, char *argv[]) {
S
slzhou 已提交
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
  if (!taosCheckSystemIsSmallEnd()) {
    printf("failed to start since on non-small-end machines\n");
    return -1;
  }

  if (udfdParseArgs(argc, argv) != 0) {
    printf("failed to start since parse args error\n");
    return -1;
  }

  if (global.printVersion) {
    udfdPrintVersion();
    return 0;
  }

  if (udfdInitLog() != 0) {
    printf("failed to start since init log error\n");
    return -1;
  }

wafwerar's avatar
wafwerar 已提交
858
  if (taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0) != 0) {
S
slzhou 已提交
859
    fnError("failed to start since read config error");
860
    return -2;
S
slzhou 已提交
861 862
  }

863
  initEpSetFromCfg(tsFirst, tsSecond, &global.mgmtEp);
864 865 866 867 868
  if (udfdOpenClientRpc() != 0) {
    fnError("open rpc connection to mnode failure");
    return -3;
  }

869 870 871
  int32_t retryMnodeTimes = 0;
  int32_t code = 0;
  while (retryMnodeTimes++ < TSDB_MAX_REPLICA) {
dengyihao's avatar
dengyihao 已提交
872
    uv_sleep(500 * (1 << retryMnodeTimes));
873 874 875 876 877 878 879 880
    code = udfdConnectToMnode();
    if (code == 0) {
      break;
    }
    fnError("can not connect to mnode, code: %s. retry", tstrerror(code));
  }

  if (code != 0) {
881 882 883 884
    fnError("failed to start since can not connect to mnode");
    return -4;
  }

S
slzhou 已提交
885 886 887 888 889
  if (udfdUvInit() != 0) {
    fnError("uv init failure");
    return -5;
  }

890 891
  udfdRun();

S
slzhou 已提交
892
  removeListeningPipe();
893

S
slzhou 已提交
894
  udfdCloseClientRpc();
895
}