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

taosdata / TDengine / #4912

04 Jan 2026 09:05AM UTC coverage: 64.888% (-0.1%) from 65.028%
#4912

push

travis-ci

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

1206 of 4524 new or added lines in 22 files covered. (26.66%)

5351 existing lines in 123 files now uncovered.

194856 of 300296 relevant lines covered (64.89%)

118198896.2 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; }
1,721✔
54

55
int32_t udfdCPluginClose() { return 0; }
1,721✔
56

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

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

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

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

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

87
  return 0;
10,734✔
88
}
89

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

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

112
  if (udf->funcType == UDF_FUNC_TYPE_SCALAR) {
42,556✔
113
    char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
31,246✔
114
    snprintf(processFuncName, sizeof(processFuncName), "%s", udfName);
31,246✔
115
    if (uv_dlsym(&udfCtx->lib, processFuncName, (void **)(&udfCtx->scalarProcFunc)) != 0) {
31,246✔
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,310✔
121
    err = udfdCPluginUdfInitLoadAggFuncs(udfCtx, udfName);
11,310✔
122
    if (err != 0) {
11,310✔
123
      fnError("can not load aggregation functions. error: %d", err);
576✔
124
      err = TSDB_CODE_UDF_LOAD_UDF_FAILURE;
576✔
125
      goto _exit;
576✔
126
    }
127
  }
128

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

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

156
int32_t udfdCPluginUdfScalarProc(SUdfDataBlock *block, SUdfColumn *resultCol, void *udfCtx) {
1,652,326✔
157
  TAOS_UDF_CHECK_PTR_RCODE(block, resultCol, udfCtx);
6,609,119✔
158
  SUdfCPluginCtx *ctx = udfCtx;
1,652,326✔
159
  if (ctx->scalarProcFunc) {
1,652,326✔
160
    return ctx->scalarProcFunc(block, resultCol);
1,652,497✔
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) {
111,080✔
168
  TAOS_UDF_CHECK_PTR_RCODE(buf, udfCtx);
333,240✔
169
  SUdfCPluginCtx *ctx = udfCtx;
111,080✔
170
  if (ctx->aggStartFunc) {
111,080✔
171
    return ctx->aggStartFunc(buf);
111,080✔
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) {
259,990✔
180
  TAOS_UDF_CHECK_PTR_RCODE(block, interBuf, newInterBuf, udfCtx);
1,299,950✔
181
  SUdfCPluginCtx *ctx = udfCtx;
259,990✔
182
  if (ctx->aggProcFunc) {
259,990✔
183
    return ctx->aggProcFunc(block, interBuf, newInterBuf);
259,990✔
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) {
109,864✔
203
  TAOS_UDF_CHECK_PTR_RCODE(buf, resultData, udfCtx);
439,456✔
204
  SUdfCPluginCtx *ctx = udfCtx;
109,864✔
205
  if (ctx->aggFinishFunc) {
109,864✔
206
    return ctx->aggFinishFunc(buf, resultData);
109,864✔
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); }
97,367✔
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) {
1,721✔
365
  TAOS_UDF_CHECK_PTR_RCODE(plugin);
3,442✔
366
  plugin->scriptType = TSDB_FUNC_SCRIPT_BIN_LIB;
1,721✔
367
  plugin->openFunc = udfdCPluginOpen;
1,721✔
368
  plugin->closeFunc = udfdCPluginClose;
1,721✔
369
  plugin->udfInitFunc = udfdCPluginUdfInit;
1,721✔
370
  plugin->udfDestroyFunc = udfdCPluginUdfDestroy;
1,721✔
371
  plugin->udfScalarProcFunc = udfdCPluginUdfScalarProc;
1,721✔
372
  plugin->udfAggStartFunc = udfdCPluginUdfAggStart;
1,721✔
373
  plugin->udfAggProcFunc = udfdCPluginUdfAggProc;
1,721✔
374
  // plugin->udfAggMergeFunc = udfdCPluginUdfAggMerge;
375
  plugin->udfAggFinishFunc = udfdCPluginUdfAggFinish;
1,721✔
376

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

383
int32_t udfdLoadSharedLib(char *libPath, uv_lib_t *pLib, const char *funcName[], void **func[], int numOfFuncs) {
60✔
384
  TAOS_UDF_CHECK_PTR_RCODE(libPath, pLib, funcName, func);
300✔
385
  int err = uv_dlopen(libPath, pLib);
60✔
386
  if (err != 0) {
60✔
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) {
600✔
392
    err = uv_dlsym(pLib, funcName[i], func[i]);
540✔
393
    if (err != 0) {
540✔
394
      fnError("load library function failed. lib %s function %s", libPath, funcName[i]);
×
395
    }
396
  }
397
  return 0;
60✔
398
}
399

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

419
  if (plugin->openFunc) {
60✔
420
    int16_t lenPythonPath =
60✔
421
        strlen(tsUdfdLdLibPath) + strlen(global.udfDataDir) + 1 + 1;  // global.udfDataDir:tsUdfdLdLibPath
60✔
422
    char *pythonPath = taosMemoryMalloc(lenPythonPath);
60✔
423
    if(pythonPath == NULL) {
60✔
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);
60✔
431
#endif
432
    SScriptUdfEnvItem items[] = {{"PYTHONPATH", pythonPath}, {"LOGDIR", tsLogDir}};
60✔
433
    err = plugin->openFunc(items, 2);
60✔
434
    taosMemoryFree(pythonPath);
60✔
435
  }
436
  if (err != 0) {
60✔
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;
60✔
442

443
  return 0;
60✔
444
}
445

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

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

487
int32_t udfdInitScriptPlugin(int8_t scriptType) {
1,781✔
488
  SUdfScriptPlugin *plugin = taosMemoryCalloc(1, sizeof(SUdfScriptPlugin));
1,781✔
489
  if (plugin == NULL) {
1,781✔
490
    return terrno;
×
491
  }
492
  int32_t err = 0;
1,781✔
493
  switch (scriptType) {
1,781✔
494
    case TSDB_FUNC_SCRIPT_BIN_LIB:
1,721✔
495
      err = udfdInitializeCPlugin(plugin);
1,721✔
496
      if (err != 0) {
1,721✔
497
        fnError("udf script c plugin init failed. error: %d", err);
×
498
        taosMemoryFree(plugin);
×
499
        return err;
×
500
      }
501
      break;
1,721✔
502
    case TSDB_FUNC_SCRIPT_PYTHON: {
60✔
503
      err = udfdInitializePythonPlugin(plugin);
60✔
504
      if (err != 0) {
60✔
505
        fnError("udf script python plugin init failed. error: %d", err);
×
506
        taosMemoryFree(plugin);
×
507
        return err;
×
508
      }
509
      break;
60✔
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;
1,781✔
518
  return TSDB_CODE_SUCCESS;
1,781✔
519
}
520

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

530
  plugin = global.scriptPlugins[TSDB_FUNC_SCRIPT_BIN_LIB];
568,613✔
531
  if (plugin != NULL) {
568,613✔
532
    udfdDeinitCPlugin(plugin);
1,721✔
533
    taosMemoryFree(plugin);
1,721✔
534
    global.scriptPlugins[TSDB_FUNC_SCRIPT_BIN_LIB] = NULL;
1,721✔
535
  }
536
  return;
568,613✔
537
}
538

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

554
  switch (request.type) {
2,386,397✔
555
    case UDF_TASK_SETUP: {
97,367✔
556
      udfdProcessSetupRequest(uvUdf, &request);
97,367✔
557
      break;
97,367✔
558
    }
559

560
    case UDF_TASK_CALL: {
2,195,891✔
561
      udfdProcessCallRequest(uvUdf, &request);
2,195,891✔
562
      break;
2,196,233✔
563
    }
564
    case UDF_TASK_TEARDOWN: {
93,139✔
565
      udfdProcessTeardownRequest(uvUdf, &request);
93,139✔
566
      break;
93,139✔
567
    }
568
    default: {
×
569
      break;
×
570
    }
571
  }
572
}
573

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

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

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

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

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

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

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

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

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

709
  return 0;
52,252✔
710
}
711

712
void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
97,367✔
713
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
292,101✔
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);
97,367✔
716

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

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

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

761
  int32_t len = encodeUdfResponse(NULL, &rsp);
97,367✔
762
  if(len < 0) {
97,367✔
763
    fnError("udfdProcessSetupRequest: encode udf response failed. len %d", len);
×
764
    return;
×
765
  }
766
  rsp.msgLen = len;
97,367✔
767
  void *bufBegin = taosMemoryMalloc(len);
97,367✔
768
  if(bufBegin == NULL) {
97,367✔
769
    fnError("udfdProcessSetupRequest: malloc failed. len %d", len);
×
770
    return;
×
771
  }
772
  void *buf = bufBegin;
97,367✔
773
  if(encodeUdfResponse(&buf, &rsp) < 0) {
97,367✔
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);
97,367✔
780

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

785
static int32_t checkUDFScalaResult(SSDataBlock *block, SUdfColumn *output) {
1,673,898✔
786
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_NEVER) {
1,673,898✔
787
    return TSDB_CODE_SUCCESS;
×
788
  }
789
  if (output->colData.numOfRows != block->info.rows) {
1,673,898✔
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,673,898✔
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,673,898✔
813
}
814

815
static int32_t checkUDFAggResult(SSDataBlock *block, SUdfInterBuf *output) {
294,010✔
816
  if (tsSafetyCheckLevel == TSDB_SAFETY_CHECK_LEVELL_NEVER) {
294,010✔
817
    return TSDB_CODE_SUCCESS;
×
818
  }
819
  if (output->numOfResult != 1 && output->numOfResult != 0) {
294,010✔
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);
294,010✔
824
  TAOS_UDF_CHECK_CONDITION(output->bufLen > 0, TSDB_CODE_UDF_FUNC_EXEC_FAILURE);
294,010✔
825
  return TSDB_CODE_SUCCESS;
294,010✔
826
}
827

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

839
  int32_t code = TSDB_CODE_SUCCESS;
2,195,948✔
840
  switch (call->callType) {
2,195,948✔
841
    case TSDB_UDF_CALL_SCALA_PROC: {
1,675,834✔
842
      SUdfColumn output = {0};
1,675,834✔
843
      output.colMeta.bytes = udf->outputLen;
1,675,834✔
844
      output.colMeta.type = udf->outputType;
1,675,834✔
845
      output.colMeta.precision = 0;
1,675,834✔
846
      output.colMeta.scale = 0;
1,675,834✔
847
      if (udfColEnsureCapacity(&output, call->block.info.rows) == TSDB_CODE_SUCCESS) {
3,351,668✔
848
        SUdfDataBlock input = {0};
1,675,948✔
849
        code = convertDataBlockToUdfDataBlock(&call->block, &input);
1,675,948✔
850
        if (code == TSDB_CODE_SUCCESS) code = udf->scriptPlugin->udfScalarProcFunc(&input, &output, udf->scriptUdfCtx);
1,674,808✔
851
        freeUdfDataDataBlock(&input);
1,674,808✔
852
        if (code == TSDB_CODE_SUCCESS) code = checkUDFScalaResult(&call->block, &output);
1,675,549✔
853
        if (code == TSDB_CODE_SUCCESS) code = convertUdfColumnToDataBlock(&output, &response.callRsp.resultData);
1,674,631✔
854
      }
855
      freeUdfColumn(&output);
1,675,492✔
856
      break;
1,676,005✔
857
    }
858
    case TSDB_UDF_CALL_AGG_INIT: {
113,660✔
859
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
113,660✔
860
      if (outBuf.buf != NULL) {
113,660✔
861
        code = udf->scriptPlugin->udfAggStartFunc(&outBuf, udf->scriptUdfCtx);
113,660✔
862
      } else {
863
        code = terrno;
×
864
      }
865
      subRsp->resultBuf = outBuf;
113,660✔
866
      break;
113,660✔
867
    }
868
    case TSDB_UDF_CALL_AGG_PROC: {
294,010✔
869
      SUdfDataBlock input = {0};
294,010✔
870
      if (convertDataBlockToUdfDataBlock(&call->block, &input) == TSDB_CODE_SUCCESS) {
294,010✔
871
        SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
294,010✔
872
        if (outBuf.buf != NULL) {
294,010✔
873
          code = udf->scriptPlugin->udfAggProcFunc(&input, &call->interBuf, &outBuf, udf->scriptUdfCtx);
294,010✔
874
          freeUdfInterBuf(&call->interBuf);
294,010✔
875
          if (code == TSDB_CODE_SUCCESS) code = checkUDFAggResult(&call->block, &outBuf);
294,010✔
876
          subRsp->resultBuf = outBuf;
294,010✔
877
        } else {
878
          code = terrno;
×
879
        }
880
      }
881
      freeUdfDataDataBlock(&input);
294,010✔
882

883
      break;
294,010✔
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: {
112,444✔
899
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
112,444✔
900
      if (outBuf.buf != NULL) {
112,444✔
901
        code = udf->scriptPlugin->udfAggFinishFunc(&call->interBuf, &outBuf, udf->scriptUdfCtx);
112,444✔
902
        freeUdfInterBuf(&call->interBuf);
112,444✔
903
        subRsp->resultBuf = outBuf;
112,444✔
904
      } else {
905
        code = terrno;
×
906
      }
907

908
      break;
112,444✔
909
    }
910
    default:
×
911
      break;
×
912
  }
913

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

919
  int32_t len = encodeUdfResponse(NULL, rsp);
2,196,119✔
920
  if(len < 0) {
2,194,114✔
921
    fnError("udfdProcessCallRequest: encode udf response failed. len %d", len);
×
922
    goto _exit;
×
923
  }
924
  rsp->msgLen = len;
2,194,114✔
925
  void *bufBegin = taosMemoryMalloc(len);
2,194,114✔
926
  if (bufBegin == NULL) {
2,195,482✔
927
    fnError("udfdProcessCallRequest: malloc failed. len %d", len);
×
928
    goto _exit;
×
929
  }
930
  void *buf = bufBegin;
2,195,482✔
931
  if(encodeUdfResponse(&buf, rsp) < 0) {
2,195,482✔
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,194,523✔
938

939
_exit:
2,195,606✔
940
  switch (call->callType) {
2,195,606✔
941
    case TSDB_UDF_CALL_SCALA_PROC: {
1,675,492✔
942
      blockDataFreeRes(&call->block);
1,675,492✔
943
      blockDataFreeRes(&subRsp->resultData);
1,675,195✔
944
      break;
1,676,002✔
945
    }
946
    case TSDB_UDF_CALL_AGG_INIT: {
113,660✔
947
      freeUdfInterBuf(&subRsp->resultBuf);
113,660✔
948
      break;
113,660✔
949
    }
950
    case TSDB_UDF_CALL_AGG_PROC: {
294,010✔
951
      blockDataFreeRes(&call->block);
294,010✔
952
      freeUdfInterBuf(&subRsp->resultBuf);
294,010✔
953
      break;
293,950✔
954
    }
955
    // case TSDB_UDF_CALL_AGG_MERGE: {
956
    //   freeUdfInterBuf(&subRsp->resultBuf);
957
    //   break;
958
    // }
959
    case TSDB_UDF_CALL_AGG_FIN: {
112,444✔
960
      freeUdfInterBuf(&subRsp->resultBuf);
112,444✔
961
      break;
112,444✔
962
    }
963
    default:
×
964
      break;
×
965
  }
966

967
  taosMemoryFreeClear(uvUdf->input.base);
2,196,056✔
968
  return;
2,196,287✔
969
}
970

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

980
  uv_mutex_lock(&global.udfsMutex);
93,139✔
981
  udf->refCount--;
93,139✔
982
  if (udf->refCount == 0 && (!udf->resident || udf->expired)) {
93,139✔
983
    unloadUdf = true;
48,456✔
984
    code = taosHashRemove(global.udfsHash, udf->name, strlen(udf->name));
48,456✔
985
    if (code != 0) {
48,456✔
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);
93,139✔
992
  if (unloadUdf) {
93,139✔
993
    fnInfo("udf teardown. udf name: %s type %d: context %p", udf->name, udf->scriptType, (void *)(udf->scriptUdfCtx));
48,456✔
994
    uv_cond_destroy(&udf->condReady);
48,456✔
995
    uv_mutex_destroy(&udf->lock);
48,456✔
996
    code = udf->scriptPlugin->udfDestroyFunc(udf->scriptUdfCtx);
48,456✔
997
    fnDebug("udfd destroy function returns %d", code);
48,456✔
998
    taosMemoryFree(udf);
48,456✔
999
  }
1000

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

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

1031
void udfdGetFuncBodyPath(const SUdf *udf, char *path) {
53,148✔
1032
  TAOS_UDF_CHECK_PTR_RVOID(udf, path);
159,444✔
1033
  if (udf->scriptType == TSDB_FUNC_SCRIPT_BIN_LIB) {
53,148✔
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,
43,068✔
1038
             udf->createdTime);
43,068✔
1039
#endif
1040
  } else if (udf->scriptType == TSDB_FUNC_SCRIPT_PYTHON) {
10,080✔
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);
10,080✔
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) {
53,148✔
1056
  TAOS_UDF_CHECK_PTR_RCODE(pFuncInfo, udf);
159,444✔
1057
  if (!osDataSpaceAvailable()) {
53,148✔
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};
53,148✔
1064
  udfdGetFuncBodyPath(udf, path);
53,148✔
1065
  bool fileExist = !(taosStatFile(path, NULL, NULL, NULL) < 0);
53,148✔
1066
  if (fileExist) {
53,148✔
1067
    tstrncpy(udf->path, path, PATH_MAX);
47,226✔
1068
    fnInfo("udfd func body file. reuse existing file %s", path);
47,226✔
1069
    return TSDB_CODE_SUCCESS;
47,226✔
1070
  }
1071

1072
  TdFilePtr file = taosOpenFile(path, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_READ | TD_FILE_TRUNC);
5,922✔
1073
  if (file == NULL) {
5,922✔
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);
5,922✔
1078
  if (count != pFuncInfo->codeSize) {
5,922✔
1079
    fnError("udfd write udf shared library failed");
×
1080
    return TSDB_CODE_FILE_CORRUPTED;
×
1081
  }
1082
  if(taosCloseFile(&file) != 0) {
5,922✔
1083
    fnError("udfdSaveFuncBodyToFile, udfd close file failed");
×
1084
    return TSDB_CODE_FILE_CORRUPTED;
×
1085
  }
1086

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

1091
void udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet) {
53,148✔
1092
  TAOS_UDF_CHECK_PTR_RVOID(parent, pMsg);
159,444✔
1093
  SUdfdRpcSendRecvInfo *msgInfo = (SUdfdRpcSendRecvInfo *)pMsg->info.ahandle;
53,148✔
1094

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

1101
  if (pMsg->code != TSDB_CODE_SUCCESS) {
53,148✔
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) {
53,148✔
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) {
53,148✔
1131
    SRetrieveFuncRsp retrieveRsp = {0};
53,148✔
1132
    if(tDeserializeSRetrieveFuncRsp(pMsg->pCont, pMsg->contLen, &retrieveRsp) < 0){
53,148✔
1133
      fnError("udfd deserialize retrieve func response failed");
×
1134
      goto _return;
×
1135
    }
1136

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

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

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

1163
int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf) {
53,148✔
1164
  TAOS_UDF_CHECK_PTR_RCODE(clientRpc, udfName, udf);
212,592✔
1165
  SRetrieveFuncReq retrieveReq = {0};
53,148✔
1166
  retrieveReq.numOfFuncs = 1;
53,148✔
1167
  retrieveReq.pFuncNames = taosArrayInit(1, TSDB_FUNC_NAME_LEN);
53,148✔
1168
  if(taosArrayPush(retrieveReq.pFuncNames, udfName) == NULL) {
106,296✔
1169
    taosArrayDestroy(retrieveReq.pFuncNames);
×
1170
    return terrno;
×
1171
  }
1172

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

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

1197
  SRpcMsg rpcMsg = {0};
53,148✔
1198
  rpcMsg.pCont = pReq;
53,148✔
1199
  rpcMsg.contLen = contLen;
53,148✔
1200
  rpcMsg.msgType = TDMT_MND_RETRIEVE_FUNC;
53,148✔
1201
  rpcMsg.info.ahandle = msgInfo;
53,148✔
1202
  int32_t code = rpcSendRequest(clientRpc, &global.mgmtEp.epSet, &rpcMsg, NULL);
53,148✔
1203
  if (code == 0) {
53,148✔
1204
    uv_sem_wait(&msgInfo->resultSem);
53,148✔
1205
    uv_sem_destroy(&msgInfo->resultSem);
53,148✔
1206
    code = msgInfo->code;
53,148✔
1207
  }
1208
  taosMemoryFree(msgInfo);
53,148✔
1209
  return code;
53,148✔
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) {
568,613✔
1227
  pEpSet->version = 0;
568,613✔
1228

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

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

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

1246
    mgmtEpSet->numOfEps++;
568,613✔
1247
  }
1248

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

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

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

1268
  return 0;
568,613✔
1269
}
1270

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

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

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

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

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

1313
void udfdOnWrite(uv_write_t *req, int status) {
2,386,853✔
1314
  TAOS_UDF_CHECK_PTR_RVOID(req);
4,773,706✔
1315
  SUvUdfWork *work = (SUvUdfWork *)req->data;
2,386,853✔
1316
  if (status < 0) {
2,386,853✔
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) {
2,386,853✔
1321
    SUvUdfWork **ppWork;
1322
    for (ppWork = &work->conn->pWorkList; *ppWork && (*ppWork != work); ppWork = &((*ppWork)->pWorkNext)) {
4,745,617✔
1323
    }
1324
    if (*ppWork == work) {
2,386,853✔
1325
      *ppWork = work->pWorkNext;
2,386,853✔
1326
    } else {
1327
      fnError("work not in conn any more");
×
1328
    }
1329
  }
1330
  taosMemoryFree(work->output.base);
2,386,853✔
1331
  taosMemoryFree(work);
2,386,853✔
1332
  taosMemoryFree(req);
2,386,853✔
1333
}
1334

1335
void udfdSendResponse(uv_work_t *work, int status) {
2,386,853✔
1336
  TAOS_UDF_CHECK_PTR_RVOID(work);
4,773,706✔
1337
  SUvUdfWork *udfWork = (SUvUdfWork *)(work->data);
2,386,853✔
1338

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

1356
void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
6,942,102✔
1357
  TAOS_UDF_CHECK_PTR_RVOID(handle, buf);
20,826,306✔
1358
  SUdfdUvConn *ctx = handle->data;
6,942,102✔
1359
  int32_t      msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
6,942,102✔
1360
  if (ctx->inputCap == 0) {
6,942,102✔
1361
    ctx->inputBuf = taosMemoryMalloc(msgHeadSize);
2,484,220✔
1362
    if (ctx->inputBuf) {
2,484,220✔
1363
      ctx->inputLen = 0;
2,484,220✔
1364
      ctx->inputCap = msgHeadSize;
2,484,220✔
1365
      ctx->inputTotal = -1;
2,484,220✔
1366

1367
      buf->base = ctx->inputBuf;
2,484,220✔
1368
      buf->len = ctx->inputCap;
2,484,220✔
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) {
4,457,882✔
1374
    buf->base = ctx->inputBuf + ctx->inputLen;
2,068,869✔
1375
    buf->len = msgHeadSize - ctx->inputLen;
2,068,869✔
1376
  } else {
1377
    ctx->inputCap = ctx->inputTotal > ctx->inputCap ? ctx->inputTotal : ctx->inputCap;
2,389,013✔
1378
    void *inputBuf = taosMemoryRealloc(ctx->inputBuf, ctx->inputCap);
2,389,013✔
1379
    if (inputBuf) {
2,389,013✔
1380
      ctx->inputBuf = inputBuf;
2,389,013✔
1381
      buf->base = ctx->inputBuf + ctx->inputLen;
2,389,013✔
1382
      buf->len = ctx->inputCap - ctx->inputLen;
2,389,013✔
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) {
4,775,866✔
1391
  if (pipe == NULL) {
4,775,866✔
1392
    fnError("udfd pipe is NULL, LINE:%d", __LINE__);
×
1393
    return false;
×
1394
  }
1395
  if (pipe->inputTotal == -1 && pipe->inputLen >= sizeof(int32_t)) {
4,775,866✔
1396
    pipe->inputTotal = *(int32_t *)(pipe->inputBuf);
2,386,853✔
1397
  }
1398
  if (pipe->inputLen == pipe->inputCap && pipe->inputTotal == pipe->inputCap) {
4,775,866✔
1399
    fnDebug("receive request complete. length %d", pipe->inputLen);
2,386,853✔
1400
    return true;
2,386,853✔
1401
  }
1402
  return false;
2,389,013✔
1403
}
1404

1405
void udfdHandleRequest(SUdfdUvConn *conn) {
2,386,853✔
1406
  TAOS_UDF_CHECK_PTR_RVOID(conn);
4,773,706✔
1407
  char   *inputBuf = conn->inputBuf;
2,386,853✔
1408
  int32_t inputLen = conn->inputLen;
2,386,853✔
1409

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

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

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

1452
void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
6,942,102✔
1453
  TAOS_UDF_CHECK_PTR_RVOID(client, buf);
20,826,306✔
1454
  fnDebug("udfd read %zd bytes from client", nread);
6,942,102✔
1455
  if (nread == 0) return;
6,942,102✔
1456

1457
  SUdfdUvConn *conn = client->data;
4,873,233✔
1458

1459
  if (nread > 0) {
4,873,233✔
1460
    conn->inputLen += nread;
4,775,866✔
1461
    if (isUdfdUvMsgComplete(conn)) {
4,775,866✔
1462
      udfdHandleRequest(conn);
2,386,853✔
1463
    } else {
1464
      // log error or continue;
1465
    }
1466
    return;
4,775,866✔
1467
  }
1468

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

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

1487
  uv_pipe_t *client = (uv_pipe_t *)taosMemoryMalloc(sizeof(uv_pipe_t));
97,367✔
1488
  if(client == NULL) {
97,367✔
1489
    fnError("udfd pipe malloc failed");
×
1490
    return;
×
1491
  }
1492
  code = uv_pipe_init(global.loop, client, 0);
97,367✔
1493
  if (code) {
97,367✔
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) {
97,367✔
1499
    SUdfdUvConn *ctx = taosMemoryMalloc(sizeof(SUdfdUvConn));
97,367✔
1500
    if(ctx == NULL) {
97,367✔
1501
      fnError("udfd conn malloc failed");
×
1502
      goto _exit;
×
1503
    }
1504
    ctx->pWorkList = NULL;
97,367✔
1505
    ctx->client = (uv_stream_t *)client;
97,367✔
1506
    ctx->inputBuf = 0;
97,367✔
1507
    ctx->inputLen = 0;
97,367✔
1508
    ctx->inputCap = 0;
97,367✔
1509
    client->data = ctx;
97,367✔
1510
    ctx->client = (uv_stream_t *)client;
97,367✔
1511
    code = uv_read_start((uv_stream_t *)client, udfdAllocBuffer, udfdPipeRead);
97,367✔
1512
    if (code) {
97,367✔
1513
      fnError("udfd read start error %s", uv_strerror(code));
×
1514
      udfdUvHandleError(ctx);
×
1515
      taosMemoryFree(ctx);
×
1516
      taosMemoryFree(client);
×
1517
    }
1518
    return;
97,367✔
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[]) {
568,805✔
1541
  for (int32_t i = 1; i < argc; ++i) {
1,137,482✔
1542
    if (strcmp(argv[i], "-c") == 0) {
568,805✔
1543
      if (i < argc - 1) {
568,741✔
1544
        if (strlen(argv[++i]) >= PATH_MAX) {
568,677✔
1545
          (void)printf("config file path overflow");
64✔
1546
          return -1;
64✔
1547
        }
1548
        tstrncpy(configDir, argv[i], PATH_MAX);
568,613✔
1549
      } else {
1550
        (void)printf("'-c' requires a parameter, default is %s\n", configDir);
64✔
1551
        return -1;
64✔
1552
      }
1553
    } else if (strcmp(argv[i], "-V") == 0) {
64✔
1554
      global.printVersion = true;
64✔
1555
    } else {
1556
    }
1557
  }
1558

1559
  return 0;
568,677✔
1560
}
1561

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

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

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

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

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

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

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

1616
  removeListeningPipe();
568,613✔
1617

1618
  TAOS_CHECK_RETURN(uv_pipe_init(global.loop, &global.listeningPipe, 0));
568,613✔
1619

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

1623
  int r;
1624
  fnInfo("bind to pipe %s", global.listenPipeName);
568,613✔
1625
  if ((r = uv_pipe_bind(&global.listeningPipe, global.listenPipeName))) {
568,613✔
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))) {
568,613✔
1631
    fnError("Listen error %s", uv_err_name(r));
×
1632
    removeListeningPipe();
×
1633
    return -3;
×
1634
  }
1635
  return 0;
568,613✔
1636
}
1637

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

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

1652
  if (uv_mutex_init(&global.scriptPluginsMutex) != 0) {
568,613✔
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);
568,613✔
1658
  if (global.udfsHash == NULL) {
568,613✔
1659
    return terrno;
×
1660
  }
1661
  // taosHashSetFreeFp(global.udfsHash, udfdFreeUdf);
1662

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

1668
  return 0;
568,613✔
1669
}
1670

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

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

1686
  (void)uv_loop_close(global.loop);
568,613✔
1687

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

1696
int32_t udfdInitResidentFuncs() {
568,613✔
1697
  if (strlen(tsUdfdResFuncs) == 0) {
568,613✔
1698
    return TSDB_CODE_SUCCESS;
567,041✔
1699
  }
1700

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

1715
  return TSDB_CODE_SUCCESS;
1,572✔
1716
}
1717

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

1741
int32_t udfdCreateUdfSourceDir() {
568,613✔
1742
  snprintf(global.udfDataDir, PATH_MAX, "%s/.udf", tsDataDir);
568,613✔
1743
  int32_t code = taosMkDir(global.udfDataDir);
568,613✔
1744
  if (code != TSDB_CODE_SUCCESS) {
568,613✔
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));
568,613✔
1749

1750
  return code;
568,613✔
1751
}
1752

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

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

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

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

1777
  if (global.printVersion) {
568,677✔
1778
    udfdPrintVersion();
64✔
1779
    return 0;
64✔
1780
  }
1781

1782
  if (udfdInitLog() != 0) {
568,613✔
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
568,613✔
1787
  }
1788

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

1797
  if (initEpSetFromCfg(tsFirst, tsSecond, &global.mgmtEp) != 0) {
568,613✔
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);
568,613✔
1803
  if (udfdOpenClientRpc() != 0) {
568,613✔
1804
    fnError("open rpc connection to mnode failed");
×
1805
    code = -4;
×
1806
    goto _exit;
×
1807
  }
1808
  fnInfo("udfd rpc client is opened");
568,613✔
1809
  openClientRpcFinished = true;  // rpc is opened
568,613✔
1810

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

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

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

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

1842
  udfdRun();
568,613✔
1843
  fnInfo("udfd exit normally");
568,613✔
1844

1845
  removeListeningPipe();
568,613✔
1846

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

1868
  return code;
568,613✔
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