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

taosdata / TDengine / #4917

07 Jan 2026 03:52PM UTC coverage: 65.42% (+0.02%) from 65.402%
#4917

push

travis-ci

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

31 of 34 new or added lines in 2 files covered. (91.18%)

819 existing lines in 129 files now uncovered.

202679 of 309814 relevant lines covered (65.42%)

116724351.99 hits per line

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

75.71
/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,450✔
54

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

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

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

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

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

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

87
  return 0;
11,316✔
88
}
89

90
int32_t udfdCPluginUdfInit(SScriptUdfInfo *udf, void **pUdfCtx) {
48,225✔
91
  TAOS_UDF_CHECK_PTR_RCODE(udf, pUdfCtx);
144,675✔
92
  int32_t         err = 0;
48,225✔
93
  SUdfCPluginCtx *udfCtx = taosMemoryCalloc(1, sizeof(SUdfCPluginCtx));
48,225✔
94
  if (NULL == udfCtx) {
48,225✔
95
    return terrno;
×
96
  }
97
  err = uv_dlopen(udf->path, &udfCtx->lib);
48,225✔
98
  if (err != 0) {
48,225✔
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;
48,225✔
104

105
  err = udfdCPluginUdfInitLoadInitDestoryFuncs(udfCtx, udfName);
48,225✔
106
  if (err != 0) {
48,225✔
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) {
47,721✔
113
    char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
35,838✔
114
    snprintf(processFuncName, sizeof(processFuncName), "%s", udfName);
35,838✔
115
    if (uv_dlsym(&udfCtx->lib, processFuncName, (void **)(&udfCtx->scalarProcFunc)) != 0) {
35,838✔
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,883✔
121
    err = udfdCPluginUdfInitLoadAggFuncs(udfCtx, udfName);
11,883✔
122
    if (err != 0) {
11,883✔
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) {
47,154✔
130
    err = (udfCtx->initFunc)();
47,154✔
131
    if (err != 0) {
47,154✔
132
      fnError("udf init function failed. error: %d", err);
×
133
      goto _exit;
×
134
    }
135
  }
136
  *pUdfCtx = udfCtx;
47,154✔
137
  return 0;
47,154✔
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) {
46,587✔
145
  TAOS_UDF_CHECK_PTR_RCODE(udfCtx);
93,174✔
146
  SUdfCPluginCtx *ctx = udfCtx;
46,587✔
147
  int32_t         code = 0;
46,587✔
148
  if (ctx->destroyFunc) {
46,587✔
149
    code = (ctx->destroyFunc)();
46,587✔
150
  }
151
  uv_dlclose(&ctx->lib);
46,587✔
152
  taosMemoryFree(ctx);
46,587✔
153
  return code;
46,587✔
154
}
155

156
int32_t udfdCPluginUdfScalarProc(SUdfDataBlock *block, SUdfColumn *resultCol, void *udfCtx) {
1,742,733✔
157
  TAOS_UDF_CHECK_PTR_RCODE(block, resultCol, udfCtx);
6,970,876✔
158
  SUdfCPluginCtx *ctx = udfCtx;
1,742,733✔
159
  if (ctx->scalarProcFunc) {
1,742,733✔
160
    return ctx->scalarProcFunc(block, resultCol);
1,742,789✔
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) {
246,075✔
168
  TAOS_UDF_CHECK_PTR_RCODE(buf, udfCtx);
738,225✔
169
  SUdfCPluginCtx *ctx = udfCtx;
246,075✔
170
  if (ctx->aggStartFunc) {
246,075✔
171
    return ctx->aggStartFunc(buf);
246,075✔
172
  } else {
UNCOV
173
    fnError("udfd c plugin aggregation start not implemented");
×
UNCOV
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) {
583,120✔
180
  TAOS_UDF_CHECK_PTR_RCODE(block, interBuf, newInterBuf, udfCtx);
2,915,600✔
181
  SUdfCPluginCtx *ctx = udfCtx;
583,120✔
182
  if (ctx->aggProcFunc) {
583,120✔
183
    return ctx->aggProcFunc(block, interBuf, newInterBuf);
583,120✔
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) {
244,878✔
203
  TAOS_UDF_CHECK_PTR_RCODE(buf, resultData, udfCtx);
979,512✔
204
  SUdfCPluginCtx *ctx = udfCtx;
244,878✔
205
  if (ctx->aggFinishFunc) {
244,878✔
206
    return ctx->aggFinishFunc(buf, resultData);
244,878✔
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); }
206,563✔
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,450✔
365
  TAOS_UDF_CHECK_PTR_RCODE(plugin);
4,900✔
366
  plugin->scriptType = TSDB_FUNC_SCRIPT_BIN_LIB;
2,450✔
367
  plugin->openFunc = udfdCPluginOpen;
2,450✔
368
  plugin->closeFunc = udfdCPluginClose;
2,450✔
369
  plugin->udfInitFunc = udfdCPluginUdfInit;
2,450✔
370
  plugin->udfDestroyFunc = udfdCPluginUdfDestroy;
2,450✔
371
  plugin->udfScalarProcFunc = udfdCPluginUdfScalarProc;
2,450✔
372
  plugin->udfAggStartFunc = udfdCPluginUdfAggStart;
2,450✔
373
  plugin->udfAggProcFunc = udfdCPluginUdfAggProc;
2,450✔
374
  // plugin->udfAggMergeFunc = udfdCPluginUdfAggMerge;
375
  plugin->udfAggFinishFunc = udfdCPluginUdfAggFinish;
2,450✔
376

377
  SScriptUdfEnvItem items[1] = {{"LD_LIBRARY_PATH", tsUdfdLdLibPath}};
2,450✔
378
  int32_t           err = plugin->openFunc(items, 1);
2,450✔
379
  if (err != 0) return err;
2,450✔
380
  return 0;
2,450✔
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,450✔
447
  TAOS_UDF_CHECK_PTR_RVOID(plugin);
4,900✔
448
  if (plugin->closeFunc) {
2,450✔
449
    if (plugin->closeFunc() != 0) {
2,450✔
450
      fnError("udf script c plugin close func failed.line:%d", __LINE__);
×
451
    }
452
  }
453
  plugin->openFunc = NULL;
2,450✔
454
  plugin->closeFunc = NULL;
2,450✔
455
  plugin->udfInitFunc = NULL;
2,450✔
456
  plugin->udfDestroyFunc = NULL;
2,450✔
457
  plugin->udfScalarProcFunc = NULL;
2,450✔
458
  plugin->udfAggStartFunc = NULL;
2,450✔
459
  plugin->udfAggProcFunc = NULL;
2,450✔
460
  plugin->udfAggMergeFunc = NULL;
2,450✔
461
  plugin->udfAggFinishFunc = NULL;
2,450✔
462
  return;
2,450✔
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,509✔
488
  SUdfScriptPlugin *plugin = taosMemoryCalloc(1, sizeof(SUdfScriptPlugin));
2,509✔
489
  if (plugin == NULL) {
2,509✔
490
    return terrno;
×
491
  }
492
  int32_t err = 0;
2,509✔
493
  switch (scriptType) {
2,509✔
494
    case TSDB_FUNC_SCRIPT_BIN_LIB:
2,450✔
495
      err = udfdInitializeCPlugin(plugin);
2,450✔
496
      if (err != 0) {
2,450✔
497
        fnError("udf script c plugin init failed. error: %d", err);
×
498
        taosMemoryFree(plugin);
×
499
        return err;
×
500
      }
501
      break;
2,450✔
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,509✔
518
  return TSDB_CODE_SUCCESS;
2,509✔
519
}
520

521
void udfdDeinitScriptPlugins() {
569,862✔
522
  SUdfScriptPlugin *plugin = NULL;
569,862✔
523
  plugin = global.scriptPlugins[TSDB_FUNC_SCRIPT_PYTHON];
569,862✔
524
  if (plugin != NULL) {
569,862✔
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];
569,862✔
531
  if (plugin != NULL) {
569,862✔
532
    udfdDeinitCPlugin(plugin);
2,450✔
533
    taosMemoryFree(plugin);
2,450✔
534
    global.scriptPlugins[TSDB_FUNC_SCRIPT_BIN_LIB] = NULL;
2,450✔
535
  }
536
  return;
569,862✔
537
}
538

539
void udfdProcessRequest(uv_work_t *req) {
3,287,773✔
540
  TAOS_UDF_CHECK_PTR_RVOID(req);
6,575,490✔
541
  SUvUdfWork *uvUdf = (SUvUdfWork *)(req->data);
3,287,773✔
542
  if (uvUdf == NULL) {
3,287,773✔
543
    fnError("udf work is NULL");
×
544
    return;
×
545
  }
546
  SUdfRequest request = {0};
3,287,773✔
547
  if(decodeUdfRequest(uvUdf->input.base, &request) == NULL)
3,287,773✔
548
  {
UNCOV
549
    taosMemoryFreeClear(uvUdf->input.base);
×
UNCOV
550
    fnError("udf request decode failed");
×
551
    return;
×
552
  }
553

554
  switch (request.type) {
3,287,773✔
555
    case UDF_TASK_SETUP: {
206,563✔
556
      udfdProcessSetupRequest(uvUdf, &request);
206,563✔
557
      break;
206,563✔
558
    }
559

560
    case UDF_TASK_CALL: {
2,878,505✔
561
      udfdProcessCallRequest(uvUdf, &request);
2,878,505✔
562
      break;
2,878,281✔
563
    }
564
    case UDF_TASK_TEARDOWN: {
202,705✔
565
      udfdProcessTeardownRequest(uvUdf, &request);
202,705✔
566
      break;
202,705✔
567
    }
568
    default: {
×
569
      break;
×
570
    }
571
  }
572
}
573

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

590
static int32_t udfdInitUdf(char *udfName, SUdf *udf) {
58,196✔
591
  TAOS_UDF_CHECK_PTR_RCODE(udfName, udf);
174,588✔
592
  int32_t err = 0;
58,196✔
593
  err = udfdFillUdfInfoFromMNode(global.clientRpc, udfName, udf);
58,196✔
594
  if (err != 0) {
58,196✔
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) {
58,196✔
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);
58,196✔
604
  SUdfScriptPlugin *scriptPlugin = global.scriptPlugins[udf->scriptType];
58,196✔
605
  if (scriptPlugin == NULL) {
58,196✔
606
    err = udfdInitScriptPlugin(udf->scriptType);
2,509✔
607
    if (err != 0) {
2,509✔
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);
58,196✔
614
  udf->scriptPlugin = global.scriptPlugins[udf->scriptType];
58,196✔
615

616
  SScriptUdfInfo info = {0};
58,196✔
617
  convertUdf2UdfInfo(udf, &info);
58,196✔
618
  err = udf->scriptPlugin->udfInitFunc(&info, &udf->scriptUdfCtx);
58,196✔
619
  if (err != 0) {
58,196✔
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);
57,125✔
625
  return 0;
57,125✔
626
}
627

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

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

642
  udfNew->resident = false;
57,314✔
643
  udfNew->expired = false;
57,314✔
644
  for (int32_t i = 0; i < taosArrayGetSize(global.residentFuncs); ++i) {
59,243✔
645
    char *funcName = taosArrayGet(global.residentFuncs, i);
5,023✔
646
    if (strcmp(udfName, funcName) == 0) {
5,023✔
647
      udfNew->resident = true;
3,094✔
648
      break;
3,094✔
649
    }
650
  }
651
  *pUdf =  udfNew;
57,314✔
652
  return 0;
57,314✔
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) {
206,563✔
673
  TAOS_UDF_CHECK_PTR_RCODE(ppUdf, udfName);
619,689✔
674
  uv_mutex_lock(&global.udfsMutex);
206,563✔
675
  SUdf  **pUdfHash = taosHashGet(global.udfsHash, udfName, strlen(udfName));
206,563✔
676
  int64_t currTime = taosGetTimestampMs();
206,563✔
677
  bool    expired = false;
206,563✔
678
  if (pUdfHash) {
206,563✔
679
    expired = currTime - (*pUdfHash)->lastFetchTime > 10 * 1000;  // 10s
149,641✔
680
    if (!expired) {
149,641✔
681
      ++(*pUdfHash)->refCount;
149,249✔
682
      *ppUdf = *pUdfHash;
149,249✔
683
      uv_mutex_unlock(&global.udfsMutex);
149,249✔
684
      fnInfo("udfd reuse existing udf. udf  %s udf version %d, udf created time %" PRIx64, (*ppUdf)->name, (*ppUdf)->version,
149,249✔
685
             (*ppUdf)->createdTime);
686
      return 0;
149,249✔
687
    } else {
688
      (*pUdfHash)->expired = true;
392✔
689
      fnInfo("udfd expired, check for new version. existing udf %s udf version %d, udf created time %" PRIx64,
392✔
690
             (*pUdfHash)->name, (*pUdfHash)->version, (*pUdfHash)->createdTime);
691
      if(taosHashRemove(global.udfsHash, udfName, strlen(udfName)) != 0) {
392✔
692
        fnError("udfdGetOrCreateUdf: udfd remove udf %s failed", udfName);
×
693
      }
694
    }
695
  }
696

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

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

709
  return 0;
57,314✔
710
}
711

712
void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
206,563✔
713
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
619,689✔
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);
206,563✔
716

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

721
  code = udfdGetOrCreateUdf(&udf, setup->udfName);
206,563✔
722
  if(code != 0) {
206,563✔
723
    fnError("udfdGetOrCreateUdf failed. udf name %s", setup->udfName);
×
724
    goto _send;
×
725
  }
726
  uv_mutex_lock(&udf->lock);
206,563✔
727
  if (udf->state == UDF_STATE_INIT) {
206,563✔
728
    udf->state = UDF_STATE_LOADING;
58,196✔
729
    code = udfdInitUdf(setup->udfName, udf);
58,196✔
730
    if (code == 0) {
58,196✔
731
      udf->state = UDF_STATE_READY;
57,125✔
732
    } else {
733
      udf->state = UDF_STATE_INIT;
1,071✔
734
    }
735
    uv_cond_broadcast(&udf->condReady);
58,196✔
736
    uv_mutex_unlock(&udf->lock);
58,196✔
737
  } else {
738
    while (udf->state == UDF_STATE_LOADING) {
148,367✔
739
      uv_cond_wait(&udf->condReady, &udf->lock);
×
740
    }
741
    uv_mutex_unlock(&udf->lock);
148,367✔
742
  }
743
  SUdfcFuncHandle *handle = taosMemoryMalloc(sizeof(SUdfcFuncHandle));
206,563✔
744
  if(handle == NULL) {
206,563✔
745
    fnError("udfdProcessSetupRequest: malloc failed.");
×
746
    code = terrno;
×
747
  }
748
  handle->udf = udf;
206,563✔
749

750
_send:
206,563✔
751
  ;
752
  SUdfResponse rsp;
160,240✔
753
  rsp.seqNum = request->seqNum;
206,563✔
754
  rsp.type = request->type;
206,563✔
755
  rsp.code = (code != 0) ? TSDB_CODE_UDF_FUNC_EXEC_FAILURE : 0;
206,563✔
756
  rsp.setupRsp.udfHandle = (int64_t)(handle);
206,563✔
757
  rsp.setupRsp.outputType = udf->outputType;
206,563✔
758
  rsp.setupRsp.bytes = udf->outputLen;
206,563✔
759
  rsp.setupRsp.bufSize = udf->bufSize;
206,563✔
760

761
  int32_t len = encodeUdfResponse(NULL, &rsp);
206,563✔
762
  if(len < 0) {
206,563✔
763
    fnError("udfdProcessSetupRequest: encode udf response failed. len %d", len);
×
764
    return;
×
765
  }
766
  rsp.msgLen = len;
206,563✔
767
  void *bufBegin = taosMemoryMalloc(len);
206,563✔
768
  if(bufBegin == NULL) {
206,563✔
769
    fnError("udfdProcessSetupRequest: malloc failed. len %d", len);
×
770
    return;
×
771
  }
772
  void *buf = bufBegin;
206,563✔
773
  if(encodeUdfResponse(&buf, &rsp) < 0) {
206,563✔
774
    fnError("udfdProcessSetupRequest: encode udf response failed. len %d", len);
×
775
    taosMemoryFree(bufBegin);
×
776
    return;
×
777
  }
778
  
779
  uvUdf->output = uv_buf_init(bufBegin, len);
206,563✔
780

781
  taosMemoryFreeClear(uvUdf->input.base);
206,563✔
782
  return;
206,563✔
783
}
784

785
static int32_t checkUDFScalaResult(SSDataBlock *block, SUdfColumn *output) {
1,763,777✔
786
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_NEVER) {
1,763,777✔
787
    return TSDB_CODE_SUCCESS;
×
788
  }
789
  if (output->colData.numOfRows != block->info.rows) {
1,763,777✔
790
    fnError("udf scala result num of rows %d not equal to input rows %" PRId64, output->colData.numOfRows, block->info.rows);
×
791
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
792
  }
793

794
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_BYROW) {
1,763,777✔
795
    for (int32_t i = 0; i < output->colData.numOfRows; ++i) {
×
796
      if (!udfColDataIsNull(output, i)) {
×
797
        if (IS_VAR_DATA_TYPE(output->colMeta.type)) {
×
798
          TAOS_UDF_CHECK_CONDITION(output->colData.varLenCol.payload != NULL, TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
×
799
          TAOS_UDF_CHECK_CONDITION(output->colData.varLenCol.varOffsets[i] >= 0 &&
×
800
                                       output->colData.varLenCol.varOffsets[i] < output->colData.varLenCol.payloadLen,
801
                                   TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
802
        } else {
803
          TAOS_UDF_CHECK_CONDITION(
×
804
              output->colMeta.bytes * output->colData.numOfRows <= output->colData.fixLenCol.dataLen,
805
              TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
806
          break;
×
807
        }
808
      }
809
    }
810
  }
811

812
  return TSDB_CODE_SUCCESS;
1,763,777✔
813
}
814

815
static int32_t checkUDFAggResult(SSDataBlock *block, SUdfInterBuf *output) {
616,573✔
816
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_NEVER) {
616,573✔
817
    return TSDB_CODE_SUCCESS;
×
818
  }
819
  if (output->numOfResult != 1 && output->numOfResult != 0) {
616,573✔
820
    fnError("udf agg result num of rows %d not equal to 1", output->numOfResult);
×
821
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
×
822
  }
823
  TAOS_UDF_CHECK_CONDITION(output->buf != NULL, TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
616,573✔
824
  TAOS_UDF_CHECK_CONDITION(output->bufLen > 0, TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
616,573✔
825
  return TSDB_CODE_SUCCESS;
616,573✔
826
}
827

828
void udfdProcessCallRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
2,878,505✔
829
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
8,635,400✔
830
  SUdfCallRequest *call = &request->call;
2,878,505✔
831
  fnDebug("call request. call type %d, handle: %" PRIx64 ", seq num %" PRId64, call->callType, call->udfHandle,
2,878,505✔
832
          request->seqNum);
833
  SUdfcFuncHandle  *handle = (SUdfcFuncHandle *)(call->udfHandle);
2,878,617✔
834
  SUdf             *udf = handle->udf;
2,878,617✔
835
  SUdfResponse      response = {0};
2,878,617✔
836
  SUdfResponse     *rsp = &response;
2,878,617✔
837
  SUdfCallResponse *subRsp = &rsp->callRsp;
2,878,617✔
838

839
  int32_t code = TSDB_CODE_SUCCESS;
2,878,617✔
840
  switch (call->callType) {
2,878,617✔
841
    case TSDB_UDF_CALL_SCALA_PROC: {
1,766,017✔
842
      SUdfColumn output = {0};
1,766,017✔
843
      output.colMeta.bytes = udf->outputLen;
1,766,017✔
844
      output.colMeta.type = udf->outputType;
1,766,017✔
845
      output.colMeta.precision = 0;
1,766,017✔
846
      output.colMeta.scale = 0;
1,766,017✔
847
      if (udfColEnsureCapacity(&output, call->block.info.rows) == TSDB_CODE_SUCCESS) {
3,532,034✔
848
        SUdfDataBlock input = {0};
1,765,961✔
849
        code = convertDataBlockToUdfDataBlock(&call->block, &input);
1,765,961✔
850
        if (code == TSDB_CODE_SUCCESS) code = udf->scriptPlugin->udfScalarProcFunc(&input, &output, udf->scriptUdfCtx);
1,765,233✔
851
        freeUdfDataDataBlock(&input);
1,764,617✔
852
        if (code == TSDB_CODE_SUCCESS) code = checkUDFScalaResult(&call->block, &output);
1,765,569✔
853
        if (code == TSDB_CODE_SUCCESS) code = convertUdfColumnToDataBlock(&output, &response.callRsp.resultData);
1,764,673✔
854
      }
855
      freeUdfColumn(&output);
1,765,233✔
856
      break;
1,765,681✔
857
    }
858
    case TSDB_UDF_CALL_AGG_INIT: {
248,612✔
859
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
248,612✔
860
      if (outBuf.buf != NULL) {
248,612✔
861
        code = udf->scriptPlugin->udfAggStartFunc(&outBuf, udf->scriptUdfCtx);
248,612✔
862
      } else {
863
        code = terrno;
×
864
      }
865
      subRsp->resultBuf = outBuf;
248,612✔
866
      break;
248,612✔
867
    }
868
    case TSDB_UDF_CALL_AGG_PROC: {
616,573✔
869
      SUdfDataBlock input = {0};
616,573✔
870
      if (convertDataBlockToUdfDataBlock(&call->block, &input) == TSDB_CODE_SUCCESS) {
616,573✔
871
        SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
616,573✔
872
        if (outBuf.buf != NULL) {
616,573✔
873
          code = udf->scriptPlugin->udfAggProcFunc(&input, &call->interBuf, &outBuf, udf->scriptUdfCtx);
616,573✔
874
          freeUdfInterBuf(&call->interBuf);
616,573✔
875
          if (code == TSDB_CODE_SUCCESS) code = checkUDFAggResult(&call->block, &outBuf);
616,573✔
876
          subRsp->resultBuf = outBuf;
616,573✔
877
        } else {
878
          code = terrno;
×
879
        }
880
      }
881
      freeUdfDataDataBlock(&input);
616,573✔
882

883
      break;
616,573✔
884
    }
885
    // case TSDB_UDF_CALL_AGG_MERGE: {
886
    //   SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
887
    //   if (outBuf.buf != NULL) {
888
    //     code = udf->scriptPlugin->udfAggMergeFunc(&call->interBuf, &call->interBuf2, &outBuf, udf->scriptUdfCtx);
889
    //     freeUdfInterBuf(&call->interBuf);
890
    //     freeUdfInterBuf(&call->interBuf2);
891
    //     subRsp->resultBuf = outBuf;
892
    //   } else {
893
    //     code = terrno;
894
    //   }
895
    // 
896
    //   break;
897
    // }
898
    case TSDB_UDF_CALL_AGG_FIN: {
247,415✔
899
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
247,415✔
900
      if (outBuf.buf != NULL) {
247,415✔
901
        code = udf->scriptPlugin->udfAggFinishFunc(&call->interBuf, &outBuf, udf->scriptUdfCtx);
247,415✔
902
        freeUdfInterBuf(&call->interBuf);
247,415✔
903
        subRsp->resultBuf = outBuf;
247,415✔
904
      } else {
905
        code = terrno;
×
906
      }
907

908
      break;
247,415✔
909
    }
910
    default:
×
911
      break;
×
912
  }
913

914
  rsp->seqNum = request->seqNum;
2,878,281✔
915
  rsp->type = request->type;
2,878,281✔
916
  rsp->code = (code != 0) ? TSDB_CODE_UDF_FUNC_EXEC_FAILURE : 0;
2,878,281✔
917
  subRsp->callType = call->callType;
2,878,281✔
918

919
  int32_t len = encodeUdfResponse(NULL, rsp);
2,878,281✔
920
  if(len < 0) {
2,875,929✔
921
    fnError("udfdProcessCallRequest: encode udf response failed. len %d", len);
×
922
    goto _exit;
×
923
  }
924
  rsp->msgLen = len;
2,875,929✔
925
  void *bufBegin = taosMemoryMalloc(len);
2,875,929✔
926
  if (bufBegin == NULL) {
2,878,057✔
927
    fnError("udfdProcessCallRequest: malloc failed. len %d", len);
×
928
    goto _exit;
×
929
  }
930
  void *buf = bufBegin;
2,878,057✔
931
  if(encodeUdfResponse(&buf, rsp) < 0) {
2,878,057✔
932
    fnError("udfdProcessCallRequest: encode udf response failed. len %d", len);
×
933
    taosMemoryFree(bufBegin);
×
934
    goto _exit;
×
935
  }
936

937
  uvUdf->output = uv_buf_init(bufBegin, len);
2,876,601✔
938

939
_exit:
2,877,889✔
940
  switch (call->callType) {
2,877,889✔
941
    case TSDB_UDF_CALL_SCALA_PROC: {
1,765,289✔
942
      blockDataFreeRes(&call->block);
1,765,289✔
943
      blockDataFreeRes(&subRsp->resultData);
1,765,513✔
944
      break;
1,766,073✔
945
    }
946
    case TSDB_UDF_CALL_AGG_INIT: {
248,612✔
947
      freeUdfInterBuf(&subRsp->resultBuf);
248,612✔
948
      break;
248,612✔
949
    }
950
    case TSDB_UDF_CALL_AGG_PROC: {
616,573✔
951
      blockDataFreeRes(&call->block);
616,573✔
952
      freeUdfInterBuf(&subRsp->resultBuf);
616,573✔
953
      break;
616,573✔
954
    }
955
    // case TSDB_UDF_CALL_AGG_MERGE: {
956
    //   freeUdfInterBuf(&subRsp->resultBuf);
957
    //   break;
958
    // }
959
    case TSDB_UDF_CALL_AGG_FIN: {
247,415✔
960
      freeUdfInterBuf(&subRsp->resultBuf);
247,415✔
961
      break;
247,415✔
962
    }
963
    default:
×
964
      break;
×
965
  }
966

967
  taosMemoryFreeClear(uvUdf->input.base);
2,878,673✔
968
  return;
2,878,561✔
969
}
970

971
void udfdProcessTeardownRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
202,705✔
972
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
608,115✔
973
  SUdfTeardownRequest *teardown = &request->teardown;
202,705✔
974
  fnInfo("teardown. seq number: %" PRId64 ", handle:%" PRIx64, request->seqNum, teardown->udfHandle);
202,705✔
975
  SUdfcFuncHandle *handle = (SUdfcFuncHandle *)(teardown->udfHandle);
202,705✔
976
  SUdf            *udf = handle->udf;
202,705✔
977
  bool             unloadUdf = false;
202,705✔
978
  int32_t          code = TSDB_CODE_SUCCESS;
202,705✔
979

980
  uv_mutex_lock(&global.udfsMutex);
202,705✔
981
  udf->refCount--;
202,705✔
982
  if (udf->refCount == 0 && (!udf->resident || udf->expired)) {
202,705✔
983
    unloadUdf = true;
52,461✔
984
    code = taosHashRemove(global.udfsHash, udf->name, strlen(udf->name));
52,461✔
985
    if (code != 0) {
52,461✔
986
      fnError("udf name %s remove from hash failed, err:%0x %s", udf->name, code, tstrerror(code));
×
987
      uv_mutex_unlock(&global.udfsMutex);
×
988
      goto _send;
×
989
    }
990
  }
991
  uv_mutex_unlock(&global.udfsMutex);
202,705✔
992
  if (unloadUdf) {
202,705✔
993
    fnInfo("udf teardown. udf name: %s type %d: context %p", udf->name, udf->scriptType, (void *)(udf->scriptUdfCtx));
52,461✔
994
    uv_cond_destroy(&udf->condReady);
52,461✔
995
    uv_mutex_destroy(&udf->lock);
52,461✔
996
    code = udf->scriptPlugin->udfDestroyFunc(udf->scriptUdfCtx);
52,461✔
997
    fnDebug("udfd destroy function returns %d", code);
52,461✔
998
    taosMemoryFree(udf);
52,461✔
999
  }
1000

1001
_send:
150,244✔
1002
  taosMemoryFree(handle);
202,705✔
1003
  SUdfResponse  response = {0};
202,705✔
1004
  SUdfResponse *rsp = &response;
202,705✔
1005
  rsp->seqNum = request->seqNum;
202,705✔
1006
  rsp->type = request->type;
202,705✔
1007
  rsp->code = code;
202,705✔
1008
  int32_t len = encodeUdfResponse(NULL, rsp);
202,705✔
1009
  if (len < 0) {
202,705✔
1010
    fnError("udfdProcessTeardownRequest: encode udf response failed. len %d", len);
×
1011
    return;
×
1012
  }
1013
  rsp->msgLen = len;
202,705✔
1014
  void *bufBegin = taosMemoryMalloc(len);
202,705✔
1015
  if(bufBegin == NULL) {
202,705✔
1016
    fnError("udfdProcessTeardownRequest: malloc failed. len %d", len);
×
1017
    return;
×
1018
  }
1019
  void *buf = bufBegin;
202,705✔
1020
  if (encodeUdfResponse(&buf, rsp) < 0) {
202,705✔
1021
    fnError("udfdProcessTeardownRequest: encode udf response failed. len %d", len);
×
1022
    taosMemoryFree(bufBegin);
×
1023
    return;
×
1024
  }
1025
  uvUdf->output = uv_buf_init(bufBegin, len);
202,705✔
1026

1027
  taosMemoryFree(uvUdf->input.base);
202,705✔
1028
  return;
202,705✔
1029
}
1030

1031
void udfdGetFuncBodyPath(const SUdf *udf, char *path) {
58,196✔
1032
  TAOS_UDF_CHECK_PTR_RVOID(udf, path);
174,588✔
1033
  if (udf->scriptType == TSDB_FUNC_SCRIPT_BIN_LIB) {
58,196✔
1034
#ifdef WINDOWS
1035
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64 ".dll", global.udfDataDir, udf->name, udf->version, udf->createdTime);
1036
#else
1037
    snprintf(path, PATH_MAX, "%s/lib%s_%d_%" PRIx64 ".so", global.udfDataDir, udf->name, udf->version,
48,225✔
1038
             udf->createdTime);
48,225✔
1039
#endif
1040
  } else if (udf->scriptType == TSDB_FUNC_SCRIPT_PYTHON) {
9,971✔
1041
#ifdef WINDOWS
1042
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
1043
#else
1044
    snprintf(path, PATH_MAX, "%s/%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
9,971✔
1045
#endif
1046
  } else {
1047
#ifdef WINDOWS
1048
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64, global.udfDataDir, udf->name, udf->version, udf->createdTime);
1049
#else
1050
    snprintf(path, PATH_MAX, "%s/lib%s_%d_%" PRIx64, global.udfDataDir, udf->name, udf->version, udf->createdTime);
×
1051
#endif
1052
  }
1053
}
1054

1055
int32_t udfdSaveFuncBodyToFile(SFuncInfo *pFuncInfo, SUdf *udf) {
58,196✔
1056
  TAOS_UDF_CHECK_PTR_RCODE(pFuncInfo, udf);
174,588✔
1057
  if (!osDataSpaceAvailable()) {
58,196✔
1058
    terrno = TSDB_CODE_NO_DISKSPACE;
×
1059
    fnError("udfd create shared library failed since %s", terrstr());
×
1060
    return terrno;
×
1061
  }
1062

1063
  char path[PATH_MAX] = {0};
58,196✔
1064
  udfdGetFuncBodyPath(udf, path);
58,196✔
1065
  bool fileExist = !(taosStatFile(path, NULL, NULL, NULL) < 0);
58,196✔
1066
  if (fileExist) {
58,196✔
1067
    tstrncpy(udf->path, path, PATH_MAX);
51,605✔
1068
    fnInfo("udfd func body file. reuse existing file %s", path);
51,605✔
1069
    return TSDB_CODE_SUCCESS;
51,605✔
1070
  }
1071

1072
  TdFilePtr file = taosOpenFile(path, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_READ | TD_FILE_TRUNC);
6,591✔
1073
  if (file == NULL) {
6,591✔
1074
    fnError("udfd write udf shared library: %s failed, error: %d %s", path, ERRNO, strerror(ERRNO));
×
1075
    return TSDB_CODE_FILE_CORRUPTED;
×
1076
  }
1077
  int64_t count = taosWriteFile(file, pFuncInfo->pCode, pFuncInfo->codeSize);
6,591✔
1078
  if (count != pFuncInfo->codeSize) {
6,591✔
1079
    fnError("udfd write udf shared library failed");
×
1080
    return TSDB_CODE_FILE_CORRUPTED;
×
1081
  }
1082
  if(taosCloseFile(&file) != 0) {
6,591✔
1083
    fnError("udfdSaveFuncBodyToFile, udfd close file failed");
×
1084
    return TSDB_CODE_FILE_CORRUPTED;
×
1085
  }
1086

1087
  tstrncpy(udf->path, path, PATH_MAX);
6,591✔
1088
  return TSDB_CODE_SUCCESS;
6,591✔
1089
}
1090

1091
void udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet) {
58,196✔
1092
  TAOS_UDF_CHECK_PTR_RVOID(parent, pMsg);
174,588✔
1093
  SUdfdRpcSendRecvInfo *msgInfo = (SUdfdRpcSendRecvInfo *)pMsg->info.ahandle;
58,196✔
1094

1095
  if (pEpSet) {
58,196✔
1096
    if (!isEpsetEqual(&global.mgmtEp.epSet, pEpSet)) {
×
1097
      updateEpSet_s(&global.mgmtEp, pEpSet);
×
1098
    }
1099
  }
1100

1101
  if (pMsg->code != TSDB_CODE_SUCCESS) {
58,196✔
1102
    fnError("udfd rpc error, code:%s", tstrerror(pMsg->code));
×
1103
    msgInfo->code = pMsg->code;
×
1104
    goto _return;
×
1105
  }
1106

1107
  if (msgInfo->rpcType == UDFD_RPC_MNODE_CONNECT) {
58,196✔
1108
    SConnectRsp connectRsp = {0};
×
1109
    if(tDeserializeSConnectRsp(pMsg->pCont, pMsg->contLen, &connectRsp) < 0){
×
1110
      fnError("udfd deserialize connect response failed");
×
1111
      goto _return;
×
1112
    }
1113

1114
    int32_t now = taosGetTimestampSec();
×
1115
    int32_t delta = abs(now - connectRsp.svrTimestamp);
×
1116
    if (delta > 900) {
×
1117
      msgInfo->code = TSDB_CODE_TIME_UNSYNCED;
×
1118
      goto _return;
×
1119
    }
1120

1121
    if (connectRsp.epSet.numOfEps == 0) {
×
1122
      msgInfo->code = TSDB_CODE_APP_ERROR;
×
1123
      goto _return;
×
1124
    }
1125

1126
    if (connectRsp.dnodeNum > 1 && !isEpsetEqual(&global.mgmtEp.epSet, &connectRsp.epSet)) {
×
1127
      updateEpSet_s(&global.mgmtEp, &connectRsp.epSet);
×
1128
    }
1129
    msgInfo->code = 0;
×
1130
  } else if (msgInfo->rpcType == UDFD_RPC_RETRIVE_FUNC) {
58,196✔
1131
    SRetrieveFuncRsp retrieveRsp = {0};
58,196✔
1132
    if(tDeserializeSRetrieveFuncRsp(pMsg->pCont, pMsg->contLen, &retrieveRsp) < 0){
58,196✔
1133
      fnError("udfd deserialize retrieve func response failed");
×
1134
      goto _return;
×
1135
    }
1136

1137
    SFuncInfo *pFuncInfo = (SFuncInfo *)taosArrayGet(retrieveRsp.pFuncInfos, 0);
58,196✔
1138
    SUdf      *udf = msgInfo->param;
58,196✔
1139
    udf->funcType = pFuncInfo->funcType;
58,196✔
1140
    udf->scriptType = pFuncInfo->scriptType;
58,196✔
1141
    udf->outputType = pFuncInfo->outputType;
58,196✔
1142
    udf->outputLen = pFuncInfo->outputLen;
58,196✔
1143
    udf->bufSize = pFuncInfo->bufSize;
58,196✔
1144

1145
    SFuncExtraInfo *pFuncExtraInfo = (SFuncExtraInfo *)taosArrayGet(retrieveRsp.pFuncExtraInfos, 0);
58,196✔
1146
    udf->version = pFuncExtraInfo->funcVersion;
58,196✔
1147
    udf->createdTime = pFuncExtraInfo->funcCreatedTime;
58,196✔
1148
    msgInfo->code = udfdSaveFuncBodyToFile(pFuncInfo, udf);
58,196✔
1149
    if (msgInfo->code != 0) {
58,196✔
1150
      udf->lastFetchTime = 0;
×
1151
    }
1152
    tFreeSFuncInfo(pFuncInfo);
58,196✔
1153
    taosArrayDestroy(retrieveRsp.pFuncInfos);
58,196✔
1154
    taosArrayDestroy(retrieveRsp.pFuncExtraInfos);
58,196✔
1155
  }
1156

1157
_return:
×
1158
  rpcFreeCont(pMsg->pCont);
58,196✔
1159
  uv_sem_post(&msgInfo->resultSem);
58,196✔
1160
  return;
58,196✔
1161
}
1162

1163
int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf) {
58,196✔
1164
  TAOS_UDF_CHECK_PTR_RCODE(clientRpc, udfName, udf);
232,784✔
1165
  SRetrieveFuncReq retrieveReq = {0};
58,196✔
1166
  retrieveReq.numOfFuncs = 1;
58,196✔
1167
  retrieveReq.pFuncNames = taosArrayInit(1, TSDB_FUNC_NAME_LEN);
58,196✔
1168
  if(taosArrayPush(retrieveReq.pFuncNames, udfName) == NULL) {
116,392✔
1169
    taosArrayDestroy(retrieveReq.pFuncNames);
×
1170
    return terrno;
×
1171
  }
1172

1173
  int32_t contLen = tSerializeSRetrieveFuncReq(NULL, 0, &retrieveReq);
58,196✔
1174
  if(contLen < 0) {
58,196✔
1175
    taosArrayDestroy(retrieveReq.pFuncNames);
×
1176
    return terrno;
×
1177
  }
1178
  void   *pReq = rpcMallocCont(contLen);
58,196✔
1179
  if(tSerializeSRetrieveFuncReq(pReq, contLen, &retrieveReq)  < 0) {
58,196✔
1180
    taosArrayDestroy(retrieveReq.pFuncNames);
×
1181
    rpcFreeCont(pReq);
×
1182
    return terrno;
×
1183
  }
1184
  taosArrayDestroy(retrieveReq.pFuncNames);
58,196✔
1185

1186
  SUdfdRpcSendRecvInfo *msgInfo = taosMemoryCalloc(1, sizeof(SUdfdRpcSendRecvInfo));
58,196✔
1187
  if(NULL == msgInfo) {
58,196✔
1188
    return terrno;
×
1189
  }
1190
  msgInfo->rpcType = UDFD_RPC_RETRIVE_FUNC;
58,196✔
1191
  msgInfo->param = udf;
58,196✔
1192
  if(uv_sem_init(&msgInfo->resultSem, 0)  != 0) {
58,196✔
1193
    taosMemoryFree(msgInfo);
×
1194
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1195
  }
1196

1197
  SRpcMsg rpcMsg = {0};
58,196✔
1198
  rpcMsg.pCont = pReq;
58,196✔
1199
  rpcMsg.contLen = contLen;
58,196✔
1200
  rpcMsg.msgType = TDMT_MND_RETRIEVE_FUNC;
58,196✔
1201
  rpcMsg.info.ahandle = msgInfo;
58,196✔
1202
  int32_t code = rpcSendRequest(clientRpc, &global.mgmtEp.epSet, &rpcMsg, NULL);
58,196✔
1203
  if (code == 0) {
58,196✔
1204
    uv_sem_wait(&msgInfo->resultSem);
58,196✔
1205
    uv_sem_destroy(&msgInfo->resultSem);
58,196✔
1206
    code = msgInfo->code;
58,196✔
1207
  }
1208
  taosMemoryFree(msgInfo);
58,196✔
1209
  return code;
58,196✔
1210
}
1211

1212
static bool udfdRpcRfp(int32_t code, tmsg_t msgType) {
×
1213
  if (code == TSDB_CODE_RPC_NETWORK_UNAVAIL || code == TSDB_CODE_RPC_BROKEN_LINK || code == TSDB_CODE_SYN_NOT_LEADER ||
×
1214
      code == TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED || code == TSDB_CODE_SYN_RESTORING ||
×
1215
      code == TSDB_CODE_MNODE_NOT_FOUND || code == TSDB_CODE_APP_IS_STARTING || code == TSDB_CODE_APP_IS_STOPPING) {
×
1216
    if (msgType == TDMT_SCH_QUERY || msgType == TDMT_SCH_MERGE_QUERY || msgType == TDMT_SCH_FETCH ||
×
1217
        msgType == TDMT_SCH_MERGE_FETCH || msgType == TDMT_SCH_TASK_NOTIFY) {
×
1218
      return false;
×
1219
    }
1220
    return true;
×
1221
  } else {
1222
    return false;
×
1223
  }
1224
}
1225

1226
int initEpSetFromCfg(const char *firstEp, const char *secondEp, SCorEpSet *pEpSet) {
569,862✔
1227
  pEpSet->version = 0;
569,862✔
1228

1229
  // init mnode ip set
1230
  SEpSet *mgmtEpSet = &(pEpSet->epSet);
569,862✔
1231
  mgmtEpSet->numOfEps = 0;
569,862✔
1232
  mgmtEpSet->inUse = 0;
569,862✔
1233

1234
  if (firstEp && firstEp[0] != 0) {
569,862✔
1235
    if (strlen(firstEp) >= TSDB_EP_LEN) {
569,862✔
1236
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1237
      return -1;
×
1238
    }
1239

1240
    int32_t code = taosGetFqdnPortFromEp(firstEp, &mgmtEpSet->eps[0]);
569,862✔
1241
    if (code != TSDB_CODE_SUCCESS) {
569,862✔
1242
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1243
      return terrno;
×
1244
    }
1245

1246
    mgmtEpSet->numOfEps++;
569,862✔
1247
  }
1248

1249
  if (secondEp && secondEp[0] != 0) {
569,862✔
1250
    if (strlen(secondEp) >= TSDB_EP_LEN) {
569,862✔
1251
      terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1252
      return -1;
×
1253
    }
1254

1255
    int32_t code = taosGetFqdnPortFromEp(secondEp, &mgmtEpSet->eps[mgmtEpSet->numOfEps]);
569,862✔
1256
    if (code != TSDB_CODE_SUCCESS) {
569,862✔
1257
      fnError("invalid ep %s", secondEp);
×
1258
    } else {
1259
      mgmtEpSet->numOfEps++;
569,862✔
1260
    }
1261
  }
1262

1263
  if (mgmtEpSet->numOfEps == 0) {
569,862✔
1264
    terrno = TSDB_CODE_TSC_INVALID_FQDN;
×
1265
    return -1;
×
1266
  }
1267

1268
  return 0;
569,862✔
1269
}
1270

1271
int32_t udfdOpenClientRpc() {
569,862✔
1272
  SRpcInit rpcInit = {0};
569,862✔
1273
  rpcInit.label = "UDFD";
569,862✔
1274
  rpcInit.numOfThreads = 1;
569,862✔
1275
  rpcInit.cfp = (RpcCfp)udfdProcessRpcRsp;
569,862✔
1276
  rpcInit.sessions = 1024;
569,862✔
1277
  rpcInit.connType = TAOS_CONN_CLIENT;
569,862✔
1278
  rpcInit.idleTime = tsShellActivityTimer * 1000;
569,862✔
1279
  rpcInit.user = TSDB_DEFAULT_USER;
569,862✔
1280
  rpcInit.parent = &global;
569,862✔
1281
  rpcInit.rfp = udfdRpcRfp;
569,862✔
1282
  rpcInit.compressSize = tsCompressMsgSize;
569,862✔
1283

1284
  int32_t connLimitNum = tsNumOfRpcSessions / (tsNumOfRpcThreads * 3);
569,862✔
1285
  connLimitNum = TMAX(connLimitNum, 10);
569,862✔
1286
  connLimitNum = TMIN(connLimitNum, 500);
569,862✔
1287
  rpcInit.connLimitNum = connLimitNum;
569,862✔
1288
  rpcInit.timeToGetConn = tsTimeToGetAvailableConn;
569,862✔
1289

1290
  rpcInit.enableSSL = tsEnableTLS;
569,862✔
1291
  rpcInit.enableSasl = tsEnableSasl;
569,862✔
1292
  memcpy(rpcInit.caPath, tsTLSCaPath, strlen(tsTLSCaPath));
569,862✔
1293
  memcpy(rpcInit.certPath, tsTLSSvrCertPath, strlen(tsTLSSvrCertPath));
569,862✔
1294
  memcpy(rpcInit.keyPath, tsTLSSvrKeyPath, strlen(tsTLSSvrKeyPath));
569,862✔
1295
  memcpy(rpcInit.cliCertPath, tsTLSCliCertPath, strlen(tsTLSCliCertPath));
569,862✔
1296
  memcpy(rpcInit.cliKeyPath, tsTLSCliKeyPath, strlen(tsTLSCliKeyPath));
569,862✔
1297
  TAOS_CHECK_RETURN(taosVersionStrToInt(td_version, &rpcInit.compatibilityVer));
569,862✔
1298

1299
  global.clientRpc = rpcOpen(&rpcInit);
569,862✔
1300
  if (global.clientRpc == NULL) {
569,862✔
1301
    fnError("failed to init dnode rpc client");
×
1302
    return terrno;
×
1303
  }
1304
  return 0;
569,862✔
1305
}
1306

1307
void udfdCloseClientRpc() {
569,862✔
1308
  fnInfo("udfd begin closing rpc");
569,862✔
1309
  rpcClose(global.clientRpc);
569,862✔
1310
  fnInfo("udfd finish closing rpc");
569,862✔
1311
}
569,862✔
1312

1313
void udfdOnWrite(uv_write_t *req, int status) {
3,287,941✔
1314
  TAOS_UDF_CHECK_PTR_RVOID(req);
6,575,882✔
1315
  SUvUdfWork *work = (SUvUdfWork *)req->data;
3,287,941✔
1316
  if (status < 0) {
3,287,941✔
1317
    fnError("udfd send response error, length:%zu code:%s", work->output.len, uv_err_name(status));
×
1318
  }
1319
  // remove work from the connection work list
1320
  if (work->conn != NULL) {
3,287,941✔
1321
    SUvUdfWork **ppWork;
1322
    for (ppWork = &work->conn->pWorkList; *ppWork && (*ppWork != work); ppWork = &((*ppWork)->pWorkNext)) {
5,619,083✔
1323
    }
1324
    if (*ppWork == work) {
3,287,941✔
1325
      *ppWork = work->pWorkNext;
3,287,941✔
1326
    } else {
1327
      fnError("work not in conn any more");
×
1328
    }
1329
  }
1330
  taosMemoryFree(work->output.base);
3,287,941✔
1331
  taosMemoryFree(work);
3,287,941✔
1332
  taosMemoryFree(req);
3,287,941✔
1333
}
1334

1335
void udfdSendResponse(uv_work_t *work, int status) {
3,287,941✔
1336
  TAOS_UDF_CHECK_PTR_RVOID(work);
6,575,882✔
1337
  SUvUdfWork *udfWork = (SUvUdfWork *)(work->data);
3,287,941✔
1338

1339
  if (udfWork->conn != NULL) {
3,287,941✔
1340
    uv_write_t *write_req = taosMemoryMalloc(sizeof(uv_write_t));
3,287,941✔
1341
    if(write_req == NULL) {
3,287,941✔
1342
      fnError("udfd send response error, malloc failed");
×
1343
      taosMemoryFree(work);
×
1344
      return;
×
1345
    }
1346
    write_req->data = udfWork;
3,287,941✔
1347
    int32_t code = uv_write(write_req, udfWork->conn->client, &udfWork->output, 1, udfdOnWrite);
3,287,941✔
1348
    if (code != 0) {
3,287,941✔
1349
      fnError("udfd send response error %s", uv_strerror(code));
×
1350
      taosMemoryFree(write_req);
×
1351
   }
1352
  }
1353
  taosMemoryFree(work);
3,287,941✔
1354
}
1355

1356
void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
9,753,397✔
1357
  TAOS_UDF_CHECK_PTR_RVOID(handle, buf);
29,260,191✔
1358
  SUdfdUvConn *ctx = handle->data;
9,753,397✔
1359
  int32_t      msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
9,753,397✔
1360
  if (ctx->inputCap == 0) {
9,753,397✔
1361
    ctx->inputBuf = taosMemoryMalloc(msgHeadSize);
3,494,504✔
1362
    if (ctx->inputBuf) {
3,494,504✔
1363
      ctx->inputLen = 0;
3,494,504✔
1364
      ctx->inputCap = msgHeadSize;
3,494,504✔
1365
      ctx->inputTotal = -1;
3,494,504✔
1366

1367
      buf->base = ctx->inputBuf;
3,494,504✔
1368
      buf->len = ctx->inputCap;
3,494,504✔
1369
    } else {
1370
      fnError("udfd can not allocate enough memory") buf->base = NULL;
×
1371
      buf->len = 0;
×
1372
    }
1373
  } else if (ctx->inputTotal == -1 && ctx->inputLen < msgHeadSize) {
6,258,893✔
1374
    buf->base = ctx->inputBuf + ctx->inputLen;
2,968,710✔
1375
    buf->len = msgHeadSize - ctx->inputLen;
2,968,710✔
1376
  } else {
1377
    ctx->inputCap = ctx->inputTotal > ctx->inputCap ? ctx->inputTotal : ctx->inputCap;
3,290,183✔
1378
    void *inputBuf = taosMemoryRealloc(ctx->inputBuf, ctx->inputCap);
3,290,183✔
1379
    if (inputBuf) {
3,290,183✔
1380
      ctx->inputBuf = inputBuf;
3,290,183✔
1381
      buf->base = ctx->inputBuf + ctx->inputLen;
3,290,183✔
1382
      buf->len = ctx->inputCap - ctx->inputLen;
3,290,183✔
1383
    } else {
1384
      fnError("udfd can not allocate enough memory") buf->base = NULL;
×
1385
      buf->len = 0;
×
1386
    }
1387
  }
1388
}
1389

1390
bool isUdfdUvMsgComplete(SUdfdUvConn *pipe) {
6,578,124✔
1391
  if (pipe == NULL) {
6,578,124✔
1392
    fnError("udfd pipe is NULL, LINE:%d", __LINE__);
×
1393
    return false;
×
1394
  }
1395
  if (pipe->inputTotal == -1 && pipe->inputLen >= sizeof(int32_t)) {
6,578,124✔
1396
    pipe->inputTotal = *(int32_t *)(pipe->inputBuf);
3,287,941✔
1397
  }
1398
  if (pipe->inputLen == pipe->inputCap && pipe->inputTotal == pipe->inputCap) {
6,578,124✔
1399
    fnDebug("receive request complete. length %d", pipe->inputLen);
3,287,941✔
1400
    return true;
3,287,941✔
1401
  }
1402
  return false;
3,290,183✔
1403
}
1404

1405
void udfdHandleRequest(SUdfdUvConn *conn) {
3,287,941✔
1406
  TAOS_UDF_CHECK_PTR_RVOID(conn);
6,575,882✔
1407
  char   *inputBuf = conn->inputBuf;
3,287,941✔
1408
  int32_t inputLen = conn->inputLen;
3,287,941✔
1409

1410
  uv_work_t  *work = taosMemoryMalloc(sizeof(uv_work_t));
3,287,941✔
1411
  if(work == NULL) {
3,287,941✔
1412
    fnError("udfd malloc work failed");
×
1413
    return;
×
1414
  }
1415
  SUvUdfWork *udfWork = taosMemoryMalloc(sizeof(SUvUdfWork));
3,287,941✔
1416
  if(udfWork == NULL) {
3,287,941✔
1417
    fnError("udfd malloc udf work failed");
×
1418
    taosMemoryFree(work);
×
1419
    return;
×
1420
  }
1421
  udfWork->conn = conn;
3,287,941✔
1422
  udfWork->pWorkNext = conn->pWorkList;
3,287,941✔
1423
  conn->pWorkList = udfWork;
3,287,941✔
1424
  udfWork->input = uv_buf_init(inputBuf, inputLen);
3,287,941✔
1425
  conn->inputBuf = NULL;
3,287,941✔
1426
  conn->inputLen = 0;
3,287,941✔
1427
  conn->inputCap = 0;
3,287,941✔
1428
  conn->inputTotal = -1;
3,287,941✔
1429
  work->data = udfWork;
3,287,941✔
1430
  if(uv_queue_work(global.loop, work, udfdProcessRequest, udfdSendResponse) != 0)
3,287,941✔
1431
  {
1432
    fnError("udfd queue work failed");
×
1433
    taosMemoryFree(work);
×
1434
    taosMemoryFree(udfWork);
×
1435
  }
1436
}
1437

