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

taosdata / TDengine / #4720

08 Sep 2025 08:43AM UTC coverage: 58.139% (-0.6%) from 58.762%
#4720

push

travis-ci

web-flow
Merge pull request #32881 from taosdata/enh/add-new-windows-ci

fix(ci): update workflow reference to use new Windows CI YAML

133181 of 292179 branches covered (45.58%)

Branch coverage included in aggregate %.

201691 of 283811 relevant lines covered (71.07%)

5442780.71 hits per line

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

63.25
/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) {
2,405✔
85
  fnInfo("start to init udfd");
2,405!
86
  TAOS_UDF_CHECK_PTR_RCODE(pData);
4,810!
87

88
  int32_t              err = 0;
2,405✔
89
  uv_process_options_t options = {0};
2,405✔
90

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

122
  options.exit_cb = udfUdfdExit;
2,405✔
123

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

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

135
  options.flags = UV_PROCESS_DETACHED;
2,405✔
136

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

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

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

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

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

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

188
  char **envUdfdWithPEnv = NULL;
2,405✔
189
  if (environ != NULL) {
2,405!
190
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
2,405✔
191
    int32_t numEnviron = 0;
2,405✔
192
    while (environ[numEnviron] != NULL) {
70,675✔
193
      numEnviron++;
68,270✔
194
    }
195

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

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

210
      tstrncpy(envUdfdWithPEnv[i], environ[i], len);
68,270✔
211
    }
212

213
    for (int32_t i = 0; i < lenEnvUdfd; i++) {
14,430✔
214
      if (envUdfd[i] != NULL) {
12,025✔
215
        int32_t len = strlen(envUdfd[i]) + 1;
7,215✔
216
        envUdfdWithPEnv[numEnviron + i] = (char *)taosMemoryCalloc(len, 1);
7,215!
217
        if (envUdfdWithPEnv[numEnviron + i] == NULL) {
7,215!
218
          err = TSDB_CODE_OUT_OF_MEMORY;
×
219
          goto _OVER;
×
220
        }
221

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

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

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

260
_OVER:
×
261
  if (taosFqdnEnvItem) {
2,405!
262
    taosMemoryFree(taosFqdnEnvItem);
×
263
  }
264

265
  if (envUdfdWithPEnv != NULL) {
2,405!
266
    int32_t i = 0;
2,405✔
267
    while (envUdfdWithPEnv[i] != NULL) {
77,890✔
268
      taosMemoryFree(envUdfdWithPEnv[i]);
75,485!
269
      i++;
75,485✔
270
    }
271
    taosMemoryFree(envUdfdWithPEnv);
2,405!
272
  }
273

274
  return err;
2,405✔
275
}
276

277
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
11,824✔
278
  TAOS_UDF_CHECK_PTR_RVOID(handle);
23,648!
279
  if (!uv_is_closing(handle)) {
11,824!
280
    uv_close(handle, NULL);
11,824✔
281
  }
282
}
283

284
static void udfUdfdStopAsyncCb(uv_async_t *async) {
2,357✔
285
  TAOS_UDF_CHECK_PTR_RVOID(async);
4,714!
286
  SUdfdData *pData = async->data;
2,357✔
287
  uv_stop(&pData->loop);
2,357✔
288
}
289

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

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

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

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

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

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

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

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

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

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

661
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
2,530✔
662
  int32_t len = 0;
2,530✔
663
  len += taosEncodeFixedI64(buf, call->udfHandle);
2,530✔
664
  len += taosEncodeFixedI8(buf, call->callType);
2,530✔
665
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
2,530✔
666
    len += tEncodeDataBlock(buf, &call->block);
842✔
667
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
1,688✔
668
    len += taosEncodeFixedI8(buf, call->initFirst);
776✔
669
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
1,300✔
670
    len += tEncodeDataBlock(buf, &call->block);
912✔
671
    len += encodeUdfInterBuf(buf, &call->interBuf);
912✔
672
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
388!
673
    // len += encodeUdfInterBuf(buf, &call->interBuf);
674
    // len += encodeUdfInterBuf(buf, &call->interBuf2);
675
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
388!
676
    len += encodeUdfInterBuf(buf, &call->interBuf);
388✔
677
  }
678
  return len;
2,530✔
679
}
680

