• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #4921

08 Jan 2026 11:50AM UTC coverage: 65.541%. Remained the same
#4921

push

travis-ci

web-flow
merge: from main to 3.0 branch #34215

16 of 22 new or added lines in 3 files covered. (72.73%)

305 existing lines in 2 files now uncovered.

198770 of 303278 relevant lines covered (65.54%)

127655036.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

75.69
/source/libs/function/src/udfd.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#ifdef USE_UDF
17
// clang-format off
18
#include "uv.h"
19
#include "os.h"
20
#include "fnLog.h"
21
#include "thash.h"
22

23
#include "tudf.h"
24
#include "tudfInt.h"
25
#include "version.h"
26

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

36
#define UDFD_MAX_SCRIPT_PLUGINS 64
37
#define UDFD_MAX_SCRIPT_TYPE    1
38
#define UDFD_MAX_PLUGIN_FUNCS   9
39

40
typedef struct SUdfCPluginCtx {
41
  uv_lib_t lib;
42

43
  TUdfScalarProcFunc scalarProcFunc;
44

45
  TUdfAggStartFunc   aggStartFunc;
46
  TUdfAggProcessFunc aggProcFunc;
47
  TUdfAggFinishFunc  aggFinishFunc;
48

49
  TUdfInitFunc    initFunc;
50
  TUdfDestroyFunc destroyFunc;
51
} SUdfCPluginCtx;
52

53
int32_t udfdCPluginOpen(SScriptUdfEnvItem *items, int numItems) { return 0; }
2,115✔
54

55
int32_t udfdCPluginClose() { return 0; }
2,115✔
56

57
int32_t udfdCPluginUdfInitLoadInitDestoryFuncs(SUdfCPluginCtx *udfCtx, const char *udfName) {
87,090✔
58
  TAOS_UDF_CHECK_PTR_RCODE(udfCtx, udfName);
261,270✔
59
  char  initFuncName[TSDB_FUNC_NAME_LEN + 6] = {0};
87,090✔
60
  char *initSuffix = "_init";
87,090✔
61
  snprintf(initFuncName, sizeof(initFuncName), "%s%s", udfName, initSuffix);
87,090✔
62
  TAOS_CHECK_RETURN(uv_dlsym(&udfCtx->lib, initFuncName, (void **)(&udfCtx->initFunc)));
87,090✔
63

64
  char  destroyFuncName[TSDB_FUNC_NAME_LEN + 9] = {0};
86,586✔
65
  char *destroySuffix = "_destroy";
86,586✔
66
  snprintf(destroyFuncName, sizeof(destroyFuncName), "%s%s", udfName, destroySuffix);
86,586✔
67
  TAOS_CHECK_RETURN(uv_dlsym(&udfCtx->lib, destroyFuncName, (void **)(&udfCtx->destroyFunc)));
86,586✔
68
  return 0;
86,586✔
69
}
70

71
int32_t udfdCPluginUdfInitLoadAggFuncs(SUdfCPluginCtx *udfCtx, const char *udfName) {
11,546✔
72
  TAOS_UDF_CHECK_PTR_RCODE(udfCtx, udfName);
34,638✔
73
  char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
11,546✔
74
  snprintf(processFuncName, sizeof(processFuncName), "%s", udfName); 
11,546✔
75
  TAOS_CHECK_RETURN(uv_dlsym(&udfCtx->lib, processFuncName, (void **)(&udfCtx->aggProcFunc)));
11,546✔
76

77
  char  startFuncName[TSDB_FUNC_NAME_LEN + 7] = {0};
11,546✔
78
  char *startSuffix = "_start";
11,546✔
79
  snprintf(startFuncName, sizeof(startFuncName), "%s%s", processFuncName, startSuffix);
11,546✔
80
  TAOS_CHECK_RETURN(uv_dlsym(&udfCtx->lib, startFuncName, (void **)(&udfCtx->aggStartFunc)));
11,546✔
81

82
  char  finishFuncName[TSDB_FUNC_NAME_LEN + 8] = {0};
10,979✔
83
  char *finishSuffix = "_finish";
10,979✔
84
  snprintf(finishFuncName, sizeof(finishFuncName), "%s%s", processFuncName, finishSuffix);
10,979✔
85
  TAOS_CHECK_RETURN(uv_dlsym(&udfCtx->lib, finishFuncName, (void **)(&udfCtx->aggFinishFunc)));
10,979✔
86

87
  return 0;
10,979✔
88
}
89

90
int32_t udfdCPluginUdfInit(SScriptUdfInfo *udf, void **pUdfCtx) {
87,090✔
91
  TAOS_UDF_CHECK_PTR_RCODE(udf, pUdfCtx);
261,270✔
92
  int32_t         err = 0;
87,090✔
93
  SUdfCPluginCtx *udfCtx = taosMemoryCalloc(1, sizeof(SUdfCPluginCtx));
87,090✔
94
  if (NULL == udfCtx) {
87,090✔
95
    return terrno;
×
96
  }
97
  err = uv_dlopen(udf->path, &udfCtx->lib);
87,090✔
98
  if (err != 0) {
87,090✔
99
    fnError("can not load library %s. error: %s, %s", udf->path, uv_strerror(err), udfCtx->lib.errmsg);
×
100
    taosMemoryFree(udfCtx);
×
101
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
×
102
  }
103
  const char *udfName = udf->name;
87,090✔
104

105
  err = udfdCPluginUdfInitLoadInitDestoryFuncs(udfCtx, udfName);
87,090✔
106
  if (err != 0) {
87,090✔
107
    fnError("can not load init/destroy functions. error: %d", err);
504✔
108
    err = TSDB_CODE_UDF_LOAD_UDF_FAILURE;
504✔
109
    goto _exit;
504✔
110
  }
111

112
  if (udf->funcType == UDF_FUNC_TYPE_SCALAR) {
86,586✔
113
    char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
75,040✔
114
    snprintf(processFuncName, sizeof(processFuncName), "%s", udfName);
75,040✔
115
    if (uv_dlsym(&udfCtx->lib, processFuncName, (void **)(&udfCtx->scalarProcFunc)) != 0) {
75,040✔
116
      fnError("can not load library function %s. error: %s", processFuncName, uv_strerror(err));
×
117
      err = TSDB_CODE_UDF_LOAD_UDF_FAILURE;
×
118
      goto _exit;
×
119
    }
120
  } else if (udf->funcType == UDF_FUNC_TYPE_AGG) {
11,546✔
121
    err = udfdCPluginUdfInitLoadAggFuncs(udfCtx, udfName);
11,546✔
122
    if (err != 0) {
11,546✔
123
      fnError("can not load aggregation functions. error: %d", err);
567✔
124
      err = TSDB_CODE_UDF_LOAD_UDF_FAILURE;
567✔
125
      goto _exit;
567✔
126
    }
127
  }
128

129
  if (udfCtx->initFunc) {
86,019✔
130
    err = (udfCtx->initFunc)();
86,019✔
131
    if (err != 0) {
86,019✔
132
      fnError("udf init function failed. error: %d", err);
×
133
      goto _exit;
×
134
    }
135
  }
136
  *pUdfCtx = udfCtx;
86,019✔
137
  return 0;
86,019✔
138
_exit:
1,071✔
139
  uv_dlclose(&udfCtx->lib);
1,071✔
140
  taosMemoryFree(udfCtx);
1,071✔
141
  return err;
1,071✔
142
}
143

144
int32_t udfdCPluginUdfDestroy(void *udfCtx) {
86,019✔
145
  TAOS_UDF_CHECK_PTR_RCODE(udfCtx);
172,038✔
146
  SUdfCPluginCtx *ctx = udfCtx;
86,019✔
147
  int32_t         code = 0;
86,019✔
148
  if (ctx->destroyFunc) {
86,019✔
149
    code = (ctx->destroyFunc)();
86,019✔
150
  }
151
  uv_dlclose(&ctx->lib);
86,019✔
152
  taosMemoryFree(ctx);
86,019✔
153
  return code;
86,019✔
154
}
155

156
int32_t udfdCPluginUdfScalarProc(SUdfDataBlock *block, SUdfColumn *resultCol, void *udfCtx) {
1,697,430✔
157
  TAOS_UDF_CHECK_PTR_RCODE(block, resultCol, udfCtx);
6,790,784✔
158
  SUdfCPluginCtx *ctx = udfCtx;
1,697,430✔
159
  if (ctx->scalarProcFunc) {
1,697,430✔
160
    return ctx->scalarProcFunc(block, resultCol);
1,698,214✔
161
  } else {
162
    fnError("udfd c plugin scalar proc not implemented");
×
163
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
164
  }
165
}
166

167
int32_t udfdCPluginUdfAggStart(SUdfInterBuf *buf, void *udfCtx) {
182,163✔
168
  TAOS_UDF_CHECK_PTR_RCODE(buf, udfCtx);
546,489✔
169
  SUdfCPluginCtx *ctx = udfCtx;
182,163✔
170
  if (ctx->aggStartFunc) {
182,163✔
171
    return ctx->aggStartFunc(buf);
182,163✔
172
  } else {
173
    fnError("udfd c plugin aggregation start not implemented");
×
174
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
175
  }
176
  return 0;
177
}
178

179
int32_t udfdCPluginUdfAggProc(SUdfDataBlock *block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf, void *udfCtx) {
430,128✔
180
  TAOS_UDF_CHECK_PTR_RCODE(block, interBuf, newInterBuf, udfCtx);
2,150,640✔
181
  SUdfCPluginCtx *ctx = udfCtx;
430,128✔
182
  if (ctx->aggProcFunc) {
430,128✔
183
    return ctx->aggProcFunc(block, interBuf, newInterBuf);
430,128✔
184
  } else {
185
    fnError("udfd c plugin aggregation process not implemented");
×
186
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
187
  }
188
}
189

190
// int32_t udfdCPluginUdfAggMerge(SUdfInterBuf *inputBuf1, SUdfInterBuf *inputBuf2, SUdfInterBuf *outputBuf,
191
//                                void *udfCtx) {
192
//   TAOS_UDF_CHECK_PTR_RCODE(inputBuf1, inputBuf2, outputBuf, udfCtx);
193
//   SUdfCPluginCtx *ctx = udfCtx;
194
//   if (ctx->aggMergeFunc) {
195
//     return ctx->aggMergeFunc(inputBuf1, inputBuf2, outputBuf);
196
//   } else {
197
//     fnError("udfd c plugin aggregation merge not implemented");
198
//     return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
199
//   }
200
// }
201

202
int32_t udfdCPluginUdfAggFinish(SUdfInterBuf *buf, SUdfInterBuf *resultData, void *udfCtx) {
180,966✔
203
  TAOS_UDF_CHECK_PTR_RCODE(buf, resultData, udfCtx);
723,864✔
204
  SUdfCPluginCtx *ctx = udfCtx;
180,966✔
205
  if (ctx->aggFinishFunc) {
180,966✔
206
    return ctx->aggFinishFunc(buf, resultData);
180,966✔
207
  } else {
208
    fnError("udfd c plugin aggregation finish not implemented");
×
209
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
210
  }
211
  return 0;
212
}
213

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

219
  char     libPath[PATH_MAX];
220
  bool     libLoaded;
221
  uv_lib_t lib;
222

223
  TScriptUdfScalarProcFunc udfScalarProcFunc;
224
  TScriptUdfAggStartFunc   udfAggStartFunc;
225
  TScriptUdfAggProcessFunc udfAggProcFunc;
226
  TScriptUdfAggMergeFunc   udfAggMergeFunc;
227
  TScriptUdfAggFinishFunc  udfAggFinishFunc;
228

229
  TScriptUdfInitFunc    udfInitFunc;
230
  TScriptUdfDestoryFunc udfDestroyFunc;
231

232
  TScriptOpenFunc  openFunc;
233
  TScriptCloseFunc closeFunc;
234
} SUdfScriptPlugin;
235

236
typedef struct SUdfdContext {
237
  uv_loop_t  *loop;
238
  uv_pipe_t   ctrlPipe;
239
  uv_signal_t intrSignal;
240
  char        listenPipeName[PATH_MAX + UDF_LISTEN_PIPE_NAME_LEN + 2];
241
  uv_pipe_t   listeningPipe;
242

243
  void     *clientRpc;
244
  SCorEpSet mgmtEp;
245

246
  uv_mutex_t udfsMutex;
247
  SHashObj  *udfsHash;
248

249
  uv_mutex_t        scriptPluginsMutex;
250
  SUdfScriptPlugin *scriptPlugins[UDFD_MAX_SCRIPT_PLUGINS];
251

252
  SArray *residentFuncs;
253

254
  char udfDataDir[PATH_MAX];
255
  bool printVersion;
256
} SUdfdContext;
257

