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

taosdata / TDengine / #4867

26 Nov 2025 05:46AM UTC coverage: 64.473% (-0.03%) from 64.504%
#4867

push

travis-ci

guanshengliang
Merge branch '3.0' into cover/3.0

765 of 945 new or added lines in 33 files covered. (80.95%)

3147 existing lines in 126 files now uncovered.

158042 of 245129 relevant lines covered (64.47%)

111495961.54 hits per line

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

78.7
/source/libs/function/src/tudf.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15
#ifdef USE_UDF
16
#include "uv.h"
17

18
#include "os.h"
19

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

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

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

49
  int32_t dnodeId;
50
} SUdfdData;
51

52
SUdfdData udfdGlobal = {0};
53

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

57
extern char **environ;
58

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

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

84
static int32_t udfSpawnUdfd(SUdfdData *pData) {
672,509✔
85
  fnInfo("start to init udfd");
672,509✔
86
  TAOS_UDF_CHECK_PTR_RCODE(pData);
1,345,018✔
87

88
  int32_t              err = 0;
672,509✔
89
  uv_process_options_t options = {0};
672,509✔
90

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

122
  options.exit_cb = udfUdfdExit;
672,509✔
123

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

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

135
  options.flags = UV_PROCESS_DETACHED;
672,509✔
136

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

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

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

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

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

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

188
  char **envUdfdWithPEnv = NULL;
672,509✔
189
  if (environ != NULL) {
672,509✔
190
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
672,509✔
191
    int32_t numEnviron = 0;
672,509✔
192
    while (environ[numEnviron] != NULL) {
21,637,660✔
193
      numEnviron++;
20,965,151✔
194
    }
195

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

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

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

213
    for (int32_t i = 0; i < lenEnvUdfd; i++) {
4,035,054✔
214
      if (envUdfd[i] != NULL) {
3,362,545✔
215
        int32_t len = strlen(envUdfd[i]) + 1;
2,017,527✔
216
        envUdfdWithPEnv[numEnviron + i] = (char *)taosMemoryCalloc(len, 1);
2,017,527✔
217
        if (envUdfdWithPEnv[numEnviron + i] == NULL) {
2,017,527✔
218
          err = TSDB_CODE_OUT_OF_MEMORY;
×
219
          goto _OVER;
×
220
        }
221

222
        tstrncpy(envUdfdWithPEnv[numEnviron + i], envUdfd[i], len);
2,017,527✔
223
      }
224
    }
225
    envUdfdWithPEnv[numEnviron + lenEnvUdfd - 1] = NULL;
672,509✔
226

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

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

260
_OVER:
668,802✔
261
  if (taosFqdnEnvItem) {
672,509✔
262
    taosMemoryFree(taosFqdnEnvItem);
×
263
  }
264

265
  if (envUdfdWithPEnv != NULL) {
672,509✔
266
    int32_t i = 0;
672,509✔
267
    while (envUdfdWithPEnv[i] != NULL) {
23,655,187✔
268
      taosMemoryFree(envUdfdWithPEnv[i]);
22,982,678✔
269
      i++;
22,982,678✔
270
    }
271
    taosMemoryFree(envUdfdWithPEnv);
672,509✔
272
  }
273

274
  return err;
672,509✔
275
}
276

277
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
3,362,951✔
278
  TAOS_UDF_CHECK_PTR_RVOID(handle);
6,725,902✔
279
  if (!uv_is_closing(handle)) {
3,362,951✔
280
    uv_close(handle, NULL);
3,362,951✔
281
  }
282
}
283

284
static void udfUdfdStopAsyncCb(uv_async_t *async) {
672,509✔
285
  TAOS_UDF_CHECK_PTR_RVOID(async);
1,345,018✔
286
  SUdfdData *pData = async->data;
672,509✔
287
  uv_stop(&pData->loop);
672,509✔
288
}
289

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

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

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

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

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

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

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

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

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

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

661
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
981,674✔
662
  int32_t len = 0;
981,674✔
663
  len += taosEncodeFixedI64(buf, call->udfHandle);
981,674✔
664
  len += taosEncodeFixedI8(buf, call->callType);
981,674✔
665
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
981,674✔
666
    len += tEncodeDataBlock(buf, &call->block);
163,090✔
667
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
818,584✔
668
    len += taosEncodeFixedI8(buf, call->initFirst);
376,296✔
669
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
630,436✔
670
    len += tEncodeDataBlock(buf, &call->block);
442,288✔
671
    len += encodeUdfInterBuf(buf, &call->interBuf);
442,288✔
672
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
188,148✔
673
    // len += encodeUdfInterBuf(buf, &call->interBuf);
674
    // len += encodeUdfInterBuf(buf, &call->interBuf2);
675
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
188,148✔
676
    len += encodeUdfInterBuf(buf, &call->interBuf);
188,148✔
677
  }
678
  return len;
981,674✔
679
}
680

681
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
6,831,606✔
682
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
6,831,606✔
683
  buf = taosDecodeFixedI8(buf, &call->callType);
6,831,606✔
684
  switch (call->callType) {
6,831,606✔
685
    case TSDB_UDF_CALL_SCALA_PROC:
5,385,967✔
686
      buf = tDecodeDataBlock(buf, &call->block);
5,385,967✔
687
      break;
5,384,279✔
688
    case TSDB_UDF_CALL_AGG_INIT:
302,979✔
689
      buf = taosDecodeFixedI8(buf, &call->initFirst);
302,979✔
690
      break;
302,979✔
691
    case TSDB_UDF_CALL_AGG_PROC:
848,889✔
692
      buf = tDecodeDataBlock(buf, &call->block);
848,889✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
848,889✔
694
      break;
848,633✔
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:
293,711✔
700
      buf = decodeUdfInterBuf(buf, &call->interBuf);
293,711✔
701
      break;
293,711✔
702
  }
703
  return (void *)buf;
6,829,662✔
704
}
705

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

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

717
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
1,285,742✔
718
  int32_t len = 0;
1,285,742✔
719
  if (buf == NULL) {
1,285,742✔
720
    len += sizeof(request->msgLen);
642,871✔
721
  } else {
722
    *(int32_t *)(*buf) = request->msgLen;
642,871✔
723
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
642,871✔
724
  }
725
  len += taosEncodeFixedI64(buf, request->seqNum);
1,285,742✔
726
  len += taosEncodeFixedI8(buf, request->type);
1,285,742✔
727
  if (request->type == UDF_TASK_SETUP) {
1,285,742✔
728
    len += encodeUdfSetupRequest(buf, &request->setup);
152,034✔
729
  } else if (request->type == UDF_TASK_CALL) {
1,133,708✔
730
    len += encodeUdfCallRequest(buf, &request->call);
981,674✔
731
  } else if (request->type == UDF_TASK_TEARDOWN) {
152,034✔
732
    len += encodeUdfTeardownRequest(buf, &request->teardown);
152,034✔
733
  }
734
  return len;
1,285,742✔
735
}
736

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

741
  buf = taosDecodeFixedI64(buf, &request->seqNum);
7,299,617✔
742
  buf = taosDecodeFixedI8(buf, &request->type);
7,299,617✔
743

744
  if (request->type == UDF_TASK_SETUP) {
7,299,617✔
745
    buf = decodeUdfSetupRequest(buf, &request->setup);
241,358✔
746
  } else if (request->type == UDF_TASK_CALL) {
7,058,259✔
747
    buf = decodeUdfCallRequest(buf, &request->call);
6,831,594✔
748
  } else if (request->type == UDF_TASK_TEARDOWN) {
226,665✔
749
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
226,533✔
750
  }
751
  return (void *)buf;
7,297,817✔
752
}
753

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

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

771
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp) {
13,655,592✔
772
  int32_t len = 0;
13,655,592✔
773
  len += taosEncodeFixedI8(buf, callRsp->callType);
13,655,592✔
774
  switch (callRsp->callType) {
13,655,592✔
775
    case TSDB_UDF_CALL_SCALA_PROC:
10,764,662✔
776
      len += tEncodeDataBlock(buf, &callRsp->resultData);
10,764,662✔
777
      break;
10,757,762✔
778
    case TSDB_UDF_CALL_AGG_INIT:
605,958✔
779
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
605,958✔
780
      break;
605,958✔
781
    case TSDB_UDF_CALL_AGG_PROC:
1,697,778✔
782
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
1,697,778✔
783
      break;
1,697,778✔
784
    // case TSDB_UDF_CALL_AGG_MERGE:
785
    //   len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
786
    //   break;
787
    case TSDB_UDF_CALL_AGG_FIN:
587,422✔
788
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
587,422✔
789
      break;
587,422✔
790
  }
791
  return len;
13,648,692✔
792
}
793

794
void *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp) {
490,837✔
795
  buf = taosDecodeFixedI8(buf, &callRsp->callType);
490,837✔
796
  switch (callRsp->callType) {
490,837✔
797
    case TSDB_UDF_CALL_SCALA_PROC:
81,545✔
798
      buf = tDecodeDataBlock(buf, &callRsp->resultData);
81,545✔
799
      break;
81,545✔
800
    case TSDB_UDF_CALL_AGG_INIT:
94,074✔
801
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
94,074✔
802
      break;
94,074✔
803
    case TSDB_UDF_CALL_AGG_PROC:
221,144✔
804
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
221,144✔
805
      break;
221,144✔
806
    // case TSDB_UDF_CALL_AGG_MERGE:
807
    //   buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
808
    //   break;
809
    case TSDB_UDF_CALL_AGG_FIN:
94,074✔
810
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
94,074✔
811
      break;
94,074✔
812
  }
813
  return (void *)buf;
490,837✔
814
}
815

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

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

820
int32_t encodeUdfResponse(void **buf, const SUdfResponse *rsp) {
14,591,170✔
821
  int32_t len = 0;
14,591,170✔
822
  len += sizeof(rsp->msgLen);
14,591,170✔
823
  if (buf != NULL) {
14,591,170✔
824
    *(int32_t *)(*buf) = rsp->msgLen;
7,297,433✔
825
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->msgLen));
7,297,433✔
826
  }
827

828
  len += sizeof(rsp->seqNum);
14,591,170✔
829
  if (buf != NULL) {
14,591,170✔
830
    *(int64_t *)(*buf) = rsp->seqNum;
7,295,945✔
831
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
7,295,945✔
832
  }
833

834
  len += taosEncodeFixedI64(buf, rsp->seqNum);
14,591,170✔
835
  len += taosEncodeFixedI8(buf, rsp->type);
14,591,170✔
836
  len += taosEncodeFixedI32(buf, rsp->code);
14,591,170✔
837

838
  switch (rsp->type) {
14,591,170✔
839
    case UDF_TASK_SETUP:
482,716✔
840
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
482,716✔
841
      break;
482,716✔
842
    case UDF_TASK_CALL:
13,656,324✔
843
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
13,656,324✔
844
      break;
13,645,992✔
845
    case UDF_TASK_TEARDOWN:
453,066✔
846
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
453,066✔
847
      break;
453,066✔
UNCOV
848
    default:
×
UNCOV
849
      fnError("encode udf response, invalid udf response type %d", rsp->type);
×
850
      break;
×
851
  }
852
  return len;
14,581,774✔
853
}
854

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

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

886
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
11,845,715✔
887
  TAOS_UDF_CHECK_PTR_RVOID(data, meta);
35,538,333✔
888
  if (IS_VAR_DATA_TYPE(meta->type)) {
11,845,715✔
889
    taosMemoryFree(data->varLenCol.varOffsets);
78,792✔
890
    data->varLenCol.varOffsets = NULL;
80,616✔
891
    taosMemoryFree(data->varLenCol.payload);
80,616✔
892
    data->varLenCol.payload = NULL;
80,616✔
893
  } else {
894
    taosMemoryFree(data->fixLenCol.nullBitmap);
11,766,923✔
895
    data->fixLenCol.nullBitmap = NULL;
11,763,407✔
896
    taosMemoryFree(data->fixLenCol.data);
11,763,407✔
897
    data->fixLenCol.data = NULL;
11,767,223✔
898
  }
899
}
900

901
void freeUdfColumn(SUdfColumn *col) {
11,845,643✔
902
  TAOS_UDF_CHECK_PTR_RVOID(col);
23,692,078✔
903
  freeUdfColumnData(&col->colData, &col->colMeta);
11,845,643✔
904
}
905

906
void freeUdfDataDataBlock(SUdfDataBlock *block) {
6,229,696✔
907
  TAOS_UDF_CHECK_PTR_RVOID(block);
12,462,704✔
908
  for (int32_t i = 0; i < block->numOfCols; ++i) {
12,693,608✔
909
    freeUdfColumn(block->udfCols[i]);
6,459,856✔
910
    taosMemoryFree(block->udfCols[i]);
6,463,288✔
911
    block->udfCols[i] = NULL;
6,463,912✔
912
  }
913
  taosMemoryFree(block->udfCols);
6,233,752✔
914
  block->udfCols = NULL;
6,234,040✔
915
}
916

917
void freeUdfInterBuf(SUdfInterBuf *buf) {
2,997,471✔
918
  TAOS_UDF_CHECK_PTR_RVOID(buf);
5,994,942✔
919
  taosMemoryFree(buf->buf);
2,997,471✔
920
  buf->buf = NULL;
2,997,471✔
921
}
922

923
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
6,233,636✔
924
  TAOS_UDF_CHECK_PTR_RCODE(block, udfBlock);
18,701,752✔
925
  int32_t code = blockDataCheck(block);
6,233,636✔
926
  if (code != TSDB_CODE_SUCCESS) {
6,232,348✔
927
    return code;
×
928
  }
929
  udfBlock->numOfRows = block->info.rows;
6,232,348✔
930
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
6,232,348✔
931
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
6,232,624✔
932
  if ((udfBlock->udfCols) == NULL) {
6,234,412✔
933
    return terrno;
×
934
  }
935
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
12,697,724✔
936
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
6,463,852✔
937
    if (udfBlock->udfCols[i] == NULL) {
6,462,892✔
938
      return terrno;
×
939
    }
940
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
6,462,892✔
941
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
6,462,236✔
942
    udfCol->colMeta.type = col->info.type;
6,462,236✔
943
    udfCol->colMeta.bytes = col->info.bytes;
6,462,236✔
944
    udfCol->colMeta.scale = col->info.scale;
6,462,236✔
945
    udfCol->colMeta.precision = col->info.precision;
6,462,236✔
946
    udfCol->colData.numOfRows = udfBlock->numOfRows;
6,462,236✔
947
    udfCol->hasNull = col->hasNull;
6,462,236✔
948
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
6,462,236✔
949
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
47,333✔
950
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
47,333✔
951
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
48,516✔
952
        return terrno;
×
953
      }
954
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
48,516✔
955
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
48,516✔
956
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
48,516✔
957
      if (udfCol->colData.varLenCol.payload == NULL) {
48,516✔
958
        return terrno;
×
959
      }