681
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
1,265✔
682
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
1,265!
683
  buf = taosDecodeFixedI8(buf, &call->callType);
1,265✔
684
  switch (call->callType) {
1,265!
685
    case TSDB_UDF_CALL_SCALA_PROC:
421✔
686
      buf = tDecodeDataBlock(buf, &call->block);
421✔
687
      break;
421✔
688
    case TSDB_UDF_CALL_AGG_INIT:
194✔
689
      buf = taosDecodeFixedI8(buf, &call->initFirst);
194✔
690
      break;
194✔
691
    case TSDB_UDF_CALL_AGG_PROC:
456✔
692
      buf = tDecodeDataBlock(buf, &call->block);
456✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
456✔
694
      break;
456✔
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:
194✔
700
      buf = decodeUdfInterBuf(buf, &call->interBuf);
194✔
701
      break;
194✔
702
  }
703
  return (void *)buf;
1,265✔
704
}
705

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

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

717
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
3,188✔
718
  int32_t len = 0;
3,188✔
719
  if (buf == NULL) {
3,188✔
720
    len += sizeof(request->msgLen);
1,594✔
721
  } else {
722
    *(int32_t *)(*buf) = request->msgLen;
1,594✔
723
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
1,594✔
724
  }
725
  len += taosEncodeFixedI64(buf, request->seqNum);
3,188✔
726
  len += taosEncodeFixedI8(buf, request->type);
3,188✔
727
  if (request->type == UDF_TASK_SETUP) {
3,188✔
728
    len += encodeUdfSetupRequest(buf, &request->setup);
330✔
729
  } else if (request->type == UDF_TASK_CALL) {
2,858✔
730
    len += encodeUdfCallRequest(buf, &request->call);
2,530✔
731
  } else if (request->type == UDF_TASK_TEARDOWN) {
328!
732
    len += encodeUdfTeardownRequest(buf, &request->teardown);
328✔
733
  }
734
  return len;
3,188✔
735
}
736

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

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

744
  if (request->type == UDF_TASK_SETUP) {
1,594✔
745
    buf = decodeUdfSetupRequest(buf, &request->setup);
165✔
746
  } else if (request->type == UDF_TASK_CALL) {
1,429✔
747
    buf = decodeUdfCallRequest(buf, &request->call);
1,265✔
748
  } else if (request->type == UDF_TASK_TEARDOWN) {
164!
749
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
164✔
750
  }
751
  return (void *)buf;
1,594✔
752
}
753

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

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

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

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

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

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

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

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

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

838
  switch (rsp->type) {
3,188!
839
    case UDF_TASK_SETUP:
330✔
840
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
330✔
841
      break;
330✔
842
    case UDF_TASK_CALL:
2,530✔
843
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
2,530✔
844
      break;
2,530✔
845
    case UDF_TASK_TEARDOWN:
328✔
846
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
328✔
847
      break;
328✔
848
    default:
×
849
      fnError("encode udf response, invalid udf response type %d", rsp->type);
×
850
      break;
×
851
  }
852
  return len;
3,188✔
853
}
854

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

864
  switch (rsp->type) {
1,594!
865
    case UDF_TASK_SETUP:
165✔
866
      buf = decodeUdfSetupResponse(buf, &rsp->setupRsp);
165✔
867
      break;
165✔
868
    case UDF_TASK_CALL:
1,265✔
869
      buf = decodeUdfCallResponse(buf, &rsp->callRsp);
1,265✔
870
      break;
1,265✔
871
    case UDF_TASK_TEARDOWN:
164✔
872
      buf = decodeUdfTeardownResponse(buf, &rsp->teardownRsp);
164✔
873
      break;
164✔
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) {
1,594!
880
    rsp->code = terrno;
×
881
    fnError("decode udf response failed, code:0x%x", rsp->code);
×
882
  }
883
  return (void *)buf;
1,594✔
884
}
885

886
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
1,348✔
887
  TAOS_UDF_CHECK_PTR_RVOID(data, meta);