258
SUdfdContext global;
259

260
struct SUdfdUvConn;
261
struct SUvUdfWork;
262

263
typedef struct SUdfdUvConn {
264
  uv_stream_t *client;
265
  char        *inputBuf;
266
  int32_t      inputLen;
267
  int32_t      inputCap;
268
  int32_t      inputTotal;
269

270
  struct SUvUdfWork *pWorkList;  // head of work list
271
} SUdfdUvConn;
272

273
typedef struct SUvUdfWork {
274
  SUdfdUvConn *conn;
275
  uv_buf_t     input;
276
  uv_buf_t     output;
277

278
  struct SUvUdfWork *pWorkNext;
279
} SUvUdfWork;
280

281
typedef enum { UDF_STATE_INIT = 0, UDF_STATE_LOADING, UDF_STATE_READY } EUdfState;
282

283
typedef struct SUdf {
284
  char    name[TSDB_FUNC_NAME_LEN + 1];
285
  int32_t version;
286
  int64_t createdTime;
287

288
  int8_t  funcType;
289
  int8_t  scriptType;
290
  int8_t  outputType;
291
  int32_t outputLen;
292
  int32_t bufSize;
293

294
  char path[PATH_MAX];
295

296
  int32_t    refCount;
297
  EUdfState  state;
298
  uv_mutex_t lock;
299
  uv_cond_t  condReady;
300
  bool       resident;
301

302
  SUdfScriptPlugin *scriptPlugin;
303
  void             *scriptUdfCtx;
304

305
  int64_t lastFetchTime;  // last fetch time in milliseconds
306
  bool    expired;
307
} SUdf;
308

309
typedef struct SUdfcFuncHandle {
310
  SUdf *udf;
311
} SUdfcFuncHandle;
312

313
typedef enum EUdfdRpcReqRspType {
314
  UDFD_RPC_MNODE_CONNECT = 0,
315
  UDFD_RPC_RETRIVE_FUNC,
316
} EUdfdRpcReqRspType;
317

318
typedef struct SUdfdRpcSendRecvInfo {
319
  EUdfdRpcReqRspType rpcType;
320
  int32_t            code;
321
  void              *param;
322
  uv_sem_t           resultSem;
323
} SUdfdRpcSendRecvInfo;
324

325
static void    udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet);
326
static int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf);
327
static int32_t udfdConnectToMnode();
328
static bool    udfdRpcRfp(int32_t code, tmsg_t msgType);
329
static int     initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet);
330
static int32_t udfdOpenClientRpc();
331
static void    udfdCloseClientRpc();
332

333
static void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request);
334
static void udfdProcessCallRequest(SUvUdfWork *uvUdf, SUdfRequest *request);
335
static void udfdProcessTeardownRequest(SUvUdfWork *uvUdf, SUdfRequest *request);
336
static void udfdProcessRequest(uv_work_t *req);
337
static void udfdOnWrite(uv_write_t *req, int status);
338
static void udfdSendResponse(uv_work_t *work, int status);
339
static void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf);
340
static bool isUdfdUvMsgComplete(SUdfdUvConn *pipe);
341
static void udfdHandleRequest(SUdfdUvConn *conn);
342
static void udfdPipeCloseCb(uv_handle_t *pipe);
343
static void udfdUvHandleError(SUdfdUvConn *conn) { uv_close((uv_handle_t *)conn->client, udfdPipeCloseCb); }
219,937✔
344
static void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf);
345
static void udfdOnNewConnection(uv_stream_t *server, int status);
346

347
static void    udfdIntrSignalHandler(uv_signal_t *handle, int signum);
348
static void    removeListeningPipe();
349

350
static void    udfdPrintVersion();
351
static int32_t udfdParseArgs(int32_t argc, char *argv[]);
352
static int32_t udfdInitLog();
353

354
static void    udfdCtrlAllocBufCb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf);
355
static void    udfdCtrlReadCb(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf);
356
static int32_t udfdUvInit();
357
static void    udfdCloseWalkCb(uv_handle_t *handle, void *arg);
358
static void    udfdRun();
359
static void    udfdConnectMnodeThreadFunc(void *args);
360

361
int32_t udfdNewUdf(SUdf **pUdf,  const char *udfName);
362
void  udfdGetFuncBodyPath(const SUdf *udf, char *path);
363

364
int32_t udfdInitializeCPlugin(SUdfScriptPlugin *plugin) {
2,115✔
365
  TAOS_UDF_CHECK_PTR_RCODE(plugin);
4,230✔
366
  plugin->scriptType = TSDB_FUNC_SCRIPT_BIN_LIB;
2,115✔
367
  plugin->openFunc = udfdCPluginOpen;
2,115✔
368
  plugin->closeFunc = udfdCPluginClose;
2,115✔
369
  plugin->udfInitFunc = udfdCPluginUdfInit;
2,115✔
370
  plugin->udfDestroyFunc = udfdCPluginUdfDestroy;
2,115✔
371
  plugin->udfScalarProcFunc = udfdCPluginUdfScalarProc;
2,115✔
372
  plugin->udfAggStartFunc = udfdCPluginUdfAggStart;
2,115✔
373
  plugin->udfAggProcFunc = udfdCPluginUdfAggProc;
2,115✔
374
  // plugin->udfAggMergeFunc = udfdCPluginUdfAggMerge;
375
  plugin->udfAggFinishFunc = udfdCPluginUdfAggFinish;
2,115✔
376

377
  SScriptUdfEnvItem items[1] = {{"LD_LIBRARY_PATH", tsUdfdLdLibPath}};
2,115✔
378
  int32_t           err = plugin->openFunc(items, 1);
2,115✔
379
  if (err != 0) return err;
2,115✔
380
  return 0;
2,115✔
381
}
382

383
int32_t udfdLoadSharedLib(char *libPath, uv_lib_t *pLib, const char *funcName[], void **func[], int numOfFuncs) {
59✔
384
  TAOS_UDF_CHECK_PTR_RCODE(libPath, pLib, funcName, func);
295✔
385
  int err = uv_dlopen(libPath, pLib);
59✔
386
  if (err != 0) {
59✔
387
    fnError("can not load library %s. error: %s, %s", libPath, uv_strerror(err), pLib->errmsg);
×
388
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
×
389
  }
390

391
  for (int i = 0; i < numOfFuncs; ++i) {
590✔
392
    err = uv_dlsym(pLib, funcName[i], func[i]);
531✔
393
    if (err != 0) {
531✔
394
      fnError("load library function failed. lib %s function %s", libPath, funcName[i]);
×
395
    }
396
  }
397
  return 0;
59✔
398
}
399

400
int32_t udfdInitializePythonPlugin(SUdfScriptPlugin *plugin) {
59✔
401
  TAOS_UDF_CHECK_PTR_RCODE(plugin);
118✔
402
  plugin->scriptType = TSDB_FUNC_SCRIPT_PYTHON;
59✔
403
  // todo: windows support
404
  snprintf(plugin->libPath, PATH_MAX, "%s", "libtaospyudf.so");
59✔
405
  plugin->libLoaded = false;
59✔
406
  const char *funcName[UDFD_MAX_PLUGIN_FUNCS] = {"pyOpen",         "pyClose",         "pyUdfInit",
59✔
407
                                                 "pyUdfDestroy",   "pyUdfScalarProc", "pyUdfAggStart",
408
                                                 "pyUdfAggFinish", "pyUdfAggProc",    "pyUdfAggMerge"};
409
  void      **funcs[UDFD_MAX_PLUGIN_FUNCS] = {
59✔
410
           (void **)&plugin->openFunc,         (void **)&plugin->closeFunc,         (void **)&plugin->udfInitFunc,
59✔
411
           (void **)&plugin->udfDestroyFunc,   (void **)&plugin->udfScalarProcFunc, (void **)&plugin->udfAggStartFunc,
59✔
412
           (void **)&plugin->udfAggFinishFunc, (void **)&plugin->udfAggProcFunc,    (void **)&plugin->udfAggMergeFunc};
59✔
413
  int32_t err = udfdLoadSharedLib(plugin->libPath, &plugin->lib, funcName, funcs, UDFD_MAX_PLUGIN_FUNCS);
59✔
414
  if (err != 0) {
59✔
415
    fnError("can not load python plugin. lib path %s", plugin->libPath);
×
416
    return err;
×
417
  }
418

419
  if (plugin->openFunc) {
59✔
420
    int16_t lenPythonPath =
59✔
421
        strlen(tsUdfdLdLibPath) + strlen(global.udfDataDir) + 1 + 1;  // global.udfDataDir:tsUdfdLdLibPath
59✔
422
    char *pythonPath = taosMemoryMalloc(lenPythonPath);
59✔
423
    if(pythonPath == NULL) {
59✔
424
      uv_dlclose(&plugin->lib);
×
425
      return terrno;
×
426
    }
427
#ifdef WINDOWS
428
    snprintf(pythonPath, lenPythonPath, "%s;%s", global.udfDataDir, tsUdfdLdLibPath);
429
#else
430
    snprintf(pythonPath, lenPythonPath, "%s:%s", global.udfDataDir, tsUdfdLdLibPath);
59✔
431
#endif
432
    SScriptUdfEnvItem items[] = {{"PYTHONPATH", pythonPath}, {"LOGDIR", tsLogDir}};
59✔
433
    err = plugin->openFunc(items, 2);
59✔
434
    taosMemoryFree(pythonPath);
59✔
435
  }
436
  if (err != 0) {
59✔
437
    fnError("udf script python plugin open func failed. error: %d", err);
×
438
    uv_dlclose(&plugin->lib);
×
439
    return err;
×
440
  }
441
  plugin->libLoaded = true;
59✔
442

443
  return 0;
59✔
444
}
445

446
void udfdDeinitCPlugin(SUdfScriptPlugin *plugin) {
2,115✔
447
  TAOS_UDF_CHECK_PTR_RVOID(plugin);
4,230✔
448
  if (plugin->closeFunc) {
2,115✔
449
    if (plugin->closeFunc() != 0) {
2,115✔
450
      fnError("udf script c plugin close func failed.line:%d", __LINE__);
×
451
    }
452
  }
453
  plugin->openFunc = NULL;
2,115✔
454
  plugin->closeFunc = NULL;
2,115✔
455
  plugin->udfInitFunc = NULL;
2,115✔
456
  plugin->udfDestroyFunc = NULL;
2,115✔
457
  plugin->udfScalarProcFunc = NULL;
2,115✔
458
  plugin->udfAggStartFunc = NULL;
2,115✔
459
  plugin->udfAggProcFunc = NULL;
2,115✔
460
  plugin->udfAggMergeFunc = NULL;
2,115✔
461
  plugin->udfAggFinishFunc = NULL;
2,115✔
462
  return;
2,115✔
463
}
464

465
void udfdDeinitPythonPlugin(SUdfScriptPlugin *plugin) {
59✔
466
  TAOS_UDF_CHECK_PTR_RVOID(plugin);
118✔
467
  if (plugin->closeFunc) {
59✔
468
    if (plugin->closeFunc() != 0) {
59✔
469
      fnError("udf script python plugin close func failed.line:%d", __LINE__);
×
470
    }
471
  }
472
  uv_dlclose(&plugin->lib);
59✔
473
  if (plugin->libLoaded) {
59✔
474
    plugin->libLoaded = false;
59✔
475
  }
476
  plugin->openFunc = NULL;
59✔
477
  plugin->closeFunc = NULL;
59✔
478
  plugin->udfInitFunc = NULL;
59✔
479
  plugin->udfDestroyFunc = NULL;
59✔
480
  plugin->udfScalarProcFunc = NULL;
59✔
481
  plugin->udfAggStartFunc = NULL;
59✔
482
  plugin->udfAggProcFunc = NULL;
59✔
483
  plugin->udfAggMergeFunc = NULL;
59✔
484
  plugin->udfAggFinishFunc = NULL;
59✔
485
}
486

