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

taosdata / TDengine / #5053

13 May 2026 12:00PM UTC coverage: 73.397% (+0.06%) from 73.338%
#5053

push

travis-ci

web-flow
feat: taosdump support stream backup/restore (#35326)

139 of 170 new or added lines in 3 files covered. (81.76%)

627 existing lines in 131 files now uncovered.

281694 of 383795 relevant lines covered (73.4%)

132505311.38 hits per line

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

80.06
/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

65
void udfUdfdExit(uv_process_t *process, int64_t exitStatus, int32_t termSignal) {
×
66
  TAOS_UDF_CHECK_PTR_RVOID(process);
×
67
  fnInfo("udfd process exited with status %" PRId64 ", signal %d", exitStatus, termSignal);
×
68
  SUdfdData *pData = process->data;
×
69
  if (pData == NULL) {
×
70
    fnError("udfd process data is NULL");
×
71
    return;
×
72
  }
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 {
76
    fnInfo("udfd process restart");
×
77
    int32_t code = udfSpawnUdfd(pData);
×
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) {
741,539✔
85
  fnInfo("start to init udfd");
741,539✔
86
  TAOS_UDF_CHECK_PTR_RCODE(pData);
1,483,078✔
87

88
  int32_t              err = 0;
741,539✔
89
  uv_process_options_t options = {0};
741,539✔
90

91
  char path[PATH_MAX] = {0};
741,539✔
92
  if (tsProcPath == NULL) {
741,539✔
93
    path[0] = '.';
3,168✔
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);
738,371✔
104
    TAOS_DIRNAME(path);
738,371✔
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) {
741,539✔
114
    TAOS_STRCAT(path, "/usr/bin");
×
115
  }
116
  TAOS_STRCAT(path, "/" CUS_PROMPT "udf");
741,539✔
117
#endif
118
  char *argsUdfd[] = {path, "-c", configDir, NULL};
741,539✔
119
  options.args = argsUdfd;
741,539✔
120
  options.file = path;
741,539✔
121

122
  options.exit_cb = udfUdfdExit;
741,539✔
123

124
  TAOS_UV_LIB_ERROR_RET(uv_pipe_init(&pData->loop, &pData->ctrlPipe, 1));
741,539✔
125

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

135
  options.flags = UV_PROCESS_DETACHED;
741,539✔
136

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

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

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

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

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

170
  char *taosFqdnEnvItem = NULL;
741,539✔
171
  char *taosFqdn = getenv("TAOS_FQDN");
741,539✔
172
  if (taosFqdn != NULL) {
741,539✔
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};
741,539✔
187

188
  char **envUdfdWithPEnv = NULL;
741,539✔
189
  if (environ != NULL) {
741,539✔
190
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
741,539✔
191
    int32_t numEnviron = 0;
741,539✔
192
    while (environ[numEnviron] != NULL) {
22,413,673✔
193
      numEnviron++;
21,672,134✔
194
    }
195

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

202
    for (int32_t i = 0; i < numEnviron; i++) {
22,413,673✔
203
      int32_t len = strlen(environ[i]) + 1;
21,672,134✔
204
      envUdfdWithPEnv[i] = (char *)taosMemoryCalloc(len, 1);
21,672,134✔
205
      if (envUdfdWithPEnv[i] == NULL) {
21,672,134✔
206
        err = TSDB_CODE_OUT_OF_MEMORY;
×
207
        goto _OVER;
×
208
      }
209

210
      tstrncpy(envUdfdWithPEnv[i], environ[i], len);
21,672,134✔
211
    }
212

213
    for (int32_t i = 0; i < lenEnvUdfd; i++) {
4,449,234✔
214
      if (envUdfd[i] != NULL) {
3,707,695✔
215
        int32_t len = strlen(envUdfd[i]) + 1;
2,224,617✔
216
        envUdfdWithPEnv[numEnviron + i] = (char *)taosMemoryCalloc(len, 1);
2,224,617✔
217
        if (envUdfdWithPEnv[numEnviron + i] == NULL) {
2,224,617✔
218
          err = TSDB_CODE_OUT_OF_MEMORY;
×
219
          goto _OVER;
×
220
        }
221

222
        tstrncpy(envUdfdWithPEnv[numEnviron + i], envUdfd[i], len);
2,224,617✔
223
      }
224
    }
225
    envUdfdWithPEnv[numEnviron + lenEnvUdfd - 1] = NULL;
741,539✔
226

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

232
  err = uv_spawn(&pData->loop, &pData->process, &options);
741,539✔
233
  pData->process.data = (void *)pData;
741,539✔
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) {
741,539✔
255
    fnError("can not spawn udfd. path: %s, error: %s", path, uv_strerror(err));
3,168✔
256
  } else {
257
    fnInfo("udfd is initialized");
738,371✔
258
  }
259

260
_OVER:
738,081✔
261
  if (taosFqdnEnvItem) {
741,539✔
262
    taosMemoryFree(taosFqdnEnvItem);
×
263
  }
264

265
  if (envUdfdWithPEnv != NULL) {
741,539✔
266
    int32_t i = 0;
741,539✔
267
    while (envUdfdWithPEnv[i] != NULL) {
24,638,290✔
268
      taosMemoryFree(envUdfdWithPEnv[i]);
23,896,751✔
269
      i++;
23,896,751✔
270
    }
271
    taosMemoryFree(envUdfdWithPEnv);
741,539✔
272
  }
273

274
  return err;
741,539✔
275
}
276

277
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
3,688,463✔
278
  TAOS_UDF_CHECK_PTR_RVOID(handle);
7,376,926✔
279
  if (!uv_is_closing(handle)) {
3,688,463✔
280
    uv_close(handle, NULL);
3,688,463✔
281
  }
282
}
283

284
static void udfUdfdStopAsyncCb(uv_async_t *async) {
738,371✔
285
  TAOS_UDF_CHECK_PTR_RVOID(async);
1,476,742✔
286
  SUdfdData *pData = async->data;
738,371✔
287
  uv_stop(&pData->loop);
738,371✔
288
}
289

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

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

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

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

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

364
void udfStopUdfd() {
740,546✔
365
  SUdfdData *pData = &udfdGlobal;
740,546✔
366
  fnInfo("udfd start to stop, need cleanup:%d, spawn err:%d", pData->needCleanUp, pData->spawnErr);
740,546✔
367
  if (!pData->needCleanUp || atomic_load_32(&pData->stopCalled)) {
740,546✔
368
    return;
1,977✔
369
  }
370
  atomic_store_32(&pData->stopCalled, 1);
738,569✔
371
  pData->needCleanUp = false;
738,569✔
372
  uv_barrier_destroy(&pData->barrier);
738,569✔
373
  if (uv_async_send(&pData->stopAsync) != 0) {
738,569✔
374
    fnError("stop udfd: failed to send stop async");
×
375
  }
376
  if (uv_thread_join(&pData->thread) != 0) {
738,569✔
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");
738,569✔
384
  return;
738,569✔
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,497,133✔
619
  char    dnodeId[8] = {0};
1,497,133✔
620
  size_t  dnodeIdSize = sizeof(dnodeId);
1,497,133✔
621
  int32_t err = uv_os_getenv(UDF_DNODE_ID_ENV_NAME, dnodeId, &dnodeIdSize);
1,497,133✔
622
  if (err != 0) {
1,497,133✔
623
    fnError("failed to get dnodeId from env since %s", uv_err_name(err));
591✔
624
    dnodeId[0] = '1';
591✔
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,497,133✔
631
#endif
632
  fnInfo("get dnodeId:%s from env, pipe path:%s", dnodeId, pipeName);
1,497,133✔
633
}
1,497,133✔
634

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

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

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

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

661
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
1,246,540✔
662
  int32_t len = 0;
1,246,540✔
663
  len += taosEncodeFixedI64(buf, call->udfHandle);
1,246,540✔
664
  len += taosEncodeFixedI8(buf, call->callType);
1,246,540✔
665
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
1,246,540✔
666
    len += tEncodeDataBlock(buf, &call->block);
208,002✔
667
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
1,038,538✔
668
    len += taosEncodeFixedI8(buf, call->initFirst);
497,332✔
669
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
789,872✔
670
    len += tEncodeDataBlock(buf, &call->block);
541,206✔
671
    len += encodeUdfInterBuf(buf, &call->interBuf);
541,206✔
672
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
248,666✔
673
    // len += encodeUdfInterBuf(buf, &call->interBuf);
674
    // len += encodeUdfInterBuf(buf, &call->interBuf2);
675
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
248,666✔
676
    len += encodeUdfInterBuf(buf, &call->interBuf);
248,666✔
677
  }
678
  return len;
1,246,540✔
679
}
680

681
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
1,290,824✔
682
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
1,290,824✔
683
  buf = taosDecodeFixedI8(buf, &call->callType);
1,290,824✔
684
  switch (call->callType) {
1,290,824✔
685
    case TSDB_UDF_CALL_SCALA_PROC:
564,171✔
686
      buf = tDecodeDataBlock(buf, &call->block);
564,171✔
687
      break;
564,111✔
688
    case TSDB_UDF_CALL_AGG_INIT:
165,517✔
689
      buf = taosDecodeFixedI8(buf, &call->initFirst);
165,517✔
690
      break;
165,517✔
691
    case TSDB_UDF_CALL_AGG_PROC:
396,993✔
692
      buf = tDecodeDataBlock(buf, &call->block);
396,993✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
396,993✔
694
      break;
397,113✔
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:
164,263✔
700
      buf = decodeUdfInterBuf(buf, &call->interBuf);
164,263✔
701
      break;
164,263✔
702
  }
703
  return (void *)buf;
1,290,884✔
704
}
705

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

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

717
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
1,616,588✔
718
  int32_t len = 0;
1,616,588✔
719
  if (buf == NULL) {
1,616,588✔
720
    len += sizeof(request->msgLen);
808,294✔
721
  } else {
722
    *(int32_t *)(*buf) = request->msgLen;
808,294✔
723
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
808,294✔
724
  }
