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

taosdata / TDengine / #4803

17 Oct 2025 04:02AM UTC coverage: 61.147% (-0.05%) from 61.198%
#4803

push

travis-ci

web-flow
Merge 323e6dde0 into 1afedf5da

155455 of 324369 branches covered (47.93%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

2521 existing lines in 113 files now uncovered.

207702 of 269535 relevant lines covered (77.06%)

126661557.72 hits per line

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

63.24
/source/libs/function/src/tudf.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
#ifdef USE_UDF
16
#include "uv.h"
17

18
#include "os.h"
19

20
#include "builtinsimpl.h"
21
#include "fnLog.h"
22
#include "functionMgt.h"
23
#include "querynodes.h"
24
#include "tarray.h"
25
#include "tdatablock.h"
26
#include "tglobal.h"
27
#include "tudf.h"
28
#include "tudfInt.h"
29

30
#ifdef _TD_DARWIN_64
31
#include <mach-o/dyld.h>
32
#endif
33

34
typedef struct SUdfdData {
35
  bool         startCalled;
36
  bool         needCleanUp;
37
  uv_loop_t    loop;
38
  uv_thread_t  thread;
39
  uv_barrier_t barrier;
40
  uv_process_t process;
41
#ifdef WINDOWS
42
  HANDLE jobHandle;
43
#endif
44
  int32_t    spawnErr;
45
  uv_pipe_t  ctrlPipe;
46
  uv_async_t stopAsync;
47
  int32_t    stopCalled;
48

49
  int32_t dnodeId;
50
} SUdfdData;
51

52
SUdfdData udfdGlobal = {0};
53

54
int32_t udfStartUdfd(int32_t startDnodeId);
55
void    udfStopUdfd();
56

57
extern char **environ;
58

59
static int32_t udfSpawnUdfd(SUdfdData *pData);
60
void           udfUdfdExit(uv_process_t *process, int64_t exitStatus, int32_t termSignal);
61
static void    udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg);
62
static void    udfUdfdStopAsyncCb(uv_async_t *async);
63
static void    udfWatchUdfd(void *args);
64

UNCOV
65
void udfUdfdExit(uv_process_t *process, int64_t exitStatus, int32_t termSignal) {
×
UNCOV
66
  TAOS_UDF_CHECK_PTR_RVOID(process);
×
UNCOV
67
  fnInfo("udfd process exited with status %" PRId64 ", signal %d", exitStatus, termSignal);
×
UNCOV
68
  SUdfdData *pData = process->data;
×
UNCOV
69
  if (pData == NULL) {
×
70
    fnError("udfd process data is NULL");
×
71
    return;
×
72
  }
UNCOV
73
  if (exitStatus == 0 && termSignal == 0 || atomic_load_32(&pData->stopCalled)) {
×
74
    fnInfo("udfd process exit due to SIGINT or dnode-mgmt called stop");
×
75
  } else {
UNCOV
76
    fnInfo("udfd process restart");
×
UNCOV
77
    int32_t code = udfSpawnUdfd(pData);
×
UNCOV
78
    if (code != 0) {
×
79
      fnError("udfd process restart failed with code:%d", code);
×
80
    }
81
  }
82
}
83

84
static int32_t udfSpawnUdfd(SUdfdData *pData) {
761,561✔
85
  fnInfo("start to init udfd");
761,561!
86
  TAOS_UDF_CHECK_PTR_RCODE(pData);
1,523,122!
87

88
  int32_t              err = 0;
761,561✔
89
  uv_process_options_t options = {0};
761,561✔
90

91
  char path[PATH_MAX] = {0};
761,561✔
92
  if (tsProcPath == NULL) {
761,561✔
93
    path[0] = '.';
154✔
94
#ifdef WINDOWS
95
    GetModuleFileName(NULL, path, PATH_MAX);
96
    TAOS_DIRNAME(path);
97
#elif defined(_TD_DARWIN_64)
98
    uint32_t pathSize = sizeof(path);
99
    _NSGetExecutablePath(path, &pathSize);
100
    TAOS_DIRNAME(path);
101
#endif
102
  } else {
103
    TAOS_STRNCPY(path, tsProcPath, PATH_MAX);
761,407!
104
    TAOS_DIRNAME(path);
761,407✔
105
  }
106

107
#ifdef WINDOWS
108
  if (strlen(path) == 0) {
109
    TAOS_STRCAT(path, "C:\\TDengine");
110
  }
111
  TAOS_STRCAT(path, "\\" CUS_PROMPT "udf.exe");
112
#else
113
  if (strlen(path) == 0) {
761,561!
114
    TAOS_STRCAT(path, "/usr/bin");
×
115
  }
116
  TAOS_STRCAT(path, "/" CUS_PROMPT "udf");
761,561!
117
#endif
118
  char *argsUdfd[] = {path, "-c", configDir, NULL};
761,561✔
119
  options.args = argsUdfd;
761,561✔
120
  options.file = path;
761,561✔
121

122
  options.exit_cb = udfUdfdExit;
761,561✔
123

124
  TAOS_UV_LIB_ERROR_RET(uv_pipe_init(&pData->loop, &pData->ctrlPipe, 1));
761,561!
125

126
  uv_stdio_container_t child_stdio[3];
760,089✔
127
  child_stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE;
761,561✔
128
  child_stdio[0].data.stream = (uv_stream_t *)&pData->ctrlPipe;
761,561✔
129
  child_stdio[1].flags = UV_IGNORE;
761,561✔
130
  child_stdio[2].flags = UV_INHERIT_FD;
761,561✔
131
  child_stdio[2].data.fd = 2;
761,561✔
132
  options.stdio_count = 3;
761,561✔
133
  options.stdio = child_stdio;
761,561✔
134

135
  options.flags = UV_PROCESS_DETACHED;
761,561✔
136

137
  char dnodeIdEnvItem[32] = {0};
761,561✔
138
  char thrdPoolSizeEnvItem[32] = {0};
761,561✔
139
  snprintf(dnodeIdEnvItem, 32, "%s=%d", "DNODE_ID", pData->dnodeId);
761,561✔
140

141
  float   numCpuCores = 4;
761,561✔
142
  int32_t code = taosGetCpuCores(&numCpuCores, false);
761,561✔
143
  if (code != 0) {
761,561!
144
    fnError("failed to get cpu cores, code:0x%x", code);
×
145
  }
146
  numCpuCores = TMAX(numCpuCores, 2);
761,561!
147
  snprintf(thrdPoolSizeEnvItem, 32, "%s=%d", "UV_THREADPOOL_SIZE", (int32_t)numCpuCores * 2);
761,561!
148

149
  char    pathTaosdLdLib[512] = {0};
761,561✔
150
  size_t  taosdLdLibPathLen = sizeof(pathTaosdLdLib);
761,561✔
151
  int32_t ret = uv_os_getenv("LD_LIBRARY_PATH", pathTaosdLdLib, &taosdLdLibPathLen);
761,561✔
152
  if (ret != UV_ENOBUFS) {
761,561!
153
    taosdLdLibPathLen = strlen(pathTaosdLdLib);
761,561✔
154
  }
155

156
  char   udfdPathLdLib[1024] = {0};
761,561✔
157
  size_t udfdLdLibPathLen = strlen(tsUdfdLdLibPath);
761,561!
158
  tstrncpy(udfdPathLdLib, tsUdfdLdLibPath, sizeof(udfdPathLdLib));
761,561!
159

160
  udfdPathLdLib[udfdLdLibPathLen] = ':';
761,561✔
161
  tstrncpy(udfdPathLdLib + udfdLdLibPathLen + 1, pathTaosdLdLib, sizeof(udfdPathLdLib) - udfdLdLibPathLen - 1);
761,561!
162
  if (udfdLdLibPathLen + taosdLdLibPathLen < 1024) {
761,561!
163
    fnInfo("udfd LD_LIBRARY_PATH: %s", udfdPathLdLib);
761,561!
164
  } else {
165
    fnError("can not set correct udfd LD_LIBRARY_PATH");
×
166
  }
167
  char ldLibPathEnvItem[1024 + 32] = {0};
761,561✔
168
  snprintf(ldLibPathEnvItem, 1024 + 32, "%s=%s", "LD_LIBRARY_PATH", udfdPathLdLib);
761,561✔
169

170
  char *taosFqdnEnvItem = NULL;
761,561✔
171
  char *taosFqdn = getenv("TAOS_FQDN");
761,561✔
172
  if (taosFqdn != NULL) {
761,561!
173
    int32_t subLen = strlen(taosFqdn);
×
174
    int32_t len = strlen("TAOS_FQDN=") + subLen + 1;
×
175
    taosFqdnEnvItem = taosMemoryMalloc(len);
×
176
    if (taosFqdnEnvItem != NULL) {
×
177
      tstrncpy(taosFqdnEnvItem, "TAOS_FQDN=", len);
×
178
      TAOS_STRNCAT(taosFqdnEnvItem, taosFqdn, subLen);
×
179
      fnInfo("[UDFD]Succsess to set TAOS_FQDN:%s", taosFqdn);
×
180
    } else {
181
      fnError("[UDFD]Failed to allocate memory for TAOS_FQDN");
×
182
      return terrno;
×
183
    }
184
  }
185

186
  char *envUdfd[] = {dnodeIdEnvItem, thrdPoolSizeEnvItem, ldLibPathEnvItem, taosFqdnEnvItem, NULL};
761,561✔
187

188
  char **envUdfdWithPEnv = NULL;
761,561✔
189
  if (environ != NULL) {
761,561!
190
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
761,561✔
191
    int32_t numEnviron = 0;
761,561✔
192
    while (environ[numEnviron] != NULL) {
24,568,415✔
193
      numEnviron++;
23,806,854✔
194
    }
195

196
    envUdfdWithPEnv = (char **)taosMemoryCalloc(numEnviron + lenEnvUdfd, sizeof(char *));
761,561!
197
    if (envUdfdWithPEnv == NULL) {
761,561!
198
      err = TSDB_CODE_OUT_OF_MEMORY;
×
199
      goto _OVER;
×
200
    }
201

202
    for (int32_t i = 0; i < numEnviron; i++) {
24,568,415✔
203
      int32_t len = strlen(environ[i]) + 1;
23,806,854!
204
      envUdfdWithPEnv[i] = (char *)taosMemoryCalloc(len, 1);
23,806,854!
205
      if (envUdfdWithPEnv[i] == NULL) {
23,806,854!
206
        err = TSDB_CODE_OUT_OF_MEMORY;
×
207
        goto _OVER;
×
208
      }
209

210
      tstrncpy(envUdfdWithPEnv[i], environ[i], len);
23,806,854!
211
    }
212

213
    for (int32_t i = 0; i < lenEnvUdfd; i++) {
4,569,366✔
214
      if (envUdfd[i] != NULL) {
3,807,805✔
215
        int32_t len = strlen(envUdfd[i]) + 1;
2,284,683!
216
        envUdfdWithPEnv[numEnviron + i] = (char *)taosMemoryCalloc(len, 1);
2,284,683!
217
        if (envUdfdWithPEnv[numEnviron + i] == NULL) {
2,284,683!
218
          err = TSDB_CODE_OUT_OF_MEMORY;
×
219
          goto _OVER;
×
220
        }
221

222
        tstrncpy(envUdfdWithPEnv[numEnviron + i], envUdfd[i], len);
2,284,683!
223
      }
224
    }
225
    envUdfdWithPEnv[numEnviron + lenEnvUdfd - 1] = NULL;
761,561✔
226

227
    options.env = envUdfdWithPEnv;
761,561✔
228
  } else {
229
    options.env = envUdfd;
×
230
  }
231

232
  err = uv_spawn(&pData->loop, &pData->process, &options);
761,561✔
233
  pData->process.data = (void *)pData;
761,561✔
234

235
#ifdef WINDOWS
236
  // End udfd.exe by Job.
237
  if (pData->jobHandle != NULL) CloseHandle(pData->jobHandle);
238
  pData->jobHandle = CreateJobObject(NULL, NULL);
239
  bool add_job_ok = AssignProcessToJobObject(pData->jobHandle, pData->process.process_handle);
240
  if (!add_job_ok) {
241
    fnError("Assign udfd to job failed.");
242
  } else {
243
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info;
244
    memset(&limit_info, 0x0, sizeof(limit_info));
245
    limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
246
    bool set_auto_kill_ok =
247
        SetInformationJobObject(pData->jobHandle, JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info));
248
    if (!set_auto_kill_ok) {
249
      fnError("Set job auto kill udfd failed.");
250
    }
251
  }
252
#endif
253

254
  if (err != 0) {
761,561✔
255
    fnError("can not spawn udfd. path: %s, error: %s", path, uv_strerror(err));
154!
256
  } else {
257
    fnInfo("udfd is initialized");
761,407!
258
  }
259

260
_OVER:
760,089✔
261
  if (taosFqdnEnvItem) {
761,561!
262
    taosMemoryFree(taosFqdnEnvItem);
×
263
  }
264

265
  if (envUdfdWithPEnv != NULL) {
761,561!
266
    int32_t i = 0;
761,561✔
267
    while (envUdfdWithPEnv[i] != NULL) {
26,853,098✔
268
      taosMemoryFree(envUdfdWithPEnv[i]);
26,091,537!
269
      i++;
26,091,537✔
270
    }
271
    taosMemoryFree(envUdfdWithPEnv);
761,561!
272
  }
273

274
  return err;
761,561✔
275
}
276

277
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
3,810,191✔
278
  TAOS_UDF_CHECK_PTR_RVOID(handle);
7,620,382!
279
  if (!uv_is_closing(handle)) {
3,810,191!
280
    uv_close(handle, NULL);
3,810,191✔
281
  }
282
}
283

284
static void udfUdfdStopAsyncCb(uv_async_t *async) {
761,407✔
285
  TAOS_UDF_CHECK_PTR_RVOID(async);
1,522,814!
286
  SUdfdData *pData = async->data;
761,407✔
287
  uv_stop(&pData->loop);
761,407✔
288
}
289

