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

// clang-format off
17 18
#include "uv.h"
#include "os.h"
S
slzhou 已提交
19 20
#include "fnLog.h"
#include "thash.h"
S
shenglian zhou 已提交
21

22 23
#include "tudf.h"
#include "tudfInt.h"
D
dapan1121 已提交
24
#include "version.h"
25

26
#include "tdatablock.h"
27 28 29 30
#include "tdataformat.h"
#include "tglobal.h"
#include "tmsg.h"
#include "trpc.h"
31
#include "tmisce.h"
32
// clang-format on
33

S
slzhou 已提交
34 35 36
#define UDFD_MAX_SCRIPT_PLUGINS 64
#define UDFD_MAX_SCRIPT_TYPE    1
#define UDFD_MAX_PLUGIN_FUNCS   9
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

typedef struct SUdfCPluginCtx {
  uv_lib_t lib;

  TUdfScalarProcFunc scalarProcFunc;

  TUdfAggStartFunc   aggStartFunc;
  TUdfAggProcessFunc aggProcFunc;
  TUdfAggFinishFunc  aggFinishFunc;
  TUdfAggMergeFunc   aggMergeFunc;

  TUdfInitFunc    initFunc;
  TUdfDestroyFunc destroyFunc;
} SUdfCPluginCtx;

52
int32_t udfdCPluginOpen(SScriptUdfEnvItem *items, int numItems) { return 0; }
53

54
int32_t udfdCPluginClose() { return 0; }
55

56
const char *udfdCPluginUdfInitLoadInitDestoryFuncs(SUdfCPluginCtx *udfCtx, const char *udfName) {
D
dapan1121 已提交
57
  char  initFuncName[TSDB_FUNC_NAME_LEN + 6] = {0};
58
  char *initSuffix = "_init";
D
dapan1121 已提交
59
  snprintf(initFuncName, sizeof(initFuncName), "%s%s", udfName, initSuffix);
60 61
  uv_dlsym(&udfCtx->lib, initFuncName, (void **)(&udfCtx->initFunc));

D
dapan1121 已提交
62
  char  destroyFuncName[TSDB_FUNC_NAME_LEN + 9] = {0};
63 64
  char *destroySuffix = "_destroy";
  strcpy(destroyFuncName, udfName);
D
dapan1121 已提交
65
  snprintf(destroyFuncName, sizeof(destroyFuncName), "%s%s", udfName, destroySuffix);
66
  uv_dlsym(&udfCtx->lib, destroyFuncName, (void **)(&udfCtx->destroyFunc));
67 68 69 70 71 72 73 74
  return udfName;
}

void udfdCPluginUdfInitLoadAggFuncs(SUdfCPluginCtx *udfCtx, const char *udfName) {
  char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
  strcpy(processFuncName, udfName);
  uv_dlsym(&udfCtx->lib, processFuncName, (void **)(&udfCtx->aggProcFunc));

D
dapan1121 已提交
75
  char  startFuncName[TSDB_FUNC_NAME_LEN + 7] = {0};
76
  char *startSuffix = "_start";
D
dapan1121 已提交
77
  snprintf(startFuncName, sizeof(startFuncName), "%s%s", processFuncName, startSuffix);
78 79
  uv_dlsym(&udfCtx->lib, startFuncName, (void **)(&udfCtx->aggStartFunc));

D
dapan1121 已提交
80
  char  finishFuncName[TSDB_FUNC_NAME_LEN + 8] = {0};
81
  char *finishSuffix = "_finish";
D
dapan1121 已提交
82
  snprintf(finishFuncName, sizeof(finishFuncName), "%s%s", processFuncName, finishSuffix);
83
  uv_dlsym(&udfCtx->lib, finishFuncName, (void **)(&udfCtx->aggFinishFunc));
84

D
dapan1121 已提交
85
  char  mergeFuncName[TSDB_FUNC_NAME_LEN + 7] = {0};
86
  char *mergeSuffix = "_merge";
D
dapan1121 已提交
87
  snprintf(mergeFuncName, sizeof(mergeFuncName), "%s%s", processFuncName, mergeSuffix);
88 89 90 91 92 93 94 95 96 97 98
  uv_dlsym(&udfCtx->lib, mergeFuncName, (void **)(&udfCtx->aggMergeFunc));
}

int32_t udfdCPluginUdfInit(SScriptUdfInfo *udf, void **pUdfCtx) {
  int32_t         err = 0;
  SUdfCPluginCtx *udfCtx = taosMemoryCalloc(1, sizeof(SUdfCPluginCtx));
  err = uv_dlopen(udf->path, &udfCtx->lib);
  if (err != 0) {
    fnError("can not load library %s. error: %s", udf->path, uv_strerror(err));
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
  }
99
  const char *udfName = udf->name;
100 101

  udfdCPluginUdfInitLoadInitDestoryFuncs(udfCtx, udfName);
102

S
slzhou 已提交
103
  if (udf->funcType == UDF_FUNC_TYPE_SCALAR) {
104 105 106
    char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
    strcpy(processFuncName, udfName);
    uv_dlsym(&udfCtx->lib, processFuncName, (void **)(&udfCtx->scalarProcFunc));
S
slzhou 已提交
107
  } else if (udf->funcType == UDF_FUNC_TYPE_AGG) {
108
    udfdCPluginUdfInitLoadAggFuncs(udfCtx, udfName);
109
  }
110

S
slzhou 已提交
111
  int32_t code = 0;
112
  if (udfCtx->initFunc) {
S
slzhou 已提交
113 114 115 116 117 118
    code = (udfCtx->initFunc)();
    if (code != 0) {
      uv_dlclose(&udfCtx->lib);
      taosMemoryFree(udfCtx);
      return code;
    }
119 120 121 122 123 124 125
  }
  *pUdfCtx = udfCtx;
  return 0;
}

int32_t udfdCPluginUdfDestroy(void *udfCtx) {
  SUdfCPluginCtx *ctx = udfCtx;
S
slzhou 已提交
126
  int32_t         code = 0;
127
  if (ctx->destroyFunc) {
S
slzhou 已提交
128
    code = (ctx->destroyFunc)();
129 130 131
  }
  uv_dlclose(&ctx->lib);
  taosMemoryFree(ctx);
S
slzhou 已提交
132
  return code;
133 134 135 136 137
}

int32_t udfdCPluginUdfScalarProc(SUdfDataBlock *block, SUdfColumn *resultCol, void *udfCtx) {
  SUdfCPluginCtx *ctx = udfCtx;
  if (ctx->scalarProcFunc) {
S
slzhou 已提交
138 139
    return ctx->scalarProcFunc(block, resultCol);
  } else {
S
slzhou 已提交
140 141
    fnError("udfd c plugin scalar proc not implemented");
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
142 143 144 145 146 147
  }
}

int32_t udfdCPluginUdfAggStart(SUdfInterBuf *buf, void *udfCtx) {
  SUdfCPluginCtx *ctx = udfCtx;
  if (ctx->aggStartFunc) {
S
slzhou 已提交
148 149
    return ctx->aggStartFunc(buf);
  } else {
S
slzhou 已提交
150 151
    fnError("udfd c plugin aggregation start not implemented");
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
152 153 154 155 156 157 158
  }
  return 0;
}

int32_t udfdCPluginUdfAggProc(SUdfDataBlock *block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf, void *udfCtx) {
  SUdfCPluginCtx *ctx = udfCtx;
  if (ctx->aggProcFunc) {
S
slzhou 已提交
159 160
    return ctx->aggProcFunc(block, interBuf, newInterBuf);
  } else {
S
slzhou 已提交
161 162
    fnError("udfd c plugin aggregation process not implemented");
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
163 164 165 166 167 168 169
  }
}

