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

taosdata / TDengine / #5048

10 May 2026 03:11AM UTC coverage: 73.222% (+0.07%) from 73.152%
#5048

push

travis-ci

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

353 of 452 new or added lines in 9 files covered. (78.1%)

587 existing lines in 140 files now uncovered.

278189 of 379928 relevant lines covered (73.22%)

135206397.85 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

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

84
static int32_t udfSpawnUdfd(SUdfdData *pData) {
700,627✔
85
  fnInfo("start to init udfd");
700,627✔
86
  TAOS_UDF_CHECK_PTR_RCODE(pData);
1,401,254✔
87

88
  int32_t              err = 0;
700,627✔
89
  uv_process_options_t options = {0};
700,627✔
90

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

122
  options.exit_cb = udfUdfdExit;
700,627✔
123

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

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

135
  options.flags = UV_PROCESS_DETACHED;
700,627✔
136

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

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

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

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

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

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

188
  char **envUdfdWithPEnv = NULL;
700,627✔
189
  if (environ != NULL) {
700,627✔
190
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
700,627✔
191
    int32_t numEnviron = 0;
700,627✔
192
    while (environ[numEnviron] != NULL) {
21,180,315✔
193
      numEnviron++;
20,479,688✔
194
    }
195

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

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

210
      tstrncpy(envUdfdWithPEnv[i], environ[i], len);
20,479,688✔
211
    }
212

213
    for (int32_t i = 0; i < lenEnvUdfd; i++) {
4,203,762✔
214
      if (envUdfd[i] != NULL) {
3,503,135✔
215
        int32_t len = strlen(envUdfd[i]) + 1;
2,101,881✔
216
        envUdfdWithPEnv[numEnviron + i] = (char *)taosMemoryCalloc(len, 1);
2,101,881✔
217
        if (envUdfdWithPEnv[numEnviron + i] == NULL) {
2,101,881✔
218
          err = TSDB_CODE_OUT_OF_MEMORY;
×
219
          goto _OVER;
×
220
        }
221

222
        tstrncpy(envUdfdWithPEnv[numEnviron + i], envUdfd[i], len);
2,101,881✔
223
      }
224
    }
225
    envUdfdWithPEnv[numEnviron + lenEnvUdfd - 1] = NULL;
700,627✔
226

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

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

260
_OVER:
697,169✔
261
  if (taosFqdnEnvItem) {
700,627✔
262
    taosMemoryFree(taosFqdnEnvItem);
×
263
  }
264

265
  if (envUdfdWithPEnv != NULL) {
700,627✔
266
    int32_t i = 0;
700,627✔
267
    while (envUdfdWithPEnv[i] != NULL) {
23,282,196✔
268
      taosMemoryFree(envUdfdWithPEnv[i]);
22,581,569✔
269
      i++;
22,581,569✔
270
    }
271
    taosMemoryFree(envUdfdWithPEnv);
700,627✔
272
  }
273

274
  return err;
700,627✔
275
}
276

277
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
3,484,131✔
278
  TAOS_UDF_CHECK_PTR_RVOID(handle);
6,968,262✔
279
  if (!uv_is_closing(handle)) {
3,484,131✔
280
    uv_close(handle, NULL);
3,484,131✔
281
  }
282
}
283

284
static void udfUdfdStopAsyncCb(uv_async_t *async) {
697,451✔
285
  TAOS_UDF_CHECK_PTR_RVOID(async);
1,394,902✔
286
  SUdfdData *pData = async->data;
697,451✔
287
  uv_stop(&pData->loop);
697,451✔
288
}
289

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

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

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

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

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

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

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

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

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

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

661
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
976,952✔
662
  int32_t len = 0;
976,952✔
663
  len += taosEncodeFixedI64(buf, call->udfHandle);
976,952✔
664
  len += taosEncodeFixedI8(buf, call->callType);
976,952✔
665
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
976,952✔
666
    len += tEncodeDataBlock(buf, &call->block);
197,120✔
667
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
779,832✔
668
    len += taosEncodeFixedI8(buf, call->initFirst);
358,496✔
669
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
600,584✔
670
    len += tEncodeDataBlock(buf, &call->block);
421,336✔
671
    len += encodeUdfInterBuf(buf, &call->interBuf);
421,336✔
672
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
179,248✔
673
    // len += encodeUdfInterBuf(buf, &call->interBuf);
674
    // len += encodeUdfInterBuf(buf, &call->interBuf2);
675
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
179,248✔
676
    len += encodeUdfInterBuf(buf, &call->interBuf);
179,248✔
677
  }
678
  return len;
976,952✔
679
}
680

681
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
1,111,488✔
682
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
1,111,488✔
683
  buf = taosDecodeFixedI8(buf, &call->callType);