290
static void udfWatchUdfd(void *args) {
761,484✔
291
  TAOS_UDF_CHECK_PTR_RVOID(args);
1,522,968!
292
  SUdfdData *pData = args;
761,484✔
293
  TAOS_UV_CHECK_ERRNO(uv_loop_init(&pData->loop));
761,484!
294
  TAOS_UV_CHECK_ERRNO(uv_async_init(&pData->loop, &pData->stopAsync, udfUdfdStopAsyncCb));
761,484!
295
  pData->stopAsync.data = pData;
761,484✔
296
  TAOS_UV_CHECK_ERRNO(udfSpawnUdfd(pData));
761,484✔
297
  atomic_store_32(&pData->spawnErr, 0);
761,407✔
298
  (void)uv_barrier_wait(&pData->barrier);
761,407✔
299
  int32_t num = uv_run(&pData->loop, UV_RUN_DEFAULT);
761,407✔
300
  fnInfo("udfd loop exit with %d active handles, line:%d", num, __LINE__);
761,407!
301

302
  uv_walk(&pData->loop, udfUdfdCloseWalkCb, NULL);
761,407✔
303
  num = uv_run(&pData->loop, UV_RUN_DEFAULT);
761,407✔
304
  fnInfo("udfd loop exit with %d active handles, line:%d", num, __LINE__);
761,407!
305
  if (uv_loop_close(&pData->loop) != 0) {
761,407!
306
    fnError("udfd loop close failed, lino:%d", __LINE__);
×
307
  }
308
  return;
761,407✔
309

310
_exit:
77✔
311
  if (terrno != 0) {
77!
312
    (void)uv_barrier_wait(&pData->barrier);
77✔
313
    atomic_store_32(&pData->spawnErr, terrno);
77✔
314
    if (uv_loop_close(&pData->loop) != 0) {
77!
315
      fnError("udfd loop close failed, lino:%d", __LINE__);
77!
316
    }
317
    fnError("udfd thread exit with code:%d lino:%d", terrno, terrln);
77!
318
    terrno = TSDB_CODE_UDF_UV_EXEC_FAILURE;
77✔
319
  }
320
  return;
77✔
321
}
322

323
int32_t udfStartUdfd(int32_t startDnodeId) {
764,381✔
324
  int32_t code = 0, lino = 0;
764,381✔
325
  if (!tsStartUdfd) {
764,381!
326
    fnInfo("start udfd is disabled.") return 0;
2,897!
327
  }
328
  SUdfdData *pData = &udfdGlobal;
761,484✔
329
  if (pData->startCalled) {
761,484!
330
    fnInfo("dnode start udfd already called");
×
331
    return 0;
×
332
  }
333
  pData->startCalled = true;
761,484✔
334
  char dnodeId[8] = {0};
761,484✔
335
  snprintf(dnodeId, sizeof(dnodeId), "%d", startDnodeId);
761,484!
336
  TAOS_CHECK_GOTO(uv_os_setenv("DNODE_ID", dnodeId), &lino, _exit);
761,484!
337
  pData->dnodeId = startDnodeId;
761,484✔
338

339
  TAOS_CHECK_GOTO(uv_barrier_init(&pData->barrier, 2), &lino, _exit);
761,484!
340
  TAOS_CHECK_GOTO(uv_thread_create(&pData->thread, udfWatchUdfd, pData), &lino, _exit);
761,484!
341
  (void)uv_barrier_wait(&pData->barrier);
761,484✔
342
  int32_t err = atomic_load_32(&pData->spawnErr);
761,484✔
343
  if (err != 0) {
761,484✔
344
    uv_barrier_destroy(&pData->barrier);
77✔
345
    if (uv_async_send(&pData->stopAsync) != 0) {
77!
346
      fnError("start udfd: failed to send stop async");
×
347
    }
348
    if (uv_thread_join(&pData->thread) != 0) {
77!
349
      fnError("start udfd: failed to join udfd thread");
×
350
    }
351
    pData->needCleanUp = false;
77✔
352
    fnInfo("udfd is cleaned up after spawn err");
77!
353
    TAOS_CHECK_GOTO(err, &lino, _exit);
77!
354
  } else {
355
    pData->needCleanUp = true;
761,407✔
356
  }
357
_exit:
761,484✔
358
  if (code != 0) {
761,484✔
359
    fnError("udfd start failed with code:%d, lino:%d", code, lino);
77!
360
  }
361
  return code;
761,484✔
362
}
363

364
void udfStopUdfd() {
764,381✔
365
  SUdfdData *pData = &udfdGlobal;
764,381✔
366
  fnInfo("udfd start to stop, need cleanup:%d, spawn err:%d", pData->needCleanUp, pData->spawnErr);
764,381!
367
  if (!pData->needCleanUp || atomic_load_32(&pData->stopCalled)) {
764,381!
368
    return;
2,974✔
369
  }
370
  atomic_store_32(&pData->stopCalled, 1);
761,407✔
371
  pData->needCleanUp = false;
761,407✔
372
  uv_barrier_destroy(&pData->barrier);
761,407✔
373
  if (uv_async_send(&pData->stopAsync) != 0) {
761,407!
374
    fnError("stop udfd: failed to send stop async");
×
375
  }
376
  if (uv_thread_join(&pData->thread) != 0) {
761,407!
377
    fnError("stop udfd: failed to join udfd thread");
×
378
  }
379

380
#ifdef WINDOWS
381
  if (pData->jobHandle != NULL) CloseHandle(pData->jobHandle);
382
#endif
383
  fnInfo("udfd is cleaned up");
761,407!
384
  return;
761,407✔
385
}
386

387
/*
388
int32_t udfGetUdfdPid(int32_t* pUdfdPid) {
389
  SUdfdData *pData = &udfdGlobal;
390
  if (pData->spawnErr) {
391
    return pData->spawnErr;
392
  }
393
  uv_pid_t pid = uv_process_get_pid(&pData->process);
394
  if (pUdfdPid) {
395
    *pUdfdPid = (int32_t)pid;
396
  }
397
  return TSDB_CODE_SUCCESS;
398
}
399
*/
400

401
//==============================================================================================
402
/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl>
403
 * The QUEUE is copied from queue.h under libuv
404
 * */
405

406
typedef void *QUEUE[2];
407

408
/* Private macros. */
409
#define QUEUE_NEXT(q)      (*(QUEUE **)&((*(q))[0]))
410
#define QUEUE_PREV(q)      (*(QUEUE **)&((*(q))[1]))
411
#define QUEUE_PREV_NEXT(q) (QUEUE_NEXT(QUEUE_PREV(q)))
412
#define QUEUE_NEXT_PREV(q) (QUEUE_PREV(QUEUE_NEXT(q)))
413

414
/* Public macros. */
415
#define QUEUE_DATA(ptr, type, field) ((type *)((char *)(ptr)-offsetof(type, field)))
416

417
/* Important note: mutating the list while QUEUE_FOREACH is
418
 * iterating over its elements results in undefined behavior.
419
 */
420
#define QUEUE_FOREACH(q, h) for ((q) = QUEUE_NEXT(h); (q) != (h); (q) = QUEUE_NEXT(q))
421

422
#define QUEUE_EMPTY(q) ((const QUEUE *)(q) == (const QUEUE *)QUEUE_NEXT(q))
423

424
#define QUEUE_HEAD(q) (QUEUE_NEXT(q))
425

426
#define QUEUE_INIT(q)    \
427
  do {                   \
428
    QUEUE_NEXT(q) = (q); \
429
    QUEUE_PREV(q) = (q); \
430
  } while (0)
431

432
#define QUEUE_ADD(h, n)                 \
433
  do {                                  \
434
    QUEUE_PREV_NEXT(h) = QUEUE_NEXT(n); \
435
    QUEUE_NEXT_PREV(n) = QUEUE_PREV(h); \
436
    QUEUE_PREV(h) = QUEUE_PREV(n);      \
437
    QUEUE_PREV_NEXT(h) = (h);           \
438
  } while (0)
439

440
#define QUEUE_SPLIT(h, q, n)       \
441
  do {                             \
442
    QUEUE_PREV(n) = QUEUE_PREV(h); \
443
    QUEUE_PREV_NEXT(n) = (n);      \
444
    QUEUE_NEXT(n) = (q);           \
445
    QUEUE_PREV(h) = QUEUE_PREV(q); \
446
    QUEUE_PREV_NEXT(h) = (h);      \
447
    QUEUE_PREV(q) = (n);           \
448
  } while (0)
449

450
#define QUEUE_MOVE(h, n)        \
451
  do {                          \
452
    if (QUEUE_EMPTY(h))         \
453
      QUEUE_INIT(n);            \
454
    else {                      \
455
      QUEUE *q = QUEUE_HEAD(h); \
456
      QUEUE_SPLIT(h, q, n);     \
457
    }                           \
458
  } while (0)
459

460
#define QUEUE_INSERT_HEAD(h, q)    \
461
  do {                             \
462
    QUEUE_NEXT(q) = QUEUE_NEXT(h); \
463
    QUEUE_PREV(q) = (h);           \
464
    QUEUE_NEXT_PREV(q) = (q);      \
465
    QUEUE_NEXT(h) = (q);           \
466
  } while (0)
467

468
#define QUEUE_INSERT_TAIL(h, q)    \
469
  do {                             \
470
    QUEUE_NEXT(q) = (h);           \
471
    QUEUE_PREV(q) = QUEUE_PREV(h); \
472
    QUEUE_PREV_NEXT(q) = (q);      \
473
    QUEUE_PREV(h) = (q);           \
474
  } while (0)
475

476
#define QUEUE_REMOVE(q)                 \
477
  do {                                  \
478
    QUEUE_PREV_NEXT(q) = QUEUE_NEXT(q); \
479
    QUEUE_NEXT_PREV(q) = QUEUE_PREV(q); \
480
  } while (0)
481

482
enum { UV_TASK_CONNECT = 0, UV_TASK_REQ_RSP = 1, UV_TASK_DISCONNECT = 2 };
483

484
int64_t gUdfTaskSeqNum = 0;
485
typedef struct SUdfcFuncStub {
486
  char           udfName[TSDB_FUNC_NAME_LEN + 1];
487
  UdfcFuncHandle handle;
488
  int32_t        refCount;
489
  int64_t        createTime;
490
} SUdfcFuncStub;
491

492
typedef struct SUdfcProxy {
493
  char         udfdPipeName[PATH_MAX + UDF_LISTEN_PIPE_NAME_LEN + 2];
494
  uv_barrier_t initBarrier;
495

496
  uv_loop_t   uvLoop;
497
  uv_thread_t loopThread;
498
  uv_async_t  loopTaskAync;
499

500
  uv_async_t loopStopAsync;
501

502
  uv_mutex_t taskQueueMutex;
503
  int8_t     udfcState;
504
  QUEUE      taskQueue;
505
  QUEUE      uvProcTaskQueue;
506

507
  uv_mutex_t udfStubsMutex;
508
  SArray    *udfStubs;         // SUdfcFuncStub
509
  SArray    *expiredUdfStubs;  // SUdfcFuncStub
510

511
  uv_mutex_t udfcUvMutex;
512
  int8_t     initialized;
513
} SUdfcProxy;
514

515
SUdfcProxy gUdfcProxy = {0};
516

517
typedef struct SUdfcUvSession {
518
  SUdfcProxy *udfc;
519
  int64_t     severHandle;
520
  uv_pipe_t  *udfUvPipe;
521

522
  int8_t  outputType;
523
  int32_t bytes;
524
  int32_t bufSize;
525

526
  char udfName[TSDB_FUNC_NAME_LEN + 1];
527
} SUdfcUvSession;
528

529
typedef struct SClientUvTaskNode {
530
  SUdfcProxy *udfc;
531
  int8_t      type;
532
  int32_t     errCode;
533

534
  uv_pipe_t *pipe;
535

536
  int64_t  seqNum;
537
  uv_buf_t reqBuf;
538

539
  uv_sem_t taskSem;
540
  uv_buf_t rspBuf;
541

542
  QUEUE recvTaskQueue;
543
  QUEUE procTaskQueue;
544
  QUEUE connTaskQueue;
545
} SClientUvTaskNode;
546

547
typedef struct SClientUdfTask {
548
  int8_t type;
549

550
  SUdfcUvSession *session;
551

552
  union {
553
    struct {
554
      SUdfSetupRequest  req;
555
      SUdfSetupResponse rsp;
556
    } _setup;
557
    struct {
558
      SUdfCallRequest  req;
559
      SUdfCallResponse rsp;
560
    } _call;
561
    struct {
562
      SUdfTeardownRequest  req;
563
      SUdfTeardownResponse rsp;
564
    } _teardown;
565
  };
566

567
} SClientUdfTask;
568

569
typedef struct SClientConnBuf {
570
  char   *buf;
571
  int32_t len;
572
  int32_t cap;
573
  int32_t total;
574
} SClientConnBuf;
575

576
typedef struct SClientUvConn {
577
  uv_pipe_t      *pipe;
578
  QUEUE           taskQueue;
579
  SClientConnBuf  readBuf;
580
  SUdfcUvSession *session;
581
} SClientUvConn;
582

583
enum {
584
  UDFC_STATE_INITAL = 0,  // initial state
585
  UDFC_STATE_STARTNG,     // starting after udfcOpen
586
  UDFC_STATE_READY,       // started and begin to receive quests
587
  UDFC_STATE_STOPPING,    // stopping after udfcClose
588
};
589

590
void    getUdfdPipeName(char *pipeName, int32_t size);
591
int32_t encodeUdfSetupRequest(void **buf, const SUdfSetupRequest *setup);
592
void   *decodeUdfSetupRequest(const void *buf, SUdfSetupRequest *request);
593
int32_t encodeUdfInterBuf(void **buf, const SUdfInterBuf *state);
594
void   *decodeUdfInterBuf(const void *buf, SUdfInterBuf *state);
595
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call);
596
void   *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call);
597
int32_t encodeUdfTeardownRequest(void **buf, const SUdfTeardownRequest *teardown);
598
void   *decodeUdfTeardownRequest(const void *buf, SUdfTeardownRequest *teardown);
599
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request);
600
void   *decodeUdfRequest(const void *buf, SUdfRequest *request);
601
int32_t encodeUdfSetupResponse(void **buf, const SUdfSetupResponse *setupRsp);
602
void   *decodeUdfSetupResponse(const void *buf, SUdfSetupResponse *setupRsp);
603
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp);
604
void   *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp);
605
int32_t encodeUdfTeardownResponse(void **buf, const SUdfTeardownResponse *teardownRsp);
606
void   *decodeUdfTeardownResponse(const void *buf, SUdfTeardownResponse *teardownResponse);
607
int32_t encodeUdfResponse(void **buf, const SUdfResponse *rsp);
608
void   *decodeUdfResponse(const void *buf, SUdfResponse *rsp);
609
void    freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta);
610
void    freeUdfColumn(SUdfColumn *col);
611
void    freeUdfDataDataBlock(SUdfDataBlock *block);
612
void    freeUdfInterBuf(SUdfInterBuf *buf);
613
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock);
614
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block);
615
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output);
616
int32_t convertDataBlockToScalarParm(SSDataBlock *input, SScalarParam *output);
617