4,044!
888
  if (IS_VAR_DATA_TYPE(meta->type)) {
1,348!
889
    taosMemoryFree(data->varLenCol.varOffsets);
1!
890
    data->varLenCol.varOffsets = NULL;
1✔
891
    taosMemoryFree(data->varLenCol.payload);
1!
892
    data->varLenCol.payload = NULL;
1✔
893
  } else {
894
    taosMemoryFree(data->fixLenCol.nullBitmap);
1,347!
895
    data->fixLenCol.nullBitmap = NULL;
1,347✔
896
    taosMemoryFree(data->fixLenCol.data);
1,347!
897
    data->fixLenCol.data = NULL;
1,347✔
898
  }
899
}
900

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

906
void freeUdfDataDataBlock(SUdfDataBlock *block) {
877✔
907
  TAOS_UDF_CHECK_PTR_RVOID(block);
1,754!
908
  for (int32_t i = 0; i < block->numOfCols; ++i) {
1,804✔
909
    freeUdfColumn(block->udfCols[i]);
927✔
910
    taosMemoryFree(block->udfCols[i]);
927!
911
    block->udfCols[i] = NULL;
927✔
912
  }
913
  taosMemoryFree(block->udfCols);
877!
914
  block->udfCols = NULL;
877✔
915
}
916

917
void freeUdfInterBuf(SUdfInterBuf *buf) {
2,338✔
918
  TAOS_UDF_CHECK_PTR_RVOID(buf);
4,676!
919
  taosMemoryFree(buf->buf);
2,338!
920
  buf->buf = NULL;
2,338✔
921
}
922

923
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
877✔
924
  TAOS_UDF_CHECK_PTR_RCODE(block, udfBlock);
2,631!
925
  int32_t code = blockDataCheck(block);
877✔
926
  if (code != TSDB_CODE_SUCCESS) {
877!
927
    return code;
×
928
  }
929
  udfBlock->numOfRows = block->info.rows;
877✔
930
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
877✔
931
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
877!
932
  if ((udfBlock->udfCols) == NULL) {
877!
933
    return terrno;
×
934
  }
935
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
1,804✔
936
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
927!
937
    if (udfBlock->udfCols[i] == NULL) {
927!
938
      return terrno;
×
939
    }
940
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
927✔
941
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
927✔
942
    udfCol->colMeta.type = col->info.type;
927✔
943
    udfCol->colMeta.bytes = col->info.bytes;
927✔
944
    udfCol->colMeta.scale = col->info.scale;
927✔
945
    udfCol->colMeta.precision = col->info.precision;
927✔
946
    udfCol->colData.numOfRows = udfBlock->numOfRows;
927✔
947
    udfCol->hasNull = col->hasNull;
927✔
948
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
927!
949
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
1✔
950
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
1!
951
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
1!
952
        return terrno;
×
953
      }
954
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
1✔
955
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
1✔
956
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
1!
957
      if (udfCol->colData.varLenCol.payload == NULL) {
1!
958
        return terrno;
×
959
      }
960
      if (col->reassigned) {
1!
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);
1✔
976
      }
977
    } else {
978
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
926✔
979
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
926✔
980
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
926!
981
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
926!
982
        return terrno;
×
983
      }
984
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
926✔
985
      memcpy(bitmap, col->nullbitmap, bitmapLen);
926✔
986
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
926✔
987
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
926✔
988
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
926!
989
      if (NULL == udfCol->colData.fixLenCol.data) {
926!
990
        return terrno;
×
991
      }
992
      char *data = udfCol->colData.fixLenCol.data;
926✔
993
      memcpy(data, col->pData, dataLen);
926✔
994
    }
995
  }
996
  return TSDB_CODE_SUCCESS;
877✔
997
}
998

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

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

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

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

1015
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
97,229✔
1016
    if (udfColDataIsNull(udfCol, i)) {
96,808✔
1017
      colDataSetNULL(col, i);
196!
1018
    } else {
1019
      char *data = udfColDataGetData(udfCol, i);
96,612✔
1020
      code = colDataSetVal(col, i, data, false);
96,612✔
1021
      TAOS_CHECK_GOTO(code, &lino, _exit);
96,612!
1022
    }
1023
  }
1024
  block->info.rows = udfCol->colData.numOfRows;
421✔
1025

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

1035
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
421✔
1036
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
1,263!
1037
  int32_t code = 0, lino = 0;
421✔
1038
  int32_t numOfRows = 0;
421✔
1039
  for (int32_t i = 0; i < numOfCols; ++i) {
850✔
1040
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
429✔
1041
  }
1042

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

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

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

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

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

1060
    if (input[i].numOfRows < numOfRows) {
429!
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;
421✔
1076
_exit:
421✔
1077
  if (code != 0) {
421!
1078
    fnError("failed to convert scalar param to data block, code:%d, line:%d", code, lino);
×
1079
  }
1080
  return code;
421✔
1081
}
1082

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

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

1098
  return 0;
421✔
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) {
3,966✔
1158
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
3,966✔
1159
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
3,966✔
1160
  return strcmp(stub1->udfName, stub2->udfName);
3,966✔
1161
}
1162

1163
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle) {
1,265✔
1164
  TAOS_UDF_CHECK_PTR_RCODE(udfName, pHandle);
3,795!
1165
  int32_t code = 0, line = 0;
1,265✔
1166
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
1,265✔
1167
  SUdfcFuncStub key = {0};
1,265✔
1168
  tstrncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
1,265✔
1169
  int32_t stubIndex = taosArraySearchIdx(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
1,265✔
1170
  if (stubIndex != -1) {
1,265✔
1171
    SUdfcFuncStub *foundStub = taosArrayGet(gUdfcProxy.udfStubs, stubIndex);
1,100✔
1172
    UdfcFuncHandle handle = foundStub->handle;
1,100✔
1173
    int64_t        currUs = taosGetTimestampUs();
1,100✔
1174
    bool           expired = (currUs - foundStub->createTime) >= 10 * 1000 * 1000;
1,100✔
1175
    if (!expired) {
1,100!
1176
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
1,100!
1177
        *pHandle = foundStub->handle;
1,100✔
1178
        ++foundStub->refCount;
1,100✔
1179
        uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
1,100✔
1180
        return 0;
1,100✔
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);
165✔
1197
  *pHandle = NULL;
165✔
1198
  code = doSetupUdf(udfName, pHandle);
165✔
1199
  if (code == TSDB_CODE_SUCCESS) {
165!
1200
    SUdfcFuncStub stub = {0};
165✔
1201
    tstrncpy(stub.udfName, udfName, TSDB_FUNC_NAME_LEN);
165✔
1202
    stub.handle = *pHandle;
165✔
1203
    ++stub.refCount;
165✔
1204
    stub.createTime = taosGetTimestampUs();
165✔
1205
    uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
165✔
1206
    if (taosArrayPush(gUdfcProxy.udfStubs, &stub) == NULL) {
330!
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);
165✔
1212
    }
1213
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
165✔
1214
  } else {
1215
    *pHandle = NULL;
×
1216
  }
1217

1218
_exit:
165✔
1219
  return code;
165✔
1220
}
1221

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

1242
void cleanupExpiredUdfs() {
316✔
1243
  int32_t i = 0;
316✔
1244
  SArray *expiredUdfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
316✔
1245
  if (expiredUdfStubs == NULL) {
316!
1246
    fnError("cleanupExpiredUdfs: failed to init array");
×
1247
    return;
×
1248
  }
1249
  while (i < taosArrayGetSize(gUdfcProxy.expiredUdfStubs)) {
316!
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);
316✔
1271
  gUdfcProxy.expiredUdfStubs = expiredUdfStubs;
316✔
1272
}
1273

1274
void cleanupNotExpiredUdfs() {
316✔
1275
  SArray *udfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
316✔
1276
  if (udfStubs == NULL) {
316!
1277
    fnError("cleanupNotExpiredUdfs: failed to init array");
×
1278
    return;
×
1279
  }
1280
  int32_t i = 0;
316✔
1281
  while (i < taosArrayGetSize(gUdfcProxy.udfStubs)) {
693✔
1282
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.udfStubs, i);
377✔
1283
    if (stub->refCount == 0) {
377✔
1284
      fnInfo("tear down udf. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle, stub->refCount);
164!
1285
      (void)doTeardownUdf(stub->handle);
164✔
1286
    } else {
1287
      fnInfo("udf still in use. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p", stub->udfName,
213!
1288
             stub->refCount, stub->createTime, stub->handle);
1289
      UdfcFuncHandle handle = stub->handle;
213✔
1290
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
213!
1291
        if (taosArrayPush(udfStubs, stub) == NULL) {
213!
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;
377✔
1300
  }
1301
  taosArrayDestroy(gUdfcProxy.udfStubs);
316✔
1302
  gUdfcProxy.udfStubs = udfStubs;
316✔
1303
}
1304

1305
int32_t cleanUpUdfs() {
2,006,781✔
1306
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
2,006,781✔
1307
  if (!initialized) {
2,006,840✔
1308
    return TSDB_CODE_SUCCESS;
37✔
1309
  }
1310

1311
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
2,006,803✔
1312
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
2,006,988!
1313
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
2,006,672!
1314
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
2,006,672✔
1315
    return TSDB_CODE_SUCCESS;
2,006,672✔
1316
  }
1317

1318
  cleanupNotExpiredUdfs();
316✔
1319
  cleanupExpiredUdfs();
316✔
1320

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

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

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

1341
  if (output->columnData == NULL) {
421!
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) {
421!
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);
421✔
1352
  return code;
421✔
1353
}
1354

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

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

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

1389
  SUdfInterBuf buf = {0};
194✔
1390
  if ((udfCode = doCallUdfAggInit(handle, &buf)) != 0) {
194!
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) {
194!
1396
    memcpy(udfRes->interResBuf, buf.buf, buf.bufLen);
194✔
1397
    udfRes->interResBufLen = buf.bufLen;
194✔
1398
    udfRes->interResNum = buf.numOfResult;
194✔
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);
194✔
1405
  freeUdfInterBuf(&buf);
194✔
1406
  return TSDB_CODE_SUCCESS;
194✔
1407
}
1408

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

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

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

1430
  if (code) {
456!
1431
    return code;
×
1432
  }
1433

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

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

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

1454
  udfCode = doCallUdfAggProcess(session, inputBlock, &state, &newState);
456✔
1455
  if (udfCode != 0) {
456!
1456
    fnError("udfAggProcess error. code: %d", udfCode);
×
1457
    newState.numOfResult = 0;
×
1458
  } else {
1459
    if (newState.bufLen <= session->bufSize) {
456!
1460
      memcpy(udfRes->interResBuf, newState.buf, newState.bufLen);
456✔
1461
      udfRes->interResBufLen = newState.bufLen;
456✔
1462
      udfRes->interResNum = newState.numOfResult;
456✔
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;
456✔
1470

1471
  blockDataDestroy(inputBlock);
456✔
1472

1473
  taosArrayDestroy(pTempBlock->pDataBlock);
456✔
1474
  taosMemoryFree(pTempBlock);
456!
1475

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

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

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

1495
  SUdfInterBuf resultBuf = {0};
194✔
1496
  SUdfInterBuf state = {
194✔
1497
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
194✔
1498
  int32_t udfCallCode = 0;
194✔
1499
  udfCallCode = doCallUdfAggFinalize(session, &state, &resultBuf);
194✔
1500
  if (udfCallCode != 0) {
194!
1501
    fnError("udfAggFinalize error. doCallUdfAggFinalize step. udf code:%d", udfCallCode);
×
1502
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1503
  } else {
1504
    if (resultBuf.numOfResult == 0) {
194!
1505
      udfRes->finalResNum = 0;
×
1506
      GET_RES_INFO(pCtx)->numOfRes = 0;
×
1507
    } else {
1508
      if (resultBuf.bufLen <= session->bytes) {
194!
1509
        memcpy(udfRes->finalResBuf, resultBuf.buf, resultBuf.bufLen);
194✔
1510
        udfRes->finalResNum = resultBuf.numOfResult;
194✔
1511
        GET_RES_INFO(pCtx)->numOfRes = udfRes->finalResNum;
194✔
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);
194✔
1521

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

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

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

1558
      switch (task->type) {
1,594!
1559
        case UDF_TASK_SETUP: {
165✔
1560
          task->_setup.rsp = rsp.setupRsp;
165✔
1561
          break;
165✔
1562
        }
1563
        case UDF_TASK_CALL: {
1,265✔
1564
          task->_call.rsp = rsp.callRsp;
1,265✔
1565
          break;
1,265✔
1566
        }
1567
        case UDF_TASK_TEARDOWN: {
164✔
1568
          task->_teardown.rsp = rsp.teardownRsp;
1569
          break;
164✔
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);
1,594!
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) {
329✔
1585
    code = uvTask->errCode;
165✔
1586
    if (code != 0) {
165!
1587
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1588
    }
1589
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
164!
1590
    code = uvTask->errCode;
164✔
1591
    if (code != 0) {
164!
1592
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1593
    }
1594
  }
1595
  return code;
1,923✔
1596
}
1597

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

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

1610
      buf->base = connBuf->buf;
1,759✔
1611
      buf->len = connBuf->cap;
1,759✔
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) {
3,023!
1618
    buf->base = connBuf->buf + connBuf->len;
1,429✔
1619
    buf->len = msgHeadSize - connBuf->len;
1,429✔
1620
  } else {
1621
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
1,594✔
1622
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
1,594!
1623
    if (resultBuf) {
1,594!
1624
      connBuf->buf = resultBuf;
1,594✔
1625
      buf->base = connBuf->buf + connBuf->len;
1,594✔
1626
      buf->len = connBuf->cap - connBuf->len;
1,594✔
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);
4,782!
1635
}
4,782✔
1636

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

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

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

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

1676
  if (taskFound) {
1,594!
1677
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
1,594✔
1678
    QUEUE_REMOVE(&taskFound->connTaskQueue);
1,594✔
1679
    QUEUE_REMOVE(&taskFound->procTaskQueue);
1,594✔
1680
    uv_sem_post(&taskFound->taskSem);
1,594✔
1681
  } else {
1682
    fnError("no task is waiting for the response.");
×
1683
  }
1684
  connBuf->buf = NULL;
1,594✔
1685
  connBuf->total = -1;
1,594✔
1686
  connBuf->len = 0;
1,594✔
1687
  connBuf->cap = 0;
1,594✔
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) {
4,782✔
1706
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
4,782!
1707
  if (nread == 0) return;
4,782✔
1708

1709
  SClientUvConn  *conn = client->data;
3,188✔
1710
  SClientConnBuf *connBuf = &conn->readBuf;
3,188✔
1711
  if (nread > 0) {
3,188!
1712
    connBuf->len += nread;
3,188✔
1713
    if (isUdfcUvMsgComplete(connBuf)) {
3,188✔
1714
      udfcUvHandleRsp(conn);
1,594✔
1715
    }
1716
  }
1717
  if (nread < 0) {
3,188!
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) {
1,594✔
1727
  SClientUvConn *conn = write->data;
1,594✔
1728
  if (status < 0) {
1,594!
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);
1,594!
1733
  }
1734
  taosMemoryFree(write);
1,594!
1735
}
1,594✔
1736

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

1744
  int32_t code = uv_read_start((uv_stream_t *)uvTask->pipe, udfcAllocateBuffer, onUdfcPipeRead);
165✔
1745
  if (code != 0) {
165!
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);
165!
1750
  QUEUE_REMOVE(&uvTask->procTaskQueue);
165✔
1751
  uv_sem_post(&uvTask->taskSem);
165✔
1752
}
165✔
1753

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

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

1765
    if (task->type == UDF_TASK_SETUP) {
1,594✔
1766
      request.setup = task->_setup.req;
165✔
1767
      request.type = UDF_TASK_SETUP;
165✔
1768
    } else if (task->type == UDF_TASK_CALL) {
1,429✔
1769
      request.call = task->_call.req;
1,265✔
1770
      request.type = UDF_TASK_CALL;
1,265✔
1771
    } else if (task->type == UDF_TASK_TEARDOWN) {
164!
1772
      request.teardown = task->_teardown.req;
164✔
1773
      request.type = UDF_TASK_TEARDOWN;
164✔
1774
    } else {
1775
      fnError("udfc create uv task, invalid task type : %d", task->type);
×
1776
    }
1777
    int32_t bufLen = encodeUdfRequest(NULL, &request);
1,594✔
1778
    if (bufLen <= 0) {
1,594!
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;
1,594✔
1783
    void *bufBegin = taosMemoryMalloc(bufLen);
1,594!
1784
    if (bufBegin == NULL) {
1,594!
1785
      fnError("udfc create uv task, malloc buffer failed. size: %d", bufLen);
×
1786
      return terrno;
×
1787
    }
1788
    void *buf = bufBegin;
1,594✔
1789
    if (encodeUdfRequest(&buf, &request) <= 0) {
1,594!
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);
1,594✔
1796
    uvTask->seqNum = request.seqNum;
1,594✔
1797
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
164!
1798
    uvTask->pipe = task->session->udfUvPipe;
164✔
1799
  }
1800
  if (uv_sem_init(&uvTask->taskSem, 0) != 0) {
1,923!
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;
1,923✔
1809
}
1810

1811
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask) {
1,923✔
1812
  fnDebug("queue uv task to event loop, uvTask: %d-%p", uvTask->type, uvTask);
1,923!
1813
  SUdfcProxy *udfc = uvTask->udfc;
1,923✔
1814
  uv_mutex_lock(&udfc->taskQueueMutex);
1,923✔
1815
  QUEUE_INSERT_TAIL(&udfc->taskQueue, &uvTask->recvTaskQueue);
1,923✔
1816
  uv_mutex_unlock(&udfc->taskQueueMutex);
1,923✔
1817
  int32_t code = uv_async_send(&udfc->loopTaskAync);
1,923✔
1818
  if (code != 0) {
1,923!
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);
1,923✔
1824
  fnDebug("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
1,923!
1825
  uv_sem_destroy(&uvTask->taskSem);
1,923✔
1826

1827
  return 0;
1,923✔
1828
}
1829

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

1834
  switch (uvTask->type) {
1,923!
1835
    case UV_TASK_CONNECT: {
165✔
1836
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
165!
1837
      if (pipe == NULL) {
165!
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) {
165!
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;
165✔
1847

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

1861
      pipe->data = conn;
165✔
1862

1863
      uv_connect_t *connReq = taosMemoryMalloc(sizeof(uv_connect_t));
165!
1864
      if (connReq == NULL) {
165!
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;
165✔
1871
      uv_pipe_connect(connReq, pipe, uvTask->udfc->udfdPipeName, onUdfcPipeConnect);
165✔
1872
      code = 0;
165✔
1873
      break;
165✔
1874
    }
1875
    case UV_TASK_REQ_RSP: {
1,594✔
1876
      uv_pipe_t *pipe = uvTask->pipe;
1,594✔
1877
      if (pipe == NULL) {
1,594!
1878
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1879
      } else {
1880
        uv_write_t *write = taosMemoryMalloc(sizeof(uv_write_t));
1,594!
1881
        if (write == NULL) {
1,594!
1882
          fnError("udfc event loop start req_rsp task malloc write failed.");
×
1883
          return terrno;
×
1884
        }
1885
        write->data = pipe->data;
1,594✔
1886
        QUEUE *connTaskQueue = &((SClientUvConn *)pipe->data)->taskQueue;
1,594✔
1887
        QUEUE_INSERT_TAIL(connTaskQueue, &uvTask->connTaskQueue);
1,594✔
1888
        int32_t err = uv_write(write, (uv_stream_t *)pipe, &uvTask->reqBuf, 1, onUdfcPipeWrite);
1,594✔
1889
        if (err != 0) {
1,594!
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;
1,594✔
1894
      }
1895
      break;
1,594✔
1896
    }
1897
    case UV_TASK_DISCONNECT: {
164✔
1898
      uv_pipe_t *pipe = uvTask->pipe;
164✔
1899
      if (pipe == NULL) {
164!
1900
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1901
      } else {
1902
        SClientUvConn *conn = pipe->data;
164✔
1903
        QUEUE_INSERT_TAIL(&conn->taskQueue, &uvTask->connTaskQueue);
164✔
1904
        if (!uv_is_closing((uv_handle_t *)uvTask->pipe)) {
164!
1905
          uv_close((uv_handle_t *)uvTask->pipe, onUdfcPipeClose);
164✔
1906
        }
1907
        code = 0;
164✔
1908
      }
1909
      break;
164✔
1910
    }
1911
    default: {
×
1912
      fnError("udfc event loop unknown task type.") break;
×
1913
    }
1914
  }
1915

1916
  return code;
1,923✔
1917
}
1918

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

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

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

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

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

1948
  while (!QUEUE_EMPTY(&wq)) {
2,376!
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)) {
2,376!
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
}
2,376✔
1968

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

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

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

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

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

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

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

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

2077
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType) {
1,923✔
2078
  int32_t            code = 0, lino = 0;
1,923✔
2079
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
1,923!
2080
  if (uvTask == NULL) {
1,923!
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);
1,923!
2085

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

2098
_exit:
1,758✔
2099
  if (code != 0) {
1,923!
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);
1,923!
2103
  uvTask->reqBuf.base = NULL;
1,923✔
2104
  taosMemoryFree(uvTask);
1,923!
2105
  uvTask = NULL;
1,923✔
2106
  return code;
1,923✔
2107
}
2108

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

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

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

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

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

2144
  SUdfSetupResponse *rsp = &task->_setup.rsp;
165✔
2145
  task->session->severHandle = rsp->udfHandle;
165✔
2146
  task->session->outputType = rsp->outputType;
165✔
2147
  task->session->bytes = rsp->bytes;
165✔
2148
  task->session->bufSize = rsp->bufSize;
165✔
2149
  tstrncpy(task->session->udfName, udfName, TSDB_FUNC_NAME_LEN);
165✔
2150
  fnInfo("successfully setup udf func handle. udfName: %s, handle: %p", udfName, task->session);
165!
2151
  *funcHandle = task->session;
165✔
2152
  taosMemoryFree(task);
165!
2153
  return 0;
165✔
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,
1,265✔
2165
                SSDataBlock *output, SUdfInterBuf *newState) {
2166
  fnDebug("udfc call udf. callType: %d, funcHandle: %p", callType, handle);
1,265!
2167
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
1,265✔
2168
  if (session->udfUvPipe == NULL) {
1,265!
2169
    fnError("No pipe to udfd");
×
2170
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2171
  }
2172
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
1,265!
2173
  if (task == NULL) {
1,265!
2174
    fnError("udfc call udf. failed to allocate memory for task");
×
2175
    return terrno;
×
2176
  }
2177
  task->session = (SUdfcUvSession *)handle;
1,265✔
2178
  task->type = UDF_TASK_CALL;
1,265✔
2179

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

2184
  switch (callType) {
1,265!
2185
    case TSDB_UDF_CALL_AGG_INIT: {
194✔
2186
      req->initFirst = 1;
194✔
2187
      break;
194✔
2188
    }
2189
    case TSDB_UDF_CALL_AGG_PROC: {
456✔
2190
      req->block = *input;
456✔
2191
      req->interBuf = *state;
456✔
2192
      break;
456✔
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: {
194✔
2200
      req->interBuf = *state;
194✔
2201
      break;
194✔
2202
    }
2203
    case TSDB_UDF_CALL_SCALA_PROC: {
421✔
2204
      req->block = *input;
421✔
2205
      break;
421✔
2206
    }
2207
  }
2208

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

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

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

2246
  return err;
194✔
2247
}
2248

2249
// input: block, state
2250
// output: interbuf,
2251
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
456✔
2252
  int8_t  callType = TSDB_UDF_CALL_AGG_PROC;
456✔
2253
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
456✔
2254
  return err;
456✔
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) {
194✔
2270
  int8_t  callType = TSDB_UDF_CALL_AGG_FIN;
194✔
2271
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
194✔
2272
  return err;
194✔
2273
}
2274

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

2290
  blockDataFreeRes(&inputBlock);
421✔
2291
  return err;
421✔
2292
}
2293

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

2298
  if (session->udfUvPipe == NULL) {
164!
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));
164!
2305
  if (task == NULL) {
164!
2306
    fnError("doTeardownUdf, failed to allocate memory for task");
×
2307
    taosMemoryFree(session);
×
2308
    return terrno;
×
2309
  }
2310
  task->session = session;
164✔
2311
  task->type = UDF_TASK_TEARDOWN;
164✔
2312

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

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

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

2322
  fnInfo("tear down udf. udf name: %s, udf func handle: %p", session->udfName, handle);
164!
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:
×
2332
  if (code != 0) {
164!
2333
    fnError("failed to teardown udf. udf name: %s, err: %d, line: %d", session->udfName, code, lino);
×
2334
  }
2335
  freeTaskSession(task);
164✔
2336
  taosMemoryFree(task);
164!
2337

2338
  return code;
164✔
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

© 2025 Coveralls, Inc