int32_t udfdCPluginUdfAggMerge(SUdfInterBuf *inputBuf1, SUdfInterBuf *inputBuf2, SUdfInterBuf *outputBuf,
                               void *udfCtx) {
  SUdfCPluginCtx *ctx = udfCtx;
  if (ctx->aggMergeFunc) {
S
slzhou 已提交
170 171
    return ctx->aggMergeFunc(inputBuf1, inputBuf2, outputBuf);
  } else {
S
slzhou 已提交
172 173
    fnError("udfd c plugin aggregation merge not implemented");
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
174 175 176 177 178 179
  }
}

int32_t udfdCPluginUdfAggFinish(SUdfInterBuf *buf, SUdfInterBuf *resultData, void *udfCtx) {
  SUdfCPluginCtx *ctx = udfCtx;
  if (ctx->aggFinishFunc) {
S
slzhou 已提交
180 181
    return ctx->aggFinishFunc(buf, resultData);
  } else {
S
slzhou 已提交
182 183
    fnError("udfd c plugin aggregation finish not implemented");
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
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
  }
  return 0;
}

// for c, the function pointer are filled directly and libloaded = true;
// for others, dlopen/dlsym to find function pointers
typedef struct SUdfScriptPlugin {
  int8_t scriptType;

  char     libPath[PATH_MAX];
  bool     libLoaded;
  uv_lib_t lib;

  TScriptUdfScalarProcFunc udfScalarProcFunc;
  TScriptUdfAggStartFunc   udfAggStartFunc;
  TScriptUdfAggProcessFunc udfAggProcFunc;
  TScriptUdfAggMergeFunc   udfAggMergeFunc;
  TScriptUdfAggFinishFunc  udfAggFinishFunc;

  TScriptUdfInitFunc    udfInitFunc;
  TScriptUdfDestoryFunc udfDestroyFunc;

  TScriptOpenFunc  openFunc;
  TScriptCloseFunc closeFunc;
} SUdfScriptPlugin;

S
slzhou 已提交
210
typedef struct SUdfdContext {
211
  uv_loop_t  *loop;
S
slzhou 已提交
212
  uv_pipe_t   ctrlPipe;
213
  uv_signal_t intrSignal;
214
  char        listenPipeName[PATH_MAX + UDF_LISTEN_PIPE_NAME_LEN + 2];
S
slzhou 已提交
215
  uv_pipe_t   listeningPipe;
S
slzhou 已提交
216

217 218 219
  void     *clientRpc;
  SCorEpSet mgmtEp;

S
slzhou 已提交
220
  uv_mutex_t udfsMutex;
221
  SHashObj  *udfsHash;
S
slzhou 已提交
222

223
  uv_mutex_t        scriptPluginsMutex;
S
slzhou 已提交
224
  SUdfScriptPlugin *scriptPlugins[UDFD_MAX_SCRIPT_PLUGINS];
225

226
  SArray *residentFuncs;
227

228
  char udfDataDir[PATH_MAX];
S
slzhou 已提交
229 230 231 232
  bool printVersion;
} SUdfdContext;

SUdfdContext global;
233

234 235 236
struct SUdfdUvConn;
struct SUvUdfWork;

237
typedef struct SUdfdUvConn {
S
slzhou 已提交
238
  uv_stream_t *client;
239
  char        *inputBuf;
S
slzhou 已提交
240 241 242
  int32_t      inputLen;
  int32_t      inputCap;
  int32_t      inputTotal;
243 244

  struct SUvUdfWork *pWorkList;  // head of work list
245 246 247
} SUdfdUvConn;

typedef struct SUvUdfWork {
248
  SUdfdUvConn *conn;
S
slzhou 已提交
249 250
  uv_buf_t     input;
  uv_buf_t     output;
251 252

  struct SUvUdfWork *pWorkNext;
253 254
} SUvUdfWork;

255
typedef enum { UDF_STATE_INIT = 0, UDF_STATE_LOADING, UDF_STATE_READY } EUdfState;
256

S
slzhou 已提交
257
typedef struct SUdf {
258
  char    name[TSDB_FUNC_NAME_LEN + 1];
259
  int32_t version;
260
  int64_t createdTime;
S
slzhou 已提交
261

dengyihao's avatar
dengyihao 已提交
262 263 264
  int8_t  funcType;
  int8_t  scriptType;
  int8_t  outputType;
S
slzhou 已提交
265 266 267
  int32_t outputLen;
  int32_t bufSize;

dengyihao's avatar
dengyihao 已提交
268
  char path[PATH_MAX];
S
slzhou 已提交
269

270 271 272 273 274
  int32_t    refCount;
  EUdfState  state;
  uv_mutex_t lock;
  uv_cond_t  condReady;
  bool       resident;
275

276 277
  SUdfScriptPlugin *scriptPlugin;
  void             *scriptUdfCtx;
278 279 280

  int64_t lastFetchTime;  // last fetch time in milliseconds
  bool    expired;
281 282
} SUdf;

283
typedef struct SUdfcFuncHandle {
S
slzhou 已提交
284
  SUdf *udf;
285
} SUdfcFuncHandle;
286

287 288 289 290 291 292 293
typedef enum EUdfdRpcReqRspType {
  UDFD_RPC_MNODE_CONNECT = 0,
  UDFD_RPC_RETRIVE_FUNC,
} EUdfdRpcReqRspType;

typedef struct SUdfdRpcSendRecvInfo {
  EUdfdRpcReqRspType rpcType;
dengyihao's avatar
dengyihao 已提交
294
  int32_t            code;
295
  void              *param;
dengyihao's avatar
dengyihao 已提交
296
  uv_sem_t           resultSem;
297 298
} SUdfdRpcSendRecvInfo;

dengyihao's avatar
dengyihao 已提交
299
static void    udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet);
S
shenglian zhou 已提交
300 301
static int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf);
static int32_t udfdConnectToMnode();
dengyihao's avatar
dengyihao 已提交
302
static bool    udfdRpcRfp(int32_t code, tmsg_t msgType);
dengyihao's avatar
dengyihao 已提交
303
static int     initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet);
S
shenglian zhou 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
static int32_t udfdOpenClientRpc();
static int32_t udfdCloseClientRpc();

static void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request);
static void udfdProcessCallRequest(SUvUdfWork *uvUdf, SUdfRequest *request);
static void udfdProcessTeardownRequest(SUvUdfWork *uvUdf, SUdfRequest *request);
static void udfdProcessRequest(uv_work_t *req);
static void udfdOnWrite(uv_write_t *req, int status);
static void udfdSendResponse(uv_work_t *work, int status);
static void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf);
static bool isUdfdUvMsgComplete(SUdfdUvConn *pipe);
static void udfdHandleRequest(SUdfdUvConn *conn);
static void udfdPipeCloseCb(uv_handle_t *pipe);
static void udfdUvHandleError(SUdfdUvConn *conn) { uv_close((uv_handle_t *)conn->client, udfdPipeCloseCb); }
static void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf);
static void udfdOnNewConnection(uv_stream_t *server, int status);

dengyihao's avatar
dengyihao 已提交
321
static void    udfdIntrSignalHandler(uv_signal_t *handle, int signum);
S
shenglian zhou 已提交
322 323
static int32_t removeListeningPipe();

dengyihao's avatar
dengyihao 已提交
324
static void    udfdPrintVersion();
S
shenglian zhou 已提交
325 326 327
static int32_t udfdParseArgs(int32_t argc, char *argv[]);
static int32_t udfdInitLog();