618
void getUdfdPipeName(char *pipeName, int32_t size) {
1,550,647✔
619
  char    dnodeId[8] = {0};
1,550,647✔
620
  size_t  dnodeIdSize = sizeof(dnodeId);
1,550,647✔
621
  int32_t err = uv_os_getenv(UDF_DNODE_ID_ENV_NAME, dnodeId, &dnodeIdSize);
1,550,647✔
622
  if (err != 0) {
1,550,647✔
623
    fnError("failed to get dnodeId from env since %s", uv_err_name(err));
2,897!
624
    dnodeId[0] = '1';
2,897✔
625
  }
626
#ifdef _WIN32
627
  snprintf(pipeName, size, "%s.%x.%s", UDF_LISTEN_PIPE_NAME_PREFIX, MurmurHash3_32(tsDataDir, strlen(tsDataDir)),
628
           dnodeId);
629
#else
630
  snprintf(pipeName, size, "%s/%s%s", tsDataDir, UDF_LISTEN_PIPE_NAME_PREFIX, dnodeId);
1,550,647!
631
#endif
632
  fnInfo("get dnodeId:%s from env, pipe path:%s", dnodeId, pipeName);
1,550,647!
633
}
1,550,647✔
634

635
int32_t encodeUdfSetupRequest(void **buf, const SUdfSetupRequest *setup) {
39,976✔
636
  int32_t len = 0;
39,976✔
637
  len += taosEncodeBinary(buf, setup->udfName, TSDB_FUNC_NAME_LEN);
39,976✔
638
  return len;
39,800✔
639
}
640

641
void *decodeUdfSetupRequest(const void *buf, SUdfSetupRequest *request) {
43,208✔
642
  buf = taosDecodeBinaryTo(buf, request->udfName, TSDB_FUNC_NAME_LEN);
43,208!
643
  return (void *)buf;
43,208✔
644
}
645

646
int32_t encodeUdfInterBuf(void **buf, const SUdfInterBuf *state) {
744,340✔
647
  int32_t len = 0;
744,340✔
648
  len += taosEncodeFixedI8(buf, state->numOfResult);
744,340✔
649
  len += taosEncodeFixedI32(buf, state->bufLen);
744,340✔
650
  len += taosEncodeBinary(buf, state->buf, state->bufLen);
744,340✔
651
  return len;
744,340✔
652
}
653

654
void *decodeUdfInterBuf(const void *buf, SUdfInterBuf *state) {
349,964✔
655
  buf = taosDecodeFixedI8(buf, &state->numOfResult);
349,964✔
656
  buf = taosDecodeFixedI32(buf, &state->bufLen);
349,964!
657
  buf = taosDecodeBinary(buf, (void **)&state->buf, state->bufLen);
349,964✔
658
  return (void *)buf;
349,964✔
659
}
660

661
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
382,512✔
662
  int32_t len = 0;
382,512✔
663
  len += taosEncodeFixedI64(buf, call->udfHandle);
382,512✔
664
  len += taosEncodeFixedI8(buf, call->callType);
382,512✔
665
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
382,512✔
666
    len += tEncodeDataBlock(buf, &call->block);
85,472✔
667
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
297,040✔
668
    len += taosEncodeFixedI8(buf, call->initFirst);
136,544✔
669
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
228,768✔
670
    len += tEncodeDataBlock(buf, &call->block);
160,496✔
671
    len += encodeUdfInterBuf(buf, &call->interBuf);
160,496✔
672
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
68,272!
673
    // len += encodeUdfInterBuf(buf, &call->interBuf);
674
    // len += encodeUdfInterBuf(buf, &call->interBuf2);
675
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
68,272!
676
    len += encodeUdfInterBuf(buf, &call->interBuf);
68,272✔
677
  }
678
  return len;
382,512✔
679
}
680

681
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
707,842✔
682
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
707,842!
683
  buf = taosDecodeFixedI8(buf, &call->callType);
707,842✔
684
  switch (call->callType) {
707,842!
685
    case TSDB_UDF_CALL_SCALA_PROC:
450,056✔
686
      buf = tDecodeDataBlock(buf, &call->block);
450,056✔
687
      break;
449,986✔
688
    case TSDB_UDF_CALL_AGG_INIT:
56,342✔
689
      buf = taosDecodeFixedI8(buf, &call->initFirst);
56,342✔
690
      break;
56,342✔
691
    case TSDB_UDF_CALL_AGG_PROC:
145,786✔
692
      buf = tDecodeDataBlock(buf, &call->block);
145,786✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
145,786✔
694
      break;
145,800✔
695
    // case TSDB_UDF_CALL_AGG_MERGE:
696
    //   buf = decodeUdfInterBuf(buf, &call->interBuf);
697
    //   buf = decodeUdfInterBuf(buf, &call->interBuf2);
698
    //   break;
699
    case TSDB_UDF_CALL_AGG_FIN:
55,658✔
700
      buf = decodeUdfInterBuf(buf, &call->interBuf);
55,658✔
701
      break;
55,658✔
702
  }
703
  return (void *)buf;
707,786✔
704
}
705

706
int32_t encodeUdfTeardownRequest(void **buf, const SUdfTeardownRequest *teardown) {
39,800✔
707
  int32_t len = 0;
39,800✔
708
  len += taosEncodeFixedI64(buf, teardown->udfHandle);
39,800✔
709
  return len;
39,800✔
710
}
711

712
void *decodeUdfTeardownRequest(const void *buf, SUdfTeardownRequest *teardown) {
41,580✔
713
  buf = taosDecodeFixedI64(buf, &teardown->udfHandle);
41,580!
714
  return (void *)buf;
41,580✔
715
}
716

717
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
462,112✔
718
  int32_t len = 0;
462,112✔
719
  if (buf == NULL) {
462,112✔
720
    len += sizeof(request->msgLen);
231,232✔
721
  } else {
722
    *(int32_t *)(*buf) = request->msgLen;
230,880✔
723
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
231,056✔
724
  }
725
  len += taosEncodeFixedI64(buf, request->seqNum);
462,288✔
726
  len += taosEncodeFixedI8(buf, request->type);
462,288✔
727
  if (request->type == UDF_TASK_SETUP) {
462,112✔
728
    len += encodeUdfSetupRequest(buf, &request->setup);
39,976✔
729
  } else if (request->type == UDF_TASK_CALL) {
422,312✔
730
    len += encodeUdfCallRequest(buf, &request->call);
382,512✔
731
  } else if (request->type == UDF_TASK_TEARDOWN) {
39,800!
732
    len += encodeUdfTeardownRequest(buf, &request->teardown);
39,800✔
733
  }
734
  return len;
462,112✔
735
}
736

737
void *decodeUdfRequest(const void *buf, SUdfRequest *request) {
792,658✔
738
  request->msgLen = *(int32_t *)(buf);
792,658✔
739
  buf = POINTER_SHIFT(buf, sizeof(request->msgLen));
792,658✔
740

741
  buf = taosDecodeFixedI64(buf, &request->seqNum);
792,658!
742
  buf = taosDecodeFixedI8(buf, &request->type);
792,658✔
743

744
  if (request->type == UDF_TASK_SETUP) {
792,658✔
745
    buf = decodeUdfSetupRequest(buf, &request->setup);
43,208✔
746
  } else if (request->type == UDF_TASK_CALL) {
749,450✔
747
    buf = decodeUdfCallRequest(buf, &request->call);
707,870✔
748
  } else if (request->type == UDF_TASK_TEARDOWN) {
41,580!
749
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
41,580✔
750
  }
751
  return (void *)buf;
792,602✔
752
}
753

754
int32_t encodeUdfSetupResponse(void **buf, const SUdfSetupResponse *setupRsp) {
86,416✔
755
  int32_t len = 0;
86,416✔
756
  len += taosEncodeFixedI64(buf, setupRsp->udfHandle);
86,416✔
757
  len += taosEncodeFixedI8(buf, setupRsp->outputType);
86,416✔
758
  len += taosEncodeFixedI32(buf, setupRsp->bytes);
86,240✔
759
  len += taosEncodeFixedI32(buf, setupRsp->bufSize);
86,240✔
760
  return len;
86,240✔
761
}
762

763
void *decodeUdfSetupResponse(const void *buf, SUdfSetupResponse *setupRsp) {
20,076✔
764
  buf = taosDecodeFixedI64(buf, &setupRsp->udfHandle);
20,076!
765
  buf = taosDecodeFixedI8(buf, &setupRsp->outputType);
20,076✔
766
  buf = taosDecodeFixedI32(buf, &setupRsp->bytes);
20,076!
767
  buf = taosDecodeFixedI32(buf, &setupRsp->bufSize);
20,076!
768
  return (void *)buf;
20,076✔
769
}
770

771
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp) {
1,415,222✔
772
  int32_t len = 0;
1,415,222✔
773
  len += taosEncodeFixedI8(buf, callRsp->callType);
1,415,222✔
774
  switch (callRsp->callType) {
1,415,222!
775
    case TSDB_UDF_CALL_SCALA_PROC:
899,846✔
776
      len += tEncodeDataBlock(buf, &callRsp->resultData);
899,846✔
777
      break;
899,076✔
778
    case TSDB_UDF_CALL_AGG_INIT:
112,684✔
779
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
112,684✔
780
      break;
112,684✔
781
    case TSDB_UDF_CALL_AGG_PROC:
291,572✔
782
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
291,572✔
783
      break;
291,572✔
784
    // case TSDB_UDF_CALL_AGG_MERGE:
785
    //   len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
786
    //   break;
787
    case TSDB_UDF_CALL_AGG_FIN:
111,316✔
788
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
111,316✔
789
      break;
111,316✔
790
  }
791
  return len;
1,414,452✔
792
}
793

794
void *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp) {
191,256✔
795
  buf = taosDecodeFixedI8(buf, &callRsp->callType);
191,256✔
796
  switch (callRsp->callType) {
191,256!
797
    case TSDB_UDF_CALL_SCALA_PROC:
42,736✔
798
      buf = tDecodeDataBlock(buf, &callRsp->resultData);
42,736✔
799
      break;
42,736✔
800
    case TSDB_UDF_CALL_AGG_INIT:
34,136✔
801
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
34,136✔
802
      break;
34,136✔
803
    case TSDB_UDF_CALL_AGG_PROC:
80,248✔
804
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
80,248✔
805
      break;
80,248✔
806
    // case TSDB_UDF_CALL_AGG_MERGE:
807
    //   buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
808
    //   break;
809
    case TSDB_UDF_CALL_AGG_FIN:
34,136✔
810
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
34,136✔
811
      break;
34,136✔
812
  }
813
  return (void *)buf;
191,256✔
814
}
815

816
int32_t encodeUdfTeardownResponse(void **buf, const SUdfTeardownResponse *teardownRsp) { return 0; }
83,160✔
817

818
void *decodeUdfTeardownResponse(const void *buf, SUdfTeardownResponse *teardownResponse) { return (void *)buf; }
19,900✔
819

820
int32_t encodeUdfResponse(void **buf, const SUdfResponse *rsp) {
1,584,664✔
821
  int32_t len = 0;
1,584,664✔
822
  len += sizeof(rsp->msgLen);
1,584,664✔
823
  if (buf != NULL) {
1,584,664✔
824
    *(int32_t *)(*buf) = rsp->msgLen;
792,272✔
825
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->msgLen));
792,272✔
826
  }
827

828
  len += sizeof(rsp->seqNum);
1,584,664✔
829
  if (buf != NULL) {
1,584,664✔
830
    *(int64_t *)(*buf) = rsp->seqNum;
792,258✔
831
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
792,258✔
832
  }
833

834
  len += taosEncodeFixedI64(buf, rsp->seqNum);
1,584,664✔
835
  len += taosEncodeFixedI8(buf, rsp->type);
1,584,664✔
836
  len += taosEncodeFixedI32(buf, rsp->code);
1,584,664✔
837

838
  switch (rsp->type) {
1,584,664✔
839
    case UDF_TASK_SETUP:
86,416✔
840
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
86,416✔
841
      break;
86,240✔
842
    case UDF_TASK_CALL:
1,415,026✔
843
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
1,415,026✔
844
      break;
1,414,578✔
845
    case UDF_TASK_TEARDOWN:
83,160✔
846
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
83,160✔
847
      break;
83,336✔
848
    default:
238✔
849
      fnError("encode udf response, invalid udf response type %d", rsp->type);
238!
850
      break;
×
851
  }
852
  return len;
1,584,154✔
853
}
854

855
void *decodeUdfResponse(const void *buf, SUdfResponse *rsp) {
231,232✔
856
  rsp->msgLen = *(int32_t *)(buf);
231,232✔
857
  buf = POINTER_SHIFT(buf, sizeof(rsp->msgLen));
231,232✔
858
  rsp->seqNum = *(int64_t *)(buf);
231,232✔
859
  buf = POINTER_SHIFT(buf, sizeof(rsp->seqNum));
231,232✔
860
  buf = taosDecodeFixedI64(buf, &rsp->seqNum);
231,232!
861
  buf = taosDecodeFixedI8(buf, &rsp->type);
231,232✔
862
  buf = taosDecodeFixedI32(buf, &rsp->code);
231,232!
863

864
  switch (rsp->type) {
231,232!
865
    case UDF_TASK_SETUP:
20,076✔
866
      buf = decodeUdfSetupResponse(buf, &rsp->setupRsp);
20,076✔
867
      break;
20,076✔
868
    case UDF_TASK_CALL:
191,256✔
869
      buf = decodeUdfCallResponse(buf, &rsp->callRsp);
191,256✔
870
      break;
191,256✔
871
    case UDF_TASK_TEARDOWN:
19,900✔
872
      buf = decodeUdfTeardownResponse(buf, &rsp->teardownRsp);
19,900✔
873
      break;
19,900✔
874
    default:
×
875
      rsp->code = TSDB_CODE_UDF_INTERNAL_ERROR;
×
876
      fnError("decode udf response, invalid udf response type %d", rsp->type);
×
877
      break;
×
878
  }
879
  if (buf == NULL) {
231,232!
880
    rsp->code = terrno;
×
881
    fnError("decode udf response failed, code:0x%x", rsp->code);
×
882
  }
883
  return (void *)buf;
231,232✔
884
}
885

