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

taosdata / TDengine / #4873

04 Dec 2025 01:55AM UTC coverage: 64.558% (-0.1%) from 64.678%
#4873

push

travis-ci

guanshengliang
Merge branch '3.0' into cover/3.0

719 of 2219 new or added lines in 36 files covered. (32.4%)

6363 existing lines in 135 files now uncovered.

159381 of 246882 relevant lines covered (64.56%)

108937395.15 hits per line

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

76.04
/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,918✔
54

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

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

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

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

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

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

87
  return 0;
50,739✔
88
}
89

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

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

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

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

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

156
int32_t udfdCPluginUdfScalarProc(SUdfDataBlock *block, SUdfColumn *resultCol, void *udfCtx) {
5,312,570✔
157
  TAOS_UDF_CHECK_PTR_RCODE(block, resultCol, udfCtx);
21,250,504✔
158
  SUdfCPluginCtx *ctx = udfCtx;
5,312,570✔
159
  if (ctx->scalarProcFunc) {
5,312,570✔
160
    return ctx->scalarProcFunc(block, resultCol);
5,313,405✔
161
  } else {
UNCOV
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) {
289,497✔
168
  TAOS_UDF_CHECK_PTR_RCODE(buf, udfCtx);
868,491✔
169
  SUdfCPluginCtx *ctx = udfCtx;
289,497✔
170
  if (ctx->aggStartFunc) {
289,497✔
171
    return ctx->aggStartFunc(buf);
288,354✔
172
  } else {
173
    fnError("udfd c plugin aggregation start not implemented");
1,143✔
174
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
1,143✔
175
  }
176
  return 0;
177
}
178

179
int32_t udfdCPluginUdfAggProc(SUdfDataBlock *block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf, void *udfCtx) {
671,940✔
180
  TAOS_UDF_CHECK_PTR_RCODE(block, interBuf, newInterBuf, udfCtx);
3,359,700✔
181
  SUdfCPluginCtx *ctx = udfCtx;
671,940✔
182
  if (ctx->aggProcFunc) {
671,940✔
183
    return ctx->aggProcFunc(block, interBuf, newInterBuf);
671,940✔
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) {
282,084✔
203
  TAOS_UDF_CHECK_PTR_RCODE(buf, resultData, udfCtx);
1,128,336✔
204
  SUdfCPluginCtx *ctx = udfCtx;
282,084✔
205
  if (ctx->aggFinishFunc) {
282,084✔
206
    return ctx->aggFinishFunc(buf, resultData);
282,084✔
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); }
281,018✔
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,918✔
365
  TAOS_UDF_CHECK_PTR_RCODE(plugin);
5,836✔
366
  plugin->scriptType = TSDB_FUNC_SCRIPT_BIN_LIB;
2,918✔
367
  plugin->openFunc = udfdCPluginOpen;
2,918✔
368
  plugin->closeFunc = udfdCPluginClose;
2,918✔
369
  plugin->udfInitFunc = udfdCPluginUdfInit;
2,918✔
370
  plugin->udfDestroyFunc = udfdCPluginUdfDestroy;
2,918✔
371
  plugin->udfScalarProcFunc = udfdCPluginUdfScalarProc;
2,918✔
372
  plugin->udfAggStartFunc = udfdCPluginUdfAggStart;
2,918✔
373
  plugin->udfAggProcFunc = udfdCPluginUdfAggProc;
2,918✔
374
  // plugin->udfAggMergeFunc = udfdCPluginUdfAggMerge;
375
  plugin->udfAggFinishFunc = udfdCPluginUdfAggFinish;
2,918✔
376

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

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

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

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

443
  return 0;
325✔
444
}
445

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

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

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

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

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

539
void udfdProcessRequest(uv_work_t *req) {
7,444,121✔
540
  TAOS_UDF_CHECK_PTR_RVOID(req);
14,888,242✔
541
  SUvUdfWork *uvUdf = (SUvUdfWork *)(req->data);
7,444,121✔
542
  if (uvUdf == NULL) {
7,444,121✔
543
    fnError("udf work is NULL");
×
544
    return;
×
545
  }
546
  SUdfRequest request = {0};
7,444,121✔
547
  if(decodeUdfRequest(uvUdf->input.base, &request) == NULL)
7,444,121✔
548
  {
549
    taosMemoryFreeClear(uvUdf->input.base);
60✔
550
    fnError("udf request decode failed");
60✔
551
    return;
×
552
  }
553

554
  switch (request.type) {
7,442,593✔
555
    case UDF_TASK_SETUP: {
281,018✔
556
      udfdProcessSetupRequest(uvUdf, &request);
281,018✔
557
      break;
280,958✔
558
    }
559

560
    case UDF_TASK_CALL: {
6,895,655✔
561
      udfdProcessCallRequest(uvUdf, &request);
6,895,655✔
562
      break;
6,896,681✔
563
    }
564
    case UDF_TASK_TEARDOWN: {
265,920✔
565
      udfdProcessTeardownRequest(uvUdf, &request);
265,920✔
566
      break;
265,920✔
567
    }
568
    default: {
×
569
      break;
×
570
    }
571
  }
572
}
573

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

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

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

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

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

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

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

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

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

709
  return 0;
148,155✔
710
}
711

712
void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
281,018✔
713
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
843,054✔
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);
281,018✔
716

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

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

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

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

781
  taosMemoryFreeClear(uvUdf->input.base);
281,018✔
782
  return;
280,958✔
783
}
784

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

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

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

839
  int32_t code = TSDB_CODE_SUCCESS;
6,896,468✔
840
  switch (call->callType) {
6,896,468✔
841
    case TSDB_UDF_CALL_SCALA_PROC: {
5,440,722✔
842
      SUdfColumn output = {0};
5,440,722✔
843
      output.colMeta.bytes = udf->outputLen;
5,440,722✔
844
      output.colMeta.type = udf->outputType;
5,440,722✔
845
      output.colMeta.precision = 0;
5,440,722✔
846
      output.colMeta.scale = 0;
5,440,722✔
847
      if (udfColEnsureCapacity(&output, call->block.info.rows) == TSDB_CODE_SUCCESS) {
10,881,444✔
848
        SUdfDataBlock input = {0};
5,440,089✔
849
        code = convertDataBlockToUdfDataBlock(&call->block, &input);
5,440,089✔
850
        if (code == TSDB_CODE_SUCCESS) code = udf->scriptPlugin->udfScalarProcFunc(&input, &output, udf->scriptUdfCtx);
5,437,052✔
851
        freeUdfDataDataBlock(&input);
5,436,804✔
852
        if (code == TSDB_CODE_SUCCESS) code = checkUDFScalaResult(&call->block, &output);
5,440,422✔
853
        if (code == TSDB_CODE_SUCCESS) code = convertUdfColumnToDataBlock(&output, &response.callRsp.resultData);
5,434,397✔
854
      }
855
      freeUdfColumn(&output);
5,440,422✔
856
      break;
5,440,984✔
857
    }
858
    case TSDB_UDF_CALL_AGG_INIT: {
303,472✔
859
      SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
303,472✔
860
      if (outBuf.buf != NULL) {
303,472✔
861
        code = udf->scriptPlugin->udfAggStartFunc(&outBuf, udf->scriptUdfCtx);
303,472✔
862
      } else {
863
        code = terrno;
×
864
      }
865
      subRsp->resultBuf = outBuf;
303,472✔
866
      break;
303,472✔
867
    }
868
    case TSDB_UDF_CALL_AGG_PROC: {
856,215✔
869
      SUdfDataBlock input = {0};
856,215✔
870
      if (convertDataBlockToUdfDataBlock(&call->block, &input) == TSDB_CODE_SUCCESS) {
856,215✔
871
        SUdfInterBuf outBuf = {.buf = taosMemoryMalloc(udf->bufSize), .bufLen = udf->bufSize, .numOfResult = 0};
856,215✔
872
        if (outBuf.buf != NULL) {
856,215✔
873
          code = udf->scriptPlugin->udfAggProcFunc(&input, &call->interBuf, &outBuf, udf->scriptUdfCtx);
856,215✔
874
          freeUdfInterBuf(&call->interBuf);
856,215✔
875
          if (code == TSDB_CODE_SUCCESS) code = checkUDFAggResult(&call->block, &outBuf);
856,215✔
876
          subRsp->resultBuf = outBuf;
856,215✔
877
        } else {
878
          code = terrno;
×
879
        }
880
      }
881
      freeUdfDataDataBlock(&input);
856,215✔
882

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

908
      break;
296,059✔
909
    }
910
    default:
×
911
      break;
×
912
  }
913

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

919
  int32_t len = encodeUdfResponse(NULL, rsp);
6,896,730✔
920
  if(len < 0) {
6,885,521✔
921
    fnError("udfdProcessCallRequest: encode udf response failed. len %d", len);
×
922
    goto _exit;
×
923
  }
924
  rsp->msgLen = len;
6,885,521✔
925
  void *bufBegin = taosMemoryMalloc(len);
6,885,521✔
926
  if (bufBegin == NULL) {
6,894,880✔
927
    fnError("udfdProcessCallRequest: malloc failed. len %d", len);
×
928
    goto _exit;
×
929
  }
930
  void *buf = bufBegin;
6,894,880✔
931
  if(encodeUdfResponse(&buf, rsp) < 0) {
6,894,880✔
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);
6,888,457✔
938

939
_exit:
6,895,044✔
940
  switch (call->callType) {
6,895,044✔
941
    case TSDB_UDF_CALL_SCALA_PROC: {
5,439,298✔
942
      blockDataFreeRes(&call->block);
5,439,298✔
943
      blockDataFreeRes(&subRsp->resultData);
5,437,606✔
944
      break;
5,441,033✔
945
    }
946
    case TSDB_UDF_CALL_AGG_INIT: {
303,472✔
947
      freeUdfInterBuf(&subRsp->resultBuf);
303,472✔
948
      break;
303,472✔
949
    }
950
    case TSDB_UDF_CALL_AGG_PROC: {
856,215✔
951
      blockDataFreeRes(&call->block);
856,215✔
952
      freeUdfInterBuf(&subRsp->resultBuf);
856,215✔
953
      break;
856,144✔
954
    }
955
    // case TSDB_UDF_CALL_AGG_MERGE: {
956
    //   freeUdfInterBuf(&subRsp->resultBuf);
957
    //   break;
958
    // }
959
    case TSDB_UDF_CALL_AGG_FIN: {
296,059✔
960
      freeUdfInterBuf(&subRsp->resultBuf);
296,059✔
961
      break;
296,059✔
962
    }
963
    default:
×
964
      break;
×
965
  }
966

967
  taosMemoryFreeClear(uvUdf->input.base);
6,896,708✔
968
  return;
6,896,932✔
969
}
970

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

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

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

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

1031
void udfdGetFuncBodyPath(const SUdf *udf, char *path) {
151,759✔
1032
  TAOS_UDF_CHECK_PTR_RVOID(udf, path);
455,277✔
1033
  if (udf->scriptType == TSDB_FUNC_SCRIPT_BIN_LIB) {
151,759✔
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,
113,529✔
1038
             udf->createdTime);
113,529✔
1039
#endif
1040
  } else if (udf->scriptType == TSDB_FUNC_SCRIPT_PYTHON) {
38,230✔
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);
38,230✔
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) {
151,759✔
1056
  TAOS_UDF_CHECK_PTR_RCODE(pFuncInfo, udf);
455,277✔
1057
  if (!osDataSpaceAvailable()) {
151,759✔
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};
151,759✔
1064
  udfdGetFuncBodyPath(udf, path);
151,759✔
1065
  bool fileExist = !(taosStatFile(path, NULL, NULL, NULL) < 0);
151,759✔
1066
  if (fileExist) {
151,759✔
1067
    tstrncpy(udf->path, path, PATH_MAX);
128,071✔
1068
    fnInfo("udfd func body file. reuse existing file %s", path);
128,071✔
1069
    return TSDB_CODE_SUCCESS;
128,071✔
1070
  }
1071

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

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

1091
void udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet) {
151,759✔
1092
  TAOS_UDF_CHECK_PTR_RVOID(parent, pMsg);
455,277✔
1093
  SUdfdRpcSendRecvInfo *msgInfo = (SUdfdRpcSendRecvInfo *)pMsg->info.ahandle;
151,759✔
1094

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

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

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

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

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

1163
int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf) {
151,759✔
1164
  TAOS_UDF_CHECK_PTR_RCODE(clientRpc, udfName, udf);
607,036✔
1165
  SRetrieveFuncReq retrieveReq = {0};
151,759✔
1166
  retrieveReq.numOfFuncs = 1;
151,759✔
1167
  retrieveReq.pFuncNames = taosArrayInit(1, TSDB_FUNC_NAME_LEN);
151,759✔
1168
  if(taosArrayPush(retrieveReq.pFuncNames, udfName) == NULL) {
303,518✔
1169
    taosArrayDestroy(retrieveReq.pFuncNames);
×
1170
    return terrno;
×
1171
  }
1172

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

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

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

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

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

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

1246
    mgmtEpSet->numOfEps++;
735,757✔
1247
  }
1248

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

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

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

1268
  return 0;
735,757✔
1269
}
1270

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

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

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

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

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

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

1334
void udfdSendResponse(uv_work_t *work, int status) {
7,444,301✔
1335
  TAOS_UDF_CHECK_PTR_RVOID(work);
14,888,602✔
1336
  SUvUdfWork *udfWork = (SUvUdfWork *)(work->data);
7,444,301✔
1337

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

1355
void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
21,867,703✔
1356
  TAOS_UDF_CHECK_PTR_RVOID(handle, buf);
65,603,109✔
1357
  SUdfdUvConn *ctx = handle->data;
21,867,703✔
1358
  int32_t      msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
21,867,703✔
1359
  if (ctx->inputCap == 0) {
21,867,703✔
1360
    ctx->inputBuf = taosMemoryMalloc(msgHeadSize);
7,725,319✔
1361
    if (ctx->inputBuf) {
7,725,319✔
1362
      ctx->inputLen = 0;
7,725,319✔
1363
      ctx->inputCap = msgHeadSize;
7,725,319✔
1364
      ctx->inputTotal = -1;
7,725,319✔
1365

1366
      buf->base = ctx->inputBuf;
7,725,319✔
1367
      buf->len = ctx->inputCap;
7,725,319✔
1368
    } else {
1369
      fnError("udfd can not allocate enough memory") buf->base = NULL;
×
1370
      buf->len = 0;
×
1371
    }
1372
  } else if (ctx->inputTotal == -1 && ctx->inputLen < msgHeadSize) {
14,142,384✔
1373
    buf->base = ctx->inputBuf + ctx->inputLen;
6,692,293✔
1374
    buf->len = msgHeadSize - ctx->inputLen;
6,692,293✔
1375
  } else {
1376
    ctx->inputCap = ctx->inputTotal > ctx->inputCap ? ctx->inputTotal : ctx->inputCap;
7,450,091✔
1377
    void *inputBuf = taosMemoryRealloc(ctx->inputBuf, ctx->inputCap);
7,450,091✔
1378
    if (inputBuf) {
7,450,091✔
1379
      ctx->inputBuf = inputBuf;
7,450,091✔
1380
      buf->base = ctx->inputBuf + ctx->inputLen;
7,450,091✔
1381
      buf->len = ctx->inputCap - ctx->inputLen;
7,450,091✔
1382
    } else {
1383
      fnError("udfd can not allocate enough memory") buf->base = NULL;
×
1384
      buf->len = 0;
×
1385
    }
1386
  }
1387
}
1388

1389
bool isUdfdUvMsgComplete(SUdfdUvConn *pipe) {
14,894,392✔
1390
  if (pipe == NULL) {
14,894,392✔
1391
    fnError("udfd pipe is NULL, LINE:%d", __LINE__);
×
1392
    return false;
×
1393
  }
1394
  if (pipe->inputTotal == -1 && pipe->inputLen >= sizeof(int32_t)) {
14,894,392✔
1395
    pipe->inputTotal = *(int32_t *)(pipe->inputBuf);
7,444,301✔
1396
  }
1397
  if (pipe->inputLen == pipe->inputCap && pipe->inputTotal == pipe->inputCap) {
14,894,392✔
1398
    fnDebug("receive request complete. length %d", pipe->inputLen);
7,444,301✔
1399
    return true;
7,444,301✔
1400
  }
1401
  return false;
7,450,091✔
1402
}
1403

1404
void udfdHandleRequest(SUdfdUvConn *conn) {
7,444,301✔
1405
  TAOS_UDF_CHECK_PTR_RVOID(conn);
14,888,602✔
1406
  char   *inputBuf = conn->inputBuf;
7,444,301✔
1407
  int32_t inputLen = conn->inputLen;
7,444,301✔
1408

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

1437
void udfdPipeCloseCb(uv_handle_t *pipe) {
281,018✔
1438
  TAOS_UDF_CHECK_PTR_RVOID(pipe);
562,036✔
1439
  SUdfdUvConn *conn = pipe->data;
281,018✔
1440
  SUvUdfWork  *pWork = conn->pWorkList;
281,018✔
1441
  while (pWork != NULL) {
281,018✔
1442
    pWork->conn = NULL;
×
1443
    pWork = pWork->pWorkNext;
×
1444
  }
1445

1446
  taosMemoryFree(conn->client);
281,018✔
1447
  taosMemoryFree(conn->inputBuf);
281,018✔
1448
  taosMemoryFree(conn);
281,018✔
1449
}
1450

1451
void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
21,867,703✔
1452
  TAOS_UDF_CHECK_PTR_RVOID(client, buf);
65,603,109✔
1453
  fnDebug("udfd read %zd bytes from client", nread);
21,867,703✔
1454
  if (nread == 0) return;
21,867,703✔
1455

1456
  SUdfdUvConn *conn = client->data;
15,175,410✔
1457

1458
  if (nread > 0) {
15,175,410✔
1459
    conn->inputLen += nread;
14,894,392✔
1460
    if (isUdfdUvMsgComplete(conn)) {
14,894,392✔
1461
      udfdHandleRequest(conn);
7,444,301✔
1462
    } else {
1463
      // log error or continue;
1464
    }
1465
    return;
14,894,392✔
1466
  }
1467

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

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

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

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

1539
static int32_t udfdParseArgs(int32_t argc, char *argv[]) {
736,747✔
1540
  for (int32_t i = 1; i < argc; ++i) {
1,472,834✔
1541
    if (strcmp(argv[i], "-c") == 0) {
736,747✔
1542
      if (i < argc - 1) {
736,417✔
1543
        if (strlen(argv[++i]) >= PATH_MAX) {
736,087✔
1544
          (void)printf("config file path overflow");
330✔
1545
          return -1;
330✔
1546
        }
1547
        tstrncpy(configDir, argv[i], PATH_MAX);
735,757✔
1548
      } else {
1549
        (void)printf("'-c' requires a parameter, default is %s\n", configDir);
330✔
1550
        return -1;
330✔
1551
      }
1552
    } else if (strcmp(argv[i], "-V") == 0) {
330✔
1553
      global.printVersion = true;
330✔
1554
    } else {
1555
    }
1556
  }
1557

1558
  return 0;
736,087✔
1559
}
1560

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

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

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

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

1596
static void removeListeningPipe() {
1,471,514✔
1597
  uv_fs_t req;
1,404,090✔
1598
  int     err = uv_fs_unlink(global.loop, &req, global.listenPipeName, NULL);
1,471,514✔
1599
  uv_fs_req_cleanup(&req);
1,471,514✔
1600
  if(err) {
1,471,514✔
1601
    fnInfo("remove listening pipe %s : %s, lino:%d", global.listenPipeName, uv_strerror(err), __LINE__);
1,471,185✔
1602
  }
1603
}
1,471,514✔
1604

1605
static int32_t udfdUvInit() {
735,757✔
1606
  TAOS_CHECK_RETURN(uv_loop_init(global.loop));
735,757✔
1607

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

1615
  removeListeningPipe();
735,757✔
1616

1617
  TAOS_CHECK_RETURN(uv_pipe_init(global.loop, &global.listeningPipe, 0));
735,757✔
1618

1619
  TAOS_CHECK_RETURN(uv_signal_init(global.loop, &global.intrSignal));
735,757✔
1620
  TAOS_CHECK_RETURN(uv_signal_start(&global.intrSignal, udfdIntrSignalHandler, SIGINT));
735,757✔
1621

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

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

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

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

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

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

1667
  return 0;
735,757✔
1668
}
1669

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

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

1685
  (void)uv_loop_close(global.loop);
735,757✔
1686

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

1695
int32_t udfdInitResidentFuncs() {
735,757✔
1696
  if (strlen(tsUdfdResFuncs) == 0) {
735,757✔
1697
    return TSDB_CODE_SUCCESS;
733,438✔
1698
  }
1699

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

1714
  return TSDB_CODE_SUCCESS;
2,319✔
1715
}
1716

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

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

1749
  return code;
735,757✔
1750
}
1751

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

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

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

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

1776
  if (global.printVersion) {
736,087✔
1777
    udfdPrintVersion();
330✔
1778
    return 0;
330✔
1779
  }
1780

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

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

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

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

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

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

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

1841
  udfdRun();
735,757✔
1842
  fnInfo("udfd exit normally");
735,757✔
1843

1844
  removeListeningPipe();
735,757✔
1845

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

1867
  return code;
735,757✔
1868
}
1869
#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