725
  len += taosEncodeFixedI64(buf, request->seqNum);
1,616,588✔
726
  len += taosEncodeFixedI8(buf, request->type);
1,616,588✔
727
  if (request->type == UDF_TASK_SETUP) {
1,616,588✔
728
    len += encodeUdfSetupRequest(buf, &request->setup);
185,024✔
729
  } else if (request->type == UDF_TASK_CALL) {
1,431,564✔
730
    len += encodeUdfCallRequest(buf, &request->call);
1,246,540✔
731
  } else if (request->type == UDF_TASK_TEARDOWN) {
185,024✔
732
    len += encodeUdfTeardownRequest(buf, &request->teardown);
185,024✔
733
  }
734
  return len;
1,616,588✔
735
}
736

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

741
  buf = taosDecodeFixedI64(buf, &request->seqNum);
1,661,890✔
742
  buf = taosDecodeFixedI8(buf, &request->type);
1,661,890✔
743

744
  if (request->type == UDF_TASK_SETUP) {
1,661,890✔
745
    buf = decodeUdfSetupRequest(buf, &request->setup);
186,064✔
746
  } else if (request->type == UDF_TASK_CALL) {
1,475,826✔
747
    buf = decodeUdfCallRequest(buf, &request->call);
1,290,944✔
748
  } else if (request->type == UDF_TASK_TEARDOWN) {
184,882✔
749
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
184,942✔
750
  }
751
  return (void *)buf;
1,661,824✔
752
}
753

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

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

771
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp) {
2,581,708✔
772
  int32_t len = 0;
2,581,708✔
773
  len += taosEncodeFixedI8(buf, callRsp->callType);
2,581,708✔
774
  switch (callRsp->callType) {
2,581,708✔
775
    case TSDB_UDF_CALL_SCALA_PROC:
1,128,222✔
776
      len += tEncodeDataBlock(buf, &callRsp->resultData);
1,128,222✔
777
      break;
1,128,222✔
778
    case TSDB_UDF_CALL_AGG_INIT:
331,034✔
779
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
331,034✔
780
      break;
331,034✔
781
    case TSDB_UDF_CALL_AGG_PROC:
793,986✔
782
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
793,986✔
783
      break;
793,986✔
784
    // case TSDB_UDF_CALL_AGG_MERGE:
785
    //   len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
786
    //   break;
787
    case TSDB_UDF_CALL_AGG_FIN:
328,526✔
788
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
328,526✔
789
      break;
328,526✔
790
  }
791
  return len;
2,581,708✔
792
}
793

794
void *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp) {
623,270✔
795
  buf = taosDecodeFixedI8(buf, &callRsp->callType);
623,270✔
796
  switch (callRsp->callType) {
623,270✔
797
    case TSDB_UDF_CALL_SCALA_PROC:
104,001✔
798
      buf = tDecodeDataBlock(buf, &callRsp->resultData);
104,001✔
799
      break;
104,001✔
800
    case TSDB_UDF_CALL_AGG_INIT:
124,333✔
801
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
124,333✔
802
      break;
124,333✔
803
    case TSDB_UDF_CALL_AGG_PROC:
270,603✔
804
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
270,603✔
805
      break;
270,603✔
806
    // case TSDB_UDF_CALL_AGG_MERGE:
807
    //   buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
808
    //   break;
809
    case TSDB_UDF_CALL_AGG_FIN:
124,333✔
810
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
124,333✔
811
      break;
124,333✔
812
  }
813
  return (void *)buf;
623,270✔
814
}
815

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

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

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

828
  len += sizeof(rsp->seqNum);
3,323,720✔
829
  if (buf != NULL) {
3,323,720✔
830
    *(int64_t *)(*buf) = rsp->seqNum;
1,661,950✔
831
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
1,661,950✔
832
  }
833

834
  len += taosEncodeFixedI64(buf, rsp->seqNum);
3,323,720✔
835
  len += taosEncodeFixedI8(buf, rsp->type);
3,323,720✔
836
  len += taosEncodeFixedI32(buf, rsp->code);
3,323,720✔
837

838
  switch (rsp->type) {
3,323,720✔
839
    case UDF_TASK_SETUP:
372,128✔
840
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
372,128✔
841
      break;
372,128✔
842
    case UDF_TASK_CALL:
2,581,708✔
843
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
2,581,708✔
844
      break;
2,581,768✔
845
    case UDF_TASK_TEARDOWN:
369,884✔
846
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
369,884✔
847
      break;
369,884✔
UNCOV
848
    default:
×
UNCOV
849
      fnError("encode udf response, invalid udf response type %d", rsp->type);
×
850
      break;
×
851
  }
852
  return len;
3,323,780✔
853
}
854

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

864
  switch (rsp->type) {
808,294✔
865
    case UDF_TASK_SETUP:
92,512✔
866
      buf = decodeUdfSetupResponse(buf, &rsp->setupRsp);
92,512✔
867
      break;
92,512✔
868
    case UDF_TASK_CALL:
623,270✔
869
      if (rsp->code) {
623,270✔
870
        fnError("udf response failed, code:0x%x", rsp->code);
×
871

872
        return NULL;
×
873
      }
874

875
      buf = decodeUdfCallResponse(buf, &rsp->callRsp);
623,270✔
876
      break;
623,270✔
877
    case UDF_TASK_TEARDOWN:
92,512✔
878
      buf = decodeUdfTeardownResponse(buf, &rsp->teardownRsp);
92,512✔
879
      break;
92,512✔
880
    default:
×
881
      rsp->code = TSDB_CODE_UDF_INTERNAL_ERROR;
×
882
      fnError("decode udf response, invalid udf response type %d", rsp->type);
×
883
      break;
×
884
  }
885
  if (buf == NULL) {
808,294✔
886
    rsp->code = terrno;
×
887
    fnError("decode udf response failed, code:0x%x", rsp->code);
×
888
  }
889
  return (void *)buf;
808,294✔
890
}
891

892
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
1,591,377✔
893
  TAOS_UDF_CHECK_PTR_RVOID(data, meta);
4,774,131✔
894
  if (IS_VAR_DATA_TYPE(meta->type)) {
1,591,377✔
895
    taosMemoryFree(data->varLenCol.varOffsets);
16,865✔
896
    data->varLenCol.varOffsets = NULL;
16,985✔
897
    taosMemoryFree(data->varLenCol.payload);
16,985✔
898
    data->varLenCol.payload = NULL;
16,985✔
899
  } else {
900
    taosMemoryFree(data->fixLenCol.nullBitmap);
1,574,512✔
901
    data->fixLenCol.nullBitmap = NULL;
1,574,452✔
902
    taosMemoryFree(data->fixLenCol.data);
1,574,452✔
903
    data->fixLenCol.data = NULL;
1,574,452✔
904
  }
905
}
906

907
void freeUdfColumn(SUdfColumn *col) {
1,591,377✔
908
  TAOS_UDF_CHECK_PTR_RVOID(col);
3,182,754✔
909
  freeUdfColumnData(&col->colData, &col->colMeta);
1,591,377✔
910
}
911

912
void freeUdfDataDataBlock(SUdfDataBlock *block) {
961,164✔
913
  TAOS_UDF_CHECK_PTR_RVOID(block);
1,922,328✔
914
  for (int32_t i = 0; i < block->numOfCols; ++i) {
1,988,550✔
915
    freeUdfColumn(block->udfCols[i]);
1,027,386✔
916
    taosMemoryFree(block->udfCols[i]);
1,027,386✔
917
    block->udfCols[i] = NULL;
1,027,386✔
918
  }
919
  taosMemoryFree(block->udfCols);
961,164✔
920
  block->udfCols = NULL;
961,164✔
921
}
922

923
void freeUdfInterBuf(SUdfInterBuf *buf) {
1,807,298✔
924
  TAOS_UDF_CHECK_PTR_RVOID(buf);
3,614,596✔
925
  taosMemoryFree(buf->buf);
1,807,298✔
926
  buf->buf = NULL;
1,807,298✔
927
}
928

929
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
961,038✔
930
  TAOS_UDF_CHECK_PTR_RCODE(block, udfBlock);
2,882,514✔
931
  int32_t code = blockDataCheck(block);
961,038✔
932
  if (code != TSDB_CODE_SUCCESS) {
961,038✔
933
    return code;
×
934
  }
935
  udfBlock->numOfRows = block->info.rows;
961,038✔
936
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
961,038✔
937
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
961,038✔
938
  if ((udfBlock->udfCols) == NULL) {
960,864✔
939
    return terrno;
×
940
  }
941
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
1,988,064✔
942
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
1,027,260✔
943
    if (udfBlock->udfCols[i] == NULL) {
1,027,260✔
944
      return terrno;
×
945
    }
946
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
1,027,260✔
947
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
1,027,140✔
948
    udfCol->colMeta.type = col->info.type;
1,027,140✔
949
    udfCol->colMeta.bytes = col->info.bytes;
1,027,140✔
950
    udfCol->colMeta.scale = col->info.scale;
1,027,140✔
951
    udfCol->colMeta.precision = col->info.precision;
1,027,140✔
952
    udfCol->colData.numOfRows = udfBlock->numOfRows;
1,027,140✔
953
    udfCol->hasNull = col->hasNull;
1,027,140✔
954
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
1,027,140✔
955
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
10,505✔
956
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
10,505✔
957
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
10,385✔
958
        return terrno;
×
959
      }
960
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
10,385✔
961
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
10,385✔
962
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
10,385✔
963
      if (udfCol->colData.varLenCol.payload == NULL) {
10,385✔
964
        return terrno;
×
965
      }
966
      if (col->reassigned) {
10,385✔
967
        for (int32_t row = 0; row < udfCol->colData.numOfRows; ++row) {
×
968
          char   *pColData = col->pData + col->varmeta.offset[row];
×
969
          int32_t colSize = 0;
×
970
          if (col->info.type == TSDB_DATA_TYPE_JSON) {
×
971
            colSize = getJsonValueLen(pColData);
×
972
          } else if (IS_STR_DATA_BLOB(col->info.type)) {
×
973
            colSize = blobDataTLen(pColData);
×
974
          } else {
975
            colSize = varDataTLen(pColData);
×
976
          }
977
          memcpy(udfCol->colData.varLenCol.payload, pColData, colSize);
×
978
          udfCol->colData.varLenCol.payload += colSize;
×
979
        }
980
      } else {
981
        memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
10,385✔
982
      }