1438
void udfdPipeCloseCb(uv_handle_t *pipe) {
206,563✔
1439
  TAOS_UDF_CHECK_PTR_RVOID(pipe);
413,126✔
1440
  SUdfdUvConn *conn = pipe->data;
206,563✔
1441
  SUvUdfWork  *pWork = conn->pWorkList;
206,563✔
1442
  while (pWork != NULL) {
206,563✔
1443
    pWork->conn = NULL;
×
1444
    pWork = pWork->pWorkNext;
×
1445
  }
1446

1447
  taosMemoryFree(conn->client);
206,563✔
1448
  taosMemoryFree(conn->inputBuf);
206,563✔
1449
  taosMemoryFree(conn);
206,563✔
1450
}
1451

1452
void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
9,753,397✔
1453
  TAOS_UDF_CHECK_PTR_RVOID(client, buf);
29,260,191✔
1454
  fnDebug("udfd read %zd bytes from client", nread);
9,753,397✔
1455
  if (nread == 0) return;
9,753,397✔
1456

1457
  SUdfdUvConn *conn = client->data;
6,784,687✔
1458

1459
  if (nread > 0) {
6,784,687✔
1460
    conn->inputLen += nread;
6,578,124✔
1461
    if (isUdfdUvMsgComplete(conn)) {
6,578,124✔
1462
      udfdHandleRequest(conn);
3,287,941✔
1463
    } else {
1464
      // log error or continue;
1465
    }
1466
    return;
6,578,124✔
1467
  }