1,111,488✔
684
  switch (call->callType) {
1,111,488✔
685
    case TSDB_UDF_CALL_SCALA_PROC:
514,188✔
686
      buf = tDecodeDataBlock(buf, &call->block);
514,188✔
687
      break;
514,128✔
688
    case TSDB_UDF_CALL_AGG_INIT:
130,808✔
689
      buf = taosDecodeFixedI8(buf, &call->initFirst);
130,808✔
690
      break;
130,808✔
691
    case TSDB_UDF_CALL_AGG_PROC:
337,058✔
692
      buf = tDecodeDataBlock(buf, &call->block);
337,058✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
337,058✔
694
      break;
337,118✔
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:
129,554✔
700
      buf = decodeUdfInterBuf(buf, &call->interBuf);
129,554✔
701
      break;
129,554✔
702
  }
703
  return (void *)buf;
1,111,488✔
704
}
705

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

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

717
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
1,294,096✔
718
  int32_t len = 0;
1,294,096✔
719
  if (buf == NULL) {
1,294,096✔
720
    len += sizeof(request->msgLen);
647,048✔
721
  } else {
722
    *(int32_t *)(*buf) = request->msgLen;
647,048✔
723
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
647,048✔
724
  }
725
  len += taosEncodeFixedI64(buf, request->seqNum);
1,294,096✔
726
  len += taosEncodeFixedI8(buf, request->type);
1,294,096✔
727
  if (request->type == UDF_TASK_SETUP) {
1,294,096✔
728
    len += encodeUdfSetupRequest(buf, &request->setup);
158,572✔
729
  } else if (request->type == UDF_TASK_CALL) {
1,135,524✔
730
    len += encodeUdfCallRequest(buf, &request->call);
976,952✔
731
  } else if (request->type == UDF_TASK_TEARDOWN) {
158,572✔
732
    len += encodeUdfTeardownRequest(buf, &request->teardown);
158,572✔
733
  }
734
  return len;
1,294,096✔
735
}
736

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

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

744
  if (request->type == UDF_TASK_SETUP) {
1,434,620✔
745
    buf = decodeUdfSetupRequest(buf, &request->setup);
162,100✔
746
  } else if (request->type == UDF_TASK_CALL) {
1,272,520✔
747
    buf = decodeUdfCallRequest(buf, &request->call);
1,111,608✔
748
  } else if (request->type == UDF_TASK_TEARDOWN) {
160,912✔
749
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
160,978✔
750
  }
751
  return (void *)buf;
1,434,626✔
752
}
753

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

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

771
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp) {
2,222,190✔
772
  int32_t len = 0;
2,222,190✔
773
  len += taosEncodeFixedI8(buf, callRsp->callType);
2,222,190✔
774
  switch (callRsp->callType) {
2,222,190✔
775
    case TSDB_UDF_CALL_SCALA_PROC:
1,027,230✔
776
      len += tEncodeDataBlock(buf, &callRsp->resultData);
1,027,230✔
777
      break;
1,026,750✔
778
    case TSDB_UDF_CALL_AGG_INIT:
261,616✔
779
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
261,616✔
780
      break;
261,616✔
781
    case TSDB_UDF_CALL_AGG_PROC:
674,116✔
782
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
674,116✔
783
      break;
674,116✔
784
    // case TSDB_UDF_CALL_AGG_MERGE:
785
    //   len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
786
    //   break;
787
    case TSDB_UDF_CALL_AGG_FIN:
259,108✔
788
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
259,108✔
789
      break;
259,108✔
790
  }
791
  return len;
2,221,710✔
792
}
793

794
void *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp) {
488,476✔
795
  buf = taosDecodeFixedI8(buf, &callRsp->callType);
488,476✔
796
  switch (callRsp->callType) {
488,476✔
797
    case TSDB_UDF_CALL_SCALA_PROC:
98,560✔
798
      buf = tDecodeDataBlock(buf, &callRsp->resultData);
98,560✔
799
      break;
98,560✔
800
    case TSDB_UDF_CALL_AGG_INIT:
89,624✔
801
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
89,624✔
802
      break;
89,624✔
803
    case TSDB_UDF_CALL_AGG_PROC:
210,668✔
804
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
210,668✔
805
      break;
210,668✔
806
    // case TSDB_UDF_CALL_AGG_MERGE:
807
    //   buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
808
    //   break;
809
    case TSDB_UDF_CALL_AGG_FIN:
89,624✔
810
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
89,624✔
811
      break;
89,624✔
812
  }
813
  return (void *)buf;
488,476✔
814
}
815

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

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

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

828
  len += sizeof(rsp->seqNum);
2,868,766✔
829
  if (buf != NULL) {
2,868,766✔
830
    *(int64_t *)(*buf) = rsp->seqNum;
1,434,566✔
831
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
1,434,566✔
832
  }
833

834
  len += taosEncodeFixedI64(buf, rsp->seqNum);
2,868,766✔
835
  len += taosEncodeFixedI8(buf, rsp->type);
2,868,766✔
836
  len += taosEncodeFixedI32(buf, rsp->code);
2,868,766✔
837

838
  switch (rsp->type) {
2,868,766✔
839
    case UDF_TASK_SETUP:
324,200✔
840
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
324,200✔
841
      break;
324,200✔
842
    case UDF_TASK_CALL:
2,222,370✔
843
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
2,222,370✔
844
      break;
2,221,050✔
845
    case UDF_TASK_TEARDOWN:
321,956✔
846
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
321,956✔
847
      break;
321,956✔
848
    default:
240✔
849
      fnError("encode udf response, invalid udf response type %d", rsp->type);
240✔
850
      break;
×
851
  }
852
  return len;
2,867,206✔
853
}
854

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

864
  switch (rsp->type) {
647,048✔
865
    case UDF_TASK_SETUP:
79,286✔
866
      buf = decodeUdfSetupResponse(buf, &rsp->setupRsp);
79,286✔
867
      break;
79,286✔
868
    case UDF_TASK_CALL:
488,476✔
869
      if (rsp->code) {
488,476✔
870
        fnError("udf response failed, code:0x%x", rsp->code);
×
871

872
        return NULL;
×
873
      }
874

875
      buf = decodeUdfCallResponse(buf, &rsp->callRsp);
488,476✔
876
      break;
488,476✔
877
    case UDF_TASK_TEARDOWN:
79,286✔
878
      buf = decodeUdfTeardownResponse(buf, &rsp->teardownRsp);
79,286✔
879
      break;
79,286✔
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) {
647,048✔
886
    rsp->code = terrno;
×
887
    fnError("decode udf response failed, code:0x%x", rsp->code);
×
888
  }
889
  return (void *)buf;
647,048✔
890
}
891

892
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
1,429,726✔
893
  TAOS_UDF_CHECK_PTR_RVOID(data, meta);
4,289,286✔
894
  if (IS_VAR_DATA_TYPE(meta->type)) {
1,429,726✔
895
    taosMemoryFree(data->varLenCol.varOffsets);
17,046✔
896
    data->varLenCol.varOffsets = NULL;
17,226✔
897
    taosMemoryFree(data->varLenCol.payload);
17,226✔
898
    data->varLenCol.payload = NULL;
17,226✔
899
  } else {
900
    taosMemoryFree(data->fixLenCol.nullBitmap);
1,412,680✔
901
    data->fixLenCol.nullBitmap = NULL;
1,412,920✔
902
    taosMemoryFree(data->fixLenCol.data);
1,412,920✔
903
    data->fixLenCol.data = NULL;
1,413,034✔
904
  }
905
}
906

907
void freeUdfColumn(SUdfColumn *col) {
1,430,086✔
908
  TAOS_UDF_CHECK_PTR_RVOID(col);
2,860,172✔
909
  freeUdfColumnData(&col->colData, &col->colMeta);
1,430,086✔
910
}
911

912
void freeUdfDataDataBlock(SUdfDataBlock *block) {
850,826✔
913
  TAOS_UDF_CHECK_PTR_RVOID(block);
1,701,832✔
914
  for (int32_t i = 0; i < block->numOfCols; ++i) {
1,767,018✔
915
    freeUdfColumn(block->udfCols[i]);
916,018✔
916
    taosMemoryFree(block->udfCols[i]);
916,132✔
917
    block->udfCols[i] = NULL;
916,192✔
918
  }
919
  taosMemoryFree(block->udfCols);
851,000✔
920
  block->udfCols = NULL;
851,120✔
921
}
922

923
void freeUdfInterBuf(SUdfInterBuf *buf) {
1,453,948✔
924
  TAOS_UDF_CHECK_PTR_RVOID(buf);
2,907,896✔
925
  taosMemoryFree(buf->buf);
1,453,948✔
926
  buf->buf = NULL;
1,453,948✔
927
}
928

929
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
851,126✔
930
  TAOS_UDF_CHECK_PTR_RCODE(block, udfBlock);
2,553,318✔
931
  int32_t code = blockDataCheck(block);
851,126✔
932
  if (code != TSDB_CODE_SUCCESS) {
850,706✔
933
    return code;
×
934
  }
935
  udfBlock->numOfRows = block->info.rows;
850,706✔
936
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
850,706✔
937
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
850,526✔
938
  if ((udfBlock->udfCols) == NULL) {
851,186✔
939
    return terrno;
×
940
  }
941
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
1,767,324✔
942
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
915,958✔
943
    if (udfBlock->udfCols[i] == NULL) {
915,958✔
944
      return terrno;
×
945
    }
946
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
915,958✔
947
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
916,138✔
948
    udfCol->colMeta.type = col->info.type;
916,138✔
949
    udfCol->colMeta.bytes = col->info.bytes;
916,138✔
950
    udfCol->colMeta.scale = col->info.scale;
916,138✔
951
    udfCol->colMeta.precision = col->info.precision;
916,138✔
952
    udfCol->colData.numOfRows = udfBlock->numOfRows;
916,138✔
953
    udfCol->hasNull = col->hasNull;
916,138✔
954
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
916,138✔
955
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
10,926✔
956
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
10,926✔
957
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
10,626✔
958
        return terrno;
×
959
      }
960
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
10,626✔
961
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
10,626✔
962
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
10,626✔
963
      if (udfCol->colData.varLenCol.payload == NULL) {
10,626✔
964
        return terrno;
×
965
      }
966
      if (col->reassigned) {
10,626✔
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,626✔
982
      }
983
    } else {
984
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
905,212✔
985
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
905,212✔
986
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
905,212✔
987
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
905,332✔
988
        return terrno;
×
989
      }
990
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
905,332✔
991
      memcpy(bitmap, col->nullbitmap, bitmapLen);
905,332✔
992
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
905,332✔
993
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
905,572✔
994
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
905,572✔
995
      if (NULL == udfCol->colData.fixLenCol.data) {
905,512✔
996
        return terrno;
×
997
      }
998
      char *data = udfCol->colData.fixLenCol.data;
905,512✔
999
      memcpy(data, col->pData, dataLen);
905,512✔
1000
    }
1001
  }
1002
  return TSDB_CODE_SUCCESS;
851,366✔
1003
}
1004

1005
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
512,592✔
1006
  TAOS_UDF_CHECK_PTR_RCODE(udfCol, block);
1,537,650✔
1007
  int32_t         code = 0, lino = 0;
512,592✔
1008
  SUdfColumnMeta *meta = &udfCol->colMeta;
512,592✔
1009

1010
  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
512,592✔
1011
  code = blockDataAppendColInfo(block, &colInfoData);
512,592✔
1012
  TAOS_CHECK_GOTO(code, &lino, _exit);
512,772✔
1013

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

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

1021
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
453,789,882✔
1022
    if (udfColDataIsNull(udfCol, i)) {
454,665,612✔
1023
      colDataSetNULL(col, i);
46,319,328✔
1024
    } else {
1025
      char *data = udfColDataGetData(udfCol, i);
408,346,284✔
1026
      code = colDataSetVal(col, i, data, false);
408,346,284✔
1027
      TAOS_CHECK_GOTO(code, &lino, _exit);
406,957,782✔
1028
    }
1029
  }
1030
  block->info.rows = udfCol->colData.numOfRows;
102,570✔
1031

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

1041
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
98,560✔
1042
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
295,680✔
1043
  int32_t code = 0, lino = 0;
98,560✔
1044
  int32_t numOfRows = 0;
98,560✔
1045
  for (int32_t i = 0; i < numOfCols; ++i) {
200,816✔
1046
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
102,256✔
1047
  }
1048

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

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

1058
  TAOS_CHECK_GOTO(blockDataEnsureCapacity(output, numOfRows), &lino, _exit);
98,560✔
1059

1060
  for (int32_t i = 0; i < numOfCols; ++i) {
200,816✔
1061
    SColumnInfoData *pDest = taosArrayGet(output->pDataBlock, i);
102,256✔
1062

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

1066
    if (input[i].numOfRows < numOfRows) {
102,256✔
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;
98,560✔
1082
_exit:
98,560✔
1083
  if (code != 0) {
98,560✔
1084
    fnError("failed to convert scalar param to data block, code:%d, line:%d", code, lino);
×
1085
  }
1086
  return code;
98,560✔
1087
}
1088

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

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

1104
  return 0;
98,560✔
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,416,030✔
1164
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
1,416,030✔
1165
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
1,416,030✔
1166
  return strcmp(stub1->udfName, stub2->udfName);
1,416,030✔
1167
}
1168