487
int32_t udfdInitScriptPlugin(int8_t scriptType) {
2,174✔
488
  SUdfScriptPlugin *plugin = taosMemoryCalloc(1, sizeof(SUdfScriptPlugin));
2,174✔
489
  if (plugin == NULL) {
2,174✔
490
    return terrno;
×
491
  }
492
  int32_t err = 0;
2,174✔
493
  switch (scriptType) {
2,174✔
494
    case TSDB_FUNC_SCRIPT_BIN_LIB:
2,115✔
495
      err = udfdInitializeCPlugin(plugin);
2,115✔
496
      if (err != 0) {
2,115✔
497
        fnError("udf script c plugin init failed. error: %d", err);
×
498
        taosMemoryFree(plugin);
×
499
        return err;
×
500
      }
501
      break;
2,115✔
502
    case TSDB_FUNC_SCRIPT_PYTHON: {
59✔
503
      err = udfdInitializePythonPlugin(plugin);
59✔
504
      if (err != 0) {
59✔
505
        fnError("udf script python plugin init failed. error: %d", err);
×
506
        taosMemoryFree(plugin);
×
507
        return err;
×
508
      }
509
      break;
59✔
510
    }
511
    default:
×
512
      fnError("udf script type %d not supported", scriptType);
×
513
      taosMemoryFree(plugin);
×
514
      return TSDB_CODE_UDF_SCRIPT_NOT_SUPPORTED;
×
515
  }
516

517
  global.scriptPlugins[scriptType] = plugin;
2,174✔
518
  return TSDB_CODE_SUCCESS;
2,174✔
519
}
520

521
void udfdDeinitScriptPlugins() {
572,189✔
522
  SUdfScriptPlugin *plugin = NULL;
572,189✔
523
  plugin = global.scriptPlugins[TSDB_FUNC_SCRIPT_PYTHON];
572,189✔
524
  if (plugin != NULL) {
572,189✔
525
    udfdDeinitPythonPlugin(plugin);
59✔
526
    taosMemoryFree(plugin);
59✔
527
    global.scriptPlugins[TSDB_FUNC_SCRIPT_PYTHON] = NULL;
59✔
528
  }
529

530
  plugin = global.scriptPlugins[TSDB_FUNC_SCRIPT_BIN_LIB];
572,189✔
531
  if (plugin != NULL) {
572,189✔
532
    udfdDeinitCPlugin(plugin);
2,115✔
533
    taosMemoryFree(plugin);
2,115✔
534
    global.scriptPlugins[TSDB_FUNC_SCRIPT_BIN_LIB] = NULL;
2,115✔
535
  }
536
  return;
572,189✔
537
}
538

539
void udfdProcessRequest(uv_work_t *req) {
2,991,973✔
540
  TAOS_UDF_CHECK_PTR_RVOID(req);
5,983,946✔
541
  SUvUdfWork *uvUdf = (SUvUdfWork *)(req->data);
2,991,973✔
542
  if (uvUdf == NULL) {
2,991,973✔
543
    fnError("udf work is NULL");
×
544
    return;
×
545
  }
546
  SUdfRequest request = {0};
2,991,973✔
547
  if(decodeUdfRequest(uvUdf->input.base, &request) == NULL)
2,991,973✔
548
  {
549
    taosMemoryFreeClear(uvUdf->input.base);
280✔
550
    fnError("udf request decode failed");
280✔
551
    return;
×
552
  }
553

554
  switch (request.type) {
2,991,525✔
555
    case UDF_TASK_SETUP: {
219,937✔
556
      udfdProcessSetupRequest(uvUdf, &request);
219,937✔
557
      break;
219,937✔
558
    }
559

560
    case UDF_TASK_CALL: {
2,552,722✔
561
      udfdProcessCallRequest(uvUdf, &request);
2,552,722✔
562
      break;
2,552,778✔
563
    }
564
    case UDF_TASK_TEARDOWN: {
218,866✔
565
      udfdProcessTeardownRequest(uvUdf, &request);
218,866✔
566
      break;
218,866✔
567
    }
568
    default: {
×
569
      break;
×
570
    }
571
  }
572
}
573

574
static void convertUdf2UdfInfo(SUdf *udf, SScriptUdfInfo *udfInfo) {
102,017✔
575
  udfInfo->bufSize = udf->bufSize;
102,017✔
576
  if (udf->funcType == TSDB_FUNC_TYPE_AGGREGATE) {
102,017✔
577
    udfInfo->funcType = UDF_FUNC_TYPE_AGG;
15,688✔
578
  } else if (udf->funcType == TSDB_FUNC_TYPE_SCALAR) {
86,329✔
579
    udfInfo->funcType = UDF_FUNC_TYPE_SCALAR;
86,329✔
580
  }
581
  udfInfo->name = udf->name;
102,017✔
582
  udfInfo->version = udf->version;
102,017✔
583
  udfInfo->createdTime = udf->createdTime;
102,017✔
584
  udfInfo->outputLen = udf->outputLen;
102,017✔
585
  udfInfo->outputType = udf->outputType;
102,017✔
586
  udfInfo->path = udf->path;
102,017✔
587
  udfInfo->scriptType = udf->scriptType;
102,017✔
588
}
102,017✔
589

590
static int32_t udfdInitUdf(char *udfName, SUdf *udf) {
102,017✔
591
  TAOS_UDF_CHECK_PTR_RCODE(udfName, udf);
306,051✔
592
  int32_t err = 0;
102,017✔
593
  err = udfdFillUdfInfoFromMNode(global.clientRpc, udfName, udf);
102,017✔
594
  if (err != 0) {
102,017✔
595
    fnError("can not retrieve udf from mnode. udf name %s", udfName);
×
596
    return TSDB_CODE_UDF_LOAD_UDF_FAILURE;
×
597
  }
598
  if (udf->scriptType > UDFD_MAX_SCRIPT_TYPE) {
102,017✔
599
    fnError("udf name %s script type %d not supported", udfName, udf->scriptType);
×
600
    return TSDB_CODE_UDF_SCRIPT_NOT_SUPPORTED;
×
601
  }
602

603
  uv_mutex_lock(&global.scriptPluginsMutex);
102,017✔
604
  SUdfScriptPlugin *scriptPlugin = global.scriptPlugins[udf->scriptType];
102,017✔
605
  if (scriptPlugin == NULL) {
102,017✔
606
    err = udfdInitScriptPlugin(udf->scriptType);
2,174✔
607
    if (err != 0) {
2,174✔
608
      fnError("udf name %s init script plugin failed. error %d", udfName, err);
×
609
      uv_mutex_unlock(&global.scriptPluginsMutex);
×
610
      return err;
×
611
    }
612
  }
613
  uv_mutex_unlock(&global.scriptPluginsMutex);
102,017✔
614
  udf->scriptPlugin = global.scriptPlugins[udf->scriptType];
102,017✔
615

616
  SScriptUdfInfo info = {0};
102,017✔
617
  convertUdf2UdfInfo(udf, &info);
102,017✔
618
  err = udf->scriptPlugin->udfInitFunc(&info, &udf->scriptUdfCtx);
102,017✔
619
  if (err != 0) {
102,017✔
620
    fnError("udf name %s init failed. error %d", udfName, err);
1,071✔
621
    return err;
1,071✔
622
  }
623

624
  fnInfo("udf init succeeded. name %s type %d context %p", udf->name, udf->scriptType, (void *)udf->scriptUdfCtx);
100,946✔
625
  return 0;
100,946✔
626
}
627

628
int32_t udfdNewUdf(SUdf **pUdf, const char *udfName) {
101,135✔
629
  TAOS_UDF_CHECK_PTR_RCODE(pUdf, udfName);
303,405✔
630
  SUdf *udfNew = taosMemoryCalloc(1, sizeof(SUdf));
101,135✔
631
  if (NULL == udfNew) {
101,135✔
632
    return terrno;
×
633
  }
634
  udfNew->refCount = 1;
101,135✔
635
  udfNew->lastFetchTime = taosGetTimestampMs();
101,135✔
636
  tstrncpy(udfNew->name, udfName, TSDB_FUNC_NAME_LEN);
101,135✔
637

638
  udfNew->state = UDF_STATE_INIT;
101,135✔
639
  if (uv_mutex_init(&udfNew->lock) != 0) return TSDB_CODE_UDF_UV_EXEC_FAILURE;
101,135✔
640
  if (uv_cond_init(&udfNew->condReady) != 0) return TSDB_CODE_UDF_UV_EXEC_FAILURE;
101,135✔
641

642
  udfNew->resident = false;
101,135✔
643
  udfNew->expired = false;
101,135✔
644
  for (int32_t i = 0; i < taosArrayGetSize(global.residentFuncs); ++i) {
102,727✔
645
    char *funcName = taosArrayGet(global.residentFuncs, i);
4,009✔
646
    if (strcmp(udfName, funcName) == 0) {
4,009✔
647
      udfNew->resident = true;
2,417✔
648
      break;
2,417✔
649
    }
650
  }
651
  *pUdf =  udfNew;
101,135✔
652
  return 0;
101,135✔
653
}
654

655
void udfdFreeUdf(void *pData) {
×
656
  SUdf *pSudf = (SUdf *)pData;
×
657
  if (pSudf == NULL) {
×
658
    return;
×
659
  }
660

661
  if (pSudf->scriptPlugin != NULL) {
×
662
    if(pSudf->scriptPlugin->udfDestroyFunc(pSudf->scriptUdfCtx) != 0) {
×
663
      fnError("udfdFreeUdf: udfd destroy udf %s failed", pSudf->name);
×
664
    }
665
  }
666

667
  uv_mutex_destroy(&pSudf->lock);
×
668
  uv_cond_destroy(&pSudf->condReady);
×
669
  taosMemoryFree(pSudf);
×
670
}
671

672
int32_t udfdGetOrCreateUdf(SUdf **ppUdf, const char *udfName) {
219,937✔
673
  TAOS_UDF_CHECK_PTR_RCODE(ppUdf, udfName);
659,811✔
674
  uv_mutex_lock(&global.udfsMutex);
219,937✔
675
  SUdf  **pUdfHash = taosHashGet(global.udfsHash, udfName, strlen(udfName));
219,937✔
676
  int64_t currTime = taosGetTimestampMs();
219,937✔
677
  bool    expired = false;
219,937✔
678
  if (pUdfHash) {
219,937✔
679
    expired = currTime - (*pUdfHash)->lastFetchTime > 10 * 1000;  // 10s
118,802✔
680
    if (!expired) {
118,802✔
681
      ++(*pUdfHash)->refCount;
118,802✔
682
      *ppUdf = *pUdfHash;
118,802✔
683
      uv_mutex_unlock(&global.udfsMutex);
118,802✔
684
      fnInfo("udfd reuse existing udf. udf  %s udf version %d, udf created time %" PRIx64, (*ppUdf)->name, (*ppUdf)->version,
118,802✔
685
             (*ppUdf)->createdTime);
686
      return 0;
118,802✔
687
    } else {
688
      (*pUdfHash)->expired = true;
×
689
      fnInfo("udfd expired, check for new version. existing udf %s udf version %d, udf created time %" PRIx64,
×
690
             (*pUdfHash)->name, (*pUdfHash)->version, (*pUdfHash)->createdTime);
691
      if(taosHashRemove(global.udfsHash, udfName, strlen(udfName)) != 0) {
×
692
        fnError("udfdGetOrCreateUdf: udfd remove udf %s failed", udfName);
×
693
      }
694
    }
695
  }
696

697
  int32_t code = udfdNewUdf(ppUdf, udfName);
101,135✔
698
  if(code != 0) {
101,135✔
699
    uv_mutex_unlock(&global.udfsMutex);
×
700
    return code;
×
701
  }
702

703
  if ((code = taosHashPut(global.udfsHash, udfName, strlen(udfName), ppUdf, POINTER_BYTES)) != 0) {
101,135✔
704
    uv_mutex_unlock(&global.udfsMutex);
×
705
    return code;
×
706
  }
707
  uv_mutex_unlock(&global.udfsMutex);
101,135✔
708

709
  return 0;
101,135✔
710
}
711

712
void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
219,937✔
713
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
659,811✔
714
  // TODO: tracable id from client. connect, setup, call, teardown
715
  fnInfo("setup request. seq num: %" PRId64 ", udf name: %s", request->seqNum, request->setup.udfName);
219,937✔
716

717
  SUdfSetupRequest *setup = &request->setup;
219,937✔
718
  int32_t           code = TSDB_CODE_SUCCESS;
219,937✔
719
  SUdf *udf = NULL;
219,937✔
720

721
  code = udfdGetOrCreateUdf(&udf, setup->udfName);
219,937✔
722
  if(code != 0) {
219,937✔
723
    fnError("udfdGetOrCreateUdf failed. udf name %s", setup->udfName);
×
724
    goto _send;
×
725
  }
726
  uv_mutex_lock(&udf->lock);
219,937✔
727
  if (udf->state == UDF_STATE_INIT) {
219,937✔
728
    udf->state = UDF_STATE_LOADING;
102,017✔
729
    code = udfdInitUdf(setup->udfName, udf);
102,017✔
730
    if (code == 0) {
102,017✔
731
      udf->state = UDF_STATE_READY;
100,946✔
732
    } else {
733
      udf->state = UDF_STATE_INIT;
1,071✔
734
    }
735
    uv_cond_broadcast(&udf->condReady);
102,017✔
736
    uv_mutex_unlock(&udf->lock);
102,017✔
737
  } else {
738
    while (udf->state == UDF_STATE_LOADING) {
117,920✔
739
      uv_cond_wait(&udf->condReady, &udf->lock);
×
740
    }
741
    uv_mutex_unlock(&udf->lock);
117,920✔
742
  }
743

744
  SUdfcFuncHandle *handle = NULL;
219,937✔
745
  if (!code) {
219,937✔
746
    handle = taosMemoryMalloc(sizeof(SUdfcFuncHandle));
218,866✔
747
    if (handle == NULL) {
218,866✔
NEW
748
      fnError("udfdProcessSetupRequest: malloc failed.");
×
NEW
749
      code = terrno;
×
750
    } else {
751
      handle->udf = udf;
218,866✔
752
    }
753
  } else {
754
    --udf->refCount;
1,071✔
755
  }
756

757
_send:
219,937✔
758
  ;
759
  SUdfResponse rsp;
134,065✔
760
  rsp.seqNum = request->seqNum;
219,937✔
761
  rsp.type = request->type;
219,937✔
762
  rsp.code = (code != 0) ? TSDB_CODE_UDF_FUNC_EXEC_FAILURE : 0;
219,937✔
763
  rsp.setupRsp.udfHandle = (int64_t)(handle);
219,937✔
764
  rsp.setupRsp.outputType = udf->outputType;
219,937✔
765
  rsp.setupRsp.bytes = udf->outputLen;
219,937✔
766
  rsp.setupRsp.bufSize = udf->bufSize;
219,937✔
767

768
  int32_t len = encodeUdfResponse(NULL, &rsp);
219,937✔
769
  if(len < 0) {
219,937✔
UNCOV
770
    fnError("udfdProcessSetupRequest: encode udf response failed. len %d", len);
×
UNCOV
771
    return;
×
772
  }
773
  rsp.msgLen = len;
219,937✔
774
  void *bufBegin = taosMemoryMalloc(len);
219,937✔
775
  if(bufBegin == NULL) {
219,937✔
UNCOV
776
    fnError("udfdProcessSetupRequest: malloc failed. len %d", len);
×
777
    return;
×
778
  }
779
  void *buf = bufBegin;
219,937✔
780
  if(encodeUdfResponse(&buf, &rsp) < 0) {
219,937✔
UNCOV
781
    fnError("udfdProcessSetupRequest: encode udf response failed. len %d", len);
×
UNCOV
782
    taosMemoryFree(bufBegin);
×
783
    return;
×
784
  }
785
  
786
  uvUdf->output = uv_buf_init(bufBegin, len);
219,937✔
787

788
  taosMemoryFreeClear(uvUdf->input.base);
219,937✔
789
  return;
219,937✔
790
}
791

792
static int32_t checkUDFScalaResult(SSDataBlock *block, SUdfColumn *output) {
1,718,978✔
793
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_NEVER) {
1,718,978✔
UNCOV
794
    return TSDB_CODE_SUCCESS;
×
795
  }
796
  if (output->colData.numOfRows != block->info.rows) {
1,718,978✔
UNCOV
797
    fnError("udf scala result num of rows %d not equal to input rows %" PRId64, output->colData.numOfRows, block->info.rows);
×
UNCOV
798
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
799
  }
800

801
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_BYROW) {
1,718,978✔
UNCOV
802
    for (int32_t i = 0; i < output->colData.numOfRows; ++i) {
×
UNCOV
803
      if (!udfColDataIsNull(output, i)) {
×
804
        if (IS_VAR_DATA_TYPE(output->colMeta.type)) {
×
805
          TAOS_UDF_CHECK_CONDITION(output->colData.varLenCol.payload != NULL, TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
×
UNCOV
806
          TAOS_UDF_CHECK_CONDITION(output->colData.varLenCol.varOffsets[i] >= 0 &&
×
807
                                       output->colData.varLenCol.varOffsets[i] < output->colData.varLenCol.payloadLen,
808
                                   TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
809
        } else {
810
          TAOS_UDF_CHECK_CONDITION(
×
811
              output->colMeta.bytes * output->colData.numOfRows <= output->colData.fixLenCol.dataLen,
812
              TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
813
          break;
×
814
        }
815
      }
816
    }
817
  }
818

819
  return TSDB_CODE_SUCCESS;
1,718,978✔
820
}
821

822
static int32_t checkUDFAggResult(SSDataBlock *block, SUdfInterBuf *output) {
463,581✔
823
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_NEVER) {
463,581✔
UNCOV
824
    return TSDB_CODE_SUCCESS;
×
825
  }
826
  if (output->numOfResult != 1 && output->numOfResult != 0) {
463,581✔
UNCOV
827
    fnError("udf agg result num of rows %d not equal to 1", output->numOfResult);
×
UNCOV
828
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
829
  }
830
  TAOS_UDF_CHECK_CONDITION(output->buf != NULL, TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
463,581✔
831
  TAOS_UDF_CHECK_CONDITION(output->bufLen > 0, TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
463,581✔
832
  return TSDB_CODE_SUCCESS;
463,581✔
833
}
834

835
void udfdProcessCallRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
2,552,722✔
836
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
7,658,222✔
837
  SUdfCallRequest *call = &request->call;
2,552,722✔
838
  fnDebug("call request. call type %d, handle: %" PRIx64 ", seq num %" PRId64, call->callType, call->udfHandle,
2,552,722✔
839
          request->seqNum);
840
  SUdfcFuncHandle  *handle = (SUdfcFuncHandle *)(call->udfHandle);
2,552,890✔
841
  SUdf             *udf = handle->udf;
2,552,890✔
842
  SUdfResponse      response = {0};
2,552,890✔
843
  SUdfResponse     *rsp = &response;
2,552,890✔
844
  SUdfCallResponse *subRsp = &rsp->callRsp;
2,552,890✔
845

846
  int32_t code = TSDB_CODE_SUCCESS;
2,552,890✔
847
  switch (call->callType) {
2,552,890✔
848
    case TSDB_UDF_CALL_SCALA_PROC: {
1,721,106✔
849
      SUdfColumn output = {0};
1,721,106✔
850
      output.colMeta.bytes = udf->outputLen;
1,721,106✔
851
      output.colMeta.type = udf->outputType;
1,721,106✔
852
      output.colMeta.precision = 0;
1,721,106✔
853
      output.colMeta.scale = 0;
1,721,106✔
854
      if (udfColEnsureCapacity(&output, call->block.info.rows) == TSDB_CODE_SUCCESS) {
3,442,212✔
855
        SUdfDataBlock input = {0};
1,720,991✔
856
        code = convertDataBlockToUdfDataBlock(&call->block, &input);
1,720,991✔
857
        if (code == TSDB_CODE_SUCCESS) code = udf->scriptPlugin->udfScalarProcFunc(&input, &output, udf->scriptUdfCtx);
1,719,874✔
858
        freeUdfDataDataBlock(&input);
1,719,930✔
859
        if (code == TSDB_CODE_SUCCESS) code = checkUDFScalaResult(&call->block, &output);
1,720,882✔
860
        if (code == TSDB_CODE_SUCCESS) code = convertUdfColumnToDataBlock(&output, &response.callRsp.resultData);
1,719,930✔
861
      }
862
      freeUdfColumn(&output);
1,720,381✔
863
      break;
1,721,215✔
864
    }
865
    case TSDB_UDF_CALL_AGG_INIT: {
184,700✔
866
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
184,700✔
867
      if (outBuf.buf != NULL) {
184,700✔
868
        code = udf->scriptPlugin->udfAggStartFunc(&outBuf, udf->scriptUdfCtx);
184,700✔
869
      } else {
UNCOV
870
        code = terrno;
×
871
      }
872
      subRsp->resultBuf = outBuf;
184,700✔
873
      break;
184,700✔
874
    }
875
    case TSDB_UDF_CALL_AGG_PROC: {
463,581✔
876
      SUdfDataBlock input = {0};
463,581✔
877
      if (convertDataBlockToUdfDataBlock(&call->block, &input) == TSDB_CODE_SUCCESS) {
463,581✔
878
        SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
463,581✔
879
        if (outBuf.buf != NULL) {
463,581✔
880
          code = udf->scriptPlugin->udfAggProcFunc(&input, &call->interBuf, &outBuf, udf->scriptUdfCtx);
463,581✔
881
          freeUdfInterBuf(&call->interBuf);
463,581✔
882
          if (code == TSDB_CODE_SUCCESS) code = checkUDFAggResult(&call->block, &outBuf);
463,581✔
883
          subRsp->resultBuf = outBuf;
463,581✔
884
        } else {
UNCOV
885
          code = terrno;
×
886
        }
887
      }
888
      freeUdfDataDataBlock(&input);
463,581✔
889

890
      break;
463,581✔
891
    }
892
    // case TSDB_UDF_CALL_AGG_MERGE: {
893
    //   SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
894
    //   if (outBuf.buf != NULL) {
895
    //     code = udf->scriptPlugin->udfAggMergeFunc(&call->interBuf, &call->interBuf2, &outBuf, udf->scriptUdfCtx);
896
    //     freeUdfInterBuf(&call->interBuf);
897
    //     freeUdfInterBuf(&call->interBuf2);
898
    //     subRsp->resultBuf = outBuf;
899
    //   } else {
900
    //     code = terrno;
901
    //   }
902
    // 
903
    //   break;
904
    // }
905
    case TSDB_UDF_CALL_AGG_FIN: {
183,503✔
906
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
183,503✔
907
      if (outBuf.buf != NULL) {
183,503✔
908
        code = udf->scriptPlugin->udfAggFinishFunc(&call->interBuf, &outBuf, udf->scriptUdfCtx);
183,503✔
909
        freeUdfInterBuf(&call->interBuf);
183,503✔
910
        subRsp->resultBuf = outBuf;
183,503✔
911
      } else {
UNCOV
912
        code = terrno;
×
913
      }
914

915
      break;
183,503✔
916
    }
UNCOV
917
    default:
×
UNCOV
918
      break;
×
919
  }
920

921
  rsp->seqNum = request->seqNum;
2,552,999✔
922
  rsp->type = request->type;
2,552,999✔
923
  rsp->code = (code != 0) ? TSDB_CODE_UDF_FUNC_EXEC_FAILURE : 0;
2,552,999✔
924
  subRsp->callType = call->callType;
2,552,999✔
925

926
  int32_t len = encodeUdfResponse(NULL, rsp);
2,552,999✔
927
  if(len < 0) {
2,550,370✔
UNCOV
928
    fnError("udfdProcessCallRequest: encode udf response failed. len %d", len);
×
UNCOV
929
    goto _exit;
×
930
  }
931
  rsp->msgLen = len;
2,550,370✔
932
  void *bufBegin = taosMemoryMalloc(len);
2,550,370✔
933
  if (bufBegin == NULL) {
2,552,666✔
UNCOV
934
    fnError("udfdProcessCallRequest: malloc failed. len %d", len);
×
935
    goto _exit;
×
936
  }
937
  void *buf = bufBegin;
2,552,666✔
938
  if(encodeUdfResponse(&buf, rsp) < 0) {
2,552,666✔
UNCOV
939
    fnError("udfdProcessCallRequest: encode udf response failed. len %d", len);
×
UNCOV
940
    taosMemoryFree(bufBegin);
×
941
    goto _exit;
×
942
  }
943

944
  uvUdf->output = uv_buf_init(bufBegin, len);
2,550,818✔
945

946
_exit:
2,552,498✔
947
  switch (call->callType) {
2,552,498✔
948
    case TSDB_UDF_CALL_SCALA_PROC: {
1,720,714✔
949
      blockDataFreeRes(&call->block);
1,720,714✔
950
      blockDataFreeRes(&subRsp->resultData);
1,720,210✔
951
      break;
1,721,050✔
952
    }
953
    case TSDB_UDF_CALL_AGG_INIT: {
184,700✔
954
      freeUdfInterBuf(&subRsp->resultBuf);
184,700✔
955
      break;
184,700✔
956
    }
957
    case TSDB_UDF_CALL_AGG_PROC: {
463,581✔
958
      blockDataFreeRes(&call->block);
463,581✔
959
      freeUdfInterBuf(&subRsp->resultBuf);
463,581✔
960
      break;
463,525✔
961
    }
962
    // case TSDB_UDF_CALL_AGG_MERGE: {
963
    //   freeUdfInterBuf(&subRsp->resultBuf);
964
    //   break;
965
    // }
966
    case TSDB_UDF_CALL_AGG_FIN: {
183,503✔
967
      freeUdfInterBuf(&subRsp->resultBuf);
183,503✔
968
      break;
183,503✔
969
    }
UNCOV
970
    default:
×
UNCOV
971
      break;
×
972
  }
973

974
  taosMemoryFreeClear(uvUdf->input.base);
2,552,778✔
975
  return;
2,552,946✔
976
}
977

978
void udfdProcessTeardownRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
218,866✔
979
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
656,598✔
980
  SUdfTeardownRequest *teardown = &request->teardown;
218,866✔
981
  fnInfo("teardown. seq number: %" PRId64 ", handle:%" PRIx64, request->seqNum, teardown->udfHandle);
218,866✔
982
  SUdfcFuncHandle *handle = (SUdfcFuncHandle *)(teardown->udfHandle);
218,866✔
983
  SUdf            *udf = handle->udf;
218,866✔
984
  bool             unloadUdf = false;
218,866✔
985
  int32_t          code = TSDB_CODE_SUCCESS;
218,866✔
986

987
  uv_mutex_lock(&global.udfsMutex);
218,866✔
988
  udf->refCount--;
218,866✔
989
  if (udf->refCount == 0 && (!udf->resident || udf->expired)) {
218,866✔
990
    unloadUdf = true;
98,529✔
991
    code = taosHashRemove(global.udfsHash, udf->name, strlen(udf->name));
98,529✔
992
    if (code != 0) {
98,529✔
UNCOV
993
      fnError("udf name %s remove from hash failed, err:%0x %s", udf->name, code, tstrerror(code));
×
UNCOV
994
      uv_mutex_unlock(&global.udfsMutex);
×
UNCOV
995
      goto _send;
×
996
    }
997
  }
998
  uv_mutex_unlock(&global.udfsMutex);
218,866✔
999
  if (unloadUdf) {
218,866✔
1000
    fnInfo("udf teardown. udf name: %s type %d: context %p", udf->name, udf->scriptType, (void *)(udf->scriptUdfCtx));
98,529✔
1001
    uv_cond_destroy(&udf->condReady);
98,529✔
1002
    uv_mutex_destroy(&udf->lock);
98,529✔
1003
    code = udf->scriptPlugin->udfDestroyFunc(udf->scriptUdfCtx);
98,529✔
1004
    fnDebug("udfd destroy function returns %d", code);
98,529✔
1005
    taosMemoryFree(udf);
98,529✔
1006
  }
1007

1008
_send:
120,337✔
1009
  taosMemoryFree(handle);
218,866✔
1010
  SUdfResponse  response = {0};
218,866✔
1011
  SUdfResponse *rsp = &response;
218,866✔
1012
  rsp->seqNum = request->seqNum;
218,866✔
1013
  rsp->type = request->type;
218,866✔
1014
  rsp->code = code;
218,866✔
1015
  int32_t len = encodeUdfResponse(NULL, rsp);
218,866✔
1016
  if (len < 0) {
218,866✔
UNCOV
1017
    fnError("udfdProcessTeardownRequest: encode udf response failed. len %d", len);
×
UNCOV
1018
    return;
×
1019
  }
1020
  rsp->msgLen = len;
218,866✔
1021
  void *bufBegin = taosMemoryMalloc(len);
218,866✔
1022
  if(bufBegin == NULL) {
218,866✔
UNCOV
1023
    fnError("udfdProcessTeardownRequest: malloc failed. len %d", len);
×
1024
    return;
×
1025
  }
1026
  void *buf = bufBegin;
218,866✔
1027
  if (encodeUdfResponse(&buf, rsp) < 0) {
218,866✔
UNCOV
1028
    fnError("udfdProcessTeardownRequest: encode udf response failed. len %d", len);
×
UNCOV
1029
    taosMemoryFree(bufBegin);
×
1030
    return;
×
1031
  }
1032
  uvUdf->output = uv_buf_init(bufBegin, len);
218,866✔
1033

1034
  taosMemoryFree(uvUdf->input.base);
218,866✔
1035
  return;
218,866✔
1036
}
1037

1038
void udfdGetFuncBodyPath(const SUdf *udf, char *path) {
102,017✔
1039
  TAOS_UDF_CHECK_PTR_RVOID(udf, path);
306,051✔
1040
  if (udf->scriptType == TSDB_FUNC_SCRIPT_BIN_LIB) {
102,017✔
1041
#ifdef WINDOWS
1042
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64 ".dll", global.udfDataDir, udf->name, udf->version, udf->createdTime);
1043
#else
1044
    snprintf(path, PATH_MAX, "%s/lib%s_%d_%" PRIx64 ".so", global.udfDataDir, udf->name, udf->version,
87,090✔
1045
             udf->createdTime);
87,090✔
1046
#endif
1047
  } else if (udf->scriptType == TSDB_FUNC_SCRIPT_PYTHON) {
14,927✔
1048
#ifdef WINDOWS
1049
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
1050
#else
1051
    snprintf(path, PATH_MAX, "%s/%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
14,927✔
1052
#endif
1053
  } else {
1054
#ifdef WINDOWS
1055
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64, global.udfDataDir, udf->name, udf->version, udf->createdTime);
1056
#else
UNCOV
1057
    snprintf(path, PATH_MAX, "%s/lib%s_%d_%" PRIx64, global.udfDataDir, udf->name, udf->version, udf->createdTime);
×
1058
#endif
1059
  }
1060
}
1061