dengyihao's avatar
dengyihao 已提交
328 329
static void    udfdCtrlAllocBufCb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf);
static void    udfdCtrlReadCb(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf);
S
shenglian zhou 已提交
330
static int32_t udfdUvInit();
dengyihao's avatar
dengyihao 已提交
331
static void    udfdCloseWalkCb(uv_handle_t *handle, void *arg);
S
shenglian zhou 已提交
332
static int32_t udfdRun();
dengyihao's avatar
dengyihao 已提交
333
static void    udfdConnectMnodeThreadFunc(void *args);
S
shenglian zhou 已提交
334

335
SUdf *udfdNewUdf(const char *udfName);
336 337
void  udfdGetFuncBodyPath(const SUdf *udf, char *path);

S
slzhou 已提交
338
void udfdInitializeCPlugin(SUdfScriptPlugin *plugin) {
339 340 341 342 343 344 345 346 347 348
  plugin->scriptType = TSDB_FUNC_SCRIPT_BIN_LIB;
  plugin->openFunc = udfdCPluginOpen;
  plugin->closeFunc = udfdCPluginClose;
  plugin->udfInitFunc = udfdCPluginUdfInit;
  plugin->udfDestroyFunc = udfdCPluginUdfDestroy;
  plugin->udfScalarProcFunc = udfdCPluginUdfScalarProc;
  plugin->udfAggStartFunc = udfdCPluginUdfAggStart;
  plugin->udfAggProcFunc = udfdCPluginUdfAggProc;
  plugin->udfAggMergeFunc = udfdCPluginUdfAggMerge;
  plugin->udfAggFinishFunc = udfdCPluginUdfAggFinish;
349

S
slzhou 已提交
350 351
  SScriptUdfEnvItem items[1] = {{"LD_LIBRARY_PATH", tsUdfdLdLibPath}};
  plugin->openFunc(items, 1);
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
  return;
}

int32_t udfdLoadSharedLib(char *libPath, uv_lib_t *pLib, const char *funcName[], void **func[], int numOfFuncs) {
  int err = uv_dlopen(libPath, pLib);
  if (err != 0) {
    fnError("can not load library %s. error: %s", libPath, uv_strerror(err));
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
  }

  for (int i = 0; i < numOfFuncs; ++i) {
    err = uv_dlsym(pLib, funcName[i], func[i]);
    if (err != 0) {
      fnError("load library function failed. lib %s function %s", libPath, funcName[i]);
    }
  }
  return 0;
}

371
int32_t udfdInitializePythonPlugin(SUdfScriptPlugin *plugin) {
372
  plugin->scriptType = TSDB_FUNC_SCRIPT_PYTHON;
S
slzhou 已提交
373
  // todo: windows support
S
slzhou 已提交
374
  sprintf(plugin->libPath, "%s", "libtaospyudf.so");
375
  plugin->libLoaded = false;
S
slzhou 已提交
376 377 378 379
  const char *funcName[UDFD_MAX_PLUGIN_FUNCS] = {"pyOpen",         "pyClose",         "pyUdfInit",
                                                 "pyUdfDestroy",   "pyUdfScalarProc", "pyUdfAggStart",
                                                 "pyUdfAggFinish", "pyUdfAggProc",    "pyUdfAggMerge"};
  void      **funcs[UDFD_MAX_PLUGIN_FUNCS] = {
380 381 382
      (void **)&plugin->openFunc,         (void **)&plugin->closeFunc,         (void **)&plugin->udfInitFunc,
      (void **)&plugin->udfDestroyFunc,   (void **)&plugin->udfScalarProcFunc, (void **)&plugin->udfAggStartFunc,
      (void **)&plugin->udfAggFinishFunc, (void **)&plugin->udfAggProcFunc,    (void **)&plugin->udfAggMergeFunc};
S
slzhou 已提交
383
  int32_t err = udfdLoadSharedLib(plugin->libPath, &plugin->lib, funcName, funcs, UDFD_MAX_PLUGIN_FUNCS);
384 385
  if (err != 0) {
    fnError("can not load python plugin. lib path %s", plugin->libPath);
386
    return err;
387
  }
388

389
  if (plugin->openFunc) {
390 391 392
    int16_t lenPythonPath =
        strlen(tsUdfdLdLibPath) + strlen(global.udfDataDir) + 1 + 1;  // global.udfDataDir:tsUdfdLdLibPath
    char *pythonPath = taosMemoryMalloc(lenPythonPath);
393
#ifdef WINDOWS
394
    snprintf(pythonPath, lenPythonPath, "%s;%s", global.udfDataDir, tsUdfdLdLibPath);
395
#else
396
    snprintf(pythonPath, lenPythonPath, "%s:%s", global.udfDataDir, tsUdfdLdLibPath);
397
#endif
S
slzhou 已提交
398
    SScriptUdfEnvItem items[] = {{"PYTHONPATH", pythonPath}, {"LOGDIR", tsLogDir}};
S
slzhou 已提交
399
    err = plugin->openFunc(items, 2);
400
    taosMemoryFree(pythonPath);
401
  }
402 403 404 405 406
  if (err != 0) {
    fnError("udf script python plugin open func failed. error: %d", err);
    uv_dlclose(&plugin->lib);
    return err;
  }
407
  plugin->libLoaded = true;
408 409

  return 0;
410 411
}

412
void udfdDeinitCPlugin(SUdfScriptPlugin *plugin) {
413 414 415 416 417 418 419 420 421 422 423
  if (plugin->closeFunc) {
    plugin->closeFunc();
  }
  plugin->openFunc = NULL;
  plugin->closeFunc = NULL;
  plugin->udfInitFunc = NULL;
  plugin->udfDestroyFunc = NULL;
  plugin->udfScalarProcFunc = NULL;
  plugin->udfAggStartFunc = NULL;
  plugin->udfAggProcFunc = NULL;
  plugin->udfAggMergeFunc = NULL;
424
  plugin->udfAggFinishFunc = NULL;
425 426 427 428
  return;
}

void udfdDeinitPythonPlugin(SUdfScriptPlugin *plugin) {
429 430 431
  if (plugin->closeFunc) {
    plugin->closeFunc();
  }
S
slzhou 已提交
432
  uv_dlclose(&plugin->lib);
433 434 435
  if (plugin->libLoaded) {
    plugin->libLoaded = false;
  }
436 437 438 439 440 441 442 443 444
  plugin->openFunc = NULL;
  plugin->closeFunc = NULL;
  plugin->udfInitFunc = NULL;
  plugin->udfDestroyFunc = NULL;
  plugin->udfScalarProcFunc = NULL;
  plugin->udfAggStartFunc = NULL;
  plugin->udfAggProcFunc = NULL;
  plugin->udfAggMergeFunc = NULL;
  plugin->udfAggFinishFunc = NULL;
445 446
}

S
slzhou 已提交
447 448
int32_t udfdInitScriptPlugin(int8_t scriptType) {
  SUdfScriptPlugin *plugin = taosMemoryCalloc(1, sizeof(SUdfScriptPlugin));
449

S
slzhou 已提交
450 451 452 453
  switch (scriptType) {
    case TSDB_FUNC_SCRIPT_BIN_LIB:
      udfdInitializeCPlugin(plugin);
      break;
454 455 456 457 458 459
    case TSDB_FUNC_SCRIPT_PYTHON: {
      int32_t err = udfdInitializePythonPlugin(plugin);
      if (err != 0) {
        taosMemoryFree(plugin);
        return err;
      }
S
slzhou 已提交
460
      break;
461
    }
S
slzhou 已提交
462 463 464 465 466
    default:
      fnError("udf script type %d not supported", scriptType);
      taosMemoryFree(plugin);
      return TSDB_CODE_UDF_SCRIPT_NOT_SUPPORTED;
  }
467

S
slzhou 已提交
468 469
  global.scriptPlugins[scriptType] = plugin;
  return TSDB_CODE_SUCCESS;
470 471 472
}