960
      if (col->reassigned) {
48,516✔
961
        for (int32_t row = 0; row < udfCol->colData.numOfRows; ++row) {
×
962
          char   *pColData = col->pData + col->varmeta.offset[row];
×
963
          int32_t colSize = 0;
×
964
          if (col->info.type == TSDB_DATA_TYPE_JSON) {
×
965
            colSize = getJsonValueLen(pColData);
×
966
          } else if (IS_STR_DATA_BLOB(col->info.type)) {
×
967
            colSize = blobDataTLen(pColData);
×
968
          } else {
969
            colSize = varDataTLen(pColData);
×
970
          }
971
          memcpy(udfCol->colData.varLenCol.payload, pColData, colSize);
×
972
          udfCol->colData.varLenCol.payload += colSize;
×
973
        }
974
      } else {
975
        memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
48,516✔
976
      }
977
    } else {
978
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
6,414,903✔
979
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
6,414,903✔
980
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
6,414,903✔
981
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
6,415,024✔
982
        return terrno;
×
983
      }
984
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
6,415,024✔
985
      memcpy(bitmap, col->nullbitmap, bitmapLen);
6,415,024✔
986
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
6,415,024✔
987
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
6,414,747✔
988
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
6,414,747✔
989
      if (NULL == udfCol->colData.fixLenCol.data) {
6,414,796✔
990
        return terrno;
×
991
      }
992
      char *data = udfCol->colData.fixLenCol.data;
6,414,796✔
993
      memcpy(data, col->pData, dataLen);
6,414,796✔
994
    }
995
  }
996
  return TSDB_CODE_SUCCESS;
6,233,872✔
997
}
998

999
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
5,373,334✔
1000
  TAOS_UDF_CHECK_PTR_RCODE(udfCol, block);
16,125,858✔
1001
  int32_t         code = 0, lino = 0;
5,373,334✔
1002
  SUdfColumnMeta *meta = &udfCol->colMeta;
5,373,334✔
1003

1004
  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
5,373,334✔
1005
  code = blockDataAppendColInfo(block, &colInfoData);
5,375,890✔
1006
  TAOS_CHECK_GOTO(code, &lino, _exit);
5,378,026✔
1007

1008
  code = blockDataEnsureCapacity(block, udfCol->colData.numOfRows);
5,378,026✔
1009
  TAOS_CHECK_GOTO(code, &lino, _exit);
5,377,642✔
1010

1011
  SColumnInfoData *col = NULL;
5,377,642✔
1012
  code = bdGetColumnInfoData(block, 0, &col);
5,377,642✔
1013
  TAOS_CHECK_GOTO(code, &lino, _exit);
5,379,382✔
1014

1015
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
1,431,269,560✔
1016
    if (udfColDataIsNull(udfCol, i)) {
1,427,063,672✔
1017
      colDataSetNULL(col, i);
224,852,892✔
1018
    } else {
1019
      char *data = udfColDataGetData(udfCol, i);
1,202,210,780✔
1020
      code = colDataSetVal(col, i, data, false);
1,202,210,780✔
1021
      TAOS_CHECK_GOTO(code, &lino, _exit);
1,201,037,286✔
1022
    }
1023
  }
1024
  block->info.rows = udfCol->colData.numOfRows;
4,205,888✔
1025

1026
  code = blockDataCheck(block);
4,205,888✔
1027
  TAOS_CHECK_GOTO(code, &lino, _exit);
5,380,354✔
1028
_exit:
5,380,354✔
1029
  if (code != 0) {
5,380,354✔
1030
    fnError("failed to convert udf column to data block, code:%d, line:%d", code, lino);
×
1031
  }
1032
  return TSDB_CODE_SUCCESS;
5,378,614✔
1033
}
1034

1035
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
81,545✔
1036
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
244,635✔
1037
  int32_t code = 0, lino = 0;
81,545✔
1038
  int32_t numOfRows = 0;
81,545✔
1039
  for (int32_t i = 0; i < numOfCols; ++i) {
166,970✔
1040
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
85,425✔
1041
  }
1042

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

1049
    TAOS_CHECK_GOTO(blockDataAppendColInfo(output, &d), &lino, _exit);