1062
int32_t udfdSaveFuncBodyToFile(SFuncInfo *pFuncInfo, SUdf *udf) {
102,017✔
1063
  TAOS_UDF_CHECK_PTR_RCODE(pFuncInfo, udf);
306,051✔
1064
  if (!osDataSpaceAvailable()) {
102,017✔
UNCOV
1065
    terrno = TSDB_CODE_NO_DISKSPACE;
×
UNCOV
1066
    fnError("udfd create shared library failed since %s", terrstr());
×
UNCOV
1067
    return terrno;
×
1068
  }
1069

1070
  char path[PATH_MAX] = {0};
102,017✔
1071
  udfdGetFuncBodyPath(udf, path);
102,017✔
1072
  bool fileExist = !(taosStatFile(path, NULL, NULL, NULL) < 0);
102,017✔
1073
  if (fileExist) {
102,017✔
1074
    tstrncpy(udf->path, path, PATH_MAX);
95,760✔
1075
    fnInfo("udfd func body file. reuse existing file %s", path);
95,760✔
1076
    return TSDB_CODE_SUCCESS;
95,760✔
1077
  }
1078

1079
  TdFilePtr file = taosOpenFile(path, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_READ | TD_FILE_TRUNC);
6,257✔
1080
  if (file == NULL) {
6,257✔
UNCOV
1081
    fnError("udfd write udf shared library: %s failed, error: %d %s", path, ERRNO, strerror(ERRNO));
×
UNCOV
1082
    return TSDB_CODE_FILE_CORRUPTED;
×
1083
  }
1084
  int64_t count = taosWriteFile(file, pFuncInfo->pCode, pFuncInfo->codeSize);
6,257✔
1085
  if (count != pFuncInfo->codeSize) {
6,257✔
UNCOV
1086
    fnError("udfd write udf shared library failed");
×
UNCOV
1087
    return TSDB_CODE_FILE_CORRUPTED;
×
1088
  }
1089
  if(taosCloseFile(&file) != 0) {
6,257✔
UNCOV
1090
    fnError("udfdSaveFuncBodyToFile, udfd close file failed");
×
UNCOV
1091
    return TSDB_CODE_FILE_CORRUPTED;
×
1092
  }
1093

1094
  tstrncpy(udf->path, path, PATH_MAX);
6,257✔
1095
  return TSDB_CODE_SUCCESS;
6,257✔
1096
}
1097

1098
void udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet) {
102,017✔
1099
  TAOS_UDF_CHECK_PTR_RVOID(parent, pMsg);
306,051✔
1100
  SUdfdRpcSendRecvInfo *msgInfo = (SUdfdRpcSendRecvInfo *)pMsg->info.ahandle;
102,017✔
1101

1102
  if (pEpSet) {
102,017✔
UNCOV
1103
    if (!isEpsetEqual(&global.mgmtEp.epSet, pEpSet)) {
×
UNCOV
1104
      updateEpSet_s(&global.mgmtEp, pEpSet);
×
1105
    }
1106
  }
1107

1108
  if (pMsg->code != TSDB_CODE_SUCCESS) {
102,017✔
UNCOV
1109
    fnError("udfd rpc error, code:%s", tstrerror(pMsg->code));
×
1110
    msgInfo->code = pMsg->code;
×
1111
    goto _return;
×
1112
  }
1113

1114
  if (msgInfo->rpcType == UDFD_RPC_MNODE_CONNECT) {
102,017✔
UNCOV
1115
    SConnectRsp connectRsp = {0};
×
1116
    if(tDeserializeSConnectRsp(pMsg->pCont, pMsg->contLen, &connectRsp) < 0){
×
1117
      fnError("udfd deserialize connect response failed");
×
1118
      goto _return;
×
1119
    }
1120

UNCOV
1121
    int32_t now = taosGetTimestampSec();
×
1122
    int32_t delta = abs(now - connectRsp.svrTimestamp);
×
1123
    if (delta > 900) {
×
1124
      msgInfo->code = TSDB_CODE_TIME_UNSYNCED;
×
1125
      goto _return;
×
1126
    }
1127

1128
    if (connectRsp.epSet.numOfEps == 0) {
×
1129
      msgInfo->code = TSDB_CODE_APP_ERROR;
×
1130
      goto _return;
×
1131
    }
1132

UNCOV
1133
    if (connectRsp.dnodeNum > 1 && !isEpsetEqual(&global.mgmtEp.epSet, &connectRsp.epSet)) {
×
UNCOV
1134
      updateEpSet_s(&global.mgmtEp, &connectRsp.epSet);
×
1135
    }
1136
    msgInfo->code = 0;
×
1137
  } else if (msgInfo->rpcType == UDFD_RPC_RETRIVE_FUNC) {
102,017✔
1138
    SRetrieveFuncRsp retrieveRsp = {0};
102,017✔
1139
    if(tDeserializeSRetrieveFuncRsp(pMsg->pCont, pMsg->contLen, &retrieveRsp) < 0){
102,017✔
1140
      fnError("udfd deserialize retrieve func response failed");
×
1141
      goto _return;
×
1142
    }
1143

1144
    SFuncInfo *pFuncInfo = (SFuncInfo *)taosArrayGet(retrieveRsp.pFuncInfos, 0);
102,017✔
1145
    SUdf      *udf = msgInfo->param;
102,017✔
1146
    udf->funcType = pFuncInfo->funcType;
102,017✔
1147
    udf->scriptType = pFuncInfo->scriptType;
102,017✔
1148
    udf->outputType = pFuncInfo->outputType;
102,017✔
1149
    udf->outputLen = pFuncInfo->outputLen;
102,017✔
1150
    udf->bufSize = pFuncInfo->bufSize;
102,017✔
1151

1152
    SFuncExtraInfo *pFuncExtraInfo = (SFuncExtraInfo *)taosArrayGet(retrieveRsp.pFuncExtraInfos, 0);
102,017✔
1153
    udf->version = pFuncExtraInfo->funcVersion;
102,017✔
1154
    udf->createdTime = pFuncExtraInfo->funcCreatedTime;
102,017✔
1155
    msgInfo->code = udfdSaveFuncBodyToFile(pFuncInfo, udf);
102,017✔
1156
    if (msgInfo->code != 0) {
102,017✔
UNCOV
1157
      udf->lastFetchTime = 0;
×
1158
    }
1159
    tFreeSFuncInfo(pFuncInfo);
102,017✔
1160
    taosArrayDestroy(retrieveRsp.pFuncInfos);
102,017✔
1161
    taosArrayDestroy(retrieveRsp.pFuncExtraInfos);
102,017✔
1162
  }
1163

1164
_return:
×
1165
  rpcFreeCont(pMsg->pCont);
102,017✔
1166
  uv_sem_post(&msgInfo->resultSem);
102,017✔
1167
  return;
102,017✔
1168
}
1169

1170
int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf) {
102,017✔
1171
  TAOS_UDF_CHECK_PTR_RCODE(clientRpc, udfName, udf);
408,068✔
1172
  SRetrieveFuncReq retrieveReq = {0};
102,017✔
1173
  retrieveReq.numOfFuncs = 1;
102,017✔
1174
  retrieveReq.pFuncNames = taosArrayInit(1, TSDB_FUNC_NAME_LEN);
102,017✔
1175
  if(taosArrayPush(retrieveReq.pFuncNames, udfName) == NULL) {
204,034✔
UNCOV
1176
    taosArrayDestroy(retrieveReq.pFuncNames);
×
UNCOV
1177
    return terrno;
×
1178
  }
1179

1180
  int32_t contLen = tSerializeSRetrieveFuncReq(NULL, 0, &retrieveReq);
102,017✔
1181
  if(contLen < 0) {
102,017✔
UNCOV
1182
    taosArrayDestroy(retrieveReq.pFuncNames);
×
1183
    return terrno;
×
1184
  }
1185
  void   *pReq = rpcMallocCont(contLen);
102,017✔
1186
  if(tSerializeSRetrieveFuncReq(pReq, contLen, &retrieveReq)  < 0) {
102,017✔
UNCOV
1187
    taosArrayDestroy(retrieveReq.pFuncNames);
×
UNCOV
1188
    rpcFreeCont(pReq);
×
1189
    return terrno;
×
1190
  }
1191
  taosArrayDestroy(retrieveReq.pFuncNames);
102,017✔
1192

1193
  SUdfdRpcSendRecvInfo *msgInfo = taosMemoryCalloc(1, sizeof(SUdfdRpcSendRecvInfo));
102,017✔
1194
  if(NULL == msgInfo) {
102,017✔
1195
    return terrno;
×
1196
  }
1197
  msgInfo->rpcType = UDFD_RPC_RETRIVE_FUNC;
102,017✔
1198
  msgInfo->param = udf;
102,017✔
1199
  if(uv_sem_init(&msgInfo->resultSem, 0)  != 0) {
102,017✔
UNCOV
1200
    taosMemoryFree(msgInfo);
×
UNCOV
1201
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1202
  }
1203

1204
  SRpcMsg rpcMsg = {0};
102,017✔
1205
  rpcMsg.pCont = pReq;
102,017✔
1206
  rpcMsg.contLen = contLen;
102,017✔
1207
  rpcMsg.msgType = TDMT_MND_RETRIEVE_FUNC;
102,017✔
1208
  rpcMsg.info.ahandle = msgInfo;
102,017✔
1209
  int32_t code = rpcSendRequest(clientRpc, &global.mgmtEp.epSet, &rpcMsg, NULL);
102,017✔
1210
  if (code == 0) {
102,017✔
1211
    uv_sem_wait(&msgInfo->resultSem);
102,017✔
1212
    uv_sem_destroy(&msgInfo->resultSem);
102,017✔
1213
    code = msgInfo->code;
102,017✔
1214
  }
1215
  taosMemoryFree(msgInfo);
102,017✔
1216
  return code;
102,017✔
1217
}
1218

UNCOV
1219
static bool udfdRpcRfp(int32_t code, tmsg_t msgType) {
×
UNCOV
1220
  if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK || code == TSDB_CODE_SYN_NOT_LEADER ||
×
UNCOV
1221
      code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED || code == TSDB_CODE_SYN_RESTORING ||
×
UNCOV
1222
      code == TSDB_CODE_MNODE_NOT_FOUND || code == TSDB_CODE_APP_IS_STARTING || code == TSDB_CODE_APP_IS_STOPPING) {
×
UNCOV
1223
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
×
UNCOV
1224
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_TASK_NOTIFY) {
×
UNCOV
1225
      return false;
×
1226
    }
1227
    return true;
×
1228
  } else {
1229
    return false;
×
1230
  }
1231
}
1232

1233
int initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet) {
572,189✔
1234
  pEpSet->version = 0;
572,189✔
1235

1236
  // init mnode ip set
1237
  SEpSet *mgmtEpSet = &(pEpSet->epSet);
572,189✔
1238
  mgmtEpSet->numOfEps = 0;
572,189✔
1239
  mgmtEpSet->inUse = 0;
572,189✔
1240

1241
  if (firstEp && firstEp[0] != 0) {
572,189✔
1242
    if (strlen(firstEp) >= TSDB_EP_LEN) {
572,189✔
UNCOV
1243
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
UNCOV
1244
      return -1;
×
1245
    }
1246

1247
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[0]);
572,189✔
1248
    if (code != TSDB_CODE_SUCCESS) {
572,189✔
UNCOV
1249
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1250
      return terrno;
×
1251
    }
1252

1253
    mgmtEpSet->numOfEps++;
572,189✔
1254
  }
1255

1256
  if (secondEp && secondEp[0] != 0) {
572,189✔
1257
    if (strlen(secondEp) >= TSDB_EP_LEN) {
572,189✔
UNCOV
1258
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
UNCOV
1259
      return -1;
×
1260
    }
1261

1262
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
572,189✔
1263
    if (code != TSDB_CODE_SUCCESS) {
572,189✔
UNCOV
1264
      fnError("invalid ep %s", secondEp);
×
1265
    } else {
1266
      mgmtEpSet->numOfEps++;
572,189✔
1267
    }
1268
  }
1269

1270
  if (mgmtEpSet->numOfEps == 0) {
572,189✔
1271
    terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
UNCOV
1272
    return -1;
×
1273
  }
1274

1275
  return 0;
572,189✔
1276
}
1277

1278
int32_t udfdOpenClientRpc() {
572,189✔
1279
  SRpcInit rpcInit = {0};
572,189✔
1280
  rpcInit.label = "UDFD";
572,189✔
1281
  rpcInit.numOfThreads = 1;
572,189✔
1282
  rpcInit.cfp = (RpcCfp)udfdProcessRpcRsp;
572,189✔
1283
  rpcInit.sessions = 1024;
572,189✔
1284
  rpcInit.connType = TAOS_CONN_CLIENT;
572,189✔
1285
  rpcInit.idleTime = tsShellActivityTimer * 1000;
572,189✔
1286
  rpcInit.user = TSDB_DEFAULT_USER;
572,189✔
1287
  rpcInit.parent = &global;
572,189✔
1288
  rpcInit.rfp = udfdRpcRfp;
572,189✔
1289
  rpcInit.compressSize = tsCompressMsgSize;
572,189✔
1290

1291
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
572,189✔
1292
  connLimitNum = TMAX(connLimitNum, 10);
572,189✔
1293
  connLimitNum = TMIN(connLimitNum, 500);
572,189✔
1294
  rpcInit.connLimitNum = connLimitNum;
572,189✔
1295
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
572,189✔
1296

1297
  rpcInit.enableSSL = tsEnableTLS;
572,189✔
1298
  rpcInit.enableSasl = tsEnableSasl;
572,189✔
1299
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
572,189✔
1300
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
572,189✔
1301
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
572,189✔
1302
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
572,189✔
1303
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
572,189✔
1304
  TAOS_CHECK_RETURN(taosVersionStrToInt(td_version, &rpcInit.compatibilityVer));
572,189✔
1305

1306
  global.clientRpc = rpcOpen(&rpcInit);
572,189✔
1307
  if (global.clientRpc == NULL) {
572,189✔
UNCOV
1308
    fnError("failed to init dnode rpc client");
×
UNCOV
1309
    return terrno;
×
1310
  }
1311
  return 0;
572,189✔
1312
}
1313

1314
void udfdCloseClientRpc() {
572,189✔
1315
  fnInfo("udfd begin closing rpc");
572,189✔
1316
  rpcClose(global.clientRpc);
572,189✔
1317
  fnInfo("udfd finish closing rpc");
572,189✔
1318
}
572,189✔
1319

1320
void udfdOnWrite(uv_write_t *req, int status) {
2,992,085✔
1321
  TAOS_UDF_CHECK_PTR_RVOID(req);
5,984,170✔
1322
  SUvUdfWork *work = (SUvUdfWork *)req->data;
2,992,085✔
1323
  if (status < 0) {
2,992,085✔
UNCOV
1324
    fnError("udfd send response error, length:%zu code:%s", work->output.len, uv_err_name(status));
×
1325
  }
1326
  // remove work from the connection work list
1327
  if (work->conn != NULL) {
2,992,085✔
1328
    SUvUdfWork **ppWork;
1329
    for (ppWork = &work->conn->pWorkList; *ppWork && (*ppWork != work); ppWork = &((*ppWork)->pWorkNext)) {
5,464,018✔
1330
    }
1331
    if (*ppWork == work) {
2,992,085✔
1332
      *ppWork = work->pWorkNext;
2,992,085✔
1333
    } else {
UNCOV
1334
      fnError("work not in conn any more");
×
1335
    }
1336
  }
1337
  taosMemoryFree(work->output.base);
2,992,085✔
1338
  taosMemoryFree(work);
2,992,085✔
1339
  taosMemoryFree(req);
2,992,085✔
1340
}
1341

1342
void udfdSendResponse(uv_work_t *work, int status) {
2,992,085✔
1343
  TAOS_UDF_CHECK_PTR_RVOID(work);
5,984,170✔
1344
  SUvUdfWork *udfWork = (SUvUdfWork *)(work->data);
2,992,085✔
1345

1346
  if (udfWork->conn != NULL) {
2,992,085✔
1347
    uv_write_t *write_req = taosMemoryMalloc(sizeof(uv_write_t));
2,992,085✔
1348
    if(write_req == NULL) {
2,992,085✔
UNCOV
1349
      fnError("udfd send response error, malloc failed");
×
UNCOV
1350
      taosMemoryFree(work);
×
UNCOV
1351
      return;
×
1352
    }
1353
    write_req->data = udfWork;
2,992,085✔
1354
    int32_t code = uv_write(write_req, udfWork->conn->client, &udfWork->output, 1, udfdOnWrite);
2,992,085✔
1355
    if (code != 0) {
2,992,085✔
1356
      fnError("udfd send response error %s", uv_strerror(code));
×
1357
      taosMemoryFree(write_req);
×
1358
   }
1359
  }
1360
  taosMemoryFree(work);
2,992,085✔
1361
}
1362

1363
void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
8,906,168✔
1364
  TAOS_UDF_CHECK_PTR_RVOID(handle, buf);
26,718,504✔
1365
  SUdfdUvConn *ctx = handle->data;
8,906,168✔
1366
  int32_t      msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
8,906,168✔
1367
  if (ctx->inputCap == 0) {
8,906,168✔
1368
    ctx->inputBuf = taosMemoryMalloc(msgHeadSize);
3,212,022✔
1369
    if (ctx->inputBuf) {
3,212,022✔
1370
      ctx->inputLen = 0;
3,212,022✔
1371
      ctx->inputCap = msgHeadSize;
3,212,022✔
1372
      ctx->inputTotal = -1;
3,212,022✔
1373

1374
      buf->base = ctx->inputBuf;
3,212,022✔
1375
      buf->len = ctx->inputCap;
3,212,022✔
1376
    } else {
UNCOV
1377
      fnError("udfd can not allocate enough memory") buf->base = NULL;
×
UNCOV
1378
      buf->len = 0;
×
1379
    }
1380
  } else if (ctx->inputTotal == -1 && ctx->inputLen < msgHeadSize) {
5,694,146✔
1381
    buf->base = ctx->inputBuf + ctx->inputLen;
2,699,583✔
1382
    buf->len = msgHeadSize - ctx->inputLen;
2,699,583✔
1383
  } else {
1384
    ctx->inputCap = ctx->inputTotal > ctx->inputCap ? ctx->inputTotal : ctx->inputCap;
2,994,563✔
1385
    void *inputBuf = taosMemoryRealloc(ctx->inputBuf, ctx->inputCap);
2,994,563✔
1386
    if (inputBuf) {
2,994,563✔
1387
      ctx->inputBuf = inputBuf;
2,994,563✔
1388
      buf->base = ctx->inputBuf + ctx->inputLen;
2,994,563✔
1389
      buf->len = ctx->inputCap - ctx->inputLen;
2,994,563✔
1390
    } else {
UNCOV
1391
      fnError("udfd can not allocate enough memory") buf->base = NULL;
×
UNCOV
1392
      buf->len = 0;
×
1393
    }
1394
  }