1468

1469
  if (nread < 0) {
206,563✔
1470
    if (nread == UV_EOF) {
206,563✔
1471
      fnInfo("udfd pipe read EOF");
206,563✔
1472
    } else {
1473
      fnError("Receive error %s", uv_err_name(nread));
×
1474
    }
1475
    udfdUvHandleError(conn);
206,563✔
1476
  }
1477
}
1478

1479
void udfdOnNewConnection(uv_stream_t *server, int status) {
206,563✔
1480
  TAOS_UDF_CHECK_PTR_RVOID(server);
413,126✔
1481
  if (status < 0) {
206,563✔
1482
    fnError("udfd new connection error, code:%s", uv_strerror(status));
×
1483
    return;
×
1484
  }
1485
  int32_t code = 0;
206,563✔
1486

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

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

1540
static int32_t udfdParseArgs(int32_t argc, char *argv[]) {
572,256✔
1541
  for (int32_t i = 1; i < argc; ++i) {
1,142,916✔
1542
    if (strcmp(argv[i], "-c") == 0) {
572,256✔
1543
      if (i < argc - 1) {
571,458✔
1544
        if (strlen(argv[++i]) >= PATH_MAX) {
570,660✔
1545
          (void)printf("config file path overflow");
798✔
1546
          return -1;
798✔
1547
        }
1548
        tstrncpy(configDir, argv[i], PATH_MAX);
569,862✔
1549
      } else {
1550
        (void)printf("'-c' requires a parameter, default is %s\n", configDir);
798✔
1551
        return -1;
798✔
1552
      }
1553
    } else if (strcmp(argv[i], "-V") == 0) {
798✔
1554
      global.printVersion = true;
798✔
1555
    } else {
1556
    }
1557
  }
1558

1559
  return 0;
570,660✔
1560
}
1561

1562
static void udfdPrintVersion() {
798✔
1563
  (void)printf("%sudf version: %s compatible_version: %s\n", CUS_PROMPT, td_version, td_compatible_version);
798✔
1564
  (void)printf("git: %s\n", td_gitinfo);
798✔
1565
  (void)printf("build: %s\n", td_buildinfo);
798✔
1566
}
798✔
1567

1568
static int32_t udfdInitLog() {
569,862✔
1569
  const char *logName = "udfdlog";
569,862✔
1570
  TAOS_CHECK_RETURN(taosInitLogOutput(&logName));
569,862✔
1571
  return taosCreateLog(logName, 1, configDir, NULL, NULL, NULL, NULL, 0);
569,862✔
1572
}
1573

1574
void udfdCtrlAllocBufCb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
569,862✔
1575
  TAOS_UDF_CHECK_PTR_RVOID(buf);
1,139,724✔
1576
  buf->base = taosMemoryMalloc(suggested_size);
569,862✔
1577
  if (buf->base == NULL) {
569,862✔
1578
    fnError("udfd ctrl pipe alloc buffer failed");
×
1579
    return;
×
1580
  }
1581
  buf->len = suggested_size;
569,862✔
1582
}
1583

1584
void udfdCtrlReadCb(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) {
569,862✔
1585
  TAOS_UDF_CHECK_PTR_RVOID(q, buf);
1,709,586✔
1586
  if (nread < 0) {
569,862✔
1587
    fnError("udfd ctrl pipe read error. %s", uv_err_name(nread));
569,862✔
1588
    taosMemoryFree(buf->base);
569,862✔
1589
    uv_close((uv_handle_t *)q, NULL);
569,862✔
1590
    uv_stop(global.loop);
569,862✔
1591
    return;
569,862✔
1592
  }
1593
  fnError("udfd ctrl pipe read %zu bytes", nread);
×
1594
  taosMemoryFree(buf->base);
×
1595
}
1596

1597
static void removeListeningPipe() {
1,139,724✔
1598
  uv_fs_t req;
1,133,580✔
1599
  int     err = uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
1,139,724✔
1600
  uv_fs_req_cleanup(&req);
1,139,724✔
1601
  if(err) {
1,139,724✔
1602
    fnInfo("remove listening pipe %s : %s, lino:%d", global.listenPipeName, uv_strerror(err), __LINE__);
1,138,943✔
1603
  }
1604
}
1,139,724✔
1605

1606
static int32_t udfdUvInit() {
569,862✔
1607
  TAOS_CHECK_RETURN(uv_loop_init(global.loop));
569,862✔
1608

1609
  if (tsStartUdfd) {  // udfd is started by taosd, which shall exit when taosd exit
569,862✔
1610
    TAOS_CHECK_RETURN(uv_pipe_init(global.loop, &global.ctrlPipe, 1));
569,862✔
1611
    TAOS_CHECK_RETURN(uv_pipe_open(&global.ctrlPipe, 0));
569,862✔
1612
    TAOS_CHECK_RETURN(uv_read_start((uv_stream_t *)&global.ctrlPipe, udfdCtrlAllocBufCb, udfdCtrlReadCb));
569,862✔
1613
  }
1614
  getUdfdPipeName(global.listenPipeName, sizeof(global.listenPipeName));
569,862✔
1615

1616
  removeListeningPipe();
569,862✔
1617

1618
  TAOS_CHECK_RETURN(uv_pipe_init(global.loop, &global.listeningPipe, 0));
569,862✔
1619

1620
  TAOS_CHECK_RETURN(uv_signal_init(global.loop, &global.intrSignal));
569,862✔
1621
  TAOS_CHECK_RETURN(uv_signal_start(&global.intrSignal, udfdIntrSignalHandler, SIGINT));
569,862✔
1622

1623
  int r;
1624
  fnInfo("bind to pipe %s", global.listenPipeName);
569,862✔
1625
  if ((r = uv_pipe_bind(&global.listeningPipe, global.listenPipeName))) {
569,862✔
1626
    fnError("Bind error %s", uv_err_name(r));
×
1627
    removeListeningPipe();
×
1628
    return -2;
×
1629
  }
1630
  if ((r = uv_listen((uv_stream_t *)&global.listeningPipe, 128, udfdOnNewConnection))) {
569,862✔
1631
    fnError("Listen error %s", uv_err_name(r));
×
1632
    removeListeningPipe();
×
1633
    return -3;
×
1634
  }
1635
  return 0;
569,862✔
1636
}
1637

1638
static void udfdCloseWalkCb(uv_handle_t *handle, void *arg) {
1,139,724✔
1639
  if (!uv_is_closing(handle)) {
1,139,724✔
1640
    uv_close(handle, NULL);
1,139,724✔
1641
  }
1642
}
1,139,724✔
1643

1644
static int32_t udfdGlobalDataInit() {
569,862✔
1645
  uv_loop_t *loop = taosMemoryMalloc(sizeof(uv_loop_t));
569,862✔
1646
  if (loop == NULL) {
569,862✔
1647
    fnError("udfd init uv loop failed, mem overflow");
×
1648
    return terrno;
×
1649
  }
1650
  global.loop = loop;
569,862✔
1651

1652
  if (uv_mutex_init(&global.scriptPluginsMutex) != 0) {
569,862✔
1653
    fnError("udfd init script plugins mutex failed");
×
1654
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1655
  }
1656

1657
  global.udfsHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
569,862✔
1658
  if (global.udfsHash == NULL) {
569,862✔
1659
    return terrno;
×
1660
  }
1661
  // taosHashSetFreeFp(global.udfsHash, udfdFreeUdf);
1662

1663
  if (uv_mutex_init(&global.udfsMutex) != 0) {
569,862✔
1664
    fnError("udfd init udfs mutex failed");
×
1665
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1666
  }
1667

1668
  return 0;
569,862✔
1669
}
1670

1671
static void udfdGlobalDataDeinit() {
569,862✔
1672
  uv_mutex_destroy(&global.udfsMutex);
569,862✔
1673
  uv_mutex_destroy(&global.scriptPluginsMutex);
569,862✔
1674
  taosMemoryFreeClear(global.loop);
569,862✔
1675
  fnInfo("udfd global data deinit");
569,862✔
1676
}
569,862✔
1677

1678
static void udfdRun() {
569,862✔
1679
  fnInfo("start udfd event loop");
569,862✔
1680
  int32_t code = uv_run(global.loop, UV_RUN_DEFAULT);
569,862✔
1681
  if(code != 0) {
569,862✔
1682
    fnError("udfd event loop still has active handles or requests.");
569,862✔
1683
  }
1684
  fnInfo("udfd event loop stopped.");
569,862✔
1685

1686
  (void)uv_loop_close(global.loop);
569,862✔
1687

1688
  uv_walk(global.loop, udfdCloseWalkCb, NULL);
569,862✔
1689
  code = uv_run(global.loop, UV_RUN_DEFAULT);
569,862✔
1690
  if(code != 0) {
569,862✔
1691
    fnError("udfd event loop still has active handles or requests.");
×
1692
  }
1693
  (void)uv_loop_close(global.loop);
569,862✔
1694
}
569,862✔
1695

1696
int32_t udfdInitResidentFuncs() {
569,862✔
1697
  if (strlen(tsUdfdResFuncs) == 0) {
569,862✔
1698
    return TSDB_CODE_SUCCESS;
567,551✔
1699
  }
1700

1701
  global.residentFuncs = taosArrayInit(2, TSDB_FUNC_NAME_LEN);
2,311✔
1702
  char *pSave = tsUdfdResFuncs;
2,311✔
1703
  char *token;
1704
  while ((token = strtok_r(pSave, ",", &pSave)) != NULL) {
6,933✔
1705
    char func[TSDB_FUNC_NAME_LEN + 1] = {0};
4,622✔
1706
    tstrncpy(func, token, TSDB_FUNC_NAME_LEN);
4,622✔
1707
    fnInfo("udfd add resident function %s", func);
4,622✔
1708
    if(taosArrayPush(global.residentFuncs, func) == NULL)
9,244✔
1709
    {
1710
      taosArrayDestroy(global.residentFuncs);
×
1711
      return terrno;
×
1712
    }
1713
  }
1714

1715
  return TSDB_CODE_SUCCESS;
2,311✔
1716
}
1717

1718
void udfdDeinitResidentFuncs() {
569,862✔
1719
  for (int32_t i = 0; i < taosArrayGetSize(global.residentFuncs); ++i) {
574,484✔
1720
    char  *funcName = taosArrayGet(global.residentFuncs, i);
4,622✔
1721
    SUdf **udfInHash = taosHashGet(global.udfsHash, funcName, strlen(funcName));
4,622✔
1722
    if (udfInHash) {
4,622✔
1723
      SUdf   *udf = *udfInHash;
3,094✔
1724
      int32_t code = 0;
3,094✔
1725
      if (udf->scriptPlugin->udfDestroyFunc) {
3,094✔
1726
        code = udf->scriptPlugin->udfDestroyFunc(udf->scriptUdfCtx);
3,094✔
1727
        fnDebug("udfd %s destroy function returns %d", funcName, code);
3,094✔
1728
      }
1729
      if(taosHashRemove(global.udfsHash, funcName, strlen(funcName)) != 0)
3,094✔
1730
      {
1731
        fnError("udfd remove resident function %s failed", funcName);
×
1732
      }
1733
      taosMemoryFree(udf);
3,094✔
1734
    }
1735
  }
1736
  taosHashCleanup(global.udfsHash);
569,862✔
1737
  taosArrayDestroy(global.residentFuncs);
569,862✔
1738
  fnInfo("udfd resident functions are deinit");
569,862✔
1739
}
569,862✔
1740

1741
int32_t udfdCreateUdfSourceDir() {
569,862✔
1742
  snprintf(global.udfDataDir, PATH_MAX, "%s/.udf", tsDataDir);
569,862✔
1743
  int32_t code = taosMkDir(global.udfDataDir);
569,862✔
1744
  if (code != TSDB_CODE_SUCCESS) {
569,862✔
1745
    snprintf(global.udfDataDir, PATH_MAX, "%s/.udf", tsTempDir);
×
1746
    code = taosMkDir(global.udfDataDir);
×
1747
  }
1748
  fnInfo("udfd create udf source directory %s. result: %s", global.udfDataDir, tstrerror(code));
569,862✔
1749

1750
  return code;
569,862✔
1751
}
1752

1753
void udfdDestroyUdfSourceDir() {
569,862✔
1754
  fnInfo("destory udf source directory %s", global.udfDataDir);
569,862✔
1755
  taosRemoveDir(global.udfDataDir);
569,862✔
1756
}
569,862✔
1757

1758
int main(int argc, char *argv[]) {
572,256✔
1759
  int  code = 0;
572,256✔
1760
  bool logInitialized = false;
572,256✔
1761
  bool cfgInitialized = false;
572,256✔
1762
  bool openClientRpcFinished = false;
572,256✔
1763
  bool residentFuncsInited = false;
572,256✔
1764
  bool udfSourceDirInited = false;
572,256✔
1765
  bool globalDataInited = false;
572,256✔
1766

1767
  if (!taosCheckSystemIsLittleEnd()) {
572,256✔
1768
    (void)printf("failed to start since on non-little-end machines\n");
×
1769
    return -1;
×
1770
  }
1771

1772
  if (udfdParseArgs(argc, argv) != 0) {
572,256✔
1773
    (void)printf("failed to start since parse args error\n");
1,596✔
1774
    return -1;
1,596✔
1775
  }
1776

1777
  if (global.printVersion) {
570,660✔
1778
    udfdPrintVersion();
798✔
1779
    return 0;
798✔
1780
  }
1781

1782
  if (udfdInitLog() != 0) {
569,862✔
1783
    // ignore create log failed, because this error no matter
1784
    (void)printf("failed to init udfd log.");
×
1785
  } else {
1786
    logInitialized = true;  // log is initialized
569,862✔
1787
  }
1788

1789
  if (taosInitCfg(configDir, NULL, NULL, NULL, NULL, 0) != 0) {
569,862✔
1790
    fnError("failed to start since read config error");
×
1791
    code = -2;
×
1792
    goto _exit;
×
1793
  }
1794
  cfgInitialized = true;  // cfg is initialized
569,862✔
1795
  fnInfo("udfd start with config file %s", configDir);
569,862✔
1796

1797
  if (initEpSetFromCfg(tsFirst, tsSecond, &global.mgmtEp) != 0) {
569,862✔
1798
    fnError("init ep set from cfg failed");
×
1799
    code = -3;
×
1800
    goto _exit;
×
1801
  }
1802
  fnInfo("udfd start with mnode ep %s", global.mgmtEp.epSet.eps[0].fqdn);
569,862✔
1803
  if (udfdOpenClientRpc() != 0) {
569,862✔
1804
    fnError("open rpc connection to mnode failed");
×
1805
    code = -4;
×
1806
    goto _exit;
×
1807
  }
1808
  fnInfo("udfd rpc client is opened");
569,862✔
1809
  openClientRpcFinished = true;  // rpc is opened
569,862✔
1810

1811
  if (udfdCreateUdfSourceDir() != 0) {
569,862✔
1812
    fnError("create udf source directory failed");
×
1813
    code = -5;
×
1814
    goto _exit;
×
1815
  }
1816
  udfSourceDirInited = true;  // udf source dir is created
569,862✔
1817
  fnInfo("udfd udf source directory is created");
569,862✔
1818

1819
  if (udfdGlobalDataInit() != 0) {
569,862✔
1820
    fnError("init global data failed");
×
1821
    code = -6;
×
1822
    goto _exit;
×
1823
  }
1824
  globalDataInited = true;  // global data is inited
569,862✔
1825
  fnInfo("udfd global data is inited");
569,862✔
1826

1827
  if (udfdUvInit() != 0) {
569,862✔
1828
    fnError("uv init failure");
×
1829
    code = -7;
×
1830
    goto _exit;
×
1831
  }
1832
  fnInfo("udfd uv is inited");
569,862✔
1833

1834
  if (udfdInitResidentFuncs() != 0) {
569,862✔
1835
    fnError("init resident functions failed");
×
1836
    code = -8;
×
1837
    goto _exit;
×
1838
  }
1839
  residentFuncsInited = true;  // resident functions are inited
569,862✔
1840
  fnInfo("udfd resident functions are inited");
569,862✔
1841

1842
  udfdRun();
569,862✔
1843
  fnInfo("udfd exit normally");
569,862✔
1844

1845
  removeListeningPipe();
569,862✔
1846

1847
_exit:
569,862✔
1848
  if (residentFuncsInited) {
569,862✔
1849
    udfdDeinitResidentFuncs();
569,862✔
1850
  }
1851
  udfdDeinitScriptPlugins();
569,862✔
1852
  if (globalDataInited) {
569,862✔
1853
    udfdGlobalDataDeinit();
569,862✔
1854
  }
1855
  if (udfSourceDirInited) {
569,862✔
1856
    udfdDestroyUdfSourceDir();
569,862✔
1857
  }
1858
  if (openClientRpcFinished) {
569,862✔
1859
    udfdCloseClientRpc();
569,862✔
1860
  }
1861
  if (cfgInitialized) {
569,862✔
1862
    taosCleanupCfg();
569,862✔
1863
  }
1864
  if (logInitialized) {
569,862✔
1865
    taosCloseLog();
569,862✔
1866
  }
1867

1868
  return code;
569,862✔
1869
}
1870
#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