983
    } else {
984
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
1,016,635✔
985
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
1,016,635✔
986
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
1,016,635✔
987
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
1,016,575✔
988
        return terrno;
×
989
      }
990
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
1,016,575✔
991
      memcpy(bitmap, col->nullbitmap, bitmapLen);
1,016,575✔
992
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
1,016,575✔
993
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
1,016,395✔
994
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
1,016,395✔
995
      if (NULL == udfCol->colData.fixLenCol.data) {
1,016,815✔
996
        return terrno;
×
997
      }
998
      char *data = udfCol->colData.fixLenCol.data;
1,016,815✔
999
      memcpy(data, col->pData, dataLen);
1,016,815✔
1000
    }
1001
  }
1002
  return TSDB_CODE_SUCCESS;
960,804✔
1003
}
1004

1005
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
562,995✔
1006
  TAOS_UDF_CHECK_PTR_RCODE(udfCol, block);
1,688,985✔
1007
  int32_t         code = 0, lino = 0;
562,995✔
1008
  SUdfColumnMeta *meta = &udfCol->colMeta;
562,995✔
1009

1010
  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
562,995✔
1011
  code = blockDataAppendColInfo(block, &colInfoData);
562,995✔
1012
  TAOS_CHECK_GOTO(code, &lino, _exit);
563,055✔
1013

1014
  code = blockDataEnsureCapacity(block, udfCol->colData.numOfRows);
563,055✔
1015
  TAOS_CHECK_GOTO(code, &lino, _exit);
563,055✔
1016

1017
  SColumnInfoData *col = NULL;
563,055✔
1018
  code = bdGetColumnInfoData(block, 0, &col);
563,055✔
1019
  TAOS_CHECK_GOTO(code, &lino, _exit);
563,055✔
1020

1021
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
459,584,063✔
1022
    if (udfColDataIsNull(udfCol, i)) {
459,660,920✔
1023
      colDataSetNULL(col, i);
46,226,750✔
1024
    } else {
1025
      char *data = udfColDataGetData(udfCol, i);
413,434,170✔
1026
      code = colDataSetVal(col, i, data, false);
413,434,170✔
1027
      TAOS_CHECK_GOTO(code, &lino, _exit);
412,794,258✔
1028
    }
1029
  }
1030
  block->info.rows = udfCol->colData.numOfRows;
108,843✔
1031

1032
  code = blockDataCheck(block);
108,843✔
1033
  TAOS_CHECK_GOTO(code, &lino, _exit);
562,995✔
1034
_exit:
562,995✔
1035
  if (code != 0) {
562,995✔
1036
    fnError("failed to convert udf column to data block, code:%d, line:%d", code, lino);
×
1037
  }
1038
  return TSDB_CODE_SUCCESS;
562,995✔
1039
}
1040

1041
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
104,001✔
1042
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
312,003✔
1043
  int32_t code = 0, lino = 0;
104,001✔
1044
  int32_t numOfRows = 0;
104,001✔
1045
  for (int32_t i = 0; i < numOfCols; ++i) {
211,882✔
1046
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
107,881✔
1047
  }
1048

1049
  // create the basic block info structure
1050
  for (int32_t i = 0; i < numOfCols; ++i) {
211,882✔
1051
    SColumnInfoData *pInfo = input[i].columnData;
107,881✔
1052
    SColumnInfoData  d = {0};
107,881✔
1053
    d.info = pInfo->info;
107,881✔
1054

1055
    TAOS_CHECK_GOTO(blockDataAppendColInfo(output, &d), &lino, _exit);
107,881✔
1056
  }
1057

1058
  TAOS_CHECK_GOTO(blockDataEnsureCapacity(output, numOfRows), &lino, _exit);
104,001✔
1059

1060
  for (int32_t i = 0; i < numOfCols; ++i) {
211,882✔
1061
    SColumnInfoData *pDest = taosArrayGet(output->pDataBlock, i);
107,881✔
1062

1063
    SColumnInfoData *pColInfoData = input[i].columnData;
107,881✔
1064
    TAOS_CHECK_GOTO(colDataAssign(pDest, pColInfoData, input[i].numOfRows, &output->info), &lino, _exit);
107,881✔
1065

1066
    if (input[i].numOfRows < numOfRows) {
107,881✔
1067
      int32_t startRow = input[i].numOfRows;
×
1068
      int32_t expandRows = numOfRows - startRow;
×
1069
      bool    isNull = colDataIsNull_s(pColInfoData, (input + i)->numOfRows - 1);
×
1070
      if (isNull) {
×
1071
        colDataSetNNULL(pDest, startRow, expandRows);
×
1072
      } else {
1073
        char *src = colDataGetData(pColInfoData, (input + i)->numOfRows - 1);
×
1074
        for (int32_t j = 0; j < expandRows; ++j) {
×
1075
          TAOS_CHECK_GOTO(colDataSetVal(pDest, startRow + j, src, false), &lino, _exit);
×
1076
        }
1077
      }
1078
    }
1079
  }
1080

1081
  output->info.rows = numOfRows;
104,001✔
1082
_exit:
104,001✔
1083
  if (code != 0) {
104,001✔
1084
    fnError("failed to convert scalar param to data block, code:%d, line:%d", code, lino);
×
1085
  }
1086
  return code;
104,001✔
1087
}
1088

1089
int32_t convertDataBlockToScalarParm(SSDataBlock *input, SScalarParam *output) {
104,001✔
1090
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
312,003✔
1091
  if (taosArrayGetSize(input->pDataBlock) != 1) {
104,001✔
1092
    fnError("scalar function only support one column");
×
1093
    return 0;
×
1094
  }
1095
  output->numOfRows = input->info.rows;
104,001✔
1096

1097
  output->columnData = taosMemoryMalloc(sizeof(SColumnInfoData));
104,001✔
1098
  if (output->columnData == NULL) {
104,001✔
1099
    return terrno;
×
1100
  }
1101
  memcpy(output->columnData, taosArrayGet(input->pDataBlock, 0), sizeof(SColumnInfoData));
104,001✔
1102
  output->colAlloced = true;
104,001✔
1103

1104
  return 0;
104,001✔
1105
}
1106

1107
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
1108
// memory layout |---SUdfAggRes----|-----final result-----|---inter result----|
1109
typedef struct SUdfAggRes {
1110
  int8_t  finalResNum;
1111
  int8_t  interResNum;
1112
  int32_t interResBufLen;
1113
  char   *finalResBuf;
1114
  char   *interResBuf;
1115
} SUdfAggRes;
1116

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

1138
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
1139
                SSDataBlock *output, SUdfInterBuf *newState);
1140
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf);
1141
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState);
1142
// udf todo:  aggmerge
1143
// int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
1144
//                           SUdfInterBuf *resultBuf);
1145
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData);
1146
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1147
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1148

1149
int32_t udfcOpen();
1150
int32_t udfcClose();
1151

1152
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle);
1153
void    releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle);
1154
int32_t cleanUpUdfs();
1155

1156
bool    udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv);
1157
int32_t udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo);
1158
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx);
1159
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock);
1160

1161
void    cleanupNotExpiredUdfs();
1162
void    cleanupExpiredUdfs();
1163
int32_t compareUdfcFuncSub(const void *elem1, const void *elem2) {
1,698,198✔
1164
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
1,698,198✔
1165
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
1,698,198✔
1166
  return strcmp(stub1->udfName, stub2->udfName);
1,698,198✔
1167
}
1168

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

1223
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
92,512✔
1224

1225
_exit:
92,512✔
1226
  return code;
92,512✔
1227
}
1228

1229
void releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle) {
623,270✔
1230
  TAOS_UDF_CHECK_PTR_RVOID(udfName);
1,246,540✔
1231
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
623,270✔
1232
  SUdfcFuncStub key = {0};
623,270✔
1233
  tstrncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
623,270✔
1234
  SUdfcFuncStub *foundStub = taosArraySearch(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
623,270✔
1235
  SUdfcFuncStub *expiredStub = taosArraySearch(gUdfcProxy.expiredUdfStubs, &key, compareUdfcFuncSub, TD_EQ);
623,270✔
1236
  if (!foundStub && !expiredStub) {
623,270✔
1237
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
×
1238
    return;
×
1239
  }
1240
  if (foundStub != NULL && foundStub->handle == handle && foundStub->refCount > 0) {
623,270✔
1241
    --foundStub->refCount;
623,270✔
1242
  }
1243
  if (expiredStub != NULL && expiredStub->handle == handle && expiredStub->refCount > 0) {
623,270✔
1244
    --expiredStub->refCount;
×
1245
  }
1246
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
623,270✔
1247
}
1248

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

1281
void cleanupNotExpiredUdfs() {
76,752✔
1282
  SArray *udfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
76,752✔
1283
  if (udfStubs == NULL) {
76,752✔
1284
    fnError("cleanupNotExpiredUdfs: failed to init array");
×
1285
    return;
×
1286
  }
1287
  int32_t i = 0;
76,752✔
1288
  while (i < taosArrayGetSize(gUdfcProxy.udfStubs)) {
178,239✔
1289
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.udfStubs, i);
101,487✔
1290
    if (stub->refCount == 0) {
101,487✔
1291
      fnInfo("tear down udf. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle, stub->refCount);
92,512✔
1292
      (void)doTeardownUdf(stub->handle);
92,512✔
1293
    } else {
1294
      fnInfo("udf still in use. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p", stub->udfName,
8,975✔
1295
             stub->refCount, stub->createTime, stub->handle);
1296
      UdfcFuncHandle handle = stub->handle;
8,975✔
1297
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
8,975✔
1298
        if (taosArrayPush(udfStubs, stub) == NULL) {
8,975✔
1299
          fnError("cleanupNotExpiredUdfs: failed to push udf stub to array");
×
1300
        }
1301
      } else {
1302
        fnInfo("udf invalid handle for %s, refCount: %d, create time: %" PRId64 ". remove it from cache", stub->udfName,
×
1303
               stub->refCount, stub->createTime);
1304
      }
1305
    }
1306
    ++i;
101,487✔
1307
  }
1308
  taosArrayDestroy(gUdfcProxy.udfStubs);
76,752✔
1309
  gUdfcProxy.udfStubs = udfStubs;
76,752✔
1310
}
1311

1312
int32_t cleanUpUdfs() {
634,682,299✔
1313
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
634,682,299✔
1314
  if (!initialized) {
634,630,838✔
1315
    return TSDB_CODE_SUCCESS;
23,520✔
1316
  }
1317

1318
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
634,607,318✔
1319
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
634,714,452✔
1320
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
634,637,700✔
1321
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
634,637,700✔
1322
    return TSDB_CODE_SUCCESS;
634,636,832✔
1323
  }
1324

1325
  cleanupNotExpiredUdfs();
76,752✔
1326
  cleanupExpiredUdfs();
76,752✔
1327

1328
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
76,752✔
1329
  return 0;
76,752✔
1330
}
1331

1332
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
104,001✔
1333
  TAOS_UDF_CHECK_PTR_RCODE(udfName, input, output);
416,004✔
1334
  UdfcFuncHandle handle = NULL;
104,001✔
1335
  int32_t        code = acquireUdfFuncHandle(udfName, &handle);
104,001✔
1336
  if (code != 0) {
104,001✔
1337
    return code;
×
1338
  }
1339

1340
  SUdfcUvSession *session = handle;
104,001✔
1341
  code = doCallUdfScalarFunc(handle, input, numOfCols, output);
104,001✔
1342
  if (code != TSDB_CODE_SUCCESS) {
104,001✔
1343
    fnError("udfc scalar function execution failure");
×
1344
    releaseUdfFuncHandle(udfName, handle);
×
1345
    return code;
×
1346
  }
1347

1348
  if (output->columnData == NULL) {
104,001✔
1349
    fnError("udfc scalar function calculate error. no column data");
×
1350
    code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1351
  } else {
1352
    if (session->outputType != output->columnData->info.type || session->bytes != output->columnData->info.bytes) {
104,001✔
1353
      fnError("udfc scalar function calculate error. type mismatch. session type: %d(%d), output type: %d(%d)",
×
1354
              session->outputType, session->bytes, output->columnData->info.type, output->columnData->info.bytes);
1355
      code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1356
    }
1357
  }
1358
  releaseUdfFuncHandle(udfName, handle);
104,001✔
1359
  return code;
104,001✔
1360
}
1361

1362
bool udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv) {
53,706✔
1363
  if (pFunc == NULL || pEnv == NULL) {
53,706✔
1364
    fnError("udfAggGetEnv: invalid input lint: %d", __LINE__);
×
1365
    return false;
×
1366
  }
1367
  if (fmIsScalarFunc(pFunc->funcId)) {
53,706✔
1368
    return false;
×
1369
  }
1370
  pEnv->calcMemSize = sizeof(SUdfAggRes) + pFunc->node.resType.bytes + pFunc->udfBufSize;
53,706✔
1371
  return true;
53,706✔
1372
}
1373

1374
int32_t udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo) {
124,333✔
1375
  TAOS_UDF_CHECK_PTR_RCODE(pCtx, pResultCellInfo);
372,999✔
1376
  if (pResultCellInfo->initialized) {
124,333✔
1377
    return TSDB_CODE_SUCCESS;
×
1378
  }
1379
  if (functionSetup(pCtx, pResultCellInfo) != TSDB_CODE_SUCCESS) {
124,333✔
1380
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1381
  }
1382
  UdfcFuncHandle handle;
124,333✔
1383
  int32_t        udfCode = 0;
124,333✔
1384
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
124,333✔
1385
    fnError("udfAggInit error. step doSetupUdf. udf code: %d", udfCode);
×
1386
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1387
  }
1388
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
124,333✔
1389
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(pResultCellInfo);
124,333✔
1390
  int32_t         envSize = sizeof(SUdfAggRes) + session->bytes + session->bufSize;
124,333✔
1391
  memset(udfRes, 0, envSize);
124,333✔
1392

1393
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
124,333✔
1394
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
124,333✔
1395

1396
  SUdfInterBuf buf = {0};
124,333✔
1397
  if ((udfCode = doCallUdfAggInit(handle, &buf)) != 0) {
124,333✔
1398
    fnError("udfAggInit error. step doCallUdfAggInit. udf code: %d", udfCode);
×
1399
    releaseUdfFuncHandle(pCtx->udfName, handle);
×
1400
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1401
  }
1402
  if (buf.bufLen <= session->bufSize) {
124,333✔
1403
    memcpy(udfRes->interResBuf, buf.buf, buf.bufLen);
124,333✔
1404
    udfRes->interResBufLen = buf.bufLen;
124,333✔
1405
    udfRes->interResNum = buf.numOfResult;
124,333✔
1406
  } else {
1407
    fnError("udfc inter buf size %d is greater than function bufSize %d", buf.bufLen, session->bufSize);
×
1408
    releaseUdfFuncHandle(pCtx->udfName, handle);
×
1409
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1410
  }
1411
  releaseUdfFuncHandle(pCtx->udfName, handle);
124,333✔
1412
  freeUdfInterBuf(&buf);
124,333✔
1413
  return TSDB_CODE_SUCCESS;
124,333✔
1414
}
1415

1416
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx) {
270,603✔
1417
  TAOS_UDF_CHECK_PTR_RCODE(pCtx);
541,206✔
1418
  int32_t        udfCode = 0;
270,603✔
1419
  UdfcFuncHandle handle = 0;
270,603✔
1420
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
270,603✔
1421
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
×
1422
    return udfCode;
×
1423
  }
1424

1425
  SUdfcUvSession *session = handle;
270,603✔
1426
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
270,603✔
1427
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
270,603✔
1428
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
270,603✔
1429

1430
  SInputColumnInfoData *pInput = &pCtx->input;
270,603✔
1431
  int32_t               numOfCols = pInput->numOfInputCols;
270,603✔
1432
  int32_t               start = pInput->startRowIndex;
270,603✔
1433
  int32_t               numOfRows = pInput->numOfRows;
270,603✔
1434
  SSDataBlock          *pTempBlock = NULL;
270,603✔
1435
  int32_t               code = createDataBlock(&pTempBlock);
270,603✔
1436

1437
  if (code) {
270,603✔
1438
    return code;
×
1439
  }
1440

1441
  pTempBlock->info.rows = pInput->totalRows;
270,603✔
1442
  pTempBlock->info.id.uid = pInput->uid;
270,603✔
1443
  for (int32_t i = 0; i < numOfCols; ++i) {
561,572✔
1444
    if ((udfCode = blockDataAppendColInfo(pTempBlock, pInput->pData[i])) != 0) {
290,969✔
1445
      fnError("udfAggProcess error. step blockDataAppendColInfo. udf code: %d", udfCode);
×
1446
      blockDataDestroy(pTempBlock);
×
1447
      return udfCode;
×
1448
    }
1449
  }
1450

1451
  SSDataBlock *inputBlock = NULL;
270,603✔
1452
  code = blockDataExtractBlock(pTempBlock, start, numOfRows, &inputBlock);
270,603✔
1453
  if (code) {
270,603✔
1454
    return code;
×
1455
  }
1456

1457
  SUdfInterBuf state = {
270,603✔
1458
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
270,603✔
1459
  SUdfInterBuf newState = {0};
270,603✔
1460

1461
  udfCode = doCallUdfAggProcess(session, inputBlock, &state, &newState);
270,603✔
1462
  if (udfCode != 0) {
270,603✔
1463
    fnError("udfAggProcess error. code: %d", udfCode);
×
1464
    newState.numOfResult = 0;
×
1465
  } else {
1466
    if (newState.bufLen <= session->bufSize) {
270,603✔
1467
      memcpy(udfRes->interResBuf, newState.buf, newState.bufLen);
270,603✔
1468
      udfRes->interResBufLen = newState.bufLen;
270,603✔
1469
      udfRes->interResNum = newState.numOfResult;
270,603✔
1470
    } else {
1471
      fnError("udfc inter buf size %d is greater than function bufSize %d", newState.bufLen, session->bufSize);
×
1472
      udfCode = TSDB_CODE_UDF_INVALID_BUFSIZE;
×
1473
    }
1474
  }
1475

1476
  GET_RES_INFO(pCtx)->numOfRes = udfRes->interResNum;
270,603✔
1477

1478
  blockDataDestroy(inputBlock);
270,603✔
1479

1480
  taosArrayDestroy(pTempBlock->pDataBlock);
270,603✔
1481
  taosMemoryFree(pTempBlock);
270,603✔
1482

1483
  releaseUdfFuncHandle(pCtx->udfName, handle);
270,603✔
1484
  freeUdfInterBuf(&newState);
270,603✔
1485
  return udfCode;
270,603✔
1486
}
1487

1488
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock) {
124,333✔
1489
  TAOS_UDF_CHECK_PTR_RCODE(pCtx, pBlock);
372,999✔
1490
  int32_t        udfCode = 0;
124,333✔
1491
  UdfcFuncHandle handle = 0;
124,333✔
1492
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
124,333✔
1493
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
×
1494
    return udfCode;
×
1495
  }
1496

1497
  SUdfcUvSession *session = handle;
124,333✔
1498
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
124,333✔
1499
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
124,333✔
1500
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
124,333✔
1501

1502
  SUdfInterBuf resultBuf = {0};
124,333✔
1503
  SUdfInterBuf state = {
124,333✔
1504
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
124,333✔
1505
  int32_t udfCallCode = 0;
124,333✔
1506
  udfCallCode = doCallUdfAggFinalize(session, &state, &resultBuf);
124,333✔
1507
  if (udfCallCode != 0) {
124,333✔
1508
    fnError("udfAggFinalize error. doCallUdfAggFinalize step. udf code:%d", udfCallCode);
×
1509
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1510
  } else {
1511
    if (resultBuf.numOfResult == 0) {
124,333✔
1512
      udfRes->finalResNum = 0;
481✔
1513
      GET_RES_INFO(pCtx)->numOfRes = 0;
481✔
1514
    } else {
1515
      if (resultBuf.bufLen <= session->bytes) {
123,852✔
1516
        memcpy(udfRes->finalResBuf, resultBuf.buf, resultBuf.bufLen);
123,852✔
1517
        udfRes->finalResNum = resultBuf.numOfResult;
123,852✔
1518
        GET_RES_INFO(pCtx)->numOfRes = udfRes->finalResNum;
123,852✔
1519
      } else {
1520
        fnError("udfc inter buf size %d is greater than function output size %d", resultBuf.bufLen, session->bytes);
×
1521
        GET_RES_INFO(pCtx)->numOfRes = 0;
×
1522
        udfCallCode = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1523
      }
1524
    }
1525
  }
1526

1527
  freeUdfInterBuf(&resultBuf);
124,333✔
1528

1529
  int32_t numOfResults = functionFinalizeWithResultBuf(pCtx, pBlock, udfRes->finalResBuf);
124,333✔
1530
  releaseUdfFuncHandle(pCtx->udfName, handle);
124,333✔
1531
  return udfCallCode == 0 ? numOfResults : udfCallCode;
124,333✔
1532
}
1533

1534
void onUdfcPipeClose(uv_handle_t *handle) {
92,512✔
1535
  SClientUvConn *conn = handle->data;
92,512✔
1536
  if (!QUEUE_EMPTY(&conn->taskQueue)) {
92,512✔
1537
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
92,512✔
1538
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
92,512✔
1539
    task->errCode = 0;
92,512✔
1540
    QUEUE_REMOVE(&task->procTaskQueue);
92,512✔
1541
    uv_sem_post(&task->taskSem);
92,512✔
1542
  }
1543
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
92,512✔
1544
  if (conn->session != NULL) {
92,512✔
1545
    conn->session->udfUvPipe = NULL;
73,112✔
1546
  }
1547
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
92,512✔
1548
  taosMemoryFree(conn->readBuf.buf);
92,512✔
1549
  taosMemoryFree(conn);
92,512✔
1550
  taosMemoryFree((uv_pipe_t *)handle);
92,512✔
1551
}
92,512✔
1552

1553
int32_t udfcGetUdfTaskResultFromUvTask(SClientUdfTask *task, SClientUvTaskNode *uvTask) {
993,318✔
1554
  int32_t code = 0;
993,318✔
1555
  fnDebug("udfc get uv task result. task: %p, uvTask: %p", task, uvTask);
993,318✔
1556
  if (uvTask->type == UV_TASK_REQ_RSP) {
993,318✔
1557
    if (uvTask->rspBuf.base != NULL) {
808,294✔
1558
      SUdfResponse rsp = {0};
808,294✔
1559
      void        *buf = decodeUdfResponse(uvTask->rspBuf.base, &rsp);
808,294✔
1560
      code = rsp.code;
808,294✔
1561
      if (code != 0) {
808,294✔
1562
        fnError("udfc get udf task result failure. code: %d", code);
×
1563
      }
1564

1565
      switch (task->type) {
808,294✔
1566
        case UDF_TASK_SETUP: {
92,512✔
1567
          task->_setup.rsp = rsp.setupRsp;
92,512✔
1568
          break;
92,512✔
1569
        }
1570
        case UDF_TASK_CALL: {
623,270✔
1571
          task->_call.rsp = rsp.callRsp;
623,270✔
1572
          break;
623,270✔
1573
        }
1574
        case UDF_TASK_TEARDOWN: {
92,512✔
1575
          task->_teardown.rsp = rsp.teardownRsp;
1576
          break;
92,512✔
1577
        }
1578
        default: {
×
1579
          break;
×
1580
        }
1581
      }
1582

1583
      // TODO: the call buffer is setup and freed by udf invocation
1584
      taosMemoryFreeClear(uvTask->rspBuf.base);
808,294✔
1585
    } else {
1586
      code = uvTask->errCode;
×
1587
      if (code != 0) {
×
1588
        fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1589
      }
1590
    }
1591
  } else if (uvTask->type == UV_TASK_CONNECT) {
185,024✔
1592
    code = uvTask->errCode;
92,512✔
1593
    if (code != 0) {
92,512✔
1594
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1595
    }
1596
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
92,512✔
1597
    code = uvTask->errCode;
92,512✔
1598
    if (code != 0) {
92,512✔
1599
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1600
    }
1601
  }
1602
  return code;
993,318✔
1603
}
1604

1605
void udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
2,424,882✔
1606
  SClientUvConn  *conn = handle->data;
2,424,882✔
1607
  SClientConnBuf *connBuf = &conn->readBuf;
2,424,882✔
1608

1609
  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
2,424,882✔
1610
  if (connBuf->cap == 0) {
2,424,882✔
1611
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
900,806✔
1612
    if (connBuf->buf) {
900,806✔
1613
      connBuf->len = 0;
900,806✔
1614
      connBuf->cap = msgHeadSize;
900,806✔
1615
      connBuf->total = -1;
900,806✔
1616

1617
      buf->base = connBuf->buf;
900,806✔
1618
      buf->len = connBuf->cap;
900,806✔
1619
    } else {
1620
      fnError("udfc allocate buffer failure. size: %d", msgHeadSize);
×
1621
      buf->base = NULL;
×
1622
      buf->len = 0;
×
1623
    }
1624
  } else if (connBuf->total == -1 && connBuf->len < msgHeadSize) {
1,524,076✔
1625
    buf->base = connBuf->buf + connBuf->len;
715,782✔
1626
    buf->len = msgHeadSize - connBuf->len;
715,782✔
1627
  } else {
1628
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
808,294✔
1629
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
808,294✔
1630
    if (resultBuf) {
808,294✔
1631
      connBuf->buf = resultBuf;
808,294✔
1632
      buf->base = connBuf->buf + connBuf->len;
808,294✔
1633
      buf->len = connBuf->cap - connBuf->len;
808,294✔
1634
    } else {
1635
      fnError("udfc re-allocate buffer failure. size: %d", connBuf->cap);
×
1636
      buf->base = NULL;
×
1637
      buf->len = 0;
×
1638
    }
1639
  }
1640

1641
  fnDebug("udfc uv alloc buffer: cap - len - total : %d - %d - %d", connBuf->cap, connBuf->len, connBuf->total);
2,424,882✔
1642
}
2,424,882✔
1643

1644
bool isUdfcUvMsgComplete(SClientConnBuf *connBuf) {
1,616,588✔
1645
  if (connBuf->total == -1 && connBuf->len >= sizeof(int32_t)) {
1,616,588✔
1646
    connBuf->total = *(int32_t *)(connBuf->buf);
808,294✔
1647
  }
1648
  if (connBuf->len == connBuf->cap && connBuf->total == connBuf->cap) {
1,616,588✔
1649
    fnDebug("udfc complete message is received, now handle it");
808,294✔
1650
    return true;
808,294✔
1651
  }
1652
  return false;
808,294✔
1653
}
1654

1655
void udfcUvHandleRsp(SClientUvConn *conn) {
808,294✔
1656
  SClientConnBuf *connBuf = &conn->readBuf;
808,294✔
1657
  int64_t         seqNum = *(int64_t *)(connBuf->buf + sizeof(int32_t));  // msglen then seqnum
808,294✔
1658

1659
  if (QUEUE_EMPTY(&conn->taskQueue)) {
808,294✔
1660
    fnError("udfc no task waiting on connection. response seqnum:%" PRId64, seqNum);
×
1661
    return;
×
1662
  }
1663
  bool               found = false;
808,294✔
1664
  SClientUvTaskNode *taskFound = NULL;
808,294✔
1665
  QUEUE             *h = QUEUE_NEXT(&conn->taskQueue);
808,294✔
1666
  SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
808,294✔
1667

1668
  while (h != &conn->taskQueue) {
1,617,073✔
1669
    fnDebug("udfc handle response iterate through queue. uvTask:%" PRId64 "-%p", task->seqNum, task);
808,779✔
1670
    if (task->seqNum == seqNum) {
808,779✔
1671
      if (found == false) {
808,294✔
1672
        found = true;
808,294✔
1673
        taskFound = task;
808,294✔
1674
      } else {
1675
        fnError("udfc more than one task waiting for the same response");
×
1676
        continue;
×
1677
      }
1678
    }
1679
    h = QUEUE_NEXT(h);
808,779✔
1680
    task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
808,779✔
1681
  }
1682

1683
  if (taskFound) {
808,294✔
1684
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
808,294✔
1685
    QUEUE_REMOVE(&taskFound->connTaskQueue);
808,294✔
1686
    QUEUE_REMOVE(&taskFound->procTaskQueue);
808,294✔
1687
    uv_sem_post(&taskFound->taskSem);
808,294✔
1688
  } else {
1689
    fnError("no task is waiting for the response.");
×
1690
  }
1691
  connBuf->buf = NULL;
808,294✔
1692
  connBuf->total = -1;
808,294✔
1693
  connBuf->len = 0;
808,294✔
1694
  connBuf->cap = 0;
808,294✔
1695
}
1696

1697
void udfcUvHandleError(SClientUvConn *conn) {
×
1698
  fnDebug("handle error on conn: %p, pipe: %p", conn, conn->pipe);
×
1699
  while (!QUEUE_EMPTY(&conn->taskQueue)) {
×
1700
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
×
1701
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
×
1702
    task->errCode = TSDB_CODE_UDF_PIPE_READ_ERR;
×
1703
    QUEUE_REMOVE(&task->connTaskQueue);
×
1704
    QUEUE_REMOVE(&task->procTaskQueue);
×
1705
    uv_sem_post(&task->taskSem);
×
1706
  }
1707
  if (!uv_is_closing((uv_handle_t *)conn->pipe)) {
×
1708
    uv_close((uv_handle_t *)conn->pipe, onUdfcPipeClose);
×
1709
  }
1710
}
×
1711

1712
void onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
2,424,882✔
1713
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
2,424,882✔
1714
  if (nread == 0) return;
2,424,882✔
1715

1716
  SClientUvConn  *conn = client->data;
1,616,588✔
1717
  SClientConnBuf *connBuf = &conn->readBuf;
1,616,588✔
1718
  if (nread > 0) {
1,616,588✔
1719
    connBuf->len += nread;
1,616,588✔
1720
    if (isUdfcUvMsgComplete(connBuf)) {
1,616,588✔
1721
      udfcUvHandleRsp(conn);
808,294✔
1722
    }
1723
  }
1724
  if (nread < 0) {
1,616,588✔
1725
    fnError("udfc client pipe %p read error: %zd(%s).", client, nread, uv_strerror(nread));
×
1726
    if (nread == UV_EOF) {
×
1727
      fnError("\tudfc client pipe %p closed", client);
×
1728
    }
1729
    udfcUvHandleError(conn);
×
1730
  }
1731
}
1732

1733
void onUdfcPipeWrite(uv_write_t *write, int32_t status) {
808,294✔
1734
  SClientUvConn *conn = write->data;
808,294✔
1735
  if (status < 0) {
808,294✔
1736
    fnError("udfc client connection %p write failed. status: %d(%s)", conn, status, uv_strerror(status));
×
1737
    udfcUvHandleError(conn);
×
1738
  } else {
1739
    fnDebug("udfc client connection %p write succeed", conn);
808,294✔
1740
  }
1741
  taosMemoryFree(write);
808,294✔
1742
}
808,294✔
1743

1744
void onUdfcPipeConnect(uv_connect_t *connect, int32_t status) {
92,512✔
1745
  SClientUvTaskNode *uvTask = connect->data;
92,512✔
1746
  if (status != 0) {
92,512✔
1747
    fnError("client connect error, task seq: %" PRId64 ", code:%s", uvTask->seqNum, uv_strerror(status));
×
1748
  }
1749
  uvTask->errCode = status;
92,512✔
1750

1751
  int32_t code = uv_read_start((uv_stream_t *)uvTask->pipe, udfcAllocateBuffer, onUdfcPipeRead);
92,512✔
1752
  if (code != 0) {
92,512✔
1753
    fnError("udfc client connection %p read start failed. code: %d(%s)", uvTask->pipe, code, uv_strerror(code));
×
1754
    uvTask->errCode = code;
×
1755
  }
1756
  taosMemoryFree(connect);
92,512✔
1757
  QUEUE_REMOVE(&uvTask->procTaskQueue);
92,512✔
1758
  uv_sem_post(&uvTask->taskSem);
92,512✔
1759
}
92,512✔
1760

1761
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask) {
993,318✔
1762
  uvTask->type = uvTaskType;
993,318✔
1763
  uvTask->udfc = task->session->udfc;
993,318✔
1764

1765
  if (uvTaskType == UV_TASK_CONNECT) {
993,318✔
1766
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
900,806✔
1767
    uvTask->pipe = task->session->udfUvPipe;
808,294✔
1768
    SUdfRequest request;
808,294✔
1769
    request.type = task->type;
808,294✔
1770
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
808,294✔
1771

1772
    if (task->type == UDF_TASK_SETUP) {
808,294✔
1773
      request.setup = task->_setup.req;
92,512✔
1774
      request.type = UDF_TASK_SETUP;
92,512✔
1775
    } else if (task->type == UDF_TASK_CALL) {
715,782✔
1776
      request.call = task->_call.req;
623,270✔
1777
      request.type = UDF_TASK_CALL;
623,270✔
1778
    } else if (task->type == UDF_TASK_TEARDOWN) {
92,512✔
1779
      request.teardown = task->_teardown.req;
92,512✔
1780
      request.type = UDF_TASK_TEARDOWN;
92,512✔
1781
    } else {
1782
      fnError("udfc create uv task, invalid task type : %d", task->type);
×
1783
    }
1784
    int32_t bufLen = encodeUdfRequest(NULL, &request);
808,294✔
1785
    if (bufLen <= 0) {
808,294✔
1786
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1787
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1788
    }
1789
    request.msgLen = bufLen;
808,294✔
1790
    void *bufBegin = taosMemoryMalloc(bufLen);
808,294✔
1791
    if (bufBegin == NULL) {
808,294✔
1792
      fnError("udfc create uv task, malloc buffer failed. size: %d", bufLen);
×
1793
      return terrno;
×
1794
    }
1795
    void *buf = bufBegin;
808,294✔
1796
    if (encodeUdfRequest(&buf, &request) <= 0) {
808,294✔
1797
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1798
      taosMemoryFree(bufBegin);
×
1799
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1800
    }
1801

1802
    uvTask->reqBuf = uv_buf_init(bufBegin, bufLen);
808,294✔
1803
    uvTask->seqNum = request.seqNum;
808,294✔
1804
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
92,512✔
1805
    uvTask->pipe = task->session->udfUvPipe;
92,512✔
1806
  }
1807
  if (uv_sem_init(&uvTask->taskSem, 0) != 0) {
993,318✔
1808
    if (uvTaskType == UV_TASK_REQ_RSP) {
×
1809
      taosMemoryFreeClear(uvTask->reqBuf.base);
×
1810
    }
1811
    fnError("udfc create uv task, init semaphore failed.");
×
1812
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1813
  }
1814

1815
  return 0;
993,318✔
1816
}
1817

1818
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask) {
993,318✔
1819
  fnDebug("queue uv task to event loop, uvTask: %d-%p", uvTask->type, uvTask);
993,318✔
1820
  SUdfcProxy *udfc = uvTask->udfc;
993,318✔
1821
  uv_mutex_lock(&udfc->taskQueueMutex);
993,318✔
1822
  QUEUE_INSERT_TAIL(&udfc->taskQueue, &uvTask->recvTaskQueue);
993,318✔
1823
  uv_mutex_unlock(&udfc->taskQueueMutex);
993,318✔
1824
  int32_t code = uv_async_send(&udfc->loopTaskAync);
993,318✔
1825
  if (code != 0) {
993,318✔
1826
    fnError("udfc queue uv task to event loop failed. code:%s", uv_strerror(code));
×
1827
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1828
  }
1829

1830
  uv_sem_wait(&uvTask->taskSem);
993,318✔
1831
  fnDebug("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
993,318✔
1832
  uv_sem_destroy(&uvTask->taskSem);
993,318✔
1833

1834
  return 0;
993,318✔
1835
}
1836

1837
int32_t udfcStartUvTask(SClientUvTaskNode *uvTask) {
993,318✔
1838
  fnDebug("event loop start uv task. uvTask: %" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
993,318✔
1839
  int32_t code = 0;
993,318✔
1840

1841
  switch (uvTask->type) {
993,318✔
1842
    case UV_TASK_CONNECT: {
92,512✔
1843
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
92,512✔
1844
      if (pipe == NULL) {
92,512✔
1845
        fnError("udfc event loop start connect task malloc pipe failed.");
×
1846
        return terrno;
×
1847
      }
1848
      if (uv_pipe_init(&uvTask->udfc->uvLoop, pipe, 0) != 0) {
92,512✔
1849
        fnError("udfc event loop start connect task uv_pipe_init failed.");
×
1850
        taosMemoryFree(pipe);
×
1851
        return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1852
      }
1853
      uvTask->pipe = pipe;
92,512✔
1854

1855
      SClientUvConn *conn = taosMemoryCalloc(1, sizeof(SClientUvConn));
92,512✔
1856
      if (conn == NULL) {
92,512✔
1857
        fnError("udfc event loop start connect task malloc conn failed.");
×
1858
        taosMemoryFree(pipe);
×
1859
        return terrno;
×
1860
      }
1861
      conn->pipe = pipe;
92,512✔
1862
      conn->readBuf.len = 0;
92,512✔
1863
      conn->readBuf.cap = 0;
92,512✔
1864
      conn->readBuf.buf = 0;
92,512✔
1865
      conn->readBuf.total = -1;
92,512✔
1866
      QUEUE_INIT(&conn->taskQueue);
92,512✔
1867

1868
      pipe->data = conn;
92,512✔
1869

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

1923
  return code;
993,318✔
1924
}
1925

1926
void udfcAsyncTaskCb(uv_async_t *async) {
993,318✔
1927
  SUdfcProxy *udfc = async->data;
993,318✔
1928
  QUEUE       wq;
993,318✔
1929
  QUEUE_INIT(&wq); 
993,318✔
1930
 
1931
  uv_mutex_lock(&udfc->taskQueueMutex);
993,318✔
1932
  QUEUE_MOVE(&udfc->taskQueue, &wq);
993,318✔
1933
  uv_mutex_unlock(&udfc->taskQueueMutex);
993,318✔
1934

1935
  while (!QUEUE_EMPTY(&wq)) {
1,986,636✔
1936
    QUEUE *h = QUEUE_HEAD(&wq);
993,318✔
1937
    QUEUE_REMOVE(h);
993,318✔
1938
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
993,318✔
1939
    int32_t            code = udfcStartUvTask(task);
993,318✔
1940
    if (code == 0) {
993,318✔
1941
      QUEUE_INSERT_TAIL(&udfc->uvProcTaskQueue, &task->procTaskQueue);
993,318✔
1942
    } else {
1943
      task->errCode = code;
×
1944
      uv_sem_post(&task->taskSem);
×
1945
    }
1946
  }
1947
}
993,318✔
1948

1949
void cleanUpUvTasks(SUdfcProxy *udfc) {
736,675✔
1950
  fnDebug("clean up uv tasks");
736,675✔
1951
  QUEUE wq;
734,801✔
1952
  QUEUE_INIT(&wq); 
736,675✔
1953

1954
  uv_mutex_lock(&udfc->taskQueueMutex);
736,675✔
1955
  QUEUE_MOVE(&udfc->taskQueue, &wq);
736,675✔
1956
  uv_mutex_unlock(&udfc->taskQueueMutex);
736,675✔
1957

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

1968
  while (!QUEUE_EMPTY(&udfc->uvProcTaskQueue)) {
736,675✔
1969
    QUEUE *h = QUEUE_HEAD(&udfc->uvProcTaskQueue);
×
1970
    QUEUE_REMOVE(h);
×
1971
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, procTaskQueue);
×
1972
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
×
1973
      task->errCode = TSDB_CODE_UDF_STOPPING;
×
1974
    }
1975
    uv_sem_post(&task->taskSem);
×
1976
  }
1977
}
736,675✔
1978

1979
void udfStopAsyncCb(uv_async_t *async) {
736,675✔
1980
  SUdfcProxy *udfc = async->data;
736,675✔
1981
  cleanUpUvTasks(udfc);
736,675✔
1982
  if (udfc->udfcState == UDFC_STATE_STOPPING) {
736,675✔
1983
    uv_stop(&udfc->uvLoop);
736,675✔
1984
  }
1985
}
736,675✔
1986

1987
void constructUdfService(void *argsThread) {
736,675✔
1988
  int32_t     code = 0, lino = 0;
736,675✔
1989
  SUdfcProxy *udfc = (SUdfcProxy *)argsThread;
736,675✔
1990
  code = uv_loop_init(&udfc->uvLoop);
736,675✔
1991
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
1992

1993
  code = uv_async_init(&udfc->uvLoop, &udfc->loopTaskAync, udfcAsyncTaskCb);
736,675✔
1994
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
1995
  udfc->loopTaskAync.data = udfc;
736,675✔
1996
  code = uv_async_init(&udfc->uvLoop, &udfc->loopStopAsync, udfStopAsyncCb);
736,675✔
1997
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
1998
  udfc->loopStopAsync.data = udfc;
736,675✔
1999
  code = uv_mutex_init(&udfc->taskQueueMutex);
736,675✔
2000
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
2001
  QUEUE_INIT(&udfc->taskQueue);
736,675✔
2002
  QUEUE_INIT(&udfc->uvProcTaskQueue);
736,675✔
2003
  (void)uv_barrier_wait(&udfc->initBarrier);
736,675✔
2004
  // TODO return value of uv_run
2005
  int32_t num = uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
736,675✔
2006
  fnInfo("udfc uv loop exit. active handle num: %d", num);
736,675✔
2007
  (void)uv_loop_close(&udfc->uvLoop);
736,675✔
2008

2009
  uv_walk(&udfc->uvLoop, udfUdfdCloseWalkCb, NULL);
736,675✔
2010
  num = uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
736,675✔
2011
  fnInfo("udfc uv loop exit. active handle num: %d", num);
736,675✔
2012

2013
  (void)uv_loop_close(&udfc->uvLoop);
736,675✔
2014
_exit:
736,675✔
2015
  if (code != 0) {
736,675✔
2016
    fnError("udfc construct error. code: %d, line: %d", code, lino);
×
2017
  }
2018
  fnInfo("udfc construct finished");
736,675✔
2019
}
736,675✔
2020

2021
int32_t udfcOpen() {
836,379✔
2022
  int32_t code = 0, lino = 0;
836,379✔
2023
  int8_t  old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 0, 1);
836,379✔
2024
  if (old == 1) {
836,379✔
2025
    return 0;
99,704✔
2026
  }
2027
  SUdfcProxy *proxy = &gUdfcProxy;
736,675✔
2028
  getUdfdPipeName(proxy->udfdPipeName, sizeof(proxy->udfdPipeName));
736,675✔
2029
  proxy->udfcState = UDFC_STATE_STARTNG;
736,675✔
2030
  code = uv_barrier_init(&proxy->initBarrier, 2);
736,675✔
2031
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
2032
  code = uv_thread_create(&proxy->loopThread, constructUdfService, proxy);
736,675✔
2033
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
2034
  atomic_store_8(&proxy->udfcState, UDFC_STATE_READY);
736,675✔
2035
  proxy->udfcState = UDFC_STATE_READY;
736,675✔
2036
  (void)uv_barrier_wait(&proxy->initBarrier);
736,675✔
2037
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
2038
  code = uv_mutex_init(&proxy->udfStubsMutex);
736,675✔
2039
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
2040
  proxy->udfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
736,675✔
2041
  if (proxy->udfStubs == NULL) {
736,675✔
2042
    fnError("udfc init failed. udfStubs: %p", proxy->udfStubs);
×
2043
    return -1;
×
2044
  }
2045
  proxy->expiredUdfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
736,675✔
2046
  if (proxy->expiredUdfStubs == NULL) {
736,675✔
2047
    taosArrayDestroy(proxy->udfStubs);
×
2048
    fnError("udfc init failed. expiredUdfStubs: %p", proxy->expiredUdfStubs);
×
2049
    return -1;
×
2050
  }
2051
  code = uv_mutex_init(&proxy->udfcUvMutex);
736,675✔
2052
  TAOS_CHECK_GOTO(code, &lino, _exit);
736,675✔
2053
_exit:
736,675✔
2054
  if (code != 0) {
736,675✔
2055
    fnError("udfc open error. code: %d, line: %d", code, lino);
×
2056
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
2057
  }
2058
  fnInfo("udfc initialized");
736,675✔
2059
  return 0;
736,675✔
2060
}
2061

2062
int32_t udfcClose() {
740,546✔
2063
  int8_t old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 1, 0);
740,546✔
2064
  if (old == 0) {
740,546✔
2065
    return 0;
3,871✔
2066
  }
2067

2068
  SUdfcProxy *udfc = &gUdfcProxy;
736,675✔
2069
  udfc->udfcState = UDFC_STATE_STOPPING;
736,675✔
2070
  if (uv_async_send(&udfc->loopStopAsync) != 0) {
736,675✔
2071
    fnError("udfc close error to send stop async");
×
2072
  }
2073
  if (uv_thread_join(&udfc->loopThread) != 0) {
736,675✔
2074
    fnError("udfc close errir to join loop thread");
×
2075
  }
2076
  uv_mutex_destroy(&udfc->taskQueueMutex);
736,675✔
2077
  uv_barrier_destroy(&udfc->initBarrier);
736,675✔
2078
  taosArrayDestroy(udfc->expiredUdfStubs);
736,675✔
2079
  taosArrayDestroy(udfc->udfStubs);
736,675✔
2080
  uv_mutex_destroy(&udfc->udfStubsMutex);
736,675✔
2081
  uv_mutex_destroy(&udfc->udfcUvMutex);
736,675✔
2082
  udfc->udfcState = UDFC_STATE_INITAL;
736,675✔
2083
  fnInfo("udfc is cleaned up");
736,675✔
2084
  return 0;
736,675✔
2085
}
2086

2087
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType) {
993,318✔
2088
  int32_t            code = 0, lino = 0;
993,318✔
2089
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
993,318✔
2090
  if (uvTask == NULL) {
993,318✔
2091
    fnError("udfc client task: %p failed to allocate memory for uvTask", task);
×
2092
    return terrno;
×
2093
  }
2094
  fnDebug("udfc client task: %p created uvTask: %p. pipe: %p", task, uvTask, task->session->udfUvPipe);
993,318✔
2095

2096
  code = udfcInitializeUvTask(task, uvTaskType, uvTask);
993,318✔
2097
  TAOS_CHECK_GOTO(code, &lino, _exit);
993,318✔
2098
  code = udfcQueueUvTask(uvTask);
993,318✔
2099
  TAOS_CHECK_GOTO(code, &lino, _exit);
993,318✔
2100
  code = udfcGetUdfTaskResultFromUvTask(task, uvTask);
993,318✔
2101
  TAOS_CHECK_GOTO(code, &lino, _exit);
993,318✔
2102
  if (uvTaskType == UV_TASK_CONNECT) {
993,318✔
2103
    task->session->udfUvPipe = uvTask->pipe;
92,512✔
2104
    SClientUvConn *conn = uvTask->pipe->data;
92,512✔
2105
    conn->session = task->session;
92,512✔
2106
  }
2107

2108
_exit:
993,318✔
2109
  if (code != 0) {
993,318✔
2110
    fnError("udfc run udf uv task failure. task: %p, uvTask: %p, err: %d, line: %d", task, uvTask, code, lino);
×
2111
  }
2112
  taosMemoryFree(uvTask->reqBuf.base);
993,318✔
2113
  uvTask->reqBuf.base = NULL;
993,318✔
2114
  taosMemoryFree(uvTask);
993,318✔
2115
  uvTask = NULL;
993,318✔
2116
  return code;
993,318✔
2117
}
2118

2119
static void freeTaskSession(SClientUdfTask *task) {
92,512✔
2120
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
92,512✔
2121
  if (task->session->udfUvPipe != NULL && task->session->udfUvPipe->data != NULL) {
92,512✔
2122
    SClientUvConn *conn = task->session->udfUvPipe->data;
19,400✔
2123
    conn->session = NULL;
19,400✔
2124
  }
2125
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
92,512✔
2126
  taosMemoryFreeClear(task->session);
92,512✔
2127
}
92,512✔
2128

2129
int32_t doSetupUdf(char udfName[], UdfcFuncHandle *funcHandle) {
92,512✔
2130
  int32_t         code = TSDB_CODE_SUCCESS, lino = 0;
92,512✔
2131
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
92,512✔
2132
  if (task == NULL) {
92,512✔
2133
    fnError("doSetupUdf, failed to allocate memory for task");
×
2134
    return terrno;
×
2135
  }
2136
  task->session = taosMemoryCalloc(1, sizeof(SUdfcUvSession));
92,512✔
2137
  if (task->session == NULL) {
92,512✔
2138
    fnError("doSetupUdf, failed to allocate memory for session");
×
2139
    taosMemoryFree(task);
×
2140
    return terrno;
×
2141
  }
2142
  task->session->udfc = &gUdfcProxy;
92,512✔
2143
  task->type = UDF_TASK_SETUP;
92,512✔
2144

2145
  SUdfSetupRequest *req = &task->_setup.req;
92,512✔
2146
  tstrncpy(req->udfName, udfName, TSDB_FUNC_NAME_LEN);
92,512✔
2147

2148
  code = udfcRunUdfUvTask(task, UV_TASK_CONNECT);
92,512✔
2149
  TAOS_CHECK_GOTO(code, &lino, _exit);
92,512✔
2150

2151
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
92,512✔
2152
  TAOS_CHECK_GOTO(code, &lino, _exit);
92,512✔
2153

2154
  SUdfSetupResponse *rsp = &task->_setup.rsp;
92,512✔
2155
  task->session->severHandle = rsp->udfHandle;
92,512✔
2156
  task->session->outputType = rsp->outputType;
92,512✔
2157
  task->session->bytes = rsp->bytes;
92,512✔
2158
  task->session->bufSize = rsp->bufSize;
92,512✔
2159
  tstrncpy(task->session->udfName, udfName, TSDB_FUNC_NAME_LEN);
92,512✔
2160
  fnInfo("successfully setup udf func handle. udfName: %s, handle: %p", udfName, task->session);
92,512✔
2161
  *funcHandle = task->session;
92,512✔
2162
  taosMemoryFree(task);
92,512✔
2163
  return 0;
92,512✔
2164

2165
_exit:
×
2166
  if (code != 0) {
×
2167
    fnError("failed to setup udf. udfname: %s, err: %d line:%d", udfName, code, lino);
×
2168
  }
2169
  freeTaskSession(task);
×
2170
  taosMemoryFree(task);
×
2171
  return code;
×
2172
}
2173

2174
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
623,270✔
2175
                SSDataBlock *output, SUdfInterBuf *newState) {
2176
  fnDebug("udfc call udf. callType: %d, funcHandle: %p", callType, handle);
623,270✔
2177
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
623,270✔
2178
  if (session->udfUvPipe == NULL) {
623,270✔
2179
    fnError("No pipe to udfd");
×
2180
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2181
  }
2182
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
623,270✔
2183
  if (task == NULL) {
623,270✔
2184
    fnError("udfc call udf. failed to allocate memory for task");
×
2185
    return terrno;
×
2186
  }
2187
  task->session = (SUdfcUvSession *)handle;
623,270✔
2188
  task->type = UDF_TASK_CALL;
623,270✔
2189

2190
  SUdfCallRequest *req = &task->_call.req;
623,270✔
2191
  req->udfHandle = task->session->severHandle;
623,270✔
2192
  req->callType = callType;
623,270✔
2193

2194
  switch (callType) {
623,270✔
2195
    case TSDB_UDF_CALL_AGG_INIT: {
124,333✔
2196
      req->initFirst = 1;
124,333✔
2197
      break;
124,333✔
2198
    }
2199
    case TSDB_UDF_CALL_AGG_PROC: {
270,603✔
2200
      req->block = *input;
270,603✔
2201
      req->interBuf = *state;
270,603✔
2202
      break;
270,603✔
2203
    }
2204
    // case TSDB_UDF_CALL_AGG_MERGE: {
2205
    //   req->interBuf = *state;
2206
    //   req->interBuf2 = *state2;
2207
    //   break;
2208
    // }
2209
    case TSDB_UDF_CALL_AGG_FIN: {
124,333✔
2210
      req->interBuf = *state;
124,333✔
2211
      break;
124,333✔
2212
    }
2213
    case TSDB_UDF_CALL_SCALA_PROC: {
104,001✔
2214
      req->block = *input;
104,001✔
2215
      break;
104,001✔
2216
    }
2217
  }
2218

2219
  int32_t code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
623,270✔
2220
  if (code != 0) {
623,270✔
2221
    fnError("call udf failure. udfcRunUdfUvTask err: %d", code);
×
2222
  } else {
2223
    SUdfCallResponse *rsp = &task->_call.rsp;
623,270✔
2224
    switch (callType) {
623,270✔
2225
      case TSDB_UDF_CALL_AGG_INIT: {
124,333✔
2226
        *newState = rsp->resultBuf;
124,333✔
2227
        break;
124,333✔
2228
      }
2229
      case TSDB_UDF_CALL_AGG_PROC: {
270,603✔
2230
        *newState = rsp->resultBuf;
270,603✔
2231
        break;
270,603✔
2232
      }
2233
      // case TSDB_UDF_CALL_AGG_MERGE: {
2234
      //   *newState = rsp->resultBuf;
2235
      //   break;
2236
      // }
2237
      case TSDB_UDF_CALL_AGG_FIN: {
124,333✔
2238
        *newState = rsp->resultBuf;
124,333✔
2239
        break;
124,333✔
2240
      }
2241
      case TSDB_UDF_CALL_SCALA_PROC: {
104,001✔
2242
        *output = rsp->resultData;
104,001✔
2243
        break;
104,001✔
2244
      }
2245
    }
2246
  }
2247
  taosMemoryFree(task);
623,270✔
2248
  return code;
623,270✔
2249
}
2250

2251
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf) {
124,333✔
2252
  int8_t callType = TSDB_UDF_CALL_AGG_INIT;
124,333✔
2253

2254
  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);
124,333✔
2255

2256
  return err;
124,333✔
2257
}
2258

2259
// input: block, state
2260
// output: interbuf,
2261
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
270,603✔
2262
  int8_t  callType = TSDB_UDF_CALL_AGG_PROC;
270,603✔
2263
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
270,603✔
2264
  return err;
270,603✔
2265
}
2266

2267
// input: interbuf1, interbuf2
2268
// output: resultBuf
2269
// udf todo:  aggmerge
2270
// int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
2271
//                           SUdfInterBuf *resultBuf) {
2272
//   int8_t  callType = TSDB_UDF_CALL_AGG_MERGE;
2273
//   int32_t err = callUdf(handle, callType, NULL, interBuf1, interBuf2, NULL, resultBuf);
2274
//   return err;
2275
// }
2276

2277
// input: interBuf
2278
// output: resultData
2279
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData) {
124,333✔
2280
  int8_t  callType = TSDB_UDF_CALL_AGG_FIN;
124,333✔
2281
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
124,333✔
2282
  return err;
124,333✔
2283
}
2284

2285
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
104,001✔
2286
  int8_t      callType = TSDB_UDF_CALL_SCALA_PROC;
104,001✔
2287
  SSDataBlock inputBlock = {0};
104,001✔
2288
  int32_t     code = convertScalarParamToDataBlock(input, numOfCols, &inputBlock);
104,001✔
2289
  if (code != 0) {
104,001✔
2290
    fnError("doCallUdfScalarFunc, convertScalarParamToDataBlock failed. code: %d", code);
×
2291
    return code;
×
2292
  }
2293
  SSDataBlock resultBlock = {0};
104,001✔
2294
  int32_t     err = callUdf(handle, callType, &inputBlock, NULL, NULL, &resultBlock, NULL);
104,001✔
2295
  if (err == 0) {
104,001✔
2296
    err = convertDataBlockToScalarParm(&resultBlock, output);
104,001✔
2297
  }
2298
  taosArrayDestroy(resultBlock.pDataBlock);
104,001✔
2299

2300
  blockDataFreeRes(&inputBlock);
104,001✔
2301
  return err;
104,001✔
2302
}
2303

2304
int32_t doTeardownUdf(UdfcFuncHandle handle) {
92,512✔
2305
  int32_t         code = TSDB_CODE_SUCCESS, lino = 0;
92,512✔
2306
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
92,512✔
2307

2308
  if (session->udfUvPipe == NULL) {
92,512✔
2309
    fnError("tear down udf. pipe to udfd does not exist. udf name: %s", session->udfName);
×
2310
    taosMemoryFree(session);
×
2311
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2312
  }
2313

2314
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
92,512✔
2315
  if (task == NULL) {
92,512✔
2316
    fnError("doTeardownUdf, failed to allocate memory for task");
×
2317
    taosMemoryFree(session);
×
2318
    return terrno;
×
2319
  }
2320
  task->session = session;
92,512✔
2321
  task->type = UDF_TASK_TEARDOWN;
92,512✔
2322

2323
  SUdfTeardownRequest *req = &task->_teardown.req;
92,512✔
2324
  req->udfHandle = task->session->severHandle;
92,512✔
2325

2326
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
92,512✔
2327
  TAOS_CHECK_GOTO(code, &lino, _exit);
92,512✔
2328

2329
  code = udfcRunUdfUvTask(task, UV_TASK_DISCONNECT);
92,512✔
2330
  TAOS_CHECK_GOTO(code, &lino, _exit);
92,512✔
2331

2332
  fnInfo("tear down udf. udf name: %s, udf func handle: %p", session->udfName, handle);
92,512✔
2333
  // TODO: synchronization refactor between libuv event loop and request thread
2334
  // uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
2335
  // if (session->udfUvPipe != NULL && session->udfUvPipe->data != NULL) {
2336
  //   SClientUvConn *conn = session->udfUvPipe->data;
2337
  //   conn->session = NULL;
2338
  // }
2339
  // uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
2340

2341
_exit:
92,512✔
2342
  if (code != 0) {
92,512✔
2343
    fnError("failed to teardown udf. udf name: %s, err: %d, line: %d", session->udfName, code, lino);
×
2344
  }
2345
  freeTaskSession(task);
92,512✔
2346
  taosMemoryFree(task);
92,512✔
2347

2348
  return code;
92,512✔
2349
}
2350
#else
2351
#include "tudf.h"
2352

2353
int32_t cleanUpUdfs() { return 0; }
2354
int32_t udfcOpen() { return 0; }
2355
int32_t udfcClose() { return 0; }
2356
int32_t udfStartUdfd(int32_t startDnodeId) { return 0; }
2357
void    udfStopUdfd() { return; }
2358
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
2359
  return TSDB_CODE_OPS_NOT_SUPPORT;
2360
}
2361
#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