void udfdDeinitScriptPlugins() {
473 474
  SUdfScriptPlugin *plugin = NULL;
  plugin = global.scriptPlugins[TSDB_FUNC_SCRIPT_PYTHON];
S
slzhou 已提交
475 476 477 478
  if (plugin != NULL) {
    udfdDeinitPythonPlugin(plugin);
    taosMemoryFree(plugin);
  }
479 480

  plugin = global.scriptPlugins[TSDB_FUNC_SCRIPT_BIN_LIB];
S
slzhou 已提交
481 482 483 484
  if (plugin != NULL) {
    udfdDeinitCPlugin(plugin);
    taosMemoryFree(plugin);
  }
485 486 487
  return;
}

S
shenglian zhou 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
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: {
      udfdProcessSetupRequest(uvUdf, &request);
      break;
    }

    case UDF_TASK_CALL: {
      udfdProcessCallRequest(uvUdf, &request);
      break;
    }
    case UDF_TASK_TEARDOWN: {
      udfdProcessTeardownRequest(uvUdf, &request);
      break;
    }
    default: {
      break;
    }
  }
}

S
slzhou 已提交
513
void convertUdf2UdfInfo(SUdf *udf, SScriptUdfInfo *udfInfo) {
514
  udfInfo->bufSize = udf->bufSize;
S
slzhou 已提交
515 516 517 518 519
  if (udf->funcType == TSDB_FUNC_TYPE_AGGREGATE) {
    udfInfo->funcType = UDF_FUNC_TYPE_AGG;
  } else if (udf->funcType == TSDB_FUNC_TYPE_SCALAR) {
    udfInfo->funcType = UDF_FUNC_TYPE_SCALAR;
  }
S
slzhou 已提交
520
  udfInfo->name = udf->name;
521
  udfInfo->version = udf->version;
522
  udfInfo->createdTime = udf->createdTime;
523 524
  udfInfo->outputLen = udf->outputLen;
  udfInfo->outputType = udf->outputType;
S
slzhou 已提交
525
  udfInfo->path = udf->path;
526 527 528 529 530 531 532 533 534 535
  udfInfo->scriptType = udf->scriptType;
}

int32_t udfdInitUdf(char *udfName, SUdf *udf) {
  int32_t err = 0;
  err = udfdFillUdfInfoFromMNode(global.clientRpc, udfName, udf);
  if (err != 0) {
    fnError("can not retrieve udf from mnode. udf name %s", udfName);
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
  }
S
slzhou 已提交
536 537 538 539 540
  if (udf->scriptType > UDFD_MAX_SCRIPT_TYPE) {
    fnError("udf name %s script type %d not supported", udfName, udf->scriptType);
    return TSDB_CODE_UDF_SCRIPT_NOT_SUPPORTED;
  }

541 542
  uv_mutex_lock(&global.scriptPluginsMutex);
  SUdfScriptPlugin *scriptPlugin = global.scriptPlugins[udf->scriptType];
S
slzhou 已提交
543
  if (scriptPlugin == NULL) {
S
slzhou 已提交
544 545 546 547 548
    err = udfdInitScriptPlugin(udf->scriptType);
    if (err != 0) {
      uv_mutex_unlock(&global.scriptPluginsMutex);
      return err;
    }
549 550
  }
  uv_mutex_unlock(&global.scriptPluginsMutex);
S
slzhou 已提交
551
  udf->scriptPlugin = global.scriptPlugins[udf->scriptType];
S
slzhou 已提交
552

S
slzhou 已提交
553
  SScriptUdfInfo info = {0};
554
  convertUdf2UdfInfo(udf, &info);
S
slzhou 已提交
555 556 557 558 559
  err = udf->scriptPlugin->udfInitFunc(&info, &udf->scriptUdfCtx);
  if (err != 0) {
    fnError("udf name %s init failed. error %d", udfName, err);
    return err;
  }
560

561
  fnInfo("udf init succeeded. name %s type %d context %p", udf->name, udf->scriptType, (void *)udf->scriptUdfCtx);
562 563 564
  return 0;
}

565 566 567
SUdf *udfdNewUdf(const char *udfName) {
  SUdf *udfNew = taosMemoryCalloc(1, sizeof(SUdf));
  udfNew->refCount = 1;
568
  udfNew->lastFetchTime = taosGetTimestampMs();
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
  strncpy(udfNew->name, udfName, TSDB_FUNC_NAME_LEN);

  udfNew->state = UDF_STATE_INIT;
  uv_mutex_init(&udfNew->lock);
  uv_cond_init(&udfNew->condReady);

  udfNew->resident = false;
  udfNew->expired = false;
  for (int32_t i = 0; i < taosArrayGetSize(global.residentFuncs); ++i) {
    char *funcName = taosArrayGet(global.residentFuncs, i);
    if (strcmp(udfName, funcName) == 0) {
      udfNew->resident = true;
      break;
    }
  }
  return udfNew;
}

587
SUdf *udfdGetOrCreateUdf(const char *udfName) {
S
shenglian zhou 已提交
588
  uv_mutex_lock(&global.udfsMutex);
589
  SUdf  **pUdfHash = taosHashGet(global.udfsHash, udfName, strlen(udfName));
S
slzhou 已提交
590
  int64_t currTime = taosGetTimestampMs();
S
slzhou 已提交
591 592
  bool    expired = false;
  if (pUdfHash) {
593
    expired = currTime - (*pUdfHash)->lastFetchTime > 10 * 1000;  // 10s
S
slzhou 已提交
594 595 596 597
    if (!expired) {
      ++(*pUdfHash)->refCount;
      SUdf *udf = *pUdfHash;
      uv_mutex_unlock(&global.udfsMutex);
598 599
      fnInfo("udfd reuse existing udf. udf  %s udf version %d, udf created time %" PRIx64, udf->name, udf->version,
             udf->createdTime);
S
slzhou 已提交
600 601 602 603
      return udf;
    } else {
      (*pUdfHash)->expired = true;
      taosHashRemove(global.udfsHash, udfName, strlen(udfName));
604 605
      fnInfo("udfd expired, check for new version. existing udf %s udf version %d, udf created time %" PRIx64,
             (*pUdfHash)->name, (*pUdfHash)->version, (*pUdfHash)->createdTime);
S
slzhou 已提交
606
    }
607 608
  }

609
  SUdf *udf = udfdNewUdf(udfName);
610

611 612 613 614
  SUdf **pUdf = &udf;
  taosHashPut(global.udfsHash, udfName, strlen(udfName), pUdf, POINTER_BYTES);
  uv_mutex_unlock(&global.udfsMutex);

615 616 617 618 619 620 621 622 623
  return udf;
}

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;
624
  SUdf             *udf = NULL;
625 626

  udf = udfdGetOrCreateUdf(setup->udfName);
S
shenglian zhou 已提交
627 628 629 630

  uv_mutex_lock(&udf->lock);
  if (udf->state == UDF_STATE_INIT) {
    udf->state = UDF_STATE_LOADING;
631
    code = udfdInitUdf(setup->udfName, udf);
632 633 634 635
    if (code == 0) {
      udf->state = UDF_STATE_READY;
    } else {
      udf->state = UDF_STATE_INIT;
S
slzhou 已提交
636
    }
S
shenglian zhou 已提交
637 638 639
    uv_cond_broadcast(&udf->condReady);
    uv_mutex_unlock(&udf->lock);
  } else {
640
    while (udf->state == UDF_STATE_LOADING) {
S
shenglian zhou 已提交
641 642 643 644 645 646 647 648 649 650
      uv_cond_wait(&udf->condReady, &udf->lock);
    }
    uv_mutex_unlock(&udf->lock);
  }
  SUdfcFuncHandle *handle = taosMemoryMalloc(sizeof(SUdfcFuncHandle));
  handle->udf = udf;

  SUdfResponse rsp;
  rsp.seqNum = request->seqNum;
  rsp.type = request->type;
S
slzhou 已提交
651
  rsp.code = (code != 0) ? TSDB_CODE_UDF_FUNC_EXEC_FAILURE : 0;
S
shenglian zhou 已提交
652 653
  rsp.setupRsp.udfHandle = (int64_t)(handle);
  rsp.setupRsp.outputType = udf->outputType;
S
slzhou 已提交
654
  rsp.setupRsp.bytes = udf->outputLen;
S
shenglian zhou 已提交
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
  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;
}

void udfdProcessCallRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
  SUdfCallRequest *call = &request->call;
671 672 673 674
  fnDebug("call request. call type %d, handle: %" PRIx64 ", seq num %" PRId64, call->callType, call->udfHandle,
          request->seqNum);
  SUdfcFuncHandle  *handle = (SUdfcFuncHandle *)(call->udfHandle);
  SUdf             *udf = handle->udf;
S
shenglian zhou 已提交
675
  SUdfResponse      response = {0};
676
  SUdfResponse     *rsp = &response;
S
shenglian zhou 已提交
677 678 679 680 681 682
  SUdfCallResponse *subRsp = &rsp->callRsp;

  int32_t code = TSDB_CODE_SUCCESS;
  switch (call->callType) {
    case TSDB_UDF_CALL_SCALA_PROC: {
      SUdfColumn output = {0};
S
slzhou 已提交
683
      output.colMeta.bytes = udf->outputLen;
684 685 686
      output.colMeta.type = udf->outputType;
      output.colMeta.precision = 0;
      output.colMeta.scale = 0;
687 688
      udfColEnsureCapacity(&output, call->block.info.rows);

S
shenglian zhou 已提交
689 690
      SUdfDataBlock input = {0};
      convertDataBlockToUdfDataBlock(&call->block, &input);
691
      code = udf->scriptPlugin->udfScalarProcFunc(&input, &output, udf->scriptUdfCtx);
S
shenglian zhou 已提交
692 693 694 695 696 697 698
      freeUdfDataDataBlock(&input);
      convertUdfColumnToDataBlock(&output, &response.callRsp.resultData);
      freeUdfColumn(&output);
      break;
    }
    case TSDB_UDF_CALL_AGG_INIT: {
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
699
      code = udf->scriptPlugin->udfAggStartFunc(&outBuf, udf->scriptUdfCtx);
S
shenglian zhou 已提交
700 701 702 703 704 705 706
      subRsp->resultBuf = outBuf;
      break;
    }
    case TSDB_UDF_CALL_AGG_PROC: {
      SUdfDataBlock input = {0};
      convertDataBlockToUdfDataBlock(&call->block, &input);
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
707
      code = udf->scriptPlugin->udfAggProcFunc(&input, &call->interBuf, &outBuf, udf->scriptUdfCtx);
S
shenglian zhou 已提交
708 709 710 711 712 713
      freeUdfInterBuf(&call->interBuf);
      freeUdfDataDataBlock(&input);
      subRsp->resultBuf = outBuf;

      break;
    }
S
slzhou 已提交
714 715
    case TSDB_UDF_CALL_AGG_MERGE: {
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
716
      code = udf->scriptPlugin->udfAggMergeFunc(&call->interBuf, &call->interBuf2, &outBuf, udf->scriptUdfCtx);
S
slzhou 已提交
717 718 719 720 721 722
      freeUdfInterBuf(&call->interBuf);
      freeUdfInterBuf(&call->interBuf2);
      subRsp->resultBuf = outBuf;

      break;
    }
S
shenglian zhou 已提交
723 724
    case TSDB_UDF_CALL_AGG_FIN: {
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
725
      code = udf->scriptPlugin->udfAggFinishFunc(&call->interBuf, &outBuf, udf->scriptUdfCtx);
S
shenglian zhou 已提交
726 727 728 729 730 731 732 733 734 735
      freeUdfInterBuf(&call->interBuf);
      subRsp->resultBuf = outBuf;
      break;
    }
    default:
      break;
  }

  rsp->seqNum = request->seqNum;
  rsp->type = request->type;
S
slzhou 已提交
736
  rsp->code = (code != 0) ? TSDB_CODE_UDF_FUNC_EXEC_FAILURE : 0;
S
shenglian zhou 已提交
737 738 739 740 741 742 743 744 745 746 747
  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);

  switch (call->callType) {
    case TSDB_UDF_CALL_SCALA_PROC: {
748 749
      blockDataFreeRes(&call->block);
      blockDataFreeRes(&subRsp->resultData);
S
shenglian zhou 已提交
750 751 752 753 754 755 756
      break;
    }
    case TSDB_UDF_CALL_AGG_INIT: {
      freeUdfInterBuf(&subRsp->resultBuf);
      break;
    }
    case TSDB_UDF_CALL_AGG_PROC: {
757
      blockDataFreeRes(&call->block);
S
shenglian zhou 已提交
758 759 760
      freeUdfInterBuf(&subRsp->resultBuf);
      break;
    }
S
slzhou 已提交
761 762 763 764
    case TSDB_UDF_CALL_AGG_MERGE: {
      freeUdfInterBuf(&subRsp->resultBuf);
      break;
    }
S
shenglian zhou 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    case TSDB_UDF_CALL_AGG_FIN: {
      freeUdfInterBuf(&subRsp->resultBuf);
      break;
    }
    default:
      break;
  }

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

void udfdProcessTeardownRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
  SUdfTeardownRequest *teardown = &request->teardown;
  fnInfo("teardown. seq number: %" PRId64 ", handle:%" PRIx64, request->seqNum, teardown->udfHandle);
  SUdfcFuncHandle *handle = (SUdfcFuncHandle *)(teardown->udfHandle);
781
  SUdf            *udf = handle->udf;
S
shenglian zhou 已提交
782 783 784 785 786
  bool             unloadUdf = false;
  int32_t          code = TSDB_CODE_SUCCESS;

  uv_mutex_lock(&global.udfsMutex);
  udf->refCount--;
S
slzhou 已提交
787
  if (udf->refCount == 0 && (!udf->resident || udf->expired)) {
S
shenglian zhou 已提交
788 789 790 791 792
    unloadUdf = true;
    taosHashRemove(global.udfsHash, udf->name, strlen(udf->name));
  }
  uv_mutex_unlock(&global.udfsMutex);
  if (unloadUdf) {
793
    fnInfo("udf teardown. udf name: %s type %d: context %p", udf->name, udf->scriptType, (void *)(udf->scriptUdfCtx));
S
shenglian zhou 已提交
794 795
    uv_cond_destroy(&udf->condReady);
    uv_mutex_destroy(&udf->lock);
S
slzhou 已提交
796 797
    code = udf->scriptPlugin->udfDestroyFunc(udf->scriptUdfCtx);
    fnDebug("udfd destroy function returns %d", code);
S
slzhou 已提交
798
    taosMemoryFree(udf);
S
shenglian zhou 已提交
799 800 801
  }
  taosMemoryFree(handle);

S
slzhou 已提交
802
  SUdfResponse  response = {0};
S
shenglian zhou 已提交
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
  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;
}

818
void udfdGetFuncBodyPath(const SUdf *udf, char *path) {
S
shenglian zhou 已提交
819 820
  if (udf->scriptType == TSDB_FUNC_SCRIPT_BIN_LIB) {
#ifdef WINDOWS
821
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64 ".dll", global.udfDataDir, udf->name, udf->version, udf->createdTime);
S
shenglian zhou 已提交
822
#else
823 824
    snprintf(path, PATH_MAX, "%s/lib%s_%d_%" PRIx64 ".so", global.udfDataDir, udf->name, udf->version,
             udf->createdTime);
S
shenglian zhou 已提交
825 826 827
#endif
  } else if (udf->scriptType == TSDB_FUNC_SCRIPT_PYTHON) {
#ifdef WINDOWS
828
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
S
shenglian zhou 已提交
829
#else
830
    snprintf(path, PATH_MAX, "%s/%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
S
shenglian zhou 已提交
831 832 833
#endif
  } else {
#ifdef WINDOWS
834
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64, global.udfDataDir, udf->name, udf->version, udf->createdTime);
S
shenglian zhou 已提交
835
#else
836
    snprintf(path, PATH_MAX, "%s/lib%s_%d_%" PRIx64, global.udfDataDir, udf->name, udf->version, udf->createdTime);
S
shenglian zhou 已提交
837 838 839 840
#endif
  }
}

S
slzhou 已提交
841
int32_t udfdSaveFuncBodyToFile(SFuncInfo *pFuncInfo, SUdf *udf) {
842
  if (!osDataSpaceAvailable()) {
843
    terrno = TSDB_CODE_NO_DISKSPACE;
844 845 846 847 848
    fnError("udfd create shared library failed since %s", terrstr(terrno));
    return terrno;
  }

  char path[PATH_MAX] = {0};
S
shenglian zhou 已提交
849
  udfdGetFuncBodyPath(udf, path);
850 851
  bool fileExist = !(taosStatFile(path, NULL, NULL) < 0);
  if (fileExist) {
S
slzhou 已提交
852
    strncpy(udf->path, path, PATH_MAX);
853
    fnInfo("udfd func body file. reuse existing file %s", path);
S
slzhou 已提交
854
    return TSDB_CODE_SUCCESS;
855 856
  }

857 858 859 860 861 862 863 864 865 866 867
  TdFilePtr file = taosOpenFile(path, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_READ | TD_FILE_TRUNC);
  if (file == NULL) {
    fnError("udfd write udf shared library: %s failed, error: %d %s", path, errno, strerror(errno));
    return TSDB_CODE_FILE_CORRUPTED;
  }
  int64_t count = taosWriteFile(file, pFuncInfo->pCode, pFuncInfo->codeSize);
  if (count != pFuncInfo->codeSize) {
    fnError("udfd write udf shared library failed");
    return TSDB_CODE_FILE_CORRUPTED;
  }
  taosCloseFile(&file);
868

869 870 871 872
  strncpy(udf->path, path, PATH_MAX);
  return TSDB_CODE_SUCCESS;
}

873
void udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet) {
874
  SUdfdRpcSendRecvInfo *msgInfo = (SUdfdRpcSendRecvInfo *)pMsg->info.ahandle;
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890

  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);
891

dengyihao's avatar
dengyihao 已提交
892 893 894 895 896 897
    int32_t now = taosGetTimestampSec();
    int32_t delta = abs(now - connectRsp.svrTimestamp);
    if (delta > 900) {
      msgInfo->code = TSDB_CODE_TIME_UNSYNCED;
      goto _return;
    }
898

899
    if (connectRsp.epSet.numOfEps == 0) {
S
Shengliang Guan 已提交
900
      msgInfo->code = TSDB_CODE_APP_ERROR;
901 902 903 904 905 906 907 908 909 910
      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);
911

912
    SFuncInfo *pFuncInfo = (SFuncInfo *)taosArrayGet(retrieveRsp.pFuncInfos, 0);
913
    SUdf      *udf = msgInfo->param;
914 915
    udf->funcType = pFuncInfo->funcType;
    udf->scriptType = pFuncInfo->scriptType;
916
    udf->outputType = pFuncInfo->outputType;
917 918
    udf->outputLen = pFuncInfo->outputLen;
    udf->bufSize = pFuncInfo->bufSize;
919

920
    SFuncExtraInfo *pFuncExtraInfo = (SFuncExtraInfo *)taosArrayGet(retrieveRsp.pFuncExtraInfos, 0);
921 922
    udf->version = pFuncExtraInfo->funcVersion;
    udf->createdTime = pFuncExtraInfo->funcCreatedTime;
923
    msgInfo->code = udfdSaveFuncBodyToFile(pFuncInfo, udf);
924 925
    if (msgInfo->code != 0) {
      udf->lastFetchTime = 0;
S
shenglian zhou 已提交
926
    }
927 928
    tFreeSFuncInfo(pFuncInfo);
    taosArrayDestroy(retrieveRsp.pFuncInfos);
929
    taosArrayDestroy(retrieveRsp.pFuncExtraInfos);
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
  }

_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);
945
  void   *pReq = rpcMallocCont(contLen);
946 947 948
  tSerializeSRetrieveFuncReq(pReq, contLen, &retrieveReq);
  taosArrayDestroy(retrieveReq.pFuncNames);

dengyihao's avatar
dengyihao 已提交
949
  SUdfdRpcSendRecvInfo *msgInfo = taosMemoryCalloc(1, sizeof(SUdfdRpcSendRecvInfo));
950 951 952 953 954 955 956 957
  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;
958
  rpcMsg.info.ahandle = msgInfo;
959 960 961 962 963 964 965 966 967 968 969 970
  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 已提交
971
  tstrncpy(connReq.app, "udfd", sizeof(connReq.app));
972 973 974 975
  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));
976 977
  connReq.pid = taosGetPId();
  connReq.startTime = taosGetTimestampMs();
D
dapan1121 已提交
978
  strcpy(connReq.sVer, version);
979 980

  int32_t contLen = tSerializeSConnectReq(NULL, 0, &connReq);
981
  void   *pReq = rpcMallocCont(contLen);
982 983 984 985 986 987 988 989 990 991
  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;
992
  rpcMsg.info.ahandle = msgInfo;
993 994 995 996 997 998 999 1000
  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;
}
1001

dengyihao's avatar
dengyihao 已提交
1002
static bool udfdRpcRfp(int32_t code, tmsg_t msgType) {
1003
  if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK || code == TSDB_CODE_SYN_NOT_LEADER ||
1004 1005
      code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED || code == TSDB_CODE_SYN_RESTORING ||
      code == TSDB_CODE_MNODE_NOT_FOUND || code == TSDB_CODE_APP_IS_STARTING || code == TSDB_CODE_APP_IS_STOPPING) {
1006 1007
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
        msgType == TDMT_SCH_MERGE_FETCH) {
dengyihao's avatar
dengyihao 已提交
1008
      return false;
1009
    }
S
shenglian zhou 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    return true;
  } else {
    return false;
  }
}

int initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet) {
  pEpSet->version = 0;

  // init mnode ip set
  SEpSet *mgmtEpSet = &(pEpSet->epSet);
  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;
}

int32_t udfdOpenClientRpc() {
  SRpcInit rpcInit = {0};
  rpcInit.label = "UDFD";
  rpcInit.numOfThreads = 1;
  rpcInit.cfp = (RpcCfp)udfdProcessRpcRsp;
  rpcInit.sessions = 1024;
  rpcInit.connType = TAOS_CONN_CLIENT;
  rpcInit.idleTime = tsShellActivityTimer * 1000;
  rpcInit.user = TSDB_DEFAULT_USER;
  rpcInit.parent = &global;
  rpcInit.rfp = udfdRpcRfp;
dengyihao's avatar
dengyihao 已提交
1068
  rpcInit.compressSize = tsCompressMsgSize;
1069

dengyihao's avatar
dengyihao 已提交
1070 1071 1072 1073 1074 1075
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
  connLimitNum = TMAX(connLimitNum, 10);
  connLimitNum = TMIN(connLimitNum, 500);
  rpcInit.connLimitNum = connLimitNum;
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;

S
shenglian zhou 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084
  global.clientRpc = rpcOpen(&rpcInit);
  if (global.clientRpc == NULL) {
    fnError("failed to init dnode rpc client");
    return -1;
  }
  return 0;
}

int32_t udfdCloseClientRpc() {
1085
  fnInfo("udfd begin closing rpc");
S
shenglian zhou 已提交
1086
  rpcClose(global.clientRpc);
1087
  fnInfo("udfd finish closing rpc");
S
shenglian zhou 已提交
1088 1089 1090
  return 0;
}

1091
void udfdOnWrite(uv_write_t *req, int status) {
S
slzhou 已提交
1092 1093
  SUvUdfWork *work = (SUvUdfWork *)req->data;
  if (status < 0) {
S
slzhou 已提交
1094
    fnError("udfd send response error, length: %zu code: %s", work->output.len, uv_err_name(status));
S
slzhou 已提交
1095
  }
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  // remove work from the connection work list
  if (work->conn != NULL) {
    SUvUdfWork **ppWork;
    for (ppWork = &work->conn->pWorkList; *ppWork && (*ppWork != work); ppWork = &((*ppWork)->pWorkNext)) {
    }
    if (*ppWork == work) {
      *ppWork = work->pWorkNext;
    } else {
      fnError("work not in conn any more");
    }
  }
S
slzhou 已提交
1107 1108 1109
  taosMemoryFree(work->output.base);
  taosMemoryFree(work);
  taosMemoryFree(req);
1110 1111 1112
}

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

1115 1116 1117 1118 1119
  if (udfWork->conn != NULL) {
    uv_write_t *write_req = taosMemoryMalloc(sizeof(uv_write_t));
    write_req->data = udfWork;
    uv_write(write_req, udfWork->conn->client, &udfWork->output, 1, udfdOnWrite);
  }
S
slzhou 已提交
1120
  taosMemoryFree(work);
1121 1122 1123
}

void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
S
slzhou 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  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;
1135
    } else {
dengyihao's avatar
dengyihao 已提交
1136
      fnError("udfd can not allocate enough memory") buf->base = NULL;
S
slzhou 已提交
1137
      buf->len = 0;
1138
    }
1139
  } else if (ctx->inputTotal == -1 && ctx->inputLen < msgHeadSize) {
1140 1141
    buf->base = ctx->inputBuf + ctx->inputLen;
    buf->len = msgHeadSize - ctx->inputLen;
S
slzhou 已提交
1142 1143 1144 1145 1146 1147 1148 1149
  } 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 {
dengyihao's avatar
dengyihao 已提交
1150
      fnError("udfd can not allocate enough memory") buf->base = NULL;
S
slzhou 已提交
1151 1152 1153
      buf->len = 0;
    }
  }
1154 1155 1156
}

bool isUdfdUvMsgComplete(SUdfdUvConn *pipe) {
S
slzhou 已提交
1157 1158 1159 1160 1161 1162 1163 1164
  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;
1165 1166 1167
}

void udfdHandleRequest(SUdfdUvConn *conn) {
1168
  char   *inputBuf = conn->inputBuf;
S
shenglian zhou 已提交
1169 1170
  int32_t inputLen = conn->inputLen;

1171
  uv_work_t  *work = taosMemoryMalloc(sizeof(uv_work_t));
S
slzhou 已提交
1172
  SUvUdfWork *udfWork = taosMemoryMalloc(sizeof(SUvUdfWork));
1173 1174 1175
  udfWork->conn = conn;
  udfWork->pWorkNext = conn->pWorkList;
  conn->pWorkList = udfWork;
S
shenglian zhou 已提交
1176
  udfWork->input = uv_buf_init(inputBuf, inputLen);
S
slzhou 已提交
1177 1178 1179 1180 1181 1182
  conn->inputBuf = NULL;
  conn->inputLen = 0;
  conn->inputCap = 0;
  conn->inputTotal = -1;
  work->data = udfWork;
  uv_queue_work(global.loop, work, udfdProcessRequest, udfdSendResponse);
1183 1184 1185
}

void udfdPipeCloseCb(uv_handle_t *pipe) {
S
slzhou 已提交
1186
  SUdfdUvConn *conn = pipe->data;
1187
  SUvUdfWork  *pWork = conn->pWorkList;
1188 1189 1190 1191 1192
  while (pWork != NULL) {
    pWork->conn = NULL;
    pWork = pWork->pWorkNext;
  }

S
slzhou 已提交
1193 1194 1195
  taosMemoryFree(conn->client);
  taosMemoryFree(conn->inputBuf);
  taosMemoryFree(conn);
1196 1197 1198
}

void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
1199
  fnDebug("udfd read %zd bytes from client", nread);
S
slzhou 已提交
1200
  if (nread == 0) return;
1201

S
slzhou 已提交
1202
  SUdfdUvConn *conn = client->data;
1203

S
slzhou 已提交
1204 1205 1206 1207 1208 1209
  if (nread > 0) {
    conn->inputLen += nread;
    if (isUdfdUvMsgComplete(conn)) {
      udfdHandleRequest(conn);
    } else {
      // log error or continue;
1210
    }
S
slzhou 已提交
1211 1212
    return;
  }
1213

S
slzhou 已提交
1214 1215
  if (nread < 0) {
    if (nread == UV_EOF) {
S
slzhou 已提交
1216
      fnInfo("udfd pipe read EOF");
S
slzhou 已提交
1217
    } else {
1218
      fnError("Receive error %s", uv_err_name(nread));
1219
    }
S
slzhou 已提交
1220 1221
    udfdUvHandleError(conn);
  }
1222 1223 1224
}

void udfdOnNewConnection(uv_stream_t *server, int status) {
S
slzhou 已提交
1225
  if (status < 0) {
S
slzhou 已提交
1226
    fnError("udfd new connection error. code: %s", uv_strerror(status));
S
slzhou 已提交
1227 1228
    return;
  }
1229

S
slzhou 已提交
1230 1231 1232 1233
  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));
1234
    ctx->pWorkList = NULL;
S
slzhou 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    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);
  }
1245 1246
}

1247 1248
void udfdIntrSignalHandler(uv_signal_t *handle, int signum) {
  fnInfo("udfd signal received: %d\n", signum);
S
slzhou 已提交
1249
  uv_fs_t req;
1250 1251 1252
  uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
  uv_signal_stop(handle);
  uv_stop(global.loop);
1253 1254
}

S
slzhou 已提交
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
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 {
    }
  }
1273 1274 1275 1276

  return 0;
}

S
shenglian zhou 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
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);
}

S
slzhou 已提交
1288 1289 1290
static int32_t udfdInitLog() {
  char logName[12] = {0};
  snprintf(logName, sizeof(logName), "%slog", "udfd");
wafwerar's avatar
wafwerar 已提交
1291
  return taosCreateLog(logName, 1, configDir, NULL, NULL, NULL, NULL, 0);
S
slzhou 已提交
1292
}
1293

1294 1295 1296 1297 1298 1299 1300 1301
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));
1302
    taosMemoryFree(buf->base);
S
slzhou 已提交
1303
    uv_close((uv_handle_t *)q, NULL);
1304 1305 1306 1307 1308 1309 1310 1311 1312
    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 已提交
1313
  int     err = uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
1314 1315 1316 1317
  uv_fs_req_cleanup(&req);
  return err;
}

S
slzhou 已提交
1318
static int32_t udfdUvInit() {
S
slzhou 已提交
1319
  uv_loop_t *loop = taosMemoryMalloc(sizeof(uv_loop_t));
S
slzhou 已提交
1320 1321
  if (loop) {
    uv_loop_init(loop);
S
slzhou 已提交
1322 1323
  } else {
    return -1;
S
slzhou 已提交
1324 1325
  }
  global.loop = loop;
1326

1327
  if (tsStartUdfd) {  // udfd is started by taosd, which shall exit when taosd exit
1328 1329 1330 1331
    uv_pipe_init(global.loop, &global.ctrlPipe, 1);
    uv_pipe_open(&global.ctrlPipe, 0);
    uv_read_start((uv_stream_t *)&global.ctrlPipe, udfdCtrlAllocBufCb, udfdCtrlReadCb);
  }
1332
  getUdfdPipeName(global.listenPipeName, sizeof(global.listenPipeName));
S
slzhou 已提交
1333

1334
  removeListeningPipe();
S
slzhou 已提交
1335

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

1338 1339
  uv_signal_init(global.loop, &global.intrSignal);
  uv_signal_start(&global.intrSignal, udfdIntrSignalHandler, SIGINT);
S
slzhou 已提交
1340 1341 1342

  int r;
  fnInfo("bind to pipe %s", global.listenPipeName);
1343
  if ((r = uv_pipe_bind(&global.listeningPipe, global.listenPipeName))) {
S
slzhou 已提交
1344
    fnError("Bind error %s", uv_err_name(r));
1345
    removeListeningPipe();
S
slzhou 已提交
1346
    return -2;
S
slzhou 已提交
1347
  }
1348
  if ((r = uv_listen((uv_stream_t *)&global.listeningPipe, 128, udfdOnNewConnection))) {
S
slzhou 已提交
1349
    fnError("Listen error %s", uv_err_name(r));
1350
    removeListeningPipe();
S
slzhou 已提交
1351
    return -3;
S
slzhou 已提交
1352
  }
1353 1354
  return 0;
}
1355

dengyihao's avatar
dengyihao 已提交
1356
static void udfdCloseWalkCb(uv_handle_t *handle, void *arg) {
S
slzhou 已提交
1357 1358 1359 1360 1361
  if (!uv_is_closing(handle)) {
    uv_close(handle, NULL);
  }
}

S
slzhou 已提交
1362
static int32_t udfdRun() {
1363 1364
  uv_mutex_init(&global.scriptPluginsMutex);

S
slzhou 已提交
1365 1366
  global.udfsHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  uv_mutex_init(&global.udfsMutex);
1367

S
slzhou 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
  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 已提交
1378
  return 0;
S
slzhou 已提交
1379
}
1380

dengyihao's avatar
dengyihao 已提交
1381
void udfdConnectMnodeThreadFunc(void *args) {
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
  int32_t retryMnodeTimes = 0;
  int32_t code = 0;
  while (retryMnodeTimes++ <= TSDB_MAX_REPLICA) {
    uv_sleep(100 * (1 << retryMnodeTimes));
    code = udfdConnectToMnode();
    if (code == 0) {
      break;
    }
    fnError("udfd can not connect to mnode, code: %s. retry", tstrerror(code));
  }

  if (code != 0) {
    fnError("udfd can not connect to mnode");
  }
}

1398
int32_t udfdInitResidentFuncs() {
S
slzhou 已提交
1399 1400 1401 1402
  if (strlen(tsUdfdResFuncs) == 0) {
    return TSDB_CODE_SUCCESS;
  }

1403
  global.residentFuncs = taosArrayInit(2, TSDB_FUNC_NAME_LEN);
1404 1405
  char *pSave = tsUdfdResFuncs;
  char *token;
S
slzhou 已提交
1406
  while ((token = strtok_r(pSave, ",", &pSave)) != NULL) {
1407
    char func[TSDB_FUNC_NAME_LEN + 1] = {0};
S
shenglian zhou 已提交
1408
    strncpy(func, token, TSDB_FUNC_NAME_LEN);
1409
    fnInfo("udfd add resident function %s", func);
S
slzhou 已提交
1410 1411 1412
    taosArrayPush(global.residentFuncs, func);
  }

1413 1414 1415 1416
  return TSDB_CODE_SUCCESS;
}

int32_t udfdDeinitResidentFuncs() {
1417
  for (int32_t i = 0; i < taosArrayGetSize(global.residentFuncs); ++i) {
1418 1419
    char  *funcName = taosArrayGet(global.residentFuncs, i);
    SUdf **udfInHash = taosHashGet(global.udfsHash, funcName, strlen(funcName));
S
slzhou 已提交
1420
    if (udfInHash) {
1421
      SUdf   *udf = *udfInHash;
S
slzhou 已提交
1422 1423
      int32_t code = udf->scriptPlugin->udfDestroyFunc(udf->scriptUdfCtx);
      fnDebug("udfd destroy function returns %d", code);
S
slzhou 已提交
1424
      taosHashRemove(global.udfsHash, funcName, strlen(funcName));
S
slzhou 已提交
1425
      taosMemoryFree(udf);
S
slzhou 已提交
1426 1427
    }
  }
1428
  taosArrayDestroy(global.residentFuncs);
1429 1430 1431
  return TSDB_CODE_SUCCESS;
}

1432 1433 1434 1435 1436 1437
int32_t udfdCleanup() {
  uv_mutex_destroy(&global.udfsMutex);
  taosHashCleanup(global.udfsHash);
  return 0;
}

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
int32_t udfdCreateUdfSourceDir() {
  snprintf(global.udfDataDir, PATH_MAX, "%s/.udf", tsDataDir);
  int32_t code = taosMkDir(global.udfDataDir);
  if (code != TSDB_CODE_SUCCESS) {
    snprintf(global.udfDataDir, PATH_MAX, "%s/.udf", tsTempDir);
    code = taosMkDir(global.udfDataDir);
  }
  fnInfo("udfd create udf source directory %s. result: %s", global.udfDataDir, tstrerror(code));

  return code;
}

int32_t udfdDestroyUdfSourceDir() {
  fnInfo("destory udf source directory %s", global.udfDataDir);
  taosRemoveDir(global.udfDataDir);
  return 0;
}

S
slzhou 已提交
1456
int main(int argc, char *argv[]) {
D
dapan1121 已提交
1457 1458
  if (!taosCheckSystemIsLittleEnd()) {
    printf("failed to start since on non-little-end machines\n");
S
slzhou 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
    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) {
A
Alex Duan 已提交
1473
    // ignore create log failed, because this error no matter
S
slzhou 已提交
1474 1475 1476
    printf("failed to start since init log error\n");
  }

wafwerar's avatar
wafwerar 已提交
1477
  if (taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0) != 0) {
S
slzhou 已提交
1478
    fnError("failed to start since read config error");
1479
    return -2;
S
slzhou 已提交
1480 1481
  }

1482
  initEpSetFromCfg(tsFirst, tsSecond, &global.mgmtEp);
1483
  if (udfdOpenClientRpc() != 0) {
1484
    fnError("open rpc connection to mnode failed");
1485 1486 1487
    return -3;
  }

1488 1489 1490 1491 1492
  if (udfdCreateUdfSourceDir() != 0) {
    fnError("create udf source directory failed");
    return -4;
  }

S
slzhou 已提交
1493 1494 1495 1496 1497
  if (udfdUvInit() != 0) {
    fnError("uv init failure");
    return -5;
  }

1498 1499
  udfdInitResidentFuncs();

1500 1501
  uv_thread_t mnodeConnectThread;
  uv_thread_create(&mnodeConnectThread, udfdConnectMnodeThreadFunc, NULL);
S
slzhou 已提交
1502

1503
  udfdRun();
dengyihao's avatar
dengyihao 已提交
1504

S
slzhou 已提交
1505
  removeListeningPipe();
1506
  udfdDestroyUdfSourceDir();
S
slzhou 已提交
1507
  udfdCloseClientRpc();
S
shenglian zhou 已提交
1508

1509
  udfdDeinitResidentFuncs();
1510 1511 1512

  udfdDeinitScriptPlugins();

1513
  udfdCleanup();
S
shenglian zhou 已提交
1514
  return 0;
1515
}