85,425✔
1050
  }
1051

1052
  TAOS_CHECK_GOTO(blockDataEnsureCapacity(output, numOfRows), &lino, _exit);
81,545✔
1053

1054
  for (int32_t i = 0; i < numOfCols; ++i) {
166,970✔
1055
    SColumnInfoData *pDest = taosArrayGet(output->pDataBlock, i);
85,425✔
1056

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

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

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

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

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

1098
  return 0;
81,545✔
1099
}
1100

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

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

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

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

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

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

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

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

1218
_exit:
76,017✔
1219
  return code;
76,017✔
1220
}
1221

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

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

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

1305
int32_t cleanUpUdfs() {
285,271,187✔
1306
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
285,271,187✔
1307
  if (!initialized) {
285,292,261✔
1308
    return TSDB_CODE_SUCCESS;
78,456✔
1309
  }
1310

1311
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
285,213,805✔
1312
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
285,247,208✔
1313
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
285,195,879✔
1314
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
285,195,879✔
1315
    return TSDB_CODE_SUCCESS;
285,195,879✔
1316
  }
1317

1318
  cleanupNotExpiredUdfs();
51,329✔
1319
  cleanupExpiredUdfs();
51,329✔
1320

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

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

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

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

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

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

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

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

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

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

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

1430
  if (code) {
221,144✔
1431
    return code;
×
1432
  }
1433

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

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

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

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

1469
  GET_RES_INFO(pCtx)->numOfRes = udfRes->interResNum;
221,144✔
1470

1471
  blockDataDestroy(inputBlock);
221,144✔
1472

1473
  taosArrayDestroy(pTempBlock->pDataBlock);
221,144✔
1474
  taosMemoryFree(pTempBlock);
221,144✔
1475

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

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

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

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

1520
  freeUdfInterBuf(&resultBuf);
94,074✔
1521

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

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

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

1558
      switch (task->type) {
642,871✔
1559
        case UDF_TASK_SETUP: {
76,017✔
1560
          task->_setup.rsp = rsp.setupRsp;
76,017✔
1561
          break;
76,017✔
1562
        }
1563
        case UDF_TASK_CALL: {
490,837✔
1564
          task->_call.rsp = rsp.callRsp;
490,837✔
1565
          break;
490,837✔
1566
        }
1567
        case UDF_TASK_TEARDOWN: {
76,017✔
1568
          task->_teardown.rsp = rsp.teardownRsp;
1569
          break;
76,017✔
1570
        }
1571
        default: {
×
1572
          break;
×
1573
        }
1574
      }
1575

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

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

1602
  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
1,928,613✔
1603
  if (connBuf->cap == 0) {
1,928,613✔
1604
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
718,888✔
1605
    if (connBuf->buf) {
718,888✔
1606
      connBuf->len = 0;
718,888✔
1607
      connBuf->cap = msgHeadSize;
718,888✔
1608
      connBuf->total = -1;
718,888✔
1609

1610
      buf->base = connBuf->buf;
718,888✔
1611
      buf->len = connBuf->cap;
718,888✔
1612
    } else {
1613
      fnError("udfc allocate buffer failure. size: %d", msgHeadSize);
×
1614
      buf->base = NULL;
×
1615
      buf->len = 0;
×
1616
    }
1617
  } else if (connBuf->total == -1 && connBuf->len < msgHeadSize) {
1,209,725✔
1618
    buf->base = connBuf->buf + connBuf->len;
566,854✔
1619
    buf->len = msgHeadSize - connBuf->len;
566,854✔
1620
  } else {
1621
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
642,871✔
1622
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
642,871✔
1623
    if (resultBuf) {
642,871✔
1624
      connBuf->buf = resultBuf;
642,871✔
1625
      buf->base = connBuf->buf + connBuf->len;
642,871✔
1626
      buf->len = connBuf->cap - connBuf->len;
642,871✔
1627
    } else {
1628
      fnError("udfc re-allocate buffer failure. size: %d", connBuf->cap);
×
1629
      buf->base = NULL;
×
1630
      buf->len = 0;
×
1631
    }
1632
  }
1633

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

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

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

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

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

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

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

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

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

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

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

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

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

1758
  if (uvTaskType == UV_TASK_CONNECT) {
794,905✔
1759
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
718,888✔
1760
    uvTask->pipe = task->session->udfUvPipe;
642,871✔
1761
    SUdfRequest request;
642,871✔
1762
    request.type = task->type;
642,871✔
1763
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
642,871✔
1764

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

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

1808
  return 0;
794,905✔
1809
}
1810

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

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

1827
  return 0;
794,905✔
1828
}
1829

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

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

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

1861
      pipe->data = conn;
76,017✔
1862

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

1916
  return code;
794,905✔
1917
}
1918

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

1923
  uv_mutex_lock(&udfc->taskQueueMutex);
793,450✔
1924
  QUEUE_MOVE(&udfc->taskQueue, &wq);
793,450✔
1925
  uv_mutex_unlock(&udfc->taskQueueMutex);
793,450✔
1926

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

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

1944
  uv_mutex_lock(&udfc->taskQueueMutex);
672,712✔
1945
  QUEUE_MOVE(&udfc->taskQueue, &wq);
672,712✔
1946
  uv_mutex_unlock(&udfc->taskQueueMutex);
672,712✔
1947

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2138
  code = udfcRunUdfUvTask(task, UV_TASK_CONNECT);
76,017✔
2139
  TAOS_CHECK_GOTO(code, &lino, _exit);
76,017✔
2140

2141
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
76,017✔
2142
  TAOS_CHECK_GOTO(code, &lino, _exit);
76,017✔
2143

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

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

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

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

2184
  switch (callType) {
490,837✔
2185
    case TSDB_UDF_CALL_AGG_INIT: {
94,074✔
2186
      req->initFirst = 1;
94,074✔
2187
      break;
94,074✔
2188
    }
2189
    case TSDB_UDF_CALL_AGG_PROC: {
221,144✔
2190
      req->block = *input;
221,144✔
2191
      req->interBuf = *state;
221,144✔
2192
      break;
221,144✔
2193
    }
2194
    // case TSDB_UDF_CALL_AGG_MERGE: {
2195
    //   req->interBuf = *state;
2196
    //   req->interBuf2 = *state2;
2197
    //   break;
2198
    // }
2199
    case TSDB_UDF_CALL_AGG_FIN: {
94,074✔
2200
      req->interBuf = *state;
94,074✔
2201
      break;
94,074✔
2202
    }
2203
    case TSDB_UDF_CALL_SCALA_PROC: {
81,545✔
2204
      req->block = *input;
81,545✔
2205
      break;
81,545✔
2206
    }
2207
  }
2208

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

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

2244
  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);
94,074✔
2245

2246
  return err;
94,074✔
2247
}
2248

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

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

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

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

2290
  blockDataFreeRes(&inputBlock);
81,545✔
2291
  return err;
81,545✔
2292
}
2293

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

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

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

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

2316
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
76,017✔
2317
  TAOS_CHECK_GOTO(code, &lino, _exit);
76,017✔
2318

2319
  code = udfcRunUdfUvTask(task, UV_TASK_DISCONNECT);
76,017✔
2320
  TAOS_CHECK_GOTO(code, &lino, _exit);
76,017✔
2321

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

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

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

2343
int32_t cleanUpUdfs() { return 0; }
2344
int32_t udfcOpen() { return 0; }
2345
int32_t udfcClose() { return 0; }
2346
int32_t udfStartUdfd(int32_t startDnodeId) { return 0; }
2347
void    udfStopUdfd() { return; }
2348
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
2349
  return TSDB_CODE_OPS_NOT_SUPPORT;
2350
}
2351
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc