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

taosdata / TDengine / #4910

30 Dec 2025 10:52AM UTC coverage: 65.864% (+0.3%) from 65.542%
#4910

push

travis-ci

web-flow
enh: drop multi-stream (#33962)

60 of 106 new or added lines in 4 files covered. (56.6%)

999 existing lines in 108 files now uncovered.

194877 of 295877 relevant lines covered (65.86%)

121300574.4 hits per line

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

75.63
/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,713✔
54

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

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

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

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

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

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

87
  return 0;
10,728✔
88
}
89

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

105
  err = udfdCPluginUdfInitLoadInitDestoryFuncs(udfCtx, udfName);
45,459✔
106
  if (err != 0) {
45,459✔
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) {
44,947✔
113
    char processFuncName[TSDB_FUNC_NAME_LEN] = {0};
34,219✔
114
    snprintf(processFuncName, sizeof(processFuncName), "%s", udfName);
34,219✔
115
    if (uv_dlsym(&udfCtx->lib, processFuncName, (void **)(&udfCtx->scalarProcFunc)) != 0) {
34,219✔
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) {
10,728✔
121
    err = udfdCPluginUdfInitLoadAggFuncs(udfCtx, udfName);
10,728✔
122
    if (err != 0) {
10,728✔
UNCOV
123
      fnError("can not load aggregation functions. error: %d", err);
×
UNCOV
124
      err = TSDB_CODE_UDF_LOAD_UDF_FAILURE;
×
UNCOV
125
      goto _exit;
×
126
    }
127
  }
128

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

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

156
int32_t udfdCPluginUdfScalarProc(SUdfDataBlock *block, SUdfColumn *resultCol, void *udfCtx) {
1,668,729✔
157
  TAOS_UDF_CHECK_PTR_RCODE(block, resultCol, udfCtx);
6,674,289✔
158
  SUdfCPluginCtx *ctx = udfCtx;
1,668,729✔
159
  if (ctx->scalarProcFunc) {
1,668,729✔
160
    return ctx->scalarProcFunc(block, resultCol);
1,668,957✔
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,082✔
168
  TAOS_UDF_CHECK_PTR_RCODE(buf, udfCtx);
333,246✔
169
  SUdfCPluginCtx *ctx = udfCtx;
111,082✔
170
  if (ctx->aggStartFunc) {
111,082✔
171
    return ctx->aggStartFunc(buf);
110,506✔
172
  } else {
173
    fnError("udfd c plugin aggregation start not implemented");
576✔
174
    return TSDB_CODE_UDF_FUNC_EXEC_FAILURE;
576✔
175
  }
176
  return 0;
177
}
178

179
int32_t udfdCPluginUdfAggProc(SUdfDataBlock *block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf, void *udfCtx) {
258,630✔
180
  TAOS_UDF_CHECK_PTR_RCODE(block, interBuf, newInterBuf, udfCtx);
1,293,150✔
181
  SUdfCPluginCtx *ctx = udfCtx;
258,630✔
182
  if (ctx->aggProcFunc) {
258,630✔
183
    return ctx->aggProcFunc(block, interBuf, newInterBuf);
258,630✔
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,290✔
203
  TAOS_UDF_CHECK_PTR_RCODE(buf, resultData, udfCtx);
437,160✔
204
  SUdfCPluginCtx *ctx = udfCtx;
109,290✔
205
  if (ctx->aggFinishFunc) {
109,290✔
206
    return ctx->aggFinishFunc(buf, resultData);
109,290✔
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); }
119,572✔
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,713✔
365
  TAOS_UDF_CHECK_PTR_RCODE(plugin);
3,426✔
366
  plugin->scriptType = TSDB_FUNC_SCRIPT_BIN_LIB;
1,713✔
367
  plugin->openFunc = udfdCPluginOpen;
1,713✔
368
  plugin->closeFunc = udfdCPluginClose;
1,713✔
369
  plugin->udfInitFunc = udfdCPluginUdfInit;
1,713✔
370
  plugin->udfDestroyFunc = udfdCPluginUdfDestroy;
1,713✔
371
  plugin->udfScalarProcFunc = udfdCPluginUdfScalarProc;
1,713✔
372
  plugin->udfAggStartFunc = udfdCPluginUdfAggStart;
1,713✔
373
  plugin->udfAggProcFunc = udfdCPluginUdfAggProc;
1,713✔
374
  // plugin->udfAggMergeFunc = udfdCPluginUdfAggMerge;
375
  plugin->udfAggFinishFunc = udfdCPluginUdfAggFinish;
1,713✔
376

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

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

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

554
  switch (request.type) {
2,446,406✔
555
    case UDF_TASK_SETUP: {
119,572✔
556
      udfdProcessSetupRequest(uvUdf, &request);
119,572✔
557
      break;
119,572✔
558
    }
559

560
    case UDF_TASK_CALL: {
2,210,590✔
561
      udfdProcessCallRequest(uvUdf, &request);
2,210,590✔
562
      break;
2,210,647✔
563
    }
564
    case UDF_TASK_TEARDOWN: {
116,244✔
565
      udfdProcessTeardownRequest(uvUdf, &request);
116,244✔
566
      break;
116,244✔
567
    }
568
    default: {
×
569
      break;
×
570
    }
571
  }
572
}
573

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

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

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

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

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

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

642
  udfNew->resident = false;
54,315✔
643
  udfNew->expired = false;
54,315✔
644
  for (int32_t i = 0; i < taosArrayGetSize(global.residentFuncs); ++i) {
55,507✔
645
    char *funcName = taosArrayGet(global.residentFuncs, i);
2,826✔
646
    if (strcmp(udfName, funcName) == 0) {
2,826✔
647
      udfNew->resident = true;
1,634✔
648
      break;
1,634✔
649
    }
650
  }
651
  *pUdf =  udfNew;
54,315✔
652
  return 0;
54,315✔
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) {
119,572✔
673
  TAOS_UDF_CHECK_PTR_RCODE(ppUdf, udfName);
358,716✔
674
  uv_mutex_lock(&global.udfsMutex);
119,572✔
675
  SUdf  **pUdfHash = taosHashGet(global.udfsHash, udfName, strlen(udfName));
119,572✔
676
  int64_t currTime = taosGetTimestampMs();
119,572✔
677
  bool    expired = false;
119,572✔
678
  if (pUdfHash) {
119,572✔
679
    expired = currTime - (*pUdfHash)->lastFetchTime > 10 * 1000;  // 10s
65,656✔
680
    if (!expired) {
65,656✔
681
      ++(*pUdfHash)->refCount;
65,257✔
682
      *ppUdf = *pUdfHash;
65,257✔
683
      uv_mutex_unlock(&global.udfsMutex);
65,257✔
684
      fnInfo("udfd reuse existing udf. udf  %s udf version %d, udf created time %" PRIx64, (*ppUdf)->name, (*ppUdf)->version,
65,257✔
685
             (*ppUdf)->createdTime);
686
      return 0;
65,257✔
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);
54,315✔
698
  if(code != 0) {
54,315✔
699
    uv_mutex_unlock(&global.udfsMutex);
×
700
    return code;
×
701
  }
702

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

709
  return 0;
54,315✔
710
}
711

712
void udfdProcessSetupRequest(SUvUdfWork *uvUdf, SUdfRequest *request) {
119,572✔
713
  TAOS_UDF_CHECK_PTR_RVOID(uvUdf, request);
358,716✔
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);
119,572✔
716

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

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

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

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

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

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

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

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

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

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

908
      break;
111,870✔
909
    }
910
    default:
×
911
      break;
×
912
  }
913

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

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

939
_exit:
2,210,134✔
940
  switch (call->callType) {
2,210,134✔
941
    case TSDB_UDF_CALL_SCALA_PROC: {
1,691,952✔
942
      blockDataFreeRes(&call->block);
1,691,952✔
943
      blockDataFreeRes(&subRsp->resultData);
1,691,439✔
944
      break;
1,692,579✔
945
    }
946
    case TSDB_UDF_CALL_AGG_INIT: {
113,662✔
947
      freeUdfInterBuf(&subRsp->resultBuf);
113,662✔
948
      break;
113,662✔
949
    }
950
    case TSDB_UDF_CALL_AGG_PROC: {
292,650✔
951
      blockDataFreeRes(&call->block);
292,650✔
952
      freeUdfInterBuf(&subRsp->resultBuf);
292,650✔
953
      break;
292,764✔
954
    }
955
    // case TSDB_UDF_CALL_AGG_MERGE: {
956
    //   freeUdfInterBuf(&subRsp->resultBuf);
957
    //   break;
958
    // }
959
    case TSDB_UDF_CALL_AGG_FIN: {
111,870✔
960
      freeUdfInterBuf(&subRsp->resultBuf);
111,870✔
961
      break;
111,870✔
962
    }
963
    default:
×
964
      break;
×
965
  }
966

967
  taosMemoryFreeClear(uvUdf->input.base);
2,210,875✔
968
  return;
2,210,875✔
969
}
970

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

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

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

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

1031
void udfdGetFuncBodyPath(const SUdf *udf, char *path) {
54,699✔
1032
  TAOS_UDF_CHECK_PTR_RVOID(udf, path);
164,097✔
1033
  if (udf->scriptType == TSDB_FUNC_SCRIPT_BIN_LIB) {
54,699✔
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,
45,459✔
1038
             udf->createdTime);
45,459✔
1039
#endif
1040
  } else if (udf->scriptType == TSDB_FUNC_SCRIPT_PYTHON) {
9,240✔
1041
#ifdef WINDOWS
1042
    snprintf(path, PATH_MAX, "%s%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
1043
#else
1044
    snprintf(path, PATH_MAX, "%s/%s_%d_%" PRIx64 ".py", global.udfDataDir, udf->name, udf->version, udf->createdTime);
9,240✔
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) {
54,699✔
1056
  TAOS_UDF_CHECK_PTR_RCODE(pFuncInfo, udf);
164,097✔
1057
  if (!osDataSpaceAvailable()) {
54,699✔
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};
54,699✔
1064
  udfdGetFuncBodyPath(udf, path);
54,699✔
1065
  bool fileExist = !(taosStatFile(path, NULL, NULL, NULL) < 0);
54,699✔
1066
  if (fileExist) {
54,699✔
1067
    tstrncpy(udf->path, path, PATH_MAX);
48,851✔
1068
    fnInfo("udfd func body file. reuse existing file %s", path);
48,851✔
1069
    return TSDB_CODE_SUCCESS;
48,851✔
1070
  }
1071

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

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

1091
void udfdProcessRpcRsp(void *parent, SRpcMsg *pMsg, SEpSet *pEpSet) {
54,699✔
1092
  TAOS_UDF_CHECK_PTR_RVOID(parent, pMsg);
164,097✔
1093
  SUdfdRpcSendRecvInfo *msgInfo = (SUdfdRpcSendRecvInfo *)pMsg->info.ahandle;
54,699✔
1094

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

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

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

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

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

1163
int32_t udfdFillUdfInfoFromMNode(void *clientRpc, char *udfName, SUdf *udf) {
54,699✔
1164
  TAOS_UDF_CHECK_PTR_RCODE(clientRpc, udfName, udf);
218,796✔
1165
  SRetrieveFuncReq retrieveReq = {0};
54,699✔
1166
  retrieveReq.numOfFuncs = 1;
54,699✔
1167
  retrieveReq.pFuncNames = taosArrayInit(1, TSDB_FUNC_NAME_LEN);
54,699✔
1168
  if(taosArrayPush(retrieveReq.pFuncNames, udfName) == NULL) {
109,398✔
1169
    taosArrayDestroy(retrieveReq.pFuncNames);
×
1170
    return terrno;
×
1171
  }
1172

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

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

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

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

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

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

1246
    mgmtEpSet->numOfEps++;
562,073✔
1247
  }
1248

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

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

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

1268
  return 0;
562,073✔
1269
}
1270

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

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

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

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

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

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

1335
void udfdSendResponse(uv_work_t *work, int status) {
2,446,805✔
1336
  TAOS_UDF_CHECK_PTR_RVOID(work);
4,893,610✔
1337
  SUvUdfWork *udfWork = (SUvUdfWork *)(work->data);
2,446,805✔
1338

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

1356
void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
7,193,440✔
1357
  TAOS_UDF_CHECK_PTR_RVOID(handle, buf);
21,580,320✔
1358
  SUdfdUvConn *ctx = handle->data;
7,193,440✔
1359
  int32_t      msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
7,193,440✔
1360
  if (ctx->inputCap == 0) {
7,193,440✔
1361
    ctx->inputBuf = taosMemoryMalloc(msgHeadSize);
2,566,377✔
1362
    if (ctx->inputBuf) {
2,566,377✔
1363
      ctx->inputLen = 0;
2,566,377✔
1364
      ctx->inputCap = msgHeadSize;
2,566,377✔
1365
      ctx->inputTotal = -1;
2,566,377✔
1366

1367
      buf->base = ctx->inputBuf;
2,566,377✔
1368
      buf->len = ctx->inputCap;
2,566,377✔
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,627,063✔
1374
    buf->base = ctx->inputBuf + ctx->inputLen;
2,177,918✔
1375
    buf->len = msgHeadSize - ctx->inputLen;
2,177,918✔
1376
  } else {
1377
    ctx->inputCap = ctx->inputTotal > ctx->inputCap ? ctx->inputTotal : ctx->inputCap;
2,449,145✔
1378
    void *inputBuf = taosMemoryRealloc(ctx->inputBuf, ctx->inputCap);
2,449,145✔
1379
    if (inputBuf) {
2,449,145✔
1380
      ctx->inputBuf = inputBuf;
2,449,145✔
1381
      buf->base = ctx->inputBuf + ctx->inputLen;
2,449,145✔
1382
      buf->len = ctx->inputCap - ctx->inputLen;
2,449,145✔
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,895,950✔
1391
  if (pipe == NULL) {
4,895,950✔
1392
    fnError("udfd pipe is NULL, LINE:%d", __LINE__);
×
1393
    return false;
×
1394
  }
1395
  if (pipe->inputTotal == -1 && pipe->inputLen >= sizeof(int32_t)) {
4,895,950✔
1396
    pipe->inputTotal = *(int32_t *)(pipe->inputBuf);
2,446,805✔
1397
  }
1398
  if (pipe->inputLen == pipe->inputCap && pipe->inputTotal == pipe->inputCap) {
4,895,950✔
1399
    fnDebug("receive request complete. length %d", pipe->inputLen);
2,446,805✔
1400
    return true;
2,446,805✔
1401
  }
1402
  return false;
2,449,145✔
1403
}
1404

1405
void udfdHandleRequest(SUdfdUvConn *conn) {
2,446,805✔
1406
  TAOS_UDF_CHECK_PTR_RVOID(conn);
4,893,610✔
1407
  char   *inputBuf = conn->inputBuf;
2,446,805✔
1408
  int32_t inputLen = conn->inputLen;
2,446,805✔
1409

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

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

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

1452
void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
7,193,440✔
1453
  TAOS_UDF_CHECK_PTR_RVOID(client, buf);
21,580,320✔
1454
  fnDebug("udfd read %zd bytes from client", nread);
7,193,440✔
1455
  if (nread == 0) return;
7,193,440✔
1456

1457
  SUdfdUvConn *conn = client->data;
5,015,522✔
1458

1459
  if (nread > 0) {
5,015,522✔
1460
    conn->inputLen += nread;
4,895,950✔
1461
    if (isUdfdUvMsgComplete(conn)) {
4,895,950✔
1462
      udfdHandleRequest(conn);
2,446,805✔
1463
    } else {
1464
      // log error or continue;
1465
    }
1466
    return;
4,895,950✔
1467
  }
1468

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

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

1487
  uv_pipe_t *client = (uv_pipe_t *)taosMemoryMalloc(sizeof(uv_pipe_t));
119,572✔
1488
  if(client == NULL) {
119,572✔
1489
    fnError("udfd pipe malloc failed");
×
1490
    return;
×
1491
  }
1492
  code = uv_pipe_init(global.loop, client, 0);
119,572✔
1493
  if (code) {
119,572✔
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) {
119,572✔
1499
    SUdfdUvConn *ctx = taosMemoryMalloc(sizeof(SUdfdUvConn));
119,572✔
1500
    if(ctx == NULL) {
119,572✔
1501
      fnError("udfd conn malloc failed");
×
1502
      goto _exit;
×
1503
    }
1504
    ctx->pWorkList = NULL;
119,572✔
1505
    ctx->client = (uv_stream_t *)client;
119,572✔
1506
    ctx->inputBuf = 0;
119,572✔
1507
    ctx->inputLen = 0;
119,572✔
1508
    ctx->inputCap = 0;
119,572✔
1509
    client->data = ctx;
119,572✔
1510
    ctx->client = (uv_stream_t *)client;
119,572✔
1511
    code = uv_read_start((uv_stream_t *)client, udfdAllocBuffer, udfdPipeRead);
119,572✔
1512
    if (code) {
119,572✔
1513
      fnError("udfd read start error %s", uv_strerror(code));
×
1514
      udfdUvHandleError(ctx);
×
1515
      taosMemoryFree(ctx);
×
1516
      taosMemoryFree(client);
×
1517
    }
1518
    return;
119,572✔
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[]) {
562,265✔
1541
  for (int32_t i = 1; i < argc; ++i) {
1,124,402✔
1542
    if (strcmp(argv[i], "-c") == 0) {
562,265✔
1543
      if (i < argc - 1) {
562,201✔
1544
        if (strlen(argv[++i]) >= PATH_MAX) {
562,137✔
1545
          (void)printf("config file path overflow");
64✔
1546
          return -1;
64✔
1547
        }
1548
        tstrncpy(configDir, argv[i], PATH_MAX);
562,073✔
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;
562,137✔
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() {
562,073✔
1569
  const char *logName = "udfdlog";
562,073✔
1570
  TAOS_CHECK_RETURN(taosInitLogOutput(&logName));
562,073✔
1571
  return taosCreateLog(logName, 1, configDir, NULL, NULL, NULL, NULL, 0);
562,073✔
1572
}
1573

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

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

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

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

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

1616
  removeListeningPipe();
562,073✔
1617

1618
  TAOS_CHECK_RETURN(uv_pipe_init(global.loop, &global.listeningPipe, 0));
562,073✔
1619

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

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

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

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

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

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

1668
  return 0;
562,073✔
1669
}
1670

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

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

1686
  (void)uv_loop_close(global.loop);
562,073✔
1687

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

1696
int32_t udfdInitResidentFuncs() {
562,073✔
1697
  if (strlen(tsUdfdResFuncs) == 0) {
562,073✔
1698
    return TSDB_CODE_SUCCESS;
560,508✔
1699
  }
1700

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

1715
  return TSDB_CODE_SUCCESS;
1,565✔
1716
}
1717

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

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

1750
  return code;
562,073✔
1751
}
1752

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

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

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

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

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

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

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

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

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

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

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

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

1842
  udfdRun();
562,073✔
1843
  fnInfo("udfd exit normally");
562,073✔
1844

1845
  removeListeningPipe();
562,073✔
1846

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

1868
  return code;
562,073✔
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