1395
}
1396

1397
bool isUdfdUvMsgComplete(SUdfdUvConn *pipe) {
5,986,648✔
1398
  if (pipe == NULL) {
5,986,648✔
1399
    fnError("udfd pipe is NULL, LINE:%d", __LINE__);
×
UNCOV
1400
    return false;
×
1401
  }
1402
  if (pipe->inputTotal == -1 && pipe->inputLen >= sizeof(int32_t)) {
5,986,648✔
1403
    pipe->inputTotal = *(int32_t *)(pipe->inputBuf);
2,992,085✔
1404
  }
1405
  if (pipe->inputLen == pipe->inputCap && pipe->inputTotal == pipe->inputCap) {
5,986,648✔
1406
    fnDebug("receive request complete. length %d", pipe->inputLen);
2,992,085✔
1407
    return true;
2,992,085✔
1408
  }
1409
  return false;
2,994,563✔
1410
}
1411

1412
void udfdHandleRequest(SUdfdUvConn *conn) {
2,992,085✔
1413
  TAOS_UDF_CHECK_PTR_RVOID(conn);
5,984,170✔
1414
  char   *inputBuf = conn->inputBuf;
2,992,085✔
1415
  int32_t inputLen = conn->inputLen;
2,992,085✔
1416

1417
  uv_work_t  *work = taosMemoryMalloc(sizeof(uv_work_t));
2,992,085✔
1418
  if(work == NULL) {
2,992,085✔
UNCOV
1419
    fnError("udfd malloc work failed");
×
UNCOV
1420
    return;
×
1421
  }
1422
  SUvUdfWork *udfWork = taosMemoryMalloc(sizeof(SUvUdfWork));
2,992,085✔
1423
  if(udfWork == NULL) {
2,992,085✔
UNCOV
1424
    fnError("udfd malloc udf work failed");
×
UNCOV
1425
    taosMemoryFree(work);
×
1426
    return;
×
1427
  }
1428
  udfWork->conn = conn;
2,992,085✔
1429
  udfWork->pWorkNext = conn->pWorkList;
2,992,085✔
1430
  conn->pWorkList = udfWork;
2,992,085✔
1431
  udfWork->input = uv_buf_init(inputBuf, inputLen);
2,992,085✔
1432
  conn->inputBuf = NULL;
2,992,085✔
1433
  conn->inputLen = 0;
2,992,085✔
1434
  conn->inputCap = 0;
2,992,085✔
1435
  conn->inputTotal = -1;
2,992,085✔
1436
  work->data = udfWork;
2,992,085✔
1437
  if(uv_queue_work(global.loop, work, udfdProcessRequest, udfdSendResponse) != 0)
2,992,085✔
1438
  {
UNCOV
1439
    fnError("udfd queue work failed");
×
UNCOV
1440
    taosMemoryFree(work);
×
UNCOV
1441
    taosMemoryFree(udfWork);
×
1442
  }
1443
}
1444

1445
void udfdPipeCloseCb(uv_handle_t *pipe) {
219,937✔
1446
  TAOS_UDF_CHECK_PTR_RVOID(pipe);
439,874✔
1447
  SUdfdUvConn *conn = pipe->data;
219,937✔
1448
  SUvUdfWork  *pWork = conn->pWorkList;
219,937✔
1449
  while (pWork != NULL) {
219,937✔
UNCOV
1450
    pWork->conn = NULL;
×
UNCOV
1451
    pWork = pWork->pWorkNext;
×
1452
  }
1453

1454
  taosMemoryFree(conn->client);
219,937✔
1455
  taosMemoryFree(conn->inputBuf);
219,937✔
1456
  taosMemoryFree(conn);
219,937✔
1457
}
1458

1459
void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
8,906,168✔
1460
  TAOS_UDF_CHECK_PTR_RVOID(client, buf);
26,718,504✔
1461
  fnDebug("udfd read %zd bytes from client", nread);
8,906,168✔
1462
  if (nread == 0) return;
8,906,168✔
1463

1464
  SUdfdUvConn *conn = client->data;
6,206,585✔
1465

1466
  if (nread > 0) {
6,206,585✔
1467
    conn->inputLen += nread;
5,986,648✔
1468
    if (isUdfdUvMsgComplete(conn)) {
5,986,648✔
1469
      udfdHandleRequest(conn);
2,992,085✔
1470
    } else {
1471
      // log error or continue;
1472
    }
1473
    return;
5,986,648✔
1474
  }
1475

1476
  if (nread < 0) {
219,937✔
1477
    if (nread == UV_EOF) {
219,937✔
1478
      fnInfo("udfd pipe read EOF");
219,937✔
1479
    } else {
UNCOV
1480
      fnError("Receive error %s", uv_err_name(nread));
×
1481
    }
1482
    udfdUvHandleError(conn);
219,937✔
1483
  }
1484
}
1485

1486
void udfdOnNewConnection(uv_stream_t *server, int status) {
219,937✔
1487
  TAOS_UDF_CHECK_PTR_RVOID(server);
439,874✔
1488
  if (status < 0) {
219,937✔
UNCOV
1489
    fnError("udfd new connection error, code:%s", uv_strerror(status));
×
UNCOV
1490
    return;
×
1491
  }
1492
  int32_t code = 0;
219,937✔
1493

1494
  uv_pipe_t *client = (uv_pipe_t *)taosMemoryMalloc(sizeof(uv_pipe_t));
219,937✔
1495
  if(client == NULL) {
219,937✔
1496
    fnError("udfd pipe malloc failed");
×
1497
    return;
×
1498
  }
1499
  code = uv_pipe_init(global.loop, client, 0);
219,937✔
1500
  if (code) {
219,937✔
UNCOV
1501
    fnError("udfd pipe init error %s", uv_strerror(code));
×
UNCOV
1502
    taosMemoryFree(client);
×
1503
    return;
×
1504
  }
1505
  if (uv_accept(server, (uv_stream_t *)client) == 0) {
219,937✔
1506
    SUdfdUvConn *ctx = taosMemoryMalloc(sizeof(SUdfdUvConn));
219,937✔
1507
    if(ctx == NULL) {
219,937✔
1508
      fnError("udfd conn malloc failed");
×
1509
      goto _exit;
×
1510
    }
1511
    ctx->pWorkList = NULL;
219,937✔
1512
    ctx->client = (uv_stream_t *)client;
219,937✔
1513
    ctx->inputBuf = 0;
219,937✔
1514
    ctx->inputLen = 0;
219,937✔
1515
    ctx->inputCap = 0;
219,937✔
1516
    client->data = ctx;
219,937✔
1517
    ctx->client = (uv_stream_t *)client;
219,937✔
1518
    code = uv_read_start((uv_stream_t *)client, udfdAllocBuffer, udfdPipeRead);
219,937✔
1519
    if (code) {
219,937✔
UNCOV
1520
      fnError("udfd read start error %s", uv_strerror(code));
×
UNCOV
1521
      udfdUvHandleError(ctx);
×
UNCOV
1522
      taosMemoryFree(ctx);
×
UNCOV
1523
      taosMemoryFree(client);
×
1524
    }
1525
    return;
219,937✔
1526
  }
1527
_exit:
×
1528
    uv_close((uv_handle_t *)client, NULL);
×
1529
    taosMemoryFree(client);
×
1530
}
1531

UNCOV
1532
void udfdIntrSignalHandler(uv_signal_t *handle, int signum) {
×
UNCOV
1533
  TAOS_UDF_CHECK_PTR_RVOID(handle);
×
1534
  fnInfo("udfd signal received: %d\n", signum);
×
1535
  uv_fs_t req;
×
1536
  int32_t code = uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
×
UNCOV
1537
  if(code) {
×
UNCOV
1538
    fnError("remove listening pipe %s failed, reason:%s, lino:%d", global.listenPipeName, uv_strerror(code), __LINE__);
×
1539
  }
1540
  code = uv_signal_stop(handle);
×
1541
  if(code) {
×
1542
    fnError("stop signal handler failed, reason:%s", uv_strerror(code));
×
1543
  }
1544
  uv_stop(global.loop);
×
1545
}
1546

1547
static int32_t udfdParseArgs(int32_t argc, char *argv[]) {
573,542✔
1548
  for (int32_t i = 1; i < argc; ++i) {
1,146,182✔
1549
    if (strcmp(argv[i], "-c") == 0) {
573,542✔
1550
      if (i < argc - 1) {
573,091✔
1551
        if (strlen(argv[++i]) >= PATH_MAX) {
572,640✔
1552
          (void)printf("config file path overflow");
451✔
1553
          return -1;
451✔
1554
        }
1555
        tstrncpy(configDir, argv[i], PATH_MAX);
572,189✔
1556
      } else {
1557
        (void)printf("'-c' requires a parameter, default is %s\n", configDir);
451✔
1558
        return -1;
451✔
1559
      }
1560
    } else if (strcmp(argv[i], "-V") == 0) {
451✔
1561
      global.printVersion = true;
451✔
1562
    } else {
1563
    }
1564
  }
1565

1566
  return 0;
572,640✔
1567
}
1568

1569
static void udfdPrintVersion() {
451✔
1570
  (void)printf("%sudf version: %s compatible_version: %s\n", CUS_PROMPT, td_version, td_compatible_version);
451✔
1571
  (void)printf("git: %s\n", td_gitinfo);
451✔
1572
  (void)printf("build: %s\n", td_buildinfo);
451✔
1573
}
451✔
1574

1575
static int32_t udfdInitLog() {
572,189✔
1576
  const char *logName = "udfdlog";
572,189✔
1577
  TAOS_CHECK_RETURN(taosInitLogOutput(&logName));
572,189✔
1578
  return taosCreateLog(logName, 1, configDir, NULL, NULL, NULL, NULL, 0);
572,189✔
1579
}
1580

1581
void udfdCtrlAllocBufCb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
572,189✔
1582
  TAOS_UDF_CHECK_PTR_RVOID(buf);
1,144,378✔
1583
  buf->base = taosMemoryMalloc(suggested_size);
572,189✔
1584
  if (buf->base == NULL) {
572,189✔
UNCOV
1585
    fnError("udfd ctrl pipe alloc buffer failed");
×
UNCOV
1586
    return;
×
1587
  }
1588
  buf->len = suggested_size;
572,189✔
1589
}
1590

1591
void udfdCtrlReadCb(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) {
572,189✔
1592
  TAOS_UDF_CHECK_PTR_RVOID(q, buf);
1,716,567✔
1593
  if (nread < 0) {
572,189✔
1594
    fnError("udfd ctrl pipe read error. %s", uv_err_name(nread));
572,189✔
1595
    taosMemoryFree(buf->base);
572,189✔
1596
    uv_close((uv_handle_t *)q, NULL);
572,189✔
1597
    uv_stop(global.loop);
572,189✔
1598
    return;
572,189✔
1599
  }
UNCOV
1600
  fnError("udfd ctrl pipe read %zu bytes", nread);
×
UNCOV
1601
  taosMemoryFree(buf->base);
×
1602
}
1603

1604
static void removeListeningPipe() {
1,144,378✔
1605
  uv_fs_t req;
1,138,266✔
1606
  int     err = uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
1,144,378✔
1607
  uv_fs_req_cleanup(&req);
1,144,378✔
1608
  if(err) {
1,144,378✔
1609
    fnInfo("remove listening pipe %s : %s, lino:%d", global.listenPipeName, uv_strerror(err), __LINE__);
1,143,938✔
1610
  }
1611
}
1,144,378✔
1612