886
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
1,074,222✔
887
  TAOS_UDF_CHECK_PTR_RVOID(data, meta);
3,222,720!
888
  if (IS_VAR_DATA_TYPE(meta->type)) {
1,074,222!
889
    taosMemoryFree(data->varLenCol.varOffsets);
7,782!
890
    data->varLenCol.varOffsets = NULL;
7,880✔
891
    taosMemoryFree(data->varLenCol.payload);
7,880!
892
    data->varLenCol.payload = NULL;
7,880✔
893
  } else {
894
    taosMemoryFree(data->fixLenCol.nullBitmap);
1,066,440!
895
    data->fixLenCol.nullBitmap = NULL;
1,066,258✔
896
    taosMemoryFree(data->fixLenCol.data);
1,066,258!
897
    data->fixLenCol.data = NULL;
1,066,356✔
898
  }
899
}
900

901
void freeUdfColumn(SUdfColumn *col) {
1,074,334✔
902
  TAOS_UDF_CHECK_PTR_RVOID(col);
2,148,710!
903
  freeUdfColumnData(&col->colData, &col->colMeta);
1,074,334✔
904
}
905

906
void freeUdfDataDataBlock(SUdfDataBlock *block) {
595,534✔
907
  TAOS_UDF_CHECK_PTR_RVOID(block);
1,191,222!
908
  for (int32_t i = 0; i < block->numOfCols; ++i) {
1,219,854✔
909
    freeUdfColumn(block->udfCols[i]);
624,194✔
910
    taosMemoryFree(block->udfCols[i]);
624,334!
911
    block->udfCols[i] = NULL;
624,320✔
912
  }
913
  taosMemoryFree(block->udfCols);
595,660!
914
  block->udfCols = NULL;
595,716✔
915
}
916

917
void freeUdfInterBuf(SUdfInterBuf *buf) {
607,750✔
918
  TAOS_UDF_CHECK_PTR_RVOID(buf);
1,215,500!
919
  taosMemoryFree(buf->buf);
607,750✔
920
  buf->buf = NULL;
607,750✔
921
}
922

923
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
595,758✔
924
  TAOS_UDF_CHECK_PTR_RCODE(block, udfBlock);
1,787,302!
925
  int32_t code = blockDataCheck(block);
595,758✔
926
  if (code != TSDB_CODE_SUCCESS) {
595,674!
927
    return code;
×
928
  }
929
  udfBlock->numOfRows = block->info.rows;
595,674✔
930
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
595,674✔
931
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
595,632!
932
  if ((udfBlock->udfCols) == NULL) {
595,828!
933
    return terrno;
×
934
  }
935
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
1,220,148✔
936
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
624,446!
937
    if (udfBlock->udfCols[i] == NULL) {
624,334!
938
      return terrno;
×
939
    }
940
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
624,334✔
941
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
624,278✔
942
    udfCol->colMeta.type = col->info.type;
624,278✔
943
    udfCol->colMeta.bytes = col->info.bytes;
624,278✔
944
    udfCol->colMeta.scale = col->info.scale;
624,278✔
945
    udfCol->colMeta.precision = col->info.precision;
624,278✔
946
    udfCol->colData.numOfRows = udfBlock->numOfRows;
624,278✔
947
    udfCol->hasNull = col->hasNull;
624,278!
948
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
624,278!
949
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
4,866✔
950
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
4,866!
951
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
4,880!
952
        return terrno;
×
953
      }
954
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
4,880!
955
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
4,880✔
956
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
4,880!
957
      if (udfCol->colData.varLenCol.payload == NULL) {
4,880!
958
        return terrno;
×
959
      }
960
      if (col->reassigned) {
4,880!
961
        for (int32_t row = 0; row < udfCol->colData.numOfRows; ++row) {
×
962
          char   *pColData = col->pData + col->varmeta.offset[row];
×
963
          int32_t colSize = 0;
×
964
          if (col->info.type == TSDB_DATA_TYPE_JSON) {
×
965
            colSize = getJsonValueLen(pColData);
×
966
          } else if (IS_STR_DATA_BLOB(col->info.type)) {
×
967
            colSize = blobDataTLen(pColData);
×
968
          } else {
969
            colSize = varDataTLen(pColData);
×
970
          }
971
          memcpy(udfCol->colData.varLenCol.payload, pColData, colSize);
×
972
          udfCol->colData.varLenCol.payload += colSize;
×
973
        }
974
      } else {
975
        memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
4,880!
976
      }
977
    } else {
978
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
619,412✔
979
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
619,412✔
980
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
619,412!
981
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
619,454!
982
        return terrno;
×
983
      }
984
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
619,454✔
985
      memcpy(bitmap, col->nullbitmap, bitmapLen);
619,454!
986
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
619,454✔
987
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
619,454✔
988
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
619,454!
989
      if (NULL == udfCol->colData.fixLenCol.data) {
619,440!
990
        return terrno;
×
991
      }
992
      char *data = udfCol->colData.fixLenCol.data;
619,440✔
993
      memcpy(data, col->pData, dataLen);
619,440!
994
    }
995
  }
996
  return TSDB_CODE_SUCCESS;
595,702✔
997
}
998

999
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
449,074✔
1000
  TAOS_UDF_CHECK_PTR_RCODE(udfCol, block);
1,347,260!
1001
  int32_t         code = 0, lino = 0;
449,074✔
1002
  SUdfColumnMeta *meta = &udfCol->colMeta;
449,074✔
1003

1004
  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
449,074✔
1005
  code = blockDataAppendColInfo(block, &colInfoData);
449,186✔
1006
  TAOS_CHECK_GOTO(code, &lino, _exit);
449,184!
1007

1008
  code = blockDataEnsureCapacity(block, udfCol->colData.numOfRows);
449,184✔
1009
  TAOS_CHECK_GOTO(code, &lino, _exit);
449,214!
1010

1011
  SColumnInfoData *col = NULL;
449,214✔
1012
  code = bdGetColumnInfoData(block, 0, &col);
449,214✔
1013
  TAOS_CHECK_GOTO(code, &lino, _exit);
449,226!
1014

1015
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
115,620,024✔
1016
    if (udfColDataIsNull(udfCol, i)) {
115,453,338✔
1017
      colDataSetNULL(col, i);
20,948,372✔
1018
    } else {
1019
      char *data = udfColDataGetData(udfCol, i);
94,504,966✔
1020
      code = colDataSetVal(col, i, data, false);
94,504,966✔
1021
      TAOS_CHECK_GOTO(code, &lino, _exit);
94,222,426!
1022
    }
1023
  }
1024
  block->info.rows = udfCol->colData.numOfRows;
166,686✔
1025

1026
  code = blockDataCheck(block);
166,686✔
1027
  TAOS_CHECK_GOTO(code, &lino, _exit);
449,438!
1028
_exit:
449,438✔
1029
  if (code != 0) {
449,438!
1030
    fnError("failed to convert udf column to data block, code:%d, line:%d", code, lino);
×
1031
  }
1032
  return TSDB_CODE_SUCCESS;
449,438✔
1033
}
1034

1035
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
42,736✔
1036
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
128,208!
1037
  int32_t code = 0, lino = 0;
42,736✔
1038
  int32_t numOfRows = 0;
42,736✔
1039
  for (int32_t i = 0; i < numOfCols; ++i) {
86,880✔
1040
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
44,144✔
1041
  }
1042

1043
  // create the basic block info structure
1044
  for (int32_t i = 0; i < numOfCols; ++i) {
86,880✔
1045
    SColumnInfoData *pInfo = input[i].columnData;
44,144✔
1046
    SColumnInfoData  d = {0};
44,144✔
1047
    d.info = pInfo->info;
44,144✔
1048

1049
    TAOS_CHECK_GOTO(blockDataAppendColInfo(output, &d), &lino, _exit);
44,144!
1050
  }
1051

1052
  TAOS_CHECK_GOTO(blockDataEnsureCapacity(output, numOfRows), &lino, _exit);
42,736!
1053

1054
  for (int32_t i = 0; i < numOfCols; ++i) {
86,880✔
1055
    SColumnInfoData *pDest = taosArrayGet(output->pDataBlock, i);
44,144✔
1056

1057
    SColumnInfoData *pColInfoData = input[i].columnData;
44,144✔
1058
    TAOS_CHECK_GOTO(colDataAssign(pDest, pColInfoData, input[i].numOfRows, &output->info), &lino, _exit);
44,144!
1059

1060
    if (input[i].numOfRows < numOfRows) {
44,144!
1061
      int32_t startRow = input[i].numOfRows;
×
1062
      int32_t expandRows = numOfRows - startRow;
×
1063
      bool    isNull = colDataIsNull_s(pColInfoData, (input + i)->numOfRows - 1);
×
1064
      if (isNull) {
×
1065
        colDataSetNNULL(pDest, startRow, expandRows);
×
1066
      } else {
1067
        char *src = colDataGetData(pColInfoData, (input + i)->numOfRows - 1);
×
1068
        for (int32_t j = 0; j < expandRows; ++j) {
×
1069
          TAOS_CHECK_GOTO(colDataSetVal(pDest, startRow + j, src, false), &lino, _exit);
×
1070
        }
1071
      }
1072
    }
1073
  }
1074

1075
  output->info.rows = numOfRows;
42,736✔
1076
_exit:
42,736✔
1077
  if (code != 0) {
42,736!
1078
    fnError("failed to convert scalar param to data block, code:%d, line:%d", code, lino);
×
1079
  }
1080
  return code;
42,736✔
1081
}
1082

1083
int32_t convertDataBlockToScalarParm(SSDataBlock *input, SScalarParam *output) {
42,736✔
1084
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
128,208!
1085
  if (taosArrayGetSize(input->pDataBlock) != 1) {
42,736!
1086
    fnError("scalar function only support one column");
×
1087
    return 0;
×
1088
  }
1089
  output->numOfRows = input->info.rows;
42,736✔
1090

1091
  output->columnData = taosMemoryMalloc(sizeof(SColumnInfoData));
42,736!
1092
  if (output->columnData == NULL) {
42,736!
1093
    return terrno;
×
1094
  }
1095
  memcpy(output->columnData, taosArrayGet(input->pDataBlock, 0), sizeof(SColumnInfoData));
42,736!
1096
  output->colAlloced = true;
42,736✔
1097

1098
  return 0;
42,736✔
1099
}
1100

1101
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
1102
// memory layout |---SUdfAggRes----|-----final result-----|---inter result----|
1103
typedef struct SUdfAggRes {
1104
  int8_t  finalResNum;
1105
  int8_t  interResNum;
1106
  int32_t interResBufLen;
1107
  char   *finalResBuf;
1108
  char   *interResBuf;
1109
} SUdfAggRes;
1110

1111
void    onUdfcPipeClose(uv_handle_t *handle);
1112
int32_t udfcGetUdfTaskResultFromUvTask(SClientUdfTask *task, SClientUvTaskNode *uvTask);
1113
void    udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf);
1114
bool    isUdfcUvMsgComplete(SClientConnBuf *connBuf);
1115
void    udfcUvHandleRsp(SClientUvConn *conn);
1116
void    udfcUvHandleError(SClientUvConn *conn);
1117
void    onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf);
1118
void    onUdfcPipeWrite(uv_write_t *write, int32_t status);
1119
void    onUdfcPipeConnect(uv_connect_t *connect, int32_t status);
1120
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask);
1121
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask);
1122
int32_t udfcStartUvTask(SClientUvTaskNode *uvTask);
1123
void    udfcAsyncTaskCb(uv_async_t *async);
1124
void    cleanUpUvTasks(SUdfcProxy *udfc);
1125
void    udfStopAsyncCb(uv_async_t *async);
1126
void    constructUdfService(void *argsThread);
1127
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType);
1128
int32_t doSetupUdf(char udfName[], UdfcFuncHandle *funcHandle);
1129
int32_t compareUdfcFuncSub(const void *elem1, const void *elem2);
1130
int32_t doTeardownUdf(UdfcFuncHandle handle);
1131

1132
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
1133
                SSDataBlock *output, SUdfInterBuf *newState);
1134
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf);
1135
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState);
1136
// udf todo:  aggmerge
1137
// int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
1138
//                           SUdfInterBuf *resultBuf);
1139
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData);
1140
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1141
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1142

1143
int32_t udfcOpen();
1144
int32_t udfcClose();
1145

1146
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle);
1147
void    releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle);
1148
int32_t cleanUpUdfs();
1149

1150
bool    udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv);
1151
int32_t udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo);
1152
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx);
1153
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock);
1154

1155
void    cleanupNotExpiredUdfs();
1156
void    cleanupExpiredUdfs();
1157
int32_t compareUdfcFuncSub(const void *elem1, const void *elem2) {
654,948✔
1158
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
654,948✔
1159
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
654,948✔
1160
  return strcmp(stub1->udfName, stub2->udfName);
654,948!
1161
}
1162

1163
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle) {
191,256✔
1164
  TAOS_UDF_CHECK_PTR_RCODE(udfName, pHandle);
573,768!
1165
  int32_t code = 0, line = 0;
191,256✔
1166
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
191,256✔
1167
  SUdfcFuncStub key = {0};
191,256✔
1168
  tstrncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
191,256!
1169
  int32_t stubIndex = taosArraySearchIdx(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
191,256✔
1170
  if (stubIndex != -1) {
191,256✔
1171
    SUdfcFuncStub *foundStub = taosArrayGet(gUdfcProxy.udfStubs, stubIndex);
171,180✔
1172
    UdfcFuncHandle handle = foundStub->handle;
171,180✔
1173
    int64_t        currUs = taosGetTimestampUs();
171,180✔
1174
    bool           expired = (currUs - foundStub->createTime) >= 10 * 1000 * 1000;
171,180✔
1175
    if (!expired) {
171,180!
1176
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
171,180!
1177
        *pHandle = foundStub->handle;
171,180✔
1178
        ++foundStub->refCount;
171,180✔
1179
        uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
171,180✔
1180
        return 0;
171,180✔
1181
      } else {
1182
        fnInfo("udf invalid handle for %s, refCount: %d, create time: %" PRId64 ". remove it from cache", udfName,
×
1183
               foundStub->refCount, foundStub->createTime);
1184
        taosArrayRemove(gUdfcProxy.udfStubs, stubIndex);
×
1185
      }
1186
    } else {
1187
      fnDebug("udf handle expired for %s, will setup udf. move it to expired list", udfName);
×
1188
      if (taosArrayPush(gUdfcProxy.expiredUdfStubs, foundStub) == NULL) {
×
1189
        fnError("acquireUdfFuncHandle: failed to push udf stub to array");
×
1190
      } else {
1191
        taosArrayRemove(gUdfcProxy.udfStubs, stubIndex);
×
1192
        taosArraySort(gUdfcProxy.expiredUdfStubs, compareUdfcFuncSub);
×
1193
      }
1194
    }
1195
  }
1196
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
20,076✔
1197
  *pHandle = NULL;
20,076✔
1198
  code = doSetupUdf(udfName, pHandle);
20,076✔
1199
  if (code == TSDB_CODE_SUCCESS) {
20,076!
1200
    SUdfcFuncStub stub = {0};
20,076✔
1201
    tstrncpy(stub.udfName, udfName, TSDB_FUNC_NAME_LEN);
20,076!
1202
    stub.handle = *pHandle;
20,076✔
1203
    ++stub.refCount;
20,076✔
1204
    stub.createTime = taosGetTimestampUs();
20,076✔
1205
    uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
20,076✔
1206
    if (taosArrayPush(gUdfcProxy.udfStubs, &stub) == NULL) {
40,152!
1207
      fnError("acquireUdfFuncHandle: failed to push udf stub to array");
×
1208
      uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
×
1209
      goto _exit;
×
1210
    } else {
1211
      taosArraySort(gUdfcProxy.udfStubs, compareUdfcFuncSub);
20,076✔
1212
    }
1213
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
20,076✔
1214
  } else {
1215
    *pHandle = NULL;
×
1216
  }
1217

1218
_exit:
20,076✔
1219
  return code;
20,076✔
1220
}
1221

1222
void releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle) {
191,256✔
1223
  TAOS_UDF_CHECK_PTR_RVOID(udfName);
382,512!
1224
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
191,256✔
1225
  SUdfcFuncStub key = {0};
191,256✔
1226
  tstrncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
191,256!
1227
  SUdfcFuncStub *foundStub = taosArraySearch(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
191,256✔
1228
  SUdfcFuncStub *expiredStub = taosArraySearch(gUdfcProxy.expiredUdfStubs, &key, compareUdfcFuncSub, TD_EQ);
191,256✔
1229
  if (!foundStub && !expiredStub) {
191,256!
1230
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
×
1231
    return;
×
1232
  }
1233
  if (foundStub != NULL && foundStub->handle == handle && foundStub->refCount > 0) {
191,256!
1234
    --foundStub->refCount;
191,080✔
1235
  }
1236
  if (expiredStub != NULL && expiredStub->handle == handle && expiredStub->refCount > 0) {
191,256!
1237
    --expiredStub->refCount;
×
1238
  }
1239
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
191,256✔
1240
}
1241

1242
void cleanupExpiredUdfs() {
46,972✔
1243
  int32_t i = 0;
46,972✔
1244
  SArray *expiredUdfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
46,972✔
1245
  if (expiredUdfStubs == NULL) {
46,972!
1246
    fnError("cleanupExpiredUdfs: failed to init array");
×
1247
    return;
×
1248
  }
1249
  while (i < taosArrayGetSize(gUdfcProxy.expiredUdfStubs)) {
46,972!
1250
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.expiredUdfStubs, i);
×
1251
    if (stub->refCount == 0) {
×
1252
      fnInfo("tear down udf. expired. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle,
×
1253
             stub->refCount);
1254
      (void)doTeardownUdf(stub->handle);
×
1255
    } else {
1256
      fnInfo("udf still in use. expired. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p",
×
1257
             stub->udfName, stub->refCount, stub->createTime, stub->handle);
1258
      UdfcFuncHandle handle = stub->handle;
×
1259
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
×
1260
        if (taosArrayPush(expiredUdfStubs, stub) == NULL) {
×
1261
          fnError("cleanupExpiredUdfs: failed to push udf stub to array");
×
1262
        }
1263
      } else {
1264
        fnInfo("udf invalid handle for %s, expired. refCount: %d, create time: %" PRId64 ". remove it from cache",
×
1265
               stub->udfName, stub->refCount, stub->createTime);
1266
      }
1267
    }
1268
    ++i;
×
1269
  }
1270
  taosArrayDestroy(gUdfcProxy.expiredUdfStubs);
46,972✔
1271
  gUdfcProxy.expiredUdfStubs = expiredUdfStubs;
46,972✔
1272
}
1273

1274
void cleanupNotExpiredUdfs() {
46,972✔
1275
  SArray *udfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
46,972✔
1276
  if (udfStubs == NULL) {
46,972!
1277
    fnError("cleanupNotExpiredUdfs: failed to init array");
×
1278
    return;
×
1279
  }
1280
  int32_t i = 0;
46,972✔
1281
  while (i < taosArrayGetSize(gUdfcProxy.udfStubs)) {
104,680✔
1282
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.udfStubs, i);
57,708✔
1283
    if (stub->refCount == 0) {
57,708✔
1284
      fnInfo("tear down udf. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle, stub->refCount);
19,900!
1285
      (void)doTeardownUdf(stub->handle);
19,900✔
1286
    } else {
1287
      fnInfo("udf still in use. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p", stub->udfName,
37,808!
1288
             stub->refCount, stub->createTime, stub->handle);
1289
      UdfcFuncHandle handle = stub->handle;
37,808✔
1290
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
37,808!
1291
        if (taosArrayPush(udfStubs, stub) == NULL) {
37,808!
1292
          fnError("cleanupNotExpiredUdfs: failed to push udf stub to array");
×
1293
        }
1294
      } else {
1295
        fnInfo("udf invalid handle for %s, refCount: %d, create time: %" PRId64 ". remove it from cache", stub->udfName,
×
1296
               stub->refCount, stub->createTime);
1297
      }
1298
    }
1299
    ++i;
57,708✔
1300
  }
1301
  taosArrayDestroy(gUdfcProxy.udfStubs);
46,972✔
1302
  gUdfcProxy.udfStubs = udfStubs;
46,972✔
1303
}
1304

1305
int32_t cleanUpUdfs() {
347,997,825✔
1306
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
347,997,825✔
1307
  if (!initialized) {
347,981,896✔
1308
    return TSDB_CODE_SUCCESS;
19,627✔
1309
  }
1310

1311
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
347,962,269✔
1312
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
348,029,911!
1313
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
347,982,939!
1314
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
347,982,939✔
1315
    return TSDB_CODE_SUCCESS;
347,982,939✔
1316
  }
1317

1318
  cleanupNotExpiredUdfs();
46,972✔
1319
  cleanupExpiredUdfs();
46,972✔
1320

1321
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
46,972✔
1322
  return 0;
46,972✔
1323
}
1324

1325
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
42,736✔
1326
  TAOS_UDF_CHECK_PTR_RCODE(udfName, input, output);
170,944!
1327
  UdfcFuncHandle handle = NULL;
42,736✔
1328
  int32_t        code = acquireUdfFuncHandle(udfName, &handle);
42,736✔
1329
  if (code != 0) {
42,736!
1330
    return code;
×
1331
  }
1332

1333
  SUdfcUvSession *session = handle;
42,736✔
1334
  code = doCallUdfScalarFunc(handle, input, numOfCols, output);
42,736✔
1335
  if (code != TSDB_CODE_SUCCESS) {
42,736!
1336
    fnError("udfc scalar function execution failure");
×
1337
    releaseUdfFuncHandle(udfName, handle);
×
1338
    return code;
×
1339
  }
1340

1341
  if (output->columnData == NULL) {
42,736!
1342
    fnError("udfc scalar function calculate error. no column data");
×
1343
    code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1344
  } else {
1345
    if (session->outputType != output->columnData->info.type || session->bytes != output->columnData->info.bytes) {
42,736!
1346
      fnError("udfc scalar function calculate error. type mismatch. session type: %d(%d), output type: %d(%d)",
×
1347
              session->outputType, session->bytes, output->columnData->info.type, output->columnData->info.bytes);
1348
      code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1349
    }
1350
  }
1351
  releaseUdfFuncHandle(udfName, handle);
42,736✔
1352
  return code;
42,736✔
1353
}
1354

1355
bool udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv) {
14,952✔
1356
  if (pFunc == NULL || pEnv == NULL) {
14,952!
1357
    fnError("udfAggGetEnv: invalid input lint: %d", __LINE__);
×
1358
    return false;
×
1359
  }
1360
  if (fmIsScalarFunc(pFunc->funcId)) {
14,952!
1361
    return false;
×
1362
  }
1363
  pEnv->calcMemSize = sizeof(SUdfAggRes) + pFunc->node.resType.bytes + pFunc->udfBufSize;
14,952✔
1364
  return true;
14,952✔
1365
}
1366

1367
int32_t udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo) {
34,136✔
1368
  TAOS_UDF_CHECK_PTR_RCODE(pCtx, pResultCellInfo);
102,408!
1369
  if (pResultCellInfo->initialized) {
34,136!
1370
    return TSDB_CODE_SUCCESS;
×
1371
  }
1372
  if (functionSetup(pCtx, pResultCellInfo) != TSDB_CODE_SUCCESS) {
34,136!
1373
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1374
  }
1375
  UdfcFuncHandle handle;
34,136✔
1376
  int32_t        udfCode = 0;
34,136✔
1377
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
34,136!
1378
    fnError("udfAggInit error. step doSetupUdf. udf code: %d", udfCode);
×
1379
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1380
  }
1381
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
34,136✔
1382
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(pResultCellInfo);
34,136✔
1383
  int32_t         envSize = sizeof(SUdfAggRes) + session->bytes + session->bufSize;
34,136✔
1384
  memset(udfRes, 0, envSize);
34,136!
1385

1386
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
34,136✔
1387
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
34,136✔
1388

1389
  SUdfInterBuf buf = {0};
34,136✔
1390
  if ((udfCode = doCallUdfAggInit(handle, &buf)) != 0) {
34,136!
1391
    fnError("udfAggInit error. step doCallUdfAggInit. udf code: %d", udfCode);
×
1392
    releaseUdfFuncHandle(pCtx->udfName, handle);
×
1393
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1394
  }
1395
  if (buf.bufLen <= session->bufSize) {
34,136!
1396
    memcpy(udfRes->interResBuf, buf.buf, buf.bufLen);
34,136!
1397
    udfRes->interResBufLen = buf.bufLen;
34,136✔
1398
    udfRes->interResNum = buf.numOfResult;
34,136✔
1399
  } else {
1400
    fnError("udfc inter buf size %d is greater than function bufSize %d", buf.bufLen, session->bufSize);
×
1401
    releaseUdfFuncHandle(pCtx->udfName, handle);
×
1402
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1403
  }
1404
  releaseUdfFuncHandle(pCtx->udfName, handle);
34,136✔
1405
  freeUdfInterBuf(&buf);
34,136✔
1406
  return TSDB_CODE_SUCCESS;
34,136✔
1407
}
1408

1409
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx) {
80,248✔
1410
  TAOS_UDF_CHECK_PTR_RCODE(pCtx);
160,496!
1411
  int32_t        udfCode = 0;
80,248✔
1412
  UdfcFuncHandle handle = 0;
80,248✔
1413
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
80,248!
1414
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
×
1415
    return udfCode;
×
1416
  }
1417

1418
  SUdfcUvSession *session = handle;
80,248✔
1419
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
80,248✔
1420
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
80,248✔
1421
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
80,248✔
1422

1423
  SInputColumnInfoData *pInput = &pCtx->input;
80,248✔
1424
  int32_t               numOfCols = pInput->numOfInputCols;
80,248✔
1425
  int32_t               start = pInput->startRowIndex;
80,248✔
1426
  int32_t               numOfRows = pInput->numOfRows;
80,248✔
1427
  SSDataBlock          *pTempBlock = NULL;
80,248✔
1428
  int32_t               code = createDataBlock(&pTempBlock);
80,248✔
1429

1430
  if (code) {
80,248!
1431
    return code;
×
1432
  }
1433

1434
  pTempBlock->info.rows = pInput->totalRows;
80,248✔
1435
  pTempBlock->info.id.uid = pInput->uid;
80,248✔
1436
  for (int32_t i = 0; i < numOfCols; ++i) {
167,880✔
1437
    if ((udfCode = blockDataAppendColInfo(pTempBlock, pInput->pData[i])) != 0) {
87,632!
1438
      fnError("udfAggProcess error. step blockDataAppendColInfo. udf code: %d", udfCode);
×
1439
      blockDataDestroy(pTempBlock);
×
1440
      return udfCode;
×
1441
    }
1442
  }
1443

1444
  SSDataBlock *inputBlock = NULL;
80,248✔
1445
  code = blockDataExtractBlock(pTempBlock, start, numOfRows, &inputBlock);
80,248✔
1446
  if (code) {
80,248!
1447
    return code;
×
1448
  }
1449

1450
  SUdfInterBuf state = {
80,248✔
1451
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
80,248✔
1452
  SUdfInterBuf newState = {0};
80,248✔
1453

1454
  udfCode = doCallUdfAggProcess(session, inputBlock, &state, &newState);
80,248✔
1455
  if (udfCode != 0) {
80,248!
1456
    fnError("udfAggProcess error. code: %d", udfCode);
×
1457
    newState.numOfResult = 0;
×
1458
  } else {
1459
    if (newState.bufLen <= session->bufSize) {
80,248!
1460
      memcpy(udfRes->interResBuf, newState.buf, newState.bufLen);
80,248!
1461
      udfRes->interResBufLen = newState.bufLen;
80,248✔
1462
      udfRes->interResNum = newState.numOfResult;
80,248✔
1463
    } else {
1464
      fnError("udfc inter buf size %d is greater than function bufSize %d", newState.bufLen, session->bufSize);
×
1465
      udfCode = TSDB_CODE_UDF_INVALID_BUFSIZE;
×
1466
    }
1467
  }
1468

1469
  GET_RES_INFO(pCtx)->numOfRes = udfRes->interResNum;
80,248✔
1470

1471
  blockDataDestroy(inputBlock);
80,248✔
1472

1473
  taosArrayDestroy(pTempBlock->pDataBlock);
80,248✔
1474
  taosMemoryFree(pTempBlock);
80,248!
1475

1476
  releaseUdfFuncHandle(pCtx->udfName, handle);
80,248✔
1477
  freeUdfInterBuf(&newState);
80,248✔
1478
  return udfCode;
80,248✔
1479
}
1480

1481
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock) {
34,136✔
1482
  TAOS_UDF_CHECK_PTR_RCODE(pCtx, pBlock);
102,408!
1483
  int32_t        udfCode = 0;
34,136✔
1484
  UdfcFuncHandle handle = 0;
34,136✔
1485
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
34,136!
1486
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
×
1487
    return udfCode;
×
1488
  }
1489

1490
  SUdfcUvSession *session = handle;
34,136✔
1491
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
34,136✔
1492
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
34,136✔
1493
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
34,136✔
1494

1495
  SUdfInterBuf resultBuf = {0};
34,136✔
1496
  SUdfInterBuf state = {
34,136✔
1497
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
34,136✔
1498
  int32_t udfCallCode = 0;
34,136✔
1499
  udfCallCode = doCallUdfAggFinalize(session, &state, &resultBuf);
34,136✔
1500
  if (udfCallCode != 0) {
34,136!
1501
    fnError("udfAggFinalize error. doCallUdfAggFinalize step. udf code:%d", udfCallCode);
×
1502
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1503
  } else {
1504
    if (resultBuf.numOfResult == 0) {
34,136!
1505
      udfRes->finalResNum = 0;
×
1506
      GET_RES_INFO(pCtx)->numOfRes = 0;
×
1507
    } else {
1508
      if (resultBuf.bufLen <= session->bytes) {
34,136!
1509
        memcpy(udfRes->finalResBuf, resultBuf.buf, resultBuf.bufLen);
34,136!
1510
        udfRes->finalResNum = resultBuf.numOfResult;
34,136✔
1511
        GET_RES_INFO(pCtx)->numOfRes = udfRes->finalResNum;
34,136✔
1512
      } else {
1513
        fnError("udfc inter buf size %d is greater than function output size %d", resultBuf.bufLen, session->bytes);
×
1514
        GET_RES_INFO(pCtx)->numOfRes = 0;
×
1515
        udfCallCode = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1516
      }
1517
    }
1518
  }
1519

1520
  freeUdfInterBuf(&resultBuf);
34,136✔
1521

1522
  int32_t numOfResults = functionFinalizeWithResultBuf(pCtx, pBlock, udfRes->finalResBuf);
34,136✔
1523
  releaseUdfFuncHandle(pCtx->udfName, handle);
34,136✔
1524
  return udfCallCode == 0 ? numOfResults : udfCallCode;
34,136!
1525
}
1526

1527
void onUdfcPipeClose(uv_handle_t *handle) {
19,900✔
1528
  SClientUvConn *conn = handle->data;
19,900✔
1529
  if (!QUEUE_EMPTY(&conn->taskQueue)) {
19,900!
1530
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
19,900✔
1531
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
19,900✔
1532
    task->errCode = 0;
19,900✔
1533
    QUEUE_REMOVE(&task->procTaskQueue);
19,900✔
1534
    uv_sem_post(&task->taskSem);
19,900✔
1535
  }
1536
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
19,900✔
1537
  if (conn->session != NULL) {
19,900✔
1538
    conn->session->udfUvPipe = NULL;
19,484✔
1539
  }
1540
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
19,900✔
1541
  taosMemoryFree(conn->readBuf.buf);
19,900!
1542
  taosMemoryFree(conn);
19,900!
1543
  taosMemoryFree((uv_pipe_t *)handle);
19,900!
1544
}
19,900✔
1545

1546
int32_t udfcGetUdfTaskResultFromUvTask(SClientUdfTask *task, SClientUvTaskNode *uvTask) {
271,208✔
1547
  int32_t code = 0;
271,208✔
1548
  fnDebug("udfc get uv task result. task: %p, uvTask: %p", task, uvTask);
271,208!
1549
  if (uvTask->type == UV_TASK_REQ_RSP) {
271,208✔
1550
    if (uvTask->rspBuf.base != NULL) {
231,232!
1551
      SUdfResponse rsp = {0};
231,232✔
1552
      void        *buf = decodeUdfResponse(uvTask->rspBuf.base, &rsp);
231,232✔
1553
      code = rsp.code;
231,232✔
1554
      if (code != 0) {
231,232!
1555
        fnError("udfc get udf task result failure. code: %d", code);
×
1556
      }
1557

1558
      switch (task->type) {
231,232!
1559
        case UDF_TASK_SETUP: {
20,076✔
1560
          task->_setup.rsp = rsp.setupRsp;
20,076✔
1561
          break;
20,076✔
1562
        }
1563
        case UDF_TASK_CALL: {
191,256✔
1564
          task->_call.rsp = rsp.callRsp;
191,256✔
1565
          break;
191,256✔
1566
        }
1567
        case UDF_TASK_TEARDOWN: {
19,900✔
1568
          task->_teardown.rsp = rsp.teardownRsp;
1569
          break;
19,900✔
1570
        }
1571
        default: {
×
1572
          break;
×
1573
        }
1574
      }
1575

1576
      // TODO: the call buffer is setup and freed by udf invocation
1577
      taosMemoryFreeClear(uvTask->rspBuf.base);
231,232!
1578
    } else {
1579
      code = uvTask->errCode;
×
1580
      if (code != 0) {
×
1581
        fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1582
      }
1583
    }
1584
  } else if (uvTask->type == UV_TASK_CONNECT) {
39,976✔
1585
    code = uvTask->errCode;
20,076✔
1586
    if (code != 0) {
20,076!
1587
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1588
    }
1589
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
19,900!
1590
    code = uvTask->errCode;
19,900✔
1591
    if (code != 0) {
19,900!
1592
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1593
    }
1594
  }
1595
  return code;
271,208✔
1596
}
1597

1598
void udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
693,696✔
1599
  SClientUvConn  *conn = handle->data;
693,696✔
1600
  SClientConnBuf *connBuf = &conn->readBuf;
693,696✔
1601

1602
  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
693,696✔
1603
  if (connBuf->cap == 0) {
693,696✔
1604
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
251,308!
1605
    if (connBuf->buf) {
251,308!
1606
      connBuf->len = 0;
251,308✔
1607
      connBuf->cap = msgHeadSize;
251,308✔
1608
      connBuf->total = -1;
251,308✔
1609

1610
      buf->base = connBuf->buf;
251,308✔
1611
      buf->len = connBuf->cap;
251,308✔
1612
    } else {
1613
      fnError("udfc allocate buffer failure. size: %d", msgHeadSize);
×
1614
      buf->base = NULL;
×
1615
      buf->len = 0;
×
1616
    }
1617
  } else if (connBuf->total == -1 && connBuf->len < msgHeadSize) {
442,388!
1618
    buf->base = connBuf->buf + connBuf->len;
211,156✔
1619
    buf->len = msgHeadSize - connBuf->len;
211,156✔
1620
  } else {
1621
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
231,232✔
1622
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
231,232!
1623
    if (resultBuf) {
231,232!
1624
      connBuf->buf = resultBuf;
231,232✔
1625
      buf->base = connBuf->buf + connBuf->len;
231,232✔
1626
      buf->len = connBuf->cap - connBuf->len;
231,232✔
1627
    } else {
1628
      fnError("udfc re-allocate buffer failure. size: %d", connBuf->cap);
×
1629
      buf->base = NULL;
×
1630
      buf->len = 0;
×
1631
    }
1632
  }
1633

1634
  fnDebug("udfc uv alloc buffer: cap - len - total : %d - %d - %d", connBuf->cap, connBuf->len, connBuf->total);
693,696!
1635
}
693,696✔
1636

1637
bool isUdfcUvMsgComplete(SClientConnBuf *connBuf) {
462,464✔
1638
  if (connBuf->total == -1 && connBuf->len >= sizeof(int32_t)) {
462,464!
1639
    connBuf->total = *(int32_t *)(connBuf->buf);
231,232✔
1640
  }
1641
  if (connBuf->len == connBuf->cap && connBuf->total == connBuf->cap) {
462,464!
1642
    fnDebug("udfc complete message is received, now handle it");
231,232!
1643
    return true;
231,232✔
1644
  }
1645
  return false;
231,232✔
1646
}
1647

1648
void udfcUvHandleRsp(SClientUvConn *conn) {
231,232✔
1649
  SClientConnBuf *connBuf = &conn->readBuf;
231,232✔
1650
  int64_t         seqNum = *(int64_t *)(connBuf->buf + sizeof(int32_t));  // msglen then seqnum
231,232✔
1651

1652
  if (QUEUE_EMPTY(&conn->taskQueue)) {
231,232!
1653
    fnError("udfc no task waiting on connection. response seqnum:%" PRId64, seqNum);
×
1654
    return;
×
1655
  }
1656
  bool               found = false;
231,232✔
1657
  SClientUvTaskNode *taskFound = NULL;
231,232✔
1658
  QUEUE             *h = QUEUE_NEXT(&conn->taskQueue);
231,232✔
1659
  SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
231,232✔
1660

1661
  while (h != &conn->taskQueue) {
462,464✔
1662
    fnDebug("udfc handle response iterate through queue. uvTask:%" PRId64 "-%p", task->seqNum, task);
231,232!
1663
    if (task->seqNum == seqNum) {
231,232!
1664
      if (found == false) {
231,232!
1665
        found = true;
231,232✔
1666
        taskFound = task;
231,232✔
1667
      } else {
1668
        fnError("udfc more than one task waiting for the same response");
×
1669
        continue;
×
1670
      }
1671
    }
1672
    h = QUEUE_NEXT(h);
231,232✔
1673
    task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
231,232✔
1674
  }
1675

1676
  if (taskFound) {
231,232!
1677
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
231,232✔
1678
    QUEUE_REMOVE(&taskFound->connTaskQueue);
231,232✔
1679
    QUEUE_REMOVE(&taskFound->procTaskQueue);
231,232✔
1680
    uv_sem_post(&taskFound->taskSem);
231,232✔
1681
  } else {
1682
    fnError("no task is waiting for the response.");
×
1683
  }
1684
  connBuf->buf = NULL;
231,232✔
1685
  connBuf->total = -1;
231,232✔
1686
  connBuf->len = 0;
231,232✔
1687
  connBuf->cap = 0;
231,232✔
1688
}
1689

1690
void udfcUvHandleError(SClientUvConn *conn) {
×
1691
  fnDebug("handle error on conn: %p, pipe: %p", conn, conn->pipe);
×
1692
  while (!QUEUE_EMPTY(&conn->taskQueue)) {
×
1693
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
×
1694
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
×
1695
    task->errCode = TSDB_CODE_UDF_PIPE_READ_ERR;
×
1696
    QUEUE_REMOVE(&task->connTaskQueue);
×
1697
    QUEUE_REMOVE(&task->procTaskQueue);
×
1698
    uv_sem_post(&task->taskSem);
×
1699
  }
1700
  if (!uv_is_closing((uv_handle_t *)conn->pipe)) {
×
1701
    uv_close((uv_handle_t *)conn->pipe, onUdfcPipeClose);
×
1702
  }
1703
}
×
1704

1705
void onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
693,696✔
1706
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
693,696!
1707
  if (nread == 0) return;
693,696✔
1708

1709
  SClientUvConn  *conn = client->data;
462,464✔
1710
  SClientConnBuf *connBuf = &conn->readBuf;
462,464✔
1711
  if (nread > 0) {
462,464!
1712
    connBuf->len += nread;
462,464✔
1713
    if (isUdfcUvMsgComplete(connBuf)) {
462,464✔
1714
      udfcUvHandleRsp(conn);
231,232✔
1715
    }
1716
  }
1717
  if (nread < 0) {
462,464!
1718
    fnError("udfc client pipe %p read error: %zd(%s).", client, nread, uv_strerror(nread));
×
1719
    if (nread == UV_EOF) {
×
1720
      fnError("\tudfc client pipe %p closed", client);
×
1721
    }
1722
    udfcUvHandleError(conn);
×
1723
  }
1724
}
1725

1726
void onUdfcPipeWrite(uv_write_t *write, int32_t status) {
231,232✔
1727
  SClientUvConn *conn = write->data;
231,232✔
1728
  if (status < 0) {
231,232!
1729
    fnError("udfc client connection %p write failed. status: %d(%s)", conn, status, uv_strerror(status));
×
1730
    udfcUvHandleError(conn);
×
1731
  } else {
1732
    fnDebug("udfc client connection %p write succeed", conn);
231,232!
1733
  }
1734
  taosMemoryFree(write);
231,232!
1735
}
231,232✔
1736

1737
void onUdfcPipeConnect(uv_connect_t *connect, int32_t status) {
20,076✔
1738
  SClientUvTaskNode *uvTask = connect->data;
20,076✔
1739
  if (status != 0) {
20,076!
1740
    fnError("client connect error, task seq: %" PRId64 ", code:%s", uvTask->seqNum, uv_strerror(status));
×
1741
  }
1742
  uvTask->errCode = status;
20,076✔
1743

1744
  int32_t code = uv_read_start((uv_stream_t *)uvTask->pipe, udfcAllocateBuffer, onUdfcPipeRead);
20,076✔
1745
  if (code != 0) {
20,076!
1746
    fnError("udfc client connection %p read start failed. code: %d(%s)", uvTask->pipe, code, uv_strerror(code));
×
1747
    uvTask->errCode = code;
×
1748
  }
1749
  taosMemoryFree(connect);
20,076!
1750
  QUEUE_REMOVE(&uvTask->procTaskQueue);
20,076✔
1751
  uv_sem_post(&uvTask->taskSem);
20,076✔
1752
}
20,076✔
1753

1754
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask) {
271,032✔
1755
  uvTask->type = uvTaskType;
271,032✔
1756
  uvTask->udfc = task->session->udfc;
271,032✔
1757

1758
  if (uvTaskType == UV_TASK_CONNECT) {
271,208✔
1759
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
251,132✔
1760
    uvTask->pipe = task->session->udfUvPipe;
231,232✔
1761
    SUdfRequest request;
231,056✔
1762
    request.type = task->type;
231,056✔
1763
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
231,056✔
1764

1765
    if (task->type == UDF_TASK_SETUP) {
231,232✔
1766
      request.setup = task->_setup.req;
20,076✔
1767
      request.type = UDF_TASK_SETUP;
19,900✔
1768
    } else if (task->type == UDF_TASK_CALL) {
211,156✔
1769
      request.call = task->_call.req;
191,256✔
1770
      request.type = UDF_TASK_CALL;
191,256✔
1771
    } else if (task->type == UDF_TASK_TEARDOWN) {
19,900!
1772
      request.teardown = task->_teardown.req;
19,900✔
1773
      request.type = UDF_TASK_TEARDOWN;
19,900✔
1774
    } else {
1775
      fnError("udfc create uv task, invalid task type : %d", task->type);
×
1776
    }
1777
    int32_t bufLen = encodeUdfRequest(NULL, &request);
231,056✔
1778
    if (bufLen <= 0) {
231,056!
1779
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1780
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1781
    }
1782
    request.msgLen = bufLen;
231,056✔
1783
    void *bufBegin = taosMemoryMalloc(bufLen);
231,056!
1784
    if (bufBegin == NULL) {
231,056!
1785
      fnError("udfc create uv task, malloc buffer failed. size: %d", bufLen);
×
1786
      return terrno;
×
1787
    }
1788
    void *buf = bufBegin;
231,056✔
1789
    if (encodeUdfRequest(&buf, &request) <= 0) {
231,056!
1790
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1791
      taosMemoryFree(bufBegin);
×
1792
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1793
    }
1794

1795
    uvTask->reqBuf = uv_buf_init(bufBegin, bufLen);
231,056✔
1796
    uvTask->seqNum = request.seqNum;
231,056✔
1797
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
19,900!
1798
    uvTask->pipe = task->session->udfUvPipe;
19,900✔
1799
  }
1800
  if (uv_sem_init(&uvTask->taskSem, 0) != 0) {
271,032!
1801
    if (uvTaskType == UV_TASK_REQ_RSP) {
×
1802
      taosMemoryFreeClear(uvTask->reqBuf.base);
×
1803
    }
1804
    fnError("udfc create uv task, init semaphore failed.");
×
1805
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1806
  }
1807

1808
  return 0;
271,032✔
1809
}
1810

1811
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask) {
271,032✔
1812
  fnDebug("queue uv task to event loop, uvTask: %d-%p", uvTask->type, uvTask);
271,032!
1813
  SUdfcProxy *udfc = uvTask->udfc;
271,032✔
1814
  uv_mutex_lock(&udfc->taskQueueMutex);
271,032✔
1815
  QUEUE_INSERT_TAIL(&udfc->taskQueue, &uvTask->recvTaskQueue);
271,208✔
1816
  uv_mutex_unlock(&udfc->taskQueueMutex);
271,208✔
1817
  int32_t code = uv_async_send(&udfc->loopTaskAync);
271,208✔
1818
  if (code != 0) {
271,208!
1819
    fnError("udfc queue uv task to event loop failed. code:%s", uv_strerror(code));
×
1820
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1821
  }
1822

1823
  uv_sem_wait(&uvTask->taskSem);
271,208✔
1824
  fnDebug("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
271,208!
1825
  uv_sem_destroy(&uvTask->taskSem);
271,208✔
1826

1827
  return 0;
271,208✔
1828
}
1829

1830
int32_t udfcStartUvTask(SClientUvTaskNode *uvTask) {
271,208✔
1831
  fnDebug("event loop start uv task. uvTask: %" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
271,208!
1832
  int32_t code = 0;
271,208✔
1833

1834
  switch (uvTask->type) {
271,208!
1835
    case UV_TASK_CONNECT: {
20,076✔
1836
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
20,076!
1837
      if (pipe == NULL) {
20,076!
1838
        fnError("udfc event loop start connect task malloc pipe failed.");
×
1839
        return terrno;
×
1840
      }
1841
      if (uv_pipe_init(&uvTask->udfc->uvLoop, pipe, 0) != 0) {
20,076!
1842
        fnError("udfc event loop start connect task uv_pipe_init failed.");
×
1843
        taosMemoryFree(pipe);
×
1844
        return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1845
      }
1846
      uvTask->pipe = pipe;
20,076✔
1847

1848
      SClientUvConn *conn = taosMemoryCalloc(1, sizeof(SClientUvConn));
20,076!
1849
      if (conn == NULL) {
20,076!
1850
        fnError("udfc event loop start connect task malloc conn failed.");
×
1851
        taosMemoryFree(pipe);
×
1852
        return terrno;
×
1853
      }
1854
      conn->pipe = pipe;
20,076✔
1855
      conn->readBuf.len = 0;
20,076✔
1856
      conn->readBuf.cap = 0;
20,076✔
1857
      conn->readBuf.buf = 0;
20,076✔
1858
      conn->readBuf.total = -1;
20,076✔
1859
      QUEUE_INIT(&conn->taskQueue);
20,076✔
1860

1861
      pipe->data = conn;
20,076✔
1862

1863
      uv_connect_t *connReq = taosMemoryMalloc(sizeof(uv_connect_t));
20,076!
1864
      if (connReq == NULL) {
20,076!
1865
        fnError("udfc event loop start connect task malloc connReq failed.");
×
1866
        taosMemoryFree(pipe);
×
1867
        taosMemoryFree(conn);
×
1868
        return terrno;
×
1869
      }
1870
      connReq->data = uvTask;
20,076✔
1871
      uv_pipe_connect(connReq, pipe, uvTask->udfc->udfdPipeName, onUdfcPipeConnect);
20,076✔
1872
      code = 0;
20,076✔
1873
      break;
20,076✔
1874
    }
1875
    case UV_TASK_REQ_RSP: {
231,232✔
1876
      uv_pipe_t *pipe = uvTask->pipe;
231,232✔
1877
      if (pipe == NULL) {
231,232!
1878
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1879
      } else {
1880
        uv_write_t *write = taosMemoryMalloc(sizeof(uv_write_t));
231,232!
1881
        if (write == NULL) {
231,232!
1882
          fnError("udfc event loop start req_rsp task malloc write failed.");
×
1883
          return terrno;
×
1884
        }
1885
        write->data = pipe->data;
231,232✔
1886
        QUEUE *connTaskQueue = &((SClientUvConn *)pipe->data)->taskQueue;
231,232✔
1887
        QUEUE_INSERT_TAIL(connTaskQueue, &uvTask->connTaskQueue);
231,232✔
1888
        int32_t err = uv_write(write, (uv_stream_t *)pipe, &uvTask->reqBuf, 1, onUdfcPipeWrite);
231,232✔
1889
        if (err != 0) {
231,232!
1890
          taosMemoryFree(write);
×
1891
          fnError("udfc event loop start req_rsp task uv_write failed. uvtask: %p, code:%s", uvTask, uv_strerror(err));
×
1892
        }
1893
        code = err;
231,232✔
1894
      }
1895
      break;
231,232✔
1896
    }
1897
    case UV_TASK_DISCONNECT: {
19,900✔
1898
      uv_pipe_t *pipe = uvTask->pipe;
19,900✔
1899
      if (pipe == NULL) {
19,900!
1900
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1901
      } else {
1902
        SClientUvConn *conn = pipe->data;
19,900✔
1903
        QUEUE_INSERT_TAIL(&conn->taskQueue, &uvTask->connTaskQueue);
19,900✔
1904
        if (!uv_is_closing((uv_handle_t *)uvTask->pipe)) {
19,900!
1905
          uv_close((uv_handle_t *)uvTask->pipe, onUdfcPipeClose);
19,900✔
1906
        }
1907
        code = 0;
19,900✔
1908
      }
1909
      break;
19,900✔
1910
    }
1911
    default: {
×
1912
      fnError("udfc event loop unknown task type.") break;
×
1913
    }
1914
  }
1915

1916
  return code;
271,208✔
1917
}
1918

1919
void udfcAsyncTaskCb(uv_async_t *async) {
271,032✔
1920
  SUdfcProxy *udfc = async->data;
271,032✔
1921
  QUEUE       wq;
271,032✔
1922

1923
  uv_mutex_lock(&udfc->taskQueueMutex);
271,032✔
1924
  QUEUE_MOVE(&udfc->taskQueue, &wq);
271,032!
1925
  uv_mutex_unlock(&udfc->taskQueueMutex);
271,032✔
1926

1927
  while (!QUEUE_EMPTY(&wq)) {
542,240✔
1928
    QUEUE *h = QUEUE_HEAD(&wq);
271,208✔
1929
    QUEUE_REMOVE(h);
271,208✔
1930
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
271,208✔
1931
    int32_t            code = udfcStartUvTask(task);
271,208✔
1932
    if (code == 0) {
271,208!
1933
      QUEUE_INSERT_TAIL(&udfc->uvProcTaskQueue, &task->procTaskQueue);
271,208✔
1934
    } else {
1935
      task->errCode = code;
×
1936
      uv_sem_post(&task->taskSem);
×
1937
    }
1938
  }
1939
}
271,032✔
1940

1941
void cleanUpUvTasks(SUdfcProxy *udfc) {
762,897✔
1942
  fnDebug("clean up uv tasks") QUEUE wq;
762,897✔
1943

1944
  uv_mutex_lock(&udfc->taskQueueMutex);
762,897✔
1945
  QUEUE_MOVE(&udfc->taskQueue, &wq);
762,897!
1946
  uv_mutex_unlock(&udfc->taskQueueMutex);
762,897✔
1947

1948
  while (!QUEUE_EMPTY(&wq)) {
762,897!
1949
    QUEUE *h = QUEUE_HEAD(&wq);
×
1950
    QUEUE_REMOVE(h);
×
1951
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
×
1952
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
×
1953
      task->errCode = TSDB_CODE_UDF_STOPPING;
×
1954
    }
1955
    uv_sem_post(&task->taskSem);
×
1956
  }
1957

1958
  while (!QUEUE_EMPTY(&udfc->uvProcTaskQueue)) {
762,897!
1959
    QUEUE *h = QUEUE_HEAD(&udfc->uvProcTaskQueue);
×
1960
    QUEUE_REMOVE(h);
×
1961
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, procTaskQueue);
×
1962
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
×
1963
      task->errCode = TSDB_CODE_UDF_STOPPING;
×
1964
    }
1965
    uv_sem_post(&task->taskSem);
×
1966
  }
1967
}
762,897✔
1968

1969
void udfStopAsyncCb(uv_async_t *async) {
762,897✔
1970
  SUdfcProxy *udfc = async->data;
762,897✔
1971
  cleanUpUvTasks(udfc);
762,897✔
1972
  if (udfc->udfcState == UDFC_STATE_STOPPING) {
762,897!
1973
    uv_stop(&udfc->uvLoop);
762,897✔
1974
  }
1975
}
762,897✔
1976

1977
void constructUdfService(void *argsThread) {
762,897✔
1978
  int32_t     code = 0, lino = 0;
762,897✔
1979
  SUdfcProxy *udfc = (SUdfcProxy *)argsThread;
762,897✔
1980
  code = uv_loop_init(&udfc->uvLoop);
762,897✔
1981
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
1982

1983
  code = uv_async_init(&udfc->uvLoop, &udfc->loopTaskAync, udfcAsyncTaskCb);
762,897✔
1984
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
1985
  udfc->loopTaskAync.data = udfc;
762,897✔
1986
  code = uv_async_init(&udfc->uvLoop, &udfc->loopStopAsync, udfStopAsyncCb);
762,897✔
1987
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
1988
  udfc->loopStopAsync.data = udfc;
762,897✔
1989
  code = uv_mutex_init(&udfc->taskQueueMutex);
762,897✔
1990
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
1991
  QUEUE_INIT(&udfc->taskQueue);
762,897✔
1992
  QUEUE_INIT(&udfc->uvProcTaskQueue);
762,897✔
1993
  (void)uv_barrier_wait(&udfc->initBarrier);
762,897✔
1994
  // TODO return value of uv_run
1995
  int32_t num = uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
762,897✔
1996
  fnInfo("udfc uv loop exit. active handle num: %d", num);
762,897!
1997
  (void)uv_loop_close(&udfc->uvLoop);
762,897✔
1998

1999
  uv_walk(&udfc->uvLoop, udfUdfdCloseWalkCb, NULL);
762,897✔
2000
  num = uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
762,897✔
2001
  fnInfo("udfc uv loop exit. active handle num: %d", num);
762,897!
2002

2003
  (void)uv_loop_close(&udfc->uvLoop);
762,897✔
2004
_exit:
762,897✔
2005
  if (code != 0) {
762,897!
2006
    fnError("udfc construct error. code: %d, line: %d", code, lino);
×
2007
  }
2008
  fnInfo("udfc construct finished");
762,897!
2009
}
762,897✔
2010

2011
int32_t udfcOpen() {
901,733✔
2012
  int32_t code = 0, lino = 0;
901,733✔
2013
  int8_t  old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 0, 1);
901,733✔
2014
  if (old == 1) {
901,733✔
2015
    return 0;
138,836✔
2016
  }
2017
  SUdfcProxy *proxy = &gUdfcProxy;
762,897✔
2018
  getUdfdPipeName(proxy->udfdPipeName, sizeof(proxy->udfdPipeName));
762,897✔
2019
  proxy->udfcState = UDFC_STATE_STARTNG;
762,897✔
2020
  code = uv_barrier_init(&proxy->initBarrier, 2);
762,897✔
2021
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
2022
  code = uv_thread_create(&proxy->loopThread, constructUdfService, proxy);
762,897✔
2023
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
2024
  atomic_store_8(&proxy->udfcState, UDFC_STATE_READY);
762,897✔
2025
  proxy->udfcState = UDFC_STATE_READY;
762,897✔
2026
  (void)uv_barrier_wait(&proxy->initBarrier);
762,897✔
2027
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
2028
  code = uv_mutex_init(&proxy->udfStubsMutex);
762,897✔
2029
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
2030
  proxy->udfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
762,897✔
2031
  if (proxy->udfStubs == NULL) {
762,897!
2032
    fnError("udfc init failed. udfStubs: %p", proxy->udfStubs);
×
2033
    return -1;
×
2034
  }
2035
  proxy->expiredUdfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
762,897✔
2036
  if (proxy->expiredUdfStubs == NULL) {
762,897!
2037
    taosArrayDestroy(proxy->udfStubs);
×
2038
    fnError("udfc init failed. expiredUdfStubs: %p", proxy->expiredUdfStubs);
×
2039
    return -1;
×
2040
  }
2041
  code = uv_mutex_init(&proxy->udfcUvMutex);
762,897✔
2042
  TAOS_CHECK_GOTO(code, &lino, _exit);
762,897!
2043
_exit:
762,897✔
2044
  if (code != 0) {
762,897!
2045
    fnError("udfc open error. code: %d, line: %d", code, lino);
×
2046
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
2047
  }
2048
  fnInfo("udfc initialized");
762,897!
2049
  return 0;
762,897✔
2050
}
2051

2052
int32_t udfcClose() {
764,381✔
2053
  int8_t old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 1, 0);
764,381✔
2054
  if (old == 0) {
764,381✔
2055
    return 0;
1,484✔
2056
  }
2057

2058
  SUdfcProxy *udfc = &gUdfcProxy;
762,897✔
2059
  udfc->udfcState = UDFC_STATE_STOPPING;
762,897✔
2060
  if (uv_async_send(&udfc->loopStopAsync) != 0) {
762,897!
2061
    fnError("udfc close error to send stop async");
×
2062
  }
2063
  if (uv_thread_join(&udfc->loopThread) != 0) {
762,897!
2064
    fnError("udfc close errir to join loop thread");
×
2065
  }
2066
  uv_mutex_destroy(&udfc->taskQueueMutex);
762,897✔
2067
  uv_barrier_destroy(&udfc->initBarrier);
762,897✔
2068
  taosArrayDestroy(udfc->expiredUdfStubs);
762,897✔
2069
  taosArrayDestroy(udfc->udfStubs);
762,897✔
2070
  uv_mutex_destroy(&udfc->udfStubsMutex);
762,897✔
2071
  uv_mutex_destroy(&udfc->udfcUvMutex);
762,897✔
2072
  udfc->udfcState = UDFC_STATE_INITAL;
762,897✔
2073
  fnInfo("udfc is cleaned up");
762,897!
2074
  return 0;
762,897✔
2075
}
2076

2077
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType) {
271,032✔
2078
  int32_t            code = 0, lino = 0;
271,032✔
2079
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
271,032!
2080
  if (uvTask == NULL) {
271,032!
2081
    fnError("udfc client task: %p failed to allocate memory for uvTask", task);
×
2082
    return terrno;
×
2083
  }
2084
  fnDebug("udfc client task: %p created uvTask: %p. pipe: %p", task, uvTask, task->session->udfUvPipe);
271,032!
2085

2086
  code = udfcInitializeUvTask(task, uvTaskType, uvTask);
271,032✔
2087
  TAOS_CHECK_GOTO(code, &lino, _exit);
271,208!
2088
  code = udfcQueueUvTask(uvTask);
271,208✔
2089
  TAOS_CHECK_GOTO(code, &lino, _exit);
271,208!
2090
  code = udfcGetUdfTaskResultFromUvTask(task, uvTask);
271,208✔
2091
  TAOS_CHECK_GOTO(code, &lino, _exit);
271,208!
2092
  if (uvTaskType == UV_TASK_CONNECT) {
271,208✔
2093
    task->session->udfUvPipe = uvTask->pipe;
20,076✔
2094
    SClientUvConn *conn = uvTask->pipe->data;
20,076✔
2095
    conn->session = task->session;
20,076✔
2096
  }
2097

2098
_exit:
271,208✔
2099
  if (code != 0) {
271,208!
2100
    fnError("udfc run udf uv task failure. task: %p, uvTask: %p, err: %d, line: %d", task, uvTask, code, lino);
×
2101
  }
2102
  taosMemoryFree(uvTask->reqBuf.base);
271,208!
2103
  uvTask->reqBuf.base = NULL;
271,032✔
2104
  taosMemoryFree(uvTask);
271,032!
2105
  uvTask = NULL;
271,208✔
2106
  return code;
271,208✔
2107
}
2108

2109
static void freeTaskSession(SClientUdfTask *task) {
19,900✔
2110
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
19,900✔
2111
  if (task->session->udfUvPipe != NULL && task->session->udfUvPipe->data != NULL) {
19,900!
2112
    SClientUvConn *conn = task->session->udfUvPipe->data;
416✔
2113
    conn->session = NULL;
416✔
2114
  }
2115
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
19,900✔
2116
  taosMemoryFreeClear(task->session);
19,900!
2117
}
19,900✔
2118

2119
int32_t doSetupUdf(char udfName[], UdfcFuncHandle *funcHandle) {
20,076✔
2120
  int32_t         code = TSDB_CODE_SUCCESS, lino = 0;
20,076✔
2121
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
20,076!
2122
  if (task == NULL) {
20,076!
2123
    fnError("doSetupUdf, failed to allocate memory for task");
×
2124
    return terrno;
×
2125
  }
2126
  task->session = taosMemoryCalloc(1, sizeof(SUdfcUvSession));
20,076!
2127
  if (task->session == NULL) {
20,076!
2128
    fnError("doSetupUdf, failed to allocate memory for session");
×
2129
    taosMemoryFree(task);
×
2130
    return terrno;
×
2131
  }
2132
  task->session->udfc = &gUdfcProxy;
20,076✔
2133
  task->type = UDF_TASK_SETUP;
20,076✔
2134

2135
  SUdfSetupRequest *req = &task->_setup.req;
20,076✔
2136
  tstrncpy(req->udfName, udfName, TSDB_FUNC_NAME_LEN);
20,076!
2137

2138
  code = udfcRunUdfUvTask(task, UV_TASK_CONNECT);
20,076✔
2139
  TAOS_CHECK_GOTO(code, &lino, _exit);
19,900!
2140

2141
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
19,900✔
2142
  TAOS_CHECK_GOTO(code, &lino, _exit);
20,076!
2143

2144
  SUdfSetupResponse *rsp = &task->_setup.rsp;
20,076✔
2145
  task->session->severHandle = rsp->udfHandle;
20,076✔
2146
  task->session->outputType = rsp->outputType;
20,076✔
2147
  task->session->bytes = rsp->bytes;
20,076✔
2148
  task->session->bufSize = rsp->bufSize;
20,076✔
2149
  tstrncpy(task->session->udfName, udfName, TSDB_FUNC_NAME_LEN);
20,076!
2150
  fnInfo("successfully setup udf func handle. udfName: %s, handle: %p", udfName, task->session);
20,076!
2151
  *funcHandle = task->session;
20,076✔
2152
  taosMemoryFree(task);
20,076!
2153
  return 0;
20,076✔
2154

2155
_exit:
×
2156
  if (code != 0) {
×
2157
    fnError("failed to setup udf. udfname: %s, err: %d line:%d", udfName, code, lino);
×
2158
  }
2159
  freeTaskSession(task);
×
2160
  taosMemoryFree(task);
×
2161
  return code;
×
2162
}
2163

2164
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
191,256✔
2165
                SSDataBlock *output, SUdfInterBuf *newState) {
2166
  fnDebug("udfc call udf. callType: %d, funcHandle: %p", callType, handle);
191,256!
2167
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
191,256✔
2168
  if (session->udfUvPipe == NULL) {
191,256!
2169
    fnError("No pipe to udfd");
×
2170
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2171
  }
2172
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
191,256!
2173
  if (task == NULL) {
191,256!
2174
    fnError("udfc call udf. failed to allocate memory for task");
×
2175
    return terrno;
×
2176
  }
2177
  task->session = (SUdfcUvSession *)handle;
191,256✔
2178
  task->type = UDF_TASK_CALL;
191,256✔
2179

2180
  SUdfCallRequest *req = &task->_call.req;
191,256✔
2181
  req->udfHandle = task->session->severHandle;
191,256✔
2182
  req->callType = callType;
191,256✔
2183

2184
  switch (callType) {
191,256!
2185
    case TSDB_UDF_CALL_AGG_INIT: {
34,136✔
2186
      req->initFirst = 1;
34,136✔
2187
      break;
34,136✔
2188
    }
2189
    case TSDB_UDF_CALL_AGG_PROC: {
80,248✔
2190
      req->block = *input;
80,248✔
2191
      req->interBuf = *state;
80,248✔
2192
      break;
80,248✔
2193
    }
2194
    // case TSDB_UDF_CALL_AGG_MERGE: {
2195
    //   req->interBuf = *state;
2196
    //   req->interBuf2 = *state2;
2197
    //   break;
2198
    // }
2199
    case TSDB_UDF_CALL_AGG_FIN: {
34,136✔
2200
      req->interBuf = *state;
34,136✔
2201
      break;
34,136✔
2202
    }
2203
    case TSDB_UDF_CALL_SCALA_PROC: {
42,736✔
2204
      req->block = *input;
42,736✔
2205
      break;
42,736✔
2206
    }
2207
  }
2208

2209
  int32_t code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
191,256✔
2210
  if (code != 0) {
191,256!
2211
    fnError("call udf failure. udfcRunUdfUvTask err: %d", code);
×
2212
  } else {
2213
    SUdfCallResponse *rsp = &task->_call.rsp;
191,256✔
2214
    switch (callType) {
191,256!
2215
      case TSDB_UDF_CALL_AGG_INIT: {
34,136✔
2216
        *newState = rsp->resultBuf;
34,136✔
2217
        break;
34,136✔
2218
      }
2219
      case TSDB_UDF_CALL_AGG_PROC: {
80,248✔
2220
        *newState = rsp->resultBuf;
80,248✔
2221
        break;
80,248✔
2222
      }
2223
      // case TSDB_UDF_CALL_AGG_MERGE: {
2224
      //   *newState = rsp->resultBuf;
2225
      //   break;
2226
      // }
2227
      case TSDB_UDF_CALL_AGG_FIN: {
34,136✔
2228
        *newState = rsp->resultBuf;
34,136✔
2229
        break;
34,136✔
2230
      }
2231
      case TSDB_UDF_CALL_SCALA_PROC: {
42,736✔
2232
        *output = rsp->resultData;
42,736✔
2233
        break;
42,736✔
2234
      }
2235
    }
2236
  }
2237
  taosMemoryFree(task);
191,256!
2238
  return code;
191,256✔
2239
}
2240

2241
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf) {
34,136✔
2242
  int8_t callType = TSDB_UDF_CALL_AGG_INIT;
34,136✔
2243

2244
  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);
34,136✔
2245

2246
  return err;
34,136✔
2247
}
2248

2249
// input: block, state
2250
// output: interbuf,
2251
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
80,248✔
2252
  int8_t  callType = TSDB_UDF_CALL_AGG_PROC;
80,248✔
2253
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
80,248✔
2254
  return err;
80,248✔
2255
}
2256

2257
// input: interbuf1, interbuf2
2258
// output: resultBuf
2259
// udf todo:  aggmerge
2260
// int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
2261
//                           SUdfInterBuf *resultBuf) {
2262
//   int8_t  callType = TSDB_UDF_CALL_AGG_MERGE;
2263
//   int32_t err = callUdf(handle, callType, NULL, interBuf1, interBuf2, NULL, resultBuf);
2264
//   return err;
2265
// }
2266

2267
// input: interBuf
2268
// output: resultData
2269
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData) {
34,136✔
2270
  int8_t  callType = TSDB_UDF_CALL_AGG_FIN;
34,136✔
2271
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
34,136✔
2272
  return err;
34,136✔
2273
}
2274

2275
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
42,736✔
2276
  int8_t      callType = TSDB_UDF_CALL_SCALA_PROC;
42,736✔
2277
  SSDataBlock inputBlock = {0};
42,736✔
2278
  int32_t     code = convertScalarParamToDataBlock(input, numOfCols, &inputBlock);
42,736✔
2279
  if (code != 0) {
42,736!
2280
    fnError("doCallUdfScalarFunc, convertScalarParamToDataBlock failed. code: %d", code);
×
2281
    return code;
×
2282
  }
2283
  SSDataBlock resultBlock = {0};
42,736✔
2284
  int32_t     err = callUdf(handle, callType, &inputBlock, NULL, NULL, &resultBlock, NULL);
42,736✔
2285
  if (err == 0) {
42,736!
2286
    err = convertDataBlockToScalarParm(&resultBlock, output);
42,736✔
2287
    taosArrayDestroy(resultBlock.pDataBlock);
42,736✔
2288
  }
2289

2290
  blockDataFreeRes(&inputBlock);
42,736✔
2291
  return err;
42,736✔
2292
}
2293

2294
int32_t doTeardownUdf(UdfcFuncHandle handle) {
19,900✔
2295
  int32_t         code = TSDB_CODE_SUCCESS, lino = 0;
19,900✔
2296
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
19,900✔
2297

2298
  if (session->udfUvPipe == NULL) {
19,900!
2299
    fnError("tear down udf. pipe to udfd does not exist. udf name: %s", session->udfName);
×
2300
    taosMemoryFree(session);
×
2301
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2302
  }
2303

2304
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
19,900!
2305
  if (task == NULL) {
19,900!
2306
    fnError("doTeardownUdf, failed to allocate memory for task");
×
2307
    taosMemoryFree(session);
×
2308
    return terrno;
×
2309
  }
2310
  task->session = session;
19,900✔
2311
  task->type = UDF_TASK_TEARDOWN;
19,900✔
2312

2313
  SUdfTeardownRequest *req = &task->_teardown.req;
19,900✔
2314
  req->udfHandle = task->session->severHandle;
19,900✔
2315

2316
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
19,900✔
2317
  TAOS_CHECK_GOTO(code, &lino, _exit);
19,900!
2318

2319
  code = udfcRunUdfUvTask(task, UV_TASK_DISCONNECT);
19,900✔
2320
  TAOS_CHECK_GOTO(code, &lino, _exit);
19,900!
2321

2322
  fnInfo("tear down udf. udf name: %s, udf func handle: %p", session->udfName, handle);
19,900!
2323
  // TODO: synchronization refactor between libuv event loop and request thread
2324
  // uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
2325
  // if (session->udfUvPipe != NULL && session->udfUvPipe->data != NULL) {
2326
  //   SClientUvConn *conn = session->udfUvPipe->data;
2327
  //   conn->session = NULL;
2328
  // }
2329
  // uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
2330

2331
_exit:
19,900✔
2332
  if (code != 0) {
19,900!
2333
    fnError("failed to teardown udf. udf name: %s, err: %d, line: %d", session->udfName, code, lino);
×
2334
  }
2335
  freeTaskSession(task);
19,900✔
2336
  taosMemoryFree(task);
19,900!
2337

2338
  return code;
19,900✔
2339
}
2340
#else
2341
#include "tudf.h"
2342

2343
int32_t cleanUpUdfs() { return 0; }
2344
int32_t udfcOpen() { return 0; }
2345
int32_t udfcClose() { return 0; }
2346
int32_t udfStartUdfd(int32_t startDnodeId) { return 0; }
2347
void    udfStopUdfd() { return; }
2348
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
2349
  return TSDB_CODE_OPS_NOT_SUPPORT;
2350
}
2351
#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