1169
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle) {
488,476✔
1170
  TAOS_UDF_CHECK_PTR_RCODE(udfName, pHandle);
1,465,428✔
1171
  int32_t code = 0, line = 0;
488,476✔
1172
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
488,476✔
1173
  SUdfcFuncStub key = {0};
488,476✔
1174
  tstrncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
488,476✔
1175
  int32_t stubIndex = taosArraySearchIdx(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
488,476✔
1176
  if (stubIndex != -1) {
488,476✔
1177
    SUdfcFuncStub *foundStub = taosArrayGet(gUdfcProxy.udfStubs, stubIndex);
409,190✔
1178
    UdfcFuncHandle handle = foundStub->handle;
409,190✔
1179
    int64_t        currUs = taosGetTimestampUs();
409,190✔
1180
    bool           expired = (currUs - foundStub->createTime) >= 10 * 1000 * 1000;
409,190✔
1181
    if (!expired) {
409,190✔
1182
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
409,190✔
1183
        *pHandle = foundStub->handle;
409,190✔
1184
        ++foundStub->refCount;
409,190✔
1185
        uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
409,190✔
1186
        return 0;
409,190✔
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;
79,286✔
1204
  code = doSetupUdf(udfName, pHandle);
79,286✔
1205
  if (code == TSDB_CODE_SUCCESS) {
79,286✔
1206
    SUdfcFuncStub stub = {0};
79,286✔
1207
    tstrncpy(stub.udfName, udfName, TSDB_FUNC_NAME_LEN);
79,286✔
1208
    stub.handle = *pHandle;
79,286✔
1209
    ++stub.refCount;
79,286✔
1210
    stub.createTime = taosGetTimestampUs();
79,286✔
1211
    //uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
1212
    if (taosArrayPush(gUdfcProxy.udfStubs, &stub) == NULL) {
158,572✔
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);
79,286✔
1218
    }
1219
  } else {
1220
    *pHandle = NULL;
×
1221
  }
1222

1223
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
79,286✔
1224

1225
_exit:
79,286✔
1226
  return code;
79,286✔
1227
}
1228

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

1249
void cleanupExpiredUdfs() {
65,734✔
1250
  int32_t i = 0;
65,734✔
1251
  SArray *expiredUdfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
65,734✔
1252
  if (expiredUdfStubs == NULL) {
65,734✔
1253
    fnError("cleanupExpiredUdfs: failed to init array");
×
1254
    return;
×
1255
  }
1256
  while (i < taosArrayGetSize(gUdfcProxy.expiredUdfStubs)) {
65,734✔
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);
65,734✔
1278
  gUdfcProxy.expiredUdfStubs = expiredUdfStubs;
65,734✔
1279
}
1280

1281
void cleanupNotExpiredUdfs() {
65,734✔
1282
  SArray *udfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
65,734✔
1283
  if (udfStubs == NULL) {
65,734✔
1284
    fnError("cleanupNotExpiredUdfs: failed to init array");
×
1285
    return;
×
1286
  }
1287
  int32_t i = 0;
65,734✔
1288
  while (i < taosArrayGetSize(gUdfcProxy.udfStubs)) {
155,030✔
1289
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.udfStubs, i);
89,296✔
1290
    if (stub->refCount == 0) {
89,296✔
1291
      fnInfo("tear down udf. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle, stub->refCount);
79,286✔
1292
      (void)doTeardownUdf(stub->handle);
79,286✔
1293
    } else {
1294
      fnInfo("udf still in use. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p", stub->udfName,
10,010✔
1295
             stub->refCount, stub->createTime, stub->handle);
1296
      UdfcFuncHandle handle = stub->handle;
10,010✔
1297
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
10,010✔
1298
        if (taosArrayPush(udfStubs, stub) == NULL) {
10,010✔
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;
89,296✔
1307
  }
1308
  taosArrayDestroy(gUdfcProxy.udfStubs);
65,734✔
1309
  gUdfcProxy.udfStubs = udfStubs;
65,734✔
1310
}
1311

1312
int32_t cleanUpUdfs() {
655,631,941✔
1313
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
655,631,941✔
1314
  if (!initialized) {
655,581,400✔
1315
    return TSDB_CODE_SUCCESS;
22,131✔
1316
  }
1317

1318
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
655,559,269✔
1319
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
655,682,322✔
1320
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
655,616,588✔
1321
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
655,616,588✔
1322
    return TSDB_CODE_SUCCESS;
655,616,588✔
1323
  }
1324

1325
  cleanupNotExpiredUdfs();
65,734✔
1326
  cleanupExpiredUdfs();
65,734✔
1327

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

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

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

1348
  if (output->columnData == NULL) {
98,560✔
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) {
98,560✔
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);
98,560✔
1359
  return code;
98,560✔
1360
}
1361

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

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

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

1396
  SUdfInterBuf buf = {0};
89,624✔
1397
  if ((udfCode = doCallUdfAggInit(handle, &buf)) != 0) {
89,624✔
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) {
89,624✔
1403
    memcpy(udfRes->interResBuf, buf.buf, buf.bufLen);
89,624✔
1404
    udfRes->interResBufLen = buf.bufLen;
89,624✔
1405
    udfRes->interResNum = buf.numOfResult;
89,624✔
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);
89,624✔
1412
  freeUdfInterBuf(&buf);
89,624✔
1413
  return TSDB_CODE_SUCCESS;
89,624✔
1414
}
1415

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

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

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

1437
  if (code) {
210,668✔
1438
    return code;
×
1439
  }
1440

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

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

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

1461
  udfCode = doCallUdfAggProcess(session, inputBlock, &state, &newState);
210,668✔
1462
  if (udfCode != 0) {
210,668✔
1463
    fnError("udfAggProcess error. code: %d", udfCode);
×
1464
    newState.numOfResult = 0;
×
1465
  } else {
1466
    if (newState.bufLen <= session->bufSize) {
210,668✔
1467
      memcpy(udfRes->interResBuf, newState.buf, newState.bufLen);
210,668✔
1468
      udfRes->interResBufLen = newState.bufLen;
210,668✔
1469
      udfRes->interResNum = newState.numOfResult;
210,668✔
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;
210,668✔
1477

1478
  blockDataDestroy(inputBlock);
210,668✔
1479

1480
  taosArrayDestroy(pTempBlock->pDataBlock);
210,668✔
1481
  taosMemoryFree(pTempBlock);
210,668✔
1482

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

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

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

1502
  SUdfInterBuf resultBuf = {0};
89,624✔
1503
  SUdfInterBuf state = {
89,624✔
1504
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
89,624✔
1505
  int32_t udfCallCode = 0;
89,624✔
1506
  udfCallCode = doCallUdfAggFinalize(session, &state, &resultBuf);
89,624✔
1507
  if (udfCallCode != 0) {
89,624✔
1508
    fnError("udfAggFinalize error. doCallUdfAggFinalize step. udf code:%d", udfCallCode);
×
1509
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1510
  } else {
1511
    if (resultBuf.numOfResult == 0) {
89,624✔
1512
      udfRes->finalResNum = 0;
×
1513
      GET_RES_INFO(pCtx)->numOfRes = 0;
×
1514
    } else {
1515
      if (resultBuf.bufLen <= session->bytes) {
89,624✔
1516
        memcpy(udfRes->finalResBuf, resultBuf.buf, resultBuf.bufLen);
89,624✔
1517
        udfRes->finalResNum = resultBuf.numOfResult;
89,624✔
1518
        GET_RES_INFO(pCtx)->numOfRes = udfRes->finalResNum;
89,624✔
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);
89,624✔
1528

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

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

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

1565
      switch (task->type) {
647,048✔
1566
        case UDF_TASK_SETUP: {
79,286✔
1567
          task->_setup.rsp = rsp.setupRsp;
79,286✔
1568
          break;
79,286✔
1569
        }
1570
        case UDF_TASK_CALL: {
488,476✔
1571
          task->_call.rsp = rsp.callRsp;
488,476✔
1572
          break;
488,476✔
1573
        }
1574
        case UDF_TASK_TEARDOWN: {
79,286✔
1575
          task->_teardown.rsp = rsp.teardownRsp;
1576
          break;
79,286✔
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);
647,048✔
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) {
158,572✔
1592
    code = uvTask->errCode;
79,286✔
1593
    if (code != 0) {
79,286✔
1594
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1595
    }
1596
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
79,286✔
1597
    code = uvTask->errCode;
79,286✔
1598
    if (code != 0) {
79,286✔
1599
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1600
    }
1601
  }
1602
  return code;
805,620✔
1603
}
1604

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

1609
  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
1,941,144✔
1610
  if (connBuf->cap == 0) {
1,941,144✔
1611
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
726,334✔
1612
    if (connBuf->buf) {
726,334✔
1613
      connBuf->len = 0;
726,334✔
1614
      connBuf->cap = msgHeadSize;
726,334✔
1615
      connBuf->total = -1;
726,334✔
1616

1617
      buf->base = connBuf->buf;
726,334✔
1618
      buf->len = connBuf->cap;
726,334✔
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,214,810✔
1625
    buf->base = connBuf->buf + connBuf->len;
567,762✔
1626
    buf->len = msgHeadSize - connBuf->len;
567,762✔
1627
  } else {
1628
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
647,048✔
1629
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
647,048✔
1630
    if (resultBuf) {
647,048✔
1631
      connBuf->buf = resultBuf;
647,048✔
1632
      buf->base = connBuf->buf + connBuf->len;
647,048✔
1633
      buf->len = connBuf->cap - connBuf->len;
647,048✔
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);
1,941,144✔
1642
}
1,941,144✔
1643

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

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

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

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

1683
  if (taskFound) {
647,048✔
1684
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
647,048✔
1685
    QUEUE_REMOVE(&taskFound->connTaskQueue);
647,048✔
1686
    QUEUE_REMOVE(&taskFound->procTaskQueue);
647,048✔
1687
    uv_sem_post(&taskFound->taskSem);
647,048✔
1688
  } else {
1689
    fnError("no task is waiting for the response.");
×
1690
  }
1691
  connBuf->buf = NULL;
647,048✔
1692
  connBuf->total = -1;
647,048✔
1693
  connBuf->len = 0;
647,048✔
1694
  connBuf->cap = 0;
647,048✔
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) {
1,941,144✔
1713
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
1,941,144✔
1714
  if (nread == 0) return;
1,941,144✔
1715

1716
  SClientUvConn  *conn = client->data;
1,294,096✔
1717
  SClientConnBuf *connBuf = &conn->readBuf;
1,294,096✔
1718
  if (nread > 0) {
1,294,096✔
1719
    connBuf->len += nread;
1,294,096✔
1720
    if (isUdfcUvMsgComplete(connBuf)) {
1,294,096✔
1721
      udfcUvHandleRsp(conn);
647,048✔
1722
    }
1723
  }
1724
  if (nread < 0) {
1,294,096✔
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) {
647,048✔
1734
  SClientUvConn *conn = write->data;
647,048✔
1735
  if (status < 0) {
647,048✔
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);
647,048✔
1740
  }
1741
  taosMemoryFree(write);
647,048✔
1742
}
647,048✔
1743

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

1751
  int32_t code = uv_read_start((uv_stream_t *)uvTask->pipe, udfcAllocateBuffer, onUdfcPipeRead);
79,286✔
1752
  if (code != 0) {
79,286✔
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);
79,286✔
1757
  QUEUE_REMOVE(&uvTask->procTaskQueue);
79,286✔
1758
  uv_sem_post(&uvTask->taskSem);
79,286✔
1759
}
79,286✔
1760

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

1765
  if (uvTaskType == UV_TASK_CONNECT) {
805,620✔
1766
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
726,334✔
1767
    uvTask->pipe = task->session->udfUvPipe;
647,048✔
1768
    SUdfRequest request;
647,048✔
1769
    request.type = task->type;
647,048✔
1770
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
647,048✔
1771

1772
    if (task->type == UDF_TASK_SETUP) {
647,048✔
1773
      request.setup = task->_setup.req;
79,286✔
1774
      request.type = UDF_TASK_SETUP;
79,286✔
1775
    } else if (task->type == UDF_TASK_CALL) {
567,762✔
1776
      request.call = task->_call.req;
488,476✔
1777
      request.type = UDF_TASK_CALL;
488,476✔
1778
    } else if (task->type == UDF_TASK_TEARDOWN) {
79,286✔
1779
      request.teardown = task->_teardown.req;
79,286✔
1780
      request.type = UDF_TASK_TEARDOWN;
79,286✔
1781
    } else {
1782
      fnError("udfc create uv task, invalid task type : %d", task->type);
×
1783
    }
1784
    int32_t bufLen = encodeUdfRequest(NULL, &request);
647,048✔
1785
    if (bufLen <= 0) {
647,048✔
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;
647,048✔
1790
    void *bufBegin = taosMemoryMalloc(bufLen);
647,048✔
1791
    if (bufBegin == NULL) {
647,048✔
1792
      fnError("udfc create uv task, malloc buffer failed. size: %d", bufLen);
×
1793
      return terrno;
×
1794
    }
1795
    void *buf = bufBegin;
647,048✔
1796
    if (encodeUdfRequest(&buf, &request) <= 0) {
647,048✔
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);
647,048✔
1803
    uvTask->seqNum = request.seqNum;
647,048✔
1804
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
79,286✔
1805
    uvTask->pipe = task->session->udfUvPipe;
79,286✔
1806
  }
1807
  if (uv_sem_init(&uvTask->taskSem, 0) != 0) {
805,620✔
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;
805,620✔
1816
}
1817

1818
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask) {
805,620✔
1819
  fnDebug("queue uv task to event loop, uvTask: %d-%p", uvTask->type, uvTask);
805,620✔
1820
  SUdfcProxy *udfc = uvTask->udfc;
805,620✔
1821
  uv_mutex_lock(&udfc->taskQueueMutex);
805,620✔
1822
  QUEUE_INSERT_TAIL(&udfc->taskQueue, &uvTask->recvTaskQueue);
805,620✔
1823
  uv_mutex_unlock(&udfc->taskQueueMutex);
805,620✔
1824
  int32_t code = uv_async_send(&udfc->loopTaskAync);
805,620✔
1825
  if (code != 0) {
805,620✔
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);
805,620✔
1831
  fnDebug("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
805,620✔
1832
  uv_sem_destroy(&uvTask->taskSem);
805,620✔
1833

1834
  return 0;
805,620✔
1835
}
1836

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

1841
  switch (uvTask->type) {
805,620✔
1842
    case UV_TASK_CONNECT: {
79,286✔
1843
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
79,286✔
1844
      if (pipe == NULL) {
79,286✔
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) {
79,286✔
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;
79,286✔
1854

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

1868
      pipe->data = conn;
79,286✔
1869

1870
      uv_connect_t *connReq = taosMemoryMalloc(sizeof(uv_connect_t));
79,286✔
1871
      if (connReq == NULL) {
79,286✔
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;
79,286✔
1878
      uv_pipe_connect(connReq, pipe, uvTask->udfc->udfdPipeName, onUdfcPipeConnect);
79,286✔
1879
      code = 0;
79,286✔
1880
      break;
79,286✔
1881
    }
1882
    case UV_TASK_REQ_RSP: {
647,048✔
1883
      uv_pipe_t *pipe = uvTask->pipe;
647,048✔
1884
      if (pipe == NULL) {
647,048✔
1885
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1886
      } else {
1887
        uv_write_t *write = taosMemoryMalloc(sizeof(uv_write_t));
647,048✔
1888
        if (write == NULL) {
647,048✔
1889
          fnError("udfc event loop start req_rsp task malloc write failed.");
×
1890
          return terrno;
×
1891
        }
1892
        write->data = pipe->data;
647,048✔
1893
        QUEUE *connTaskQueue = &((SClientUvConn *)pipe->data)->taskQueue;
647,048✔
1894
        QUEUE_INSERT_TAIL(connTaskQueue, &uvTask->connTaskQueue);
647,048✔
1895
        int32_t err = uv_write(write, (uv_stream_t *)pipe, &uvTask->reqBuf, 1, onUdfcPipeWrite);
647,048✔
1896
        if (err != 0) {
647,048✔
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;
647,048✔
1901
      }
1902
      break;
647,048✔
1903
    }
1904
    case UV_TASK_DISCONNECT: {
79,286✔
1905
      uv_pipe_t *pipe = uvTask->pipe;
79,286✔
1906
      if (pipe == NULL) {
79,286✔
1907
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1908
      } else {
1909
        SClientUvConn *conn = pipe->data;
79,286✔
1910
        QUEUE_INSERT_TAIL(&conn->taskQueue, &uvTask->connTaskQueue);
79,286✔
1911
        if (!uv_is_closing((uv_handle_t *)uvTask->pipe)) {
79,286✔
1912
          uv_close((uv_handle_t *)uvTask->pipe, onUdfcPipeClose);
79,286✔
1913
        }
1914
        code = 0;
79,286✔
1915
      }
1916
      break;
79,286✔
1917
    }
1918
    default: {
×
1919
      fnError("udfc event loop unknown task type.") break;
×
1920
    }
1921
  }
1922

1923
  return code;
805,620✔
1924
}
1925

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

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

1949
void cleanUpUvTasks(SUdfcProxy *udfc) {
695,889✔
1950
  fnDebug("clean up uv tasks");
695,889✔
1951
  QUEUE wq;
694,019✔
1952
  QUEUE_INIT(&wq); 
695,889✔
1953

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

1958
  while (!QUEUE_EMPTY(&wq)) {
695,889✔
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)) {
695,889✔
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
}
695,889✔
1978

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

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

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

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

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

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

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

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

2087
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType) {
805,620✔
2088
  int32_t            code = 0, lino = 0;
805,620✔
2089
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
805,620✔
2090
  if (uvTask == NULL) {
805,620✔
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);
805,620✔
2095

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

2108
_exit:
805,620✔
2109
  if (code != 0) {
805,620✔
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);
805,620✔
2113
  uvTask->reqBuf.base = NULL;
805,620✔
2114
  taosMemoryFree(uvTask);
805,620✔
2115
  uvTask = NULL;
805,620✔
2116
  return code;
805,620✔
2117
}
2118

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

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

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

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

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

2154
  SUdfSetupResponse *rsp = &task->_setup.rsp;
79,286✔
2155
  task->session->severHandle = rsp->udfHandle;
79,286✔
2156
  task->session->outputType = rsp->outputType;
79,286✔
2157
  task->session->bytes = rsp->bytes;
79,286✔
2158
  task->session->bufSize = rsp->bufSize;
79,286✔
2159
  tstrncpy(task->session->udfName, udfName, TSDB_FUNC_NAME_LEN);
79,286✔
2160
  fnInfo("successfully setup udf func handle. udfName: %s, handle: %p", udfName, task->session);
79,286✔
2161
  *funcHandle = task->session;
79,286✔
2162
  taosMemoryFree(task);
79,286✔
2163
  return 0;
79,286✔
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,
488,476✔
2175
                SSDataBlock *output, SUdfInterBuf *newState) {
2176
  fnDebug("udfc call udf. callType: %d, funcHandle: %p", callType, handle);
488,476✔
2177
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
488,476✔
2178
  if (session->udfUvPipe == NULL) {
488,476✔
2179
    fnError("No pipe to udfd");
×
2180
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2181
  }
2182
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
488,476✔
2183
  if (task == NULL) {
488,476✔
2184
    fnError("udfc call udf. failed to allocate memory for task");
×
2185
    return terrno;
×
2186
  }
2187
  task->session = (SUdfcUvSession *)handle;
488,476✔
2188
  task->type = UDF_TASK_CALL;
488,476✔
2189

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

2194
  switch (callType) {
488,476✔
2195
    case TSDB_UDF_CALL_AGG_INIT: {
89,624✔
2196
      req->initFirst = 1;
89,624✔
2197
      break;
89,624✔
2198
    }
2199
    case TSDB_UDF_CALL_AGG_PROC: {
210,668✔
2200
      req->block = *input;
210,668✔
2201
      req->interBuf = *state;
210,668✔
2202
      break;
210,668✔
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: {
89,624✔
2210
      req->interBuf = *state;
89,624✔
2211
      break;
89,624✔
2212
    }
2213
    case TSDB_UDF_CALL_SCALA_PROC: {
98,560✔
2214
      req->block = *input;
98,560✔
2215
      break;
98,560✔
2216
    }
2217
  }
2218

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

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

2254
  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);
89,624✔
2255

2256
  return err;
89,624✔
2257
}
2258

2259
// input: block, state
2260
// output: interbuf,
2261
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
210,668✔
2262
  int8_t  callType = TSDB_UDF_CALL_AGG_PROC;
210,668✔
2263
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
210,668✔
2264
  return err;
210,668✔
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) {
89,624✔
2280
  int8_t  callType = TSDB_UDF_CALL_AGG_FIN;
89,624✔
2281
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
89,624✔
2282
  return err;
89,624✔
2283
}
2284

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

2300
  blockDataFreeRes(&inputBlock);
98,560✔
2301
  return err;
98,560✔
2302
}
2303

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

2308
  if (session->udfUvPipe == NULL) {
79,286✔
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));
79,286✔
2315
  if (task == NULL) {
79,286✔
2316
    fnError("doTeardownUdf, failed to allocate memory for task");
×
2317
    taosMemoryFree(session);
×
2318
    return terrno;
×
2319
  }
2320
  task->session = session;
79,286✔
2321
  task->type = UDF_TASK_TEARDOWN;
79,286✔
2322

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

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

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

2332
  fnInfo("tear down udf. udf name: %s, udf func handle: %p", session->udfName, handle);
79,286✔
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:
79,286✔
2342
  if (code != 0) {
79,286✔
2343
    fnError("failed to teardown udf. udf name: %s, err: %d, line: %d", session->udfName, code, lino);
×
2344
  }
2345
  freeTaskSession(task);
79,286✔
2346
  taosMemoryFree(task);
79,286✔
2347

2348
  return code;
79,286✔
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