1613
static int32_t udfdUvInit() {
572,189✔
1614
  TAOS_CHECK_RETURN(uv_loop_init(global.loop));
572,189✔
1615

1616
  if (tsStartUdfd) {  // udfd is started by taosd, which shall exit when taosd exit
572,189✔
1617
    TAOS_CHECK_RETURN(uv_pipe_init(global.loop, &global.ctrlPipe, 1));
572,189✔
1618
    TAOS_CHECK_RETURN(uv_pipe_open(&global.ctrlPipe, 0));
572,189✔
1619
    TAOS_CHECK_RETURN(uv_read_start((uv_stream_t *)&global.ctrlPipe, udfdCtrlAllocBufCb, udfdCtrlReadCb));
572,189✔
1620
  }
1621
  getUdfdPipeName(global.listenPipeName, sizeof(global.listenPipeName));
572,189✔
1622

1623
  removeListeningPipe();
572,189✔
1624

1625
  TAOS_CHECK_RETURN(uv_pipe_init(global.loop, &global.listeningPipe, 0));
572,189✔
1626

1627
  TAOS_CHECK_RETURN(uv_signal_init(global.loop, &global.intrSignal));
572,189✔
1628
  TAOS_CHECK_RETURN(uv_signal_start(&global.intrSignal, udfdIntrSignalHandler, SIGINT));
572,189✔
1629

1630
  int r;
1631
  fnInfo("bind to pipe %s", global.listenPipeName);
572,189✔
1632
  if ((r = uv_pipe_bind(&global.listeningPipe, global.listenPipeName))) {
572,189✔
UNCOV
1633
    fnError("Bind error %s", uv_err_name(r));
×
UNCOV
1634
    removeListeningPipe();
×
UNCOV
1635
    return -2;
×
1636
  }
1637
  if ((r = uv_listen((uv_stream_t *)&global.listeningPipe, 128, udfdOnNewConnection))) {
572,189✔
UNCOV
1638
    fnError("Listen error %s", uv_err_name(r));
×
UNCOV
1639
    removeListeningPipe();
×
1640
    return -3;
×
1641
  }
1642
  return 0;
572,189✔
1643
}
1644

1645
static void udfdCloseWalkCb(uv_handle_t *handle, void *arg) {
1,144,378✔
1646
  if (!uv_is_closing(handle)) {
1,144,378✔
1647
    uv_close(handle, NULL);
1,144,378✔
1648
  }
1649
}
1,144,378✔
1650

1651
static int32_t udfdGlobalDataInit() {
572,189✔
1652
  uv_loop_t *loop = taosMemoryMalloc(sizeof(uv_loop_t));
572,189✔
1653
  if (loop == NULL) {
572,189✔
UNCOV
1654
    fnError("udfd init uv loop failed, mem overflow");
×
UNCOV
1655
    return terrno;
×
1656
  }
1657
  global.loop = loop;
572,189✔
1658

1659
  if (uv_mutex_init(&global.scriptPluginsMutex) != 0) {
572,189✔
UNCOV
1660
    fnError("udfd init script plugins mutex failed");
×
1661
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1662
  }
1663

1664
  global.udfsHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
572,189✔
1665
  if (global.udfsHash == NULL) {
572,189✔
UNCOV
1666
    return terrno;
×
1667
  }
1668
  // taosHashSetFreeFp(global.udfsHash, udfdFreeUdf);
1669

1670
  if (uv_mutex_init(&global.udfsMutex) != 0) {
572,189✔
UNCOV
1671
    fnError("udfd init udfs mutex failed");
×
UNCOV
1672
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1673
  }
1674

1675
  return 0;
572,189✔
1676
}
1677

1678
static void udfdGlobalDataDeinit() {
572,189✔
1679
  uv_mutex_destroy(&global.udfsMutex);
572,189✔
1680
  uv_mutex_destroy(&global.scriptPluginsMutex);
572,189✔
1681
  taosMemoryFreeClear(global.loop);
572,189✔
1682
  fnInfo("udfd global data deinit");
572,189✔
1683
}
572,189✔
1684

1685
static void udfdRun() {
572,189✔
1686
  fnInfo("start udfd event loop");
572,189✔
1687
  int32_t code = uv_run(global.loop, UV_RUN_DEFAULT);
572,189✔
1688
  if(code != 0) {
572,189✔
1689
    fnError("udfd event loop still has active handles or requests.");
572,189✔
1690
  }
1691
  fnInfo("udfd event loop stopped.");
572,189✔
1692

1693
  (void)uv_loop_close(global.loop);
572,189✔
1694

1695
  uv_walk(global.loop, udfdCloseWalkCb, NULL);
572,189✔
1696
  code = uv_run(global.loop, UV_RUN_DEFAULT);
572,189✔
1697
  if(code != 0) {
572,189✔
UNCOV
1698
    fnError("udfd event loop still has active handles or requests.");
×
1699
  }
1700
  (void)uv_loop_close(global.loop);
572,189✔
1701
}
572,189✔
1702

1703
int32_t udfdInitResidentFuncs() {
572,189✔
1704
  if (strlen(tsUdfdResFuncs) == 0) {
572,189✔
1705
    return TSDB_CODE_SUCCESS;
570,217✔
1706
  }
1707

1708
  global.residentFuncs = taosArrayInit(2, TSDB_FUNC_NAME_LEN);
1,972✔
1709
  char *pSave = tsUdfdResFuncs;
1,972✔
1710
  char *token;
1711
  while ((token = strtok_r(pSave, ",", &pSave)) != NULL) {
5,916✔
1712
    char func[TSDB_FUNC_NAME_LEN + 1] = {0};
3,944✔
1713
    tstrncpy(func, token, TSDB_FUNC_NAME_LEN);
3,944✔
1714
    fnInfo("udfd add resident function %s", func);
3,944✔
1715
    if(taosArrayPush(global.residentFuncs, func) == NULL)
7,888✔
1716
    {
UNCOV
1717
      taosArrayDestroy(global.residentFuncs);
×
UNCOV
1718
      return terrno;
×
1719
    }
1720
  }
1721

1722
  return TSDB_CODE_SUCCESS;
1,972✔
1723
}
1724

1725
void udfdDeinitResidentFuncs() {
572,189✔
1726
  for (int32_t i = 0; i < taosArrayGetSize(global.residentFuncs); ++i) {
576,133✔
1727
    char  *funcName = taosArrayGet(global.residentFuncs, i);
3,944✔
1728
    SUdf **udfInHash = taosHashGet(global.udfsHash, funcName, strlen(funcName));
3,944✔
1729
    if (udfInHash) {
3,944✔
1730
      SUdf   *udf = *udfInHash;
2,417✔
1731
      int32_t code = 0;
2,417✔
1732
      if (udf->scriptPlugin->udfDestroyFunc) {
2,417✔
1733
        code = udf->scriptPlugin->udfDestroyFunc(udf->scriptUdfCtx);
2,417✔
1734
        fnDebug("udfd %s destroy function returns %d", funcName, code);
2,417✔
1735
      }
1736
      if(taosHashRemove(global.udfsHash, funcName, strlen(funcName)) != 0)
2,417✔
1737
      {
UNCOV
1738
        fnError("udfd remove resident function %s failed", funcName);
×
1739
      }
1740
      taosMemoryFree(udf);
2,417✔
1741
    }
1742
  }
1743
  taosHashCleanup(global.udfsHash);
572,189✔
1744
  taosArrayDestroy(global.residentFuncs);
572,189✔
1745
  fnInfo("udfd resident functions are deinit");
572,189✔
1746
}
572,189✔
1747

1748
int32_t udfdCreateUdfSourceDir() {
572,189✔
1749
  snprintf(global.udfDataDir, PATH_MAX, "%s/.udf", tsDataDir);
572,189✔
1750
  int32_t code = taosMkDir(global.udfDataDir);
572,189✔
1751
  if (code != TSDB_CODE_SUCCESS) {
572,189✔
UNCOV
1752
    snprintf(global.udfDataDir, PATH_MAX, "%s/.udf", tsTempDir);
×
UNCOV
1753
    code = taosMkDir(global.udfDataDir);
×
1754
  }
1755
  fnInfo("udfd create udf source directory %s. result: %s", global.udfDataDir, tstrerror(code));
572,189✔
1756

1757
  return code;
572,189✔
1758
}
1759

1760
void udfdDestroyUdfSourceDir() {
572,189✔
1761
  fnInfo("destory udf source directory %s", global.udfDataDir);
572,189✔
1762
  taosRemoveDir(global.udfDataDir);
572,189✔
1763
}
572,189✔
1764

1765
int main(int argc, char *argv[]) {
573,542✔
1766
  int  code = 0;
573,542✔
1767
  bool logInitialized = false;
573,542✔
1768
  bool cfgInitialized = false;
573,542✔
1769
  bool openClientRpcFinished = false;
573,542✔
1770
  bool residentFuncsInited = false;
573,542✔
1771
  bool udfSourceDirInited = false;
573,542✔
1772
  bool globalDataInited = false;
573,542✔
1773

1774
  if (!taosCheckSystemIsLittleEnd()) {
573,542✔
UNCOV
1775
    (void)printf("failed to start since on non-little-end machines\n");
×
UNCOV
1776
    return -1;
×
1777
  }
1778

1779
  if (udfdParseArgs(argc, argv) != 0) {
573,542✔
1780
    (void)printf("failed to start since parse args error\n");
902✔
1781
    return -1;
902✔
1782
  }
1783

1784
  if (global.printVersion) {
572,640✔
1785
    udfdPrintVersion();
451✔
1786
    return 0;
451✔
1787
  }
1788

1789
  if (udfdInitLog() != 0) {
572,189✔
1790
    // ignore create log failed, because this error no matter
UNCOV
1791
    (void)printf("failed to init udfd log.");
×
1792
  } else {
1793
    logInitialized = true;  // log is initialized
572,189✔
1794
  }
1795

1796
  if (taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0) != 0) {
572,189✔
UNCOV
1797
    fnError("failed to start since read config error");
×
1798
    code = -2;
×
UNCOV
1799
    goto _exit;
×
1800
  }
1801
  cfgInitialized = true;  // cfg is initialized
572,189✔
1802
  fnInfo("udfd start with config file %s", configDir);
572,189✔
1803

1804
  if (initEpSetFromCfg(tsFirst, tsSecond, &global.mgmtEp) != 0) {
572,189✔
1805
    fnError("init ep set from cfg failed");
×
1806
    code = -3;
×
UNCOV
1807
    goto _exit;
×
1808
  }
1809
  fnInfo("udfd start with mnode ep %s", global.mgmtEp.epSet.eps[0].fqdn);
572,189✔
1810
  if (udfdOpenClientRpc() != 0) {
572,189✔
UNCOV
1811
    fnError("open rpc connection to mnode failed");
×
1812
    code = -4;
×
1813
    goto _exit;
×
1814
  }
1815
  fnInfo("udfd rpc client is opened");
572,189✔
1816
  openClientRpcFinished = true;  // rpc is opened
572,189✔
1817

1818
  if (udfdCreateUdfSourceDir() != 0) {
572,189✔
1819
    fnError("create udf source directory failed");
×
1820
    code = -5;
×
UNCOV
1821
    goto _exit;
×
1822
  }
1823
  udfSourceDirInited = true;  // udf source dir is created
572,189✔
1824
  fnInfo("udfd udf source directory is created");
572,189✔
1825

1826
  if (udfdGlobalDataInit() != 0) {
572,189✔
1827
    fnError("init global data failed");
×
1828
    code = -6;
×
UNCOV
1829
    goto _exit;
×
1830
  }
1831
  globalDataInited = true;  // global data is inited
572,189✔
1832
  fnInfo("udfd global data is inited");
572,189✔
1833

1834
  if (udfdUvInit() != 0) {
572,189✔
1835
    fnError("uv init failure");
×
1836
    code = -7;
×
UNCOV
1837
    goto _exit;
×
1838
  }
1839
  fnInfo("udfd uv is inited");
572,189✔
1840

1841
  if (udfdInitResidentFuncs() != 0) {
572,189✔
1842
    fnError("init resident functions failed");
×
1843
    code = -8;
×
1844
    goto _exit;
×
1845
  }
1846
  residentFuncsInited = true;  // resident functions are inited
572,189✔
1847
  fnInfo("udfd resident functions are inited");
572,189✔
1848

1849
  udfdRun();
572,189✔
1850
  fnInfo("udfd exit normally");
572,189✔
1851

1852
  removeListeningPipe();
572,189✔
1853

1854
_exit:
572,189✔
1855
  if (residentFuncsInited) {
572,189✔
1856
    udfdDeinitResidentFuncs();
572,189✔
1857
  }
1858
  udfdDeinitScriptPlugins();
572,189✔
1859
  if (globalDataInited) {
572,189✔
1860
    udfdGlobalDataDeinit();
572,189✔
1861
  }
1862
  if (udfSourceDirInited) {
572,189✔
1863
    udfdDestroyUdfSourceDir();
572,189✔
1864
  }
1865
  if (openClientRpcFinished) {
572,189✔
1866
    udfdCloseClientRpc();
572,189✔
1867
  }
1868
  if (cfgInitialized) {
572,189✔
1869
    taosCleanupCfg();
572,189✔
1870
  }
1871
  if (logInitialized) {
572,189✔
1872
    taosCloseLog();
572,189✔
1873
  }
1874

1875
  return code;
572,189✔
1876
}
1877
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc