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

taosdata / TDengine / #3525

10 Nov 2024 03:50AM UTC coverage: 60.818% (-0.08%) from 60.898%
#3525

push

travis-ci

web-flow
Merge pull request #28709 from taosdata/main

merge: from main to 3.0 branch

118634 of 249004 branches covered (47.64%)

Branch coverage included in aggregate %.

136 of 169 new or added lines in 23 files covered. (80.47%)

542 existing lines in 129 files now uncovered.

199071 of 273386 relevant lines covered (72.82%)

15691647.46 hits per line

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

70.45
/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
#include "uv.h"
16

17
#include "os.h"
18

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

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

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

48
  int32_t dnodeId;
49
} SUdfdData;
50

51
SUdfdData udfdGlobal = {0};
52

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

56
extern char **environ;
57

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

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

82
static int32_t udfSpawnUdfd(SUdfdData *pData) {
2,424✔
83
  fnInfo("start to init udfd");
2,424!
84

85
  int32_t              err = 0;
2,424✔
86
  uv_process_options_t options = {0};
2,424✔
87

88
  char path[PATH_MAX] = {0};
2,424✔
89
  if (tsProcPath == NULL) {
2,424!
90
    path[0] = '.';
×
91
#ifdef WINDOWS
92
    GetModuleFileName(NULL, path, PATH_MAX);
93
    TAOS_DIRNAME(path);
94
#elif defined(_TD_DARWIN_64)
95
    uint32_t pathSize = sizeof(path);
96
    _NSGetExecutablePath(path, &pathSize);
97
    TAOS_DIRNAME(path);
98
#endif
99
  } else {
100
    TAOS_STRNCPY(path, tsProcPath, PATH_MAX);
2,424✔
101
    TAOS_DIRNAME(path);
2,424✔
102
  }
103
#ifdef WINDOWS
104
  if (strlen(path) == 0) {
105
    TAOS_STRCAT(path, "C:\\TDengine");
106
  }
107
  TAOS_STRCAT(path, "\\udfd.exe");
108
#else
109
  if (strlen(path) == 0) {
2,424!
110
    TAOS_STRCAT(path, "/usr/bin");
×
111
  }
112
  TAOS_STRCAT(path, "/udfd");
2,424✔
113
#endif
114
  char *argsUdfd[] = {path, "-c", configDir, NULL};
2,424✔
115
  options.args = argsUdfd;
2,424✔
116
  options.file = path;
2,424✔
117

118
  options.exit_cb = udfUdfdExit;
2,424✔
119

120
  TAOS_UV_LIB_ERROR_RET(uv_pipe_init(&pData->loop, &pData->ctrlPipe, 1));
2,424!
121

122
  uv_stdio_container_t child_stdio[3];
123
  child_stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE;
2,424✔
124
  child_stdio[0].data.stream = (uv_stream_t *)&pData->ctrlPipe;
2,424✔
125
  child_stdio[1].flags = UV_IGNORE;
2,424✔
126
  child_stdio[2].flags = UV_INHERIT_FD;
2,424✔
127
  child_stdio[2].data.fd = 2;
2,424✔
128
  options.stdio_count = 3;
2,424✔
129
  options.stdio = child_stdio;
2,424✔
130

131
  options.flags = UV_PROCESS_DETACHED;
2,424✔
132

133
  char dnodeIdEnvItem[32] = {0};
2,424✔
134
  char thrdPoolSizeEnvItem[32] = {0};
2,424✔
135
  snprintf(dnodeIdEnvItem, 32, "%s=%d", "DNODE_ID", pData->dnodeId);
2,424✔
136

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

145
  char    pathTaosdLdLib[512] = {0};
2,424✔
146
  size_t  taosdLdLibPathLen = sizeof(pathTaosdLdLib);
2,424✔
147
  int32_t ret = uv_os_getenv("LD_LIBRARY_PATH", pathTaosdLdLib, &taosdLdLibPathLen);
2,424✔
148
  if (ret != UV_ENOBUFS) {
2,424!
149
    taosdLdLibPathLen = strlen(pathTaosdLdLib);
2,424✔
150
  }
151

152
  char   udfdPathLdLib[1024] = {0};
2,424✔
153
  size_t udfdLdLibPathLen = strlen(tsUdfdLdLibPath);
2,424✔
154
  tstrncpy(udfdPathLdLib, tsUdfdLdLibPath, sizeof(udfdPathLdLib));
2,424✔
155

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

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

182
  char *envUdfd[] = {dnodeIdEnvItem, thrdPoolSizeEnvItem, ldLibPathEnvItem, taosFqdnEnvItem, NULL};
2,424✔
183

184
  char **envUdfdWithPEnv = NULL;
2,424✔
185
  if (environ != NULL) {
2,424!
186
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
2,424✔
187
    int32_t numEnviron = 0;
2,424✔
188
    while (environ[numEnviron] != NULL) {
43,149✔
189
      numEnviron++;
40,725✔
190
    }
191

192
    envUdfdWithPEnv = (char **)taosMemoryCalloc(numEnviron + lenEnvUdfd, sizeof(char *));
2,424✔
193
    if (envUdfdWithPEnv == NULL) {
2,424!
194
      err = TSDB_CODE_OUT_OF_MEMORY;
×
195
      goto _OVER;
×
196
    }
197

198
    for (int32_t i = 0; i < numEnviron; i++) {
43,149✔
199
      int32_t len = strlen(environ[i]) + 1;
40,725✔
200
      envUdfdWithPEnv[i] = (char *)taosMemoryCalloc(len, 1);
40,725✔
201
      if (envUdfdWithPEnv[i] == NULL) {
40,725!
202
        err = TSDB_CODE_OUT_OF_MEMORY;
×
203
        goto _OVER;
×
204
      }
205

206
      tstrncpy(envUdfdWithPEnv[i], environ[i], len);
40,725✔
207
    }
208

209
    for (int32_t i = 0; i < lenEnvUdfd; i++) {
14,544✔
210
      if (envUdfd[i] != NULL) {
12,120✔
211
        int32_t len = strlen(envUdfd[i]) + 1;
7,272✔
212
        envUdfdWithPEnv[numEnviron + i] = (char *)taosMemoryCalloc(len, 1);
7,272✔
213
        if (envUdfdWithPEnv[numEnviron + i] == NULL) {
7,272!
214
          err = TSDB_CODE_OUT_OF_MEMORY;
×
215
          goto _OVER;
×
216
        }
217

218
        tstrncpy(envUdfdWithPEnv[numEnviron + i], envUdfd[i], len);
7,272✔
219
      }
220
    }
221
    envUdfdWithPEnv[numEnviron + lenEnvUdfd - 1] = NULL;
2,424✔
222

223
    options.env = envUdfdWithPEnv;
2,424✔
224
  } else {
225
    options.env = envUdfd;
×
226
  }
227

228
  err = uv_spawn(&pData->loop, &pData->process, &options);
2,424✔
229
  pData->process.data = (void *)pData;
2,424✔
230

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

250
  if (err != 0) {
2,424!
251
    fnError("can not spawn udfd. path: %s, error: %s", path, uv_strerror(err));
×
252
  } else {
253
    fnInfo("udfd is initialized");
2,424!
254
  }
255

256
_OVER:
×
257
  if (taosFqdnEnvItem) {
2,424!
258
    taosMemoryFree(taosFqdnEnvItem);
×
259
  }
260

261
  if (envUdfdWithPEnv != NULL) {
2,424!
262
    int32_t i = 0;
2,424✔
263
    while (envUdfdWithPEnv[i] != NULL) {
50,421✔
264
      taosMemoryFree(envUdfdWithPEnv[i]);
47,997✔
265
      i++;
47,997✔
266
    }
267
    taosMemoryFree(envUdfdWithPEnv);
2,424✔
268
  }
269

270
  return err;
2,424✔
271
}
272

273
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
12,106✔
274
  if (!uv_is_closing(handle)) {
12,106!
275
    uv_close(handle, NULL);
12,106✔
276
  }
277
}
12,106✔
278

279
static void udfUdfdStopAsyncCb(uv_async_t *async) {
2,403✔
280
  SUdfdData *pData = async->data;
2,403✔
281
  uv_stop(&pData->loop);
2,403✔
282
}
2,403✔
283

284
static void udfWatchUdfd(void *args) {
2,403✔
285
  SUdfdData *pData = args;
2,403✔
286
  TAOS_UV_CHECK_ERRNO(uv_loop_init(&pData->loop));
2,403!
287
  TAOS_UV_CHECK_ERRNO(uv_async_init(&pData->loop, &pData->stopAsync, udfUdfdStopAsyncCb));
2,403!
288
  pData->stopAsync.data = pData;
2,403✔
289
  TAOS_UV_CHECK_ERRNO(udfSpawnUdfd(pData));
2,403!
290
  atomic_store_32(&pData->spawnErr, 0);
2,403✔
291
  (void)uv_barrier_wait(&pData->barrier);
2,403✔
292
  int32_t num = uv_run(&pData->loop, UV_RUN_DEFAULT);
2,403✔
293
  fnInfo("udfd loop exit with %d active handles, line:%d", num, __LINE__);
2,403!
294

295
  uv_walk(&pData->loop, udfUdfdCloseWalkCb, NULL);
2,403✔
296
  num = uv_run(&pData->loop, UV_RUN_DEFAULT);
2,403✔
297
  fnInfo("udfd loop exit with %d active handles, line:%d", num, __LINE__);
2,403!
298
  if (uv_loop_close(&pData->loop) != 0) {
2,403!
299
    fnError("udfd loop close failed, lino:%d", __LINE__);
×
300
  }
301
  return;
2,403✔
302

303
_exit:
×
304
  if (terrno != 0) {
×
305
    (void)uv_barrier_wait(&pData->barrier);
×
306
    atomic_store_32(&pData->spawnErr, terrno);
×
307
    if (uv_loop_close(&pData->loop) != 0) {
×
308
      fnError("udfd loop close failed, lino:%d", __LINE__);
×
309
    }
310
    fnError("udfd thread exit with code:%d lino:%d", terrno, terrln);
×
311
    terrno = TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
312
  }
313
  return;
×
314
}
315

316
int32_t udfStartUdfd(int32_t startDnodeId) {
2,404✔
317
  int32_t code = 0, lino = 0;
2,404✔
318
  if (!tsStartUdfd) {
2,404✔
319
    fnInfo("start udfd is disabled.") return 0;
1!
320
  }
321
  SUdfdData *pData = &udfdGlobal;
2,403✔
322
  if (pData->startCalled) {
2,403!
323
    fnInfo("dnode start udfd already called");
×
324
    return 0;
×
325
  }
326
  pData->startCalled = true;
2,403✔
327
  char dnodeId[8] = {0};
2,403✔
328
  snprintf(dnodeId, sizeof(dnodeId), "%d", startDnodeId);
2,403✔
329
  TAOS_CHECK_GOTO(uv_os_setenv("DNODE_ID", dnodeId), &lino, _exit);
2,403!
330
  pData->dnodeId = startDnodeId;
2,403✔
331

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

357
void udfStopUdfd() {
2,404✔
358
  SUdfdData *pData = &udfdGlobal;
2,404✔
359
  fnInfo("udfd start to stop, need cleanup:%d, spawn err:%d", pData->needCleanUp, pData->spawnErr);
2,404!
360
  if (!pData->needCleanUp || atomic_load_32(&pData->stopCalled)) {
2,404!
361
    return;
1✔
362
  }
363
  atomic_store_32(&pData->stopCalled, 1);
2,403✔
364
  pData->needCleanUp = false;
2,403✔
365
  uv_barrier_destroy(&pData->barrier);
2,403✔
366
  if (uv_async_send(&pData->stopAsync) != 0) {
2,403!
367
    fnError("stop udfd: failed to send stop async");
×
368
  }
369
  if (uv_thread_join(&pData->thread) != 0) {
2,403!
370
    fnError("stop udfd: failed to join udfd thread");
×
371
  }
372

373
#ifdef WINDOWS
374
  if (pData->jobHandle != NULL) CloseHandle(pData->jobHandle);
375
#endif
376
  fnInfo("udfd is cleaned up");
2,403!
377
  return;
2,403✔
378
}
379

380
/*
381
int32_t udfGetUdfdPid(int32_t* pUdfdPid) {
382
  SUdfdData *pData = &udfdGlobal;
383
  if (pData->spawnErr) {
384
    return pData->spawnErr;
385
  }
386
  uv_pid_t pid = uv_process_get_pid(&pData->process);
387
  if (pUdfdPid) {
388
    *pUdfdPid = (int32_t)pid;
389
  }
390
  return TSDB_CODE_SUCCESS;
391
}
392
*/
393

394
//==============================================================================================
395
/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl>
396
 * The QUEUE is copied from queue.h under libuv
397
 * */
398

399
typedef void *QUEUE[2];
400

401
/* Private macros. */
402
#define QUEUE_NEXT(q)      (*(QUEUE **)&((*(q))[0]))
403
#define QUEUE_PREV(q)      (*(QUEUE **)&((*(q))[1]))
404
#define QUEUE_PREV_NEXT(q) (QUEUE_NEXT(QUEUE_PREV(q)))
405
#define QUEUE_NEXT_PREV(q) (QUEUE_PREV(QUEUE_NEXT(q)))
406

407
/* Public macros. */
408
#define QUEUE_DATA(ptr, type, field) ((type *)((char *)(ptr) - offsetof(type, field)))
409

410
/* Important note: mutating the list while QUEUE_FOREACH is
411
 * iterating over its elements results in undefined behavior.
412
 */
413
#define QUEUE_FOREACH(q, h) for ((q) = QUEUE_NEXT(h); (q) != (h); (q) = QUEUE_NEXT(q))
414

415
#define QUEUE_EMPTY(q) ((const QUEUE *)(q) == (const QUEUE *)QUEUE_NEXT(q))
416

417
#define QUEUE_HEAD(q) (QUEUE_NEXT(q))
418

419
#define QUEUE_INIT(q)    \
420
  do {                   \
421
    QUEUE_NEXT(q) = (q); \
422
    QUEUE_PREV(q) = (q); \
423
  } while (0)
424

425
#define QUEUE_ADD(h, n)                 \
426
  do {                                  \
427
    QUEUE_PREV_NEXT(h) = QUEUE_NEXT(n); \
428
    QUEUE_NEXT_PREV(n) = QUEUE_PREV(h); \
429
    QUEUE_PREV(h) = QUEUE_PREV(n);      \
430
    QUEUE_PREV_NEXT(h) = (h);           \
431
  } while (0)
432

433
#define QUEUE_SPLIT(h, q, n)       \
434
  do {                             \
435
    QUEUE_PREV(n) = QUEUE_PREV(h); \
436
    QUEUE_PREV_NEXT(n) = (n);      \
437
    QUEUE_NEXT(n) = (q);           \
438
    QUEUE_PREV(h) = QUEUE_PREV(q); \
439
    QUEUE_PREV_NEXT(h) = (h);      \
440
    QUEUE_PREV(q) = (n);           \
441
  } while (0)
442

443
#define QUEUE_MOVE(h, n)        \
444
  do {                          \
445
    if (QUEUE_EMPTY(h))         \
446
      QUEUE_INIT(n);            \
447
    else {                      \
448
      QUEUE *q = QUEUE_HEAD(h); \
449
      QUEUE_SPLIT(h, q, n);     \
450
    }                           \
451
  } while (0)
452

453
#define QUEUE_INSERT_HEAD(h, q)    \
454
  do {                             \
455
    QUEUE_NEXT(q) = QUEUE_NEXT(h); \
456
    QUEUE_PREV(q) = (h);           \
457
    QUEUE_NEXT_PREV(q) = (q);      \
458
    QUEUE_NEXT(h) = (q);           \
459
  } while (0)
460

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

469
#define QUEUE_REMOVE(q)                 \
470
  do {                                  \
471
    QUEUE_PREV_NEXT(q) = QUEUE_NEXT(q); \
472
    QUEUE_NEXT_PREV(q) = QUEUE_PREV(q); \
473
  } while (0)
474

475
enum { UV_TASK_CONNECT = 0, UV_TASK_REQ_RSP = 1, UV_TASK_DISCONNECT = 2 };
476

477
int64_t gUdfTaskSeqNum = 0;
478
typedef struct SUdfcFuncStub {
479
  char           udfName[TSDB_FUNC_NAME_LEN + 1];
480
  UdfcFuncHandle handle;
481
  int32_t        refCount;
482
  int64_t        createTime;
483
} SUdfcFuncStub;
484

485
typedef struct SUdfcProxy {
486
  char         udfdPipeName[PATH_MAX + UDF_LISTEN_PIPE_NAME_LEN + 2];
487
  uv_barrier_t initBarrier;
488

489
  uv_loop_t   uvLoop;
490
  uv_thread_t loopThread;
491
  uv_async_t  loopTaskAync;
492

493
  uv_async_t loopStopAsync;
494

495
  uv_mutex_t taskQueueMutex;
496
  int8_t     udfcState;
497
  QUEUE      taskQueue;
498
  QUEUE      uvProcTaskQueue;
499

500
  uv_mutex_t udfStubsMutex;
501
  SArray    *udfStubs;         // SUdfcFuncStub
502
  SArray    *expiredUdfStubs;  // SUdfcFuncStub
503

504
  uv_mutex_t udfcUvMutex;
505
  int8_t     initialized;
506
} SUdfcProxy;
507

508
SUdfcProxy gUdfcProxy = {0};
509

510
typedef struct SUdfcUvSession {
511
  SUdfcProxy *udfc;
512
  int64_t     severHandle;
513
  uv_pipe_t  *udfUvPipe;
514

515
  int8_t  outputType;
516
  int32_t bytes;
517
  int32_t bufSize;
518

519
  char udfName[TSDB_FUNC_NAME_LEN + 1];
520
} SUdfcUvSession;
521

522
typedef struct SClientUvTaskNode {
523
  SUdfcProxy *udfc;
524
  int8_t      type;
525
  int32_t     errCode;
526

527
  uv_pipe_t *pipe;
528

529
  int64_t  seqNum;
530
  uv_buf_t reqBuf;
531

532
  uv_sem_t taskSem;
533
  uv_buf_t rspBuf;
534

535
  QUEUE recvTaskQueue;
536
  QUEUE procTaskQueue;
537
  QUEUE connTaskQueue;
538
} SClientUvTaskNode;
539

540
typedef struct SClientUdfTask {
541
  int8_t type;
542

543
  SUdfcUvSession *session;
544

545
  union {
546
    struct {
547
      SUdfSetupRequest  req;
548
      SUdfSetupResponse rsp;
549
    } _setup;
550
    struct {
551
      SUdfCallRequest  req;
552
      SUdfCallResponse rsp;
553
    } _call;
554
    struct {
555
      SUdfTeardownRequest  req;
556
      SUdfTeardownResponse rsp;
557
    } _teardown;
558
  };
559

560
} SClientUdfTask;
561

562
typedef struct SClientConnBuf {
563
  char   *buf;
564
  int32_t len;
565
  int32_t cap;
566
  int32_t total;
567
} SClientConnBuf;
568

569
typedef struct SClientUvConn {
570
  uv_pipe_t      *pipe;
571
  QUEUE           taskQueue;
572
  SClientConnBuf  readBuf;
573
  SUdfcUvSession *session;
574
} SClientUvConn;
575

576
enum {
577
  UDFC_STATE_INITAL = 0,  // initial state
578
  UDFC_STATE_STARTNG,     // starting after udfcOpen
579
  UDFC_STATE_READY,       // started and begin to receive quests
580
  UDFC_STATE_STOPPING,    // stopping after udfcClose
581
};
582

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

611
void getUdfdPipeName(char *pipeName, int32_t size) {
4,885✔
612
  char    dnodeId[8] = {0};
4,885✔
613
  size_t  dnodeIdSize = sizeof(dnodeId);
4,885✔
614
  int32_t err = uv_os_getenv(UDF_DNODE_ID_ENV_NAME, dnodeId, &dnodeIdSize);
4,885✔
615
  if (err != 0) {
4,885✔
616
    fnError("failed to get dnodeId from env since %s", uv_err_name(err));
1!
617
    dnodeId[0] = '1';
1✔
618
  }
619
#ifdef _WIN32
620
  snprintf(pipeName, size, "%s.%x.%s", UDF_LISTEN_PIPE_NAME_PREFIX, MurmurHash3_32(tsDataDir, strlen(tsDataDir)),
621
           dnodeId);
622
#else
623
  snprintf(pipeName, size, "%s/%s%s", tsDataDir, UDF_LISTEN_PIPE_NAME_PREFIX, dnodeId);
4,885✔
624
#endif
625
  fnInfo("get dnodeId:%s from env, pipe path:%s", dnodeId, pipeName);
4,885!
626
}
4,885✔
627

628
int32_t encodeUdfSetupRequest(void **buf, const SUdfSetupRequest *setup) {
1,977✔
629
  int32_t len = 0;
1,977✔
630
  len += taosEncodeBinary(buf, setup->udfName, TSDB_FUNC_NAME_LEN);
1,977✔
631
  return len;
1,977✔
632
}
633

634
void *decodeUdfSetupRequest(const void *buf, SUdfSetupRequest *request) {
901✔
635
  buf = taosDecodeBinaryTo(buf, request->udfName, TSDB_FUNC_NAME_LEN);
901✔
636
  return (void *)buf;
901✔
637
}
638

639
int32_t encodeUdfInterBuf(void **buf, const SUdfInterBuf *state) {
16,956✔
640
  int32_t len = 0;
16,956✔
641
  len += taosEncodeFixedI8(buf, state->numOfResult);
16,956✔
642
  len += taosEncodeFixedI32(buf, state->bufLen);
16,956✔
643
  len += taosEncodeBinary(buf, state->buf, state->bufLen);
16,956✔
644
  return len;
16,956✔
645
}
646

647
void *decodeUdfInterBuf(const void *buf, SUdfInterBuf *state) {
8,674✔
648
  buf = taosDecodeFixedI8(buf, &state->numOfResult);
8,674✔
649
  buf = taosDecodeFixedI32(buf, &state->bufLen);
8,674!
650
  buf = taosDecodeBinary(buf, (void **)&state->buf, state->bufLen);
8,674✔
651
  return (void *)buf;
8,674✔
652
}
653

654
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
65,918✔
655
  int32_t len = 0;
65,918✔
656
  len += taosEncodeFixedI64(buf, call->udfHandle);
65,918✔
657
  len += taosEncodeFixedI8(buf, call->callType);
65,918✔
658
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
65,918✔
659
    len += tEncodeDataBlock(buf, &call->block);
55,478✔
660
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
10,440✔
661
    len += taosEncodeFixedI8(buf, call->initFirst);
4,416✔
662
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
8,232✔
663
    len += tEncodeDataBlock(buf, &call->block);
6,058✔
664
    len += encodeUdfInterBuf(buf, &call->interBuf);
6,058✔
665
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
2,174!
666
    len += encodeUdfInterBuf(buf, &call->interBuf);
×
667
    len += encodeUdfInterBuf(buf, &call->interBuf2);
×
668
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
2,174✔
669
    len += encodeUdfInterBuf(buf, &call->interBuf);
2,166✔
670
  }
671
  return len;
65,887✔
672
}
673

674
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
31,976✔
675
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
31,976!
676
  buf = taosDecodeFixedI8(buf, &call->callType);
31,976✔
677
  switch (call->callType) {
31,976!
678
    case TSDB_UDF_CALL_SCALA_PROC:
27,609✔
679
      buf = tDecodeDataBlock(buf, &call->block);
27,609✔
680
      break;
27,584✔
681
    case TSDB_UDF_CALL_AGG_INIT:
908✔
682
      buf = taosDecodeFixedI8(buf, &call->initFirst);
908✔
683
      break;
908✔
684
    case TSDB_UDF_CALL_AGG_PROC:
2,571✔
685
      buf = tDecodeDataBlock(buf, &call->block);
2,571✔
686
      buf = decodeUdfInterBuf(buf, &call->interBuf);
2,571✔
687
      break;
2,571✔
688
    case TSDB_UDF_CALL_AGG_MERGE:
×
689
      buf = decodeUdfInterBuf(buf, &call->interBuf);
×
690
      buf = decodeUdfInterBuf(buf, &call->interBuf2);
×
691
      break;
×
692
    case TSDB_UDF_CALL_AGG_FIN:
887✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
887✔
694
      break;
887✔
695
  }
696
  return (void *)buf;
31,903✔
697
}
698

699
int32_t encodeUdfTeardownRequest(void **buf, const SUdfTeardownRequest *teardown) {
1,846✔
700
  int32_t len = 0;
1,846✔
701
  len += taosEncodeFixedI64(buf, teardown->udfHandle);
1,846✔
702
  return len;
1,846✔
703
}
704

705
void *decodeUdfTeardownRequest(const void *buf, SUdfTeardownRequest *teardown) {
836✔
706
  buf = taosDecodeFixedI64(buf, &teardown->udfHandle);
836!
707
  return (void *)buf;
836✔
708
}
709

710
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
69,736✔
711
  int32_t len = 0;
69,736✔
712
  if (buf == NULL) {
69,736✔
713
    len += sizeof(request->msgLen);
34,872✔
714
  } else {
715
    *(int32_t *)(*buf) = request->msgLen;
34,864✔
716
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
34,864✔
717
  }
718
  len += taosEncodeFixedI64(buf, request->seqNum);
69,736✔
719
  len += taosEncodeFixedI8(buf, request->type);
69,736✔
720
  if (request->type == UDF_TASK_SETUP) {
69,736✔
721
    len += encodeUdfSetupRequest(buf, &request->setup);
1,977✔
722
  } else if (request->type == UDF_TASK_CALL) {
67,759✔
723
    len += encodeUdfCallRequest(buf, &request->call);
65,925✔
724
  } else if (request->type == UDF_TASK_TEARDOWN) {
1,834!
725
    len += encodeUdfTeardownRequest(buf, &request->teardown);
1,846✔
726
  }
727
  return len;
69,698✔
728
}
729

730
void *decodeUdfRequest(const void *buf, SUdfRequest *request) {
33,712✔
731
  request->msgLen = *(int32_t *)(buf);
33,712✔
732
  buf = POINTER_SHIFT(buf, sizeof(request->msgLen));
33,712✔
733

734
  buf = taosDecodeFixedI64(buf, &request->seqNum);
33,712!
735
  buf = taosDecodeFixedI8(buf, &request->type);
33,712✔
736

737
  if (request->type == UDF_TASK_SETUP) {
33,712✔
738
    buf = decodeUdfSetupRequest(buf, &request->setup);
901✔
739
  } else if (request->type == UDF_TASK_CALL) {
32,811✔
740
    buf = decodeUdfCallRequest(buf, &request->call);
31,976✔
741
  } else if (request->type == UDF_TASK_TEARDOWN) {
835!
742
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
836✔
743
  }
744
  return (void *)buf;
33,653✔
745
}
746

747
int32_t encodeUdfSetupResponse(void **buf, const SUdfSetupResponse *setupRsp) {
1,802✔
748
  int32_t len = 0;
1,802✔
749
  len += taosEncodeFixedI64(buf, setupRsp->udfHandle);
1,802✔
750
  len += taosEncodeFixedI8(buf, setupRsp->outputType);
1,802✔
751
  len += taosEncodeFixedI32(buf, setupRsp->bytes);
1,802✔
752
  len += taosEncodeFixedI32(buf, setupRsp->bufSize);
1,802✔
753
  return len;
1,802✔
754
}
755

756
void *decodeUdfSetupResponse(const void *buf, SUdfSetupResponse *setupRsp) {
989✔
757
  buf = taosDecodeFixedI64(buf, &setupRsp->udfHandle);
989!
758
  buf = taosDecodeFixedI8(buf, &setupRsp->outputType);
989✔
759
  buf = taosDecodeFixedI32(buf, &setupRsp->bytes);
989!
760
  buf = taosDecodeFixedI32(buf, &setupRsp->bufSize);
989!
761
  return (void *)buf;
989✔
762
}
763

764
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp) {
63,792✔
765
  int32_t len = 0;
63,792✔
766
  len += taosEncodeFixedI8(buf, callRsp->callType);
63,792✔
767
  switch (callRsp->callType) {
63,792!
768
    case TSDB_UDF_CALL_SCALA_PROC:
55,082✔
769
      len += tEncodeDataBlock(buf, &callRsp->resultData);
55,082✔
770
      break;
54,969✔
771
    case TSDB_UDF_CALL_AGG_INIT:
1,816✔
772
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
1,816✔
773
      break;
1,816✔
774
    case TSDB_UDF_CALL_AGG_PROC:
5,142✔
775
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
5,142✔
776
      break;
5,142✔
777
    case TSDB_UDF_CALL_AGG_MERGE:
×
778
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
×
779
      break;
×
780
    case TSDB_UDF_CALL_AGG_FIN:
1,774✔
781
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
1,774✔
782
      break;
1,774✔
783
  }
784
  return len;
63,679✔
785
}
786

787
void *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp) {
32,898✔
788
  buf = taosDecodeFixedI8(buf, &callRsp->callType);
32,898✔
789
  switch (callRsp->callType) {
32,898!
790
    case TSDB_UDF_CALL_SCALA_PROC:
27,684✔
791
      buf = tDecodeDataBlock(buf, &callRsp->resultData);
27,684✔
792
      break;
27,716✔
793
    case TSDB_UDF_CALL_AGG_INIT:
1,104✔
794
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
1,104✔
795
      break;
1,104✔
796
    case TSDB_UDF_CALL_AGG_PROC:
3,029✔
797
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
3,029✔
798
      break;
3,029✔
799
    case TSDB_UDF_CALL_AGG_MERGE:
×
800
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
×
801
      break;
×
802
    case TSDB_UDF_CALL_AGG_FIN:
1,083✔
803
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
1,083✔
804
      break;
1,083✔
805
  }
806
  return (void *)buf;
32,930✔
807
}
808

809
int32_t encodeUdfTeardownResponse(void **buf, const SUdfTeardownResponse *teardownRsp) { return 0; }
1,672✔
810

811
void *decodeUdfTeardownResponse(const void *buf, SUdfTeardownResponse *teardownResponse) { return (void *)buf; }
923✔
812

813
int32_t encodeUdfResponse(void **buf, const SUdfResponse *rsp) {
67,294✔
814
  int32_t len = 0;
67,294✔
815
  len += sizeof(rsp->msgLen);
67,294✔
816
  if (buf != NULL) {
67,294✔
817
    *(int32_t *)(*buf) = rsp->msgLen;
33,693✔
818
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->msgLen));
33,693✔
819
  }
820

821
  len += sizeof(rsp->seqNum);
67,294✔
822
  if (buf != NULL) {
67,294✔
823
    *(int64_t *)(*buf) = rsp->seqNum;
33,698✔
824
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
33,698✔
825
  }
826

827
  len += taosEncodeFixedI64(buf, rsp->seqNum);
67,294✔
828
  len += taosEncodeFixedI8(buf, rsp->type);
67,294✔
829
  len += taosEncodeFixedI32(buf, rsp->code);
67,294✔
830

831
  switch (rsp->type) {
67,294!
832
    case UDF_TASK_SETUP:
1,802✔
833
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
1,802✔
834
      break;
1,802✔
835
    case UDF_TASK_CALL:
63,880✔
836
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
63,880✔
837
      break;
63,668✔
838
    case UDF_TASK_TEARDOWN:
1,672✔
839
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
1,672✔
840
      break;
1,672✔
841
    default:
×
842
      fnError("encode udf response, invalid udf response type %d", rsp->type);
×
843
      break;
×
844
  }
845
  return len;
67,142✔
846
}
847

848
void *decodeUdfResponse(const void *buf, SUdfResponse *rsp) {
34,831✔
849
  rsp->msgLen = *(int32_t *)(buf);
34,831✔
850
  buf = POINTER_SHIFT(buf, sizeof(rsp->msgLen));
34,831✔
851
  rsp->seqNum = *(int64_t *)(buf);
34,831✔
852
  buf = POINTER_SHIFT(buf, sizeof(rsp->seqNum));
34,831✔
853
  buf = taosDecodeFixedI64(buf, &rsp->seqNum);
34,831!
854
  buf = taosDecodeFixedI8(buf, &rsp->type);
34,831✔
855
  buf = taosDecodeFixedI32(buf, &rsp->code);
34,831!
856

857
  switch (rsp->type) {
34,831!
858
    case UDF_TASK_SETUP:
989✔
859
      buf = decodeUdfSetupResponse(buf, &rsp->setupRsp);
989✔
860
      break;
989✔
861
    case UDF_TASK_CALL:
32,955✔
862
      buf = decodeUdfCallResponse(buf, &rsp->callRsp);
32,955✔
863
      break;
32,890✔
864
    case UDF_TASK_TEARDOWN:
923✔
865
      buf = decodeUdfTeardownResponse(buf, &rsp->teardownRsp);
923✔
866
      break;
923✔
867
    default:
×
868
      rsp->code = TSDB_CODE_UDF_INTERNAL_ERROR;
×
869
      fnError("decode udf response, invalid udf response type %d", rsp->type);
×
870
      break;
×
871
  }
872
  if (buf == NULL) {
34,802!
873
    rsp->code = terrno;
×
874
    fnError("decode udf response failed, code:0x%x", rsp->code);
×
875
  }
876
  return (void *)buf;
34,820✔
877
}
878

879
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
58,428✔
880
  if (IS_VAR_DATA_TYPE(meta->type)) {
58,428!
881
    taosMemoryFree(data->varLenCol.varOffsets);
231✔
882
    data->varLenCol.varOffsets = NULL;
247✔
883
    taosMemoryFree(data->varLenCol.payload);
247✔
884
    data->varLenCol.payload = NULL;
247✔
885
  } else {
886
    taosMemoryFree(data->fixLenCol.nullBitmap);
58,197✔
887
    data->fixLenCol.nullBitmap = NULL;
57,986✔
888
    taosMemoryFree(data->fixLenCol.data);
57,986✔
889
    data->fixLenCol.data = NULL;
58,210✔
890
  }
891
}
58,457✔
892

893
void freeUdfColumn(SUdfColumn *col) { freeUdfColumnData(&col->colData, &col->colMeta); }
58,429✔
894

895
void freeUdfDataDataBlock(SUdfDataBlock *block) {
29,947✔
896
  for (int32_t i = 0; i < block->numOfCols; ++i) {
60,890✔
897
    freeUdfColumn(block->udfCols[i]);
30,721✔
898
    taosMemoryFree(block->udfCols[i]);
30,880✔
899
    block->udfCols[i] = NULL;
30,943✔
900
  }
901
  taosMemoryFree(block->udfCols);
30,169✔
902
  block->udfCols = NULL;
30,160✔
903
}
30,160✔
904

905
void freeUdfInterBuf(SUdfInterBuf *buf) {
13,021✔
906
  taosMemoryFree(buf->buf);
13,021✔
907
  buf->buf = NULL;
13,021✔
908
}
13,021✔
909

910
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
30,059✔
911
  udfBlock->numOfRows = block->info.rows;
30,059✔
912
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
30,059✔
913
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
30,092✔
914
  if ((udfBlock->udfCols) == NULL) {
30,149!
915
    return terrno;
×
916
  }
917
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
60,975✔
918
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
30,819✔
919
    if (udfBlock->udfCols[i] == NULL) {
30,888!
920
      return terrno;
×
921
    }
922
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
30,888✔
923
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
30,806✔
924
    udfCol->colMeta.type = col->info.type;
30,806✔
925
    udfCol->colMeta.bytes = col->info.bytes;
30,806✔
926
    udfCol->colMeta.scale = col->info.scale;
30,806✔
927
    udfCol->colMeta.precision = col->info.precision;
30,806✔
928
    udfCol->colData.numOfRows = udfBlock->numOfRows;
30,806✔
929
    udfCol->hasNull = col->hasNull;
30,806✔
930
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
30,806!
931
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
96✔
932
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
96✔
933
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
147!
934
        return terrno;
×
935
      }
936
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
147✔
937
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
147✔
938
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
147✔
939
      if (udfCol->colData.varLenCol.payload == NULL) {
147!
940
        return terrno;
×
941
      }
942
      if (col->reassigned) {
147!
943
        for (int32_t row = 0; row < udfCol->colData.numOfRows; ++row) {
×
944
          char   *pColData = col->pData + col->varmeta.offset[row];
×
945
          int32_t colSize = 0;
×
946
          if (col->info.type == TSDB_DATA_TYPE_JSON) {
×
947
            colSize = getJsonValueLen(pColData);
×
948
          } else {
949
            colSize = varDataTLen(pColData);
×
950
          }
951
          memcpy(udfCol->colData.varLenCol.payload, pColData, colSize);
×
952
          udfCol->colData.varLenCol.payload += colSize;
×
953
        }
954
      } else {
955
        memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
147✔
956
      }
957
    } else {
958
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
30,710✔
959
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
30,710✔
960
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
30,710✔
961
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
30,739!
962
        return terrno;
×
963
      }
964
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
30,739✔
965
      memcpy(bitmap, col->nullbitmap, bitmapLen);
30,739✔
966
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
30,739✔
967
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
30,736✔
968
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
30,736✔
969
      if (NULL == udfCol->colData.fixLenCol.data) {
30,679!
970
        return terrno;
×
971
      }
972
      char *data = udfCol->colData.fixLenCol.data;
30,679✔
973
      memcpy(data, col->pData, dataLen);
30,679✔
974
    }
975
  }
976
  return TSDB_CODE_SUCCESS;
30,156✔
977
}
978

979
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
27,374✔
980
  int32_t         code = 0, lino = 0;
27,374✔
981
  SUdfColumnMeta *meta = &udfCol->colMeta;
27,374✔
982

983
  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
27,374✔
984
  code = blockDataAppendColInfo(block, &colInfoData);
27,391✔
985
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,553!
986

987
  code = blockDataEnsureCapacity(block, udfCol->colData.numOfRows);
27,553✔
988
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,434!
989

990
  SColumnInfoData *col = NULL;
27,434✔
991
  code = bdGetColumnInfoData(block, 0, &col);
27,434✔
992
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,573!
993

994
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
6,553,749✔
995
    if (udfColDataIsNull(udfCol, i)) {
6,521,016✔
996
      colDataSetNULL(col, i);
697,701✔
997
    } else {
998
      char *data = udfColDataGetData(udfCol, i);
5,823,315✔
999
      code = colDataSetVal(col, i, data, false);
5,823,315✔
1000
      TAOS_CHECK_GOTO(code, &lino, _exit);
5,828,475!
1001
    }
1002
  }
1003
  block->info.rows = udfCol->colData.numOfRows;
32,733✔
1004

1005
_exit:
32,733✔
1006
  if (code != 0) {
32,733!
1007
    fnError("failed to convert udf column to data block, code:%d, line:%d", code, lino);
×
1008
  }
1009
  return TSDB_CODE_SUCCESS;
27,538✔
1010
}
1011

1012
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
27,754✔
1013
  int32_t code = 0, lino = 0;
27,754✔
1014
  int32_t numOfRows = 0;
27,754✔
1015
  for (int32_t i = 0; i < numOfCols; ++i) {
56,072✔
1016
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
28,318✔
1017
  }
1018

1019
  // create the basic block info structure
1020
  for (int32_t i = 0; i < numOfCols; ++i) {
56,072✔
1021
    SColumnInfoData *pInfo = input[i].columnData;
28,318✔
1022
    SColumnInfoData  d = {0};
28,318✔
1023
    d.info = pInfo->info;
28,318✔
1024

1025
    TAOS_CHECK_GOTO(blockDataAppendColInfo(output, &d), &lino, _exit);
28,318!
1026
  }
1027

1028
  TAOS_CHECK_GOTO(blockDataEnsureCapacity(output, numOfRows), &lino, _exit);
27,754!
1029

1030
  for (int32_t i = 0; i < numOfCols; ++i) {
56,071✔
1031
    SColumnInfoData *pDest = taosArrayGet(output->pDataBlock, i);
28,318✔
1032

1033
    SColumnInfoData *pColInfoData = input[i].columnData;
28,317✔
1034
    TAOS_CHECK_GOTO(colDataAssign(pDest, pColInfoData, input[i].numOfRows, &output->info), &lino, _exit);
28,317!
1035

1036
    if (input[i].numOfRows < numOfRows) {
28,317✔
1037
      int32_t startRow = input[i].numOfRows;
1✔
1038
      int32_t expandRows = numOfRows - startRow;
1✔
1039
      bool    isNull = colDataIsNull_s(pColInfoData, (input + i)->numOfRows - 1);
1!
1040
      if (isNull) {
1!
1041
        colDataSetNNULL(pDest, startRow, expandRows);
×
1042
      } else {
1043
        char *src = colDataGetData(pColInfoData, (input + i)->numOfRows - 1);
1!
1044
        for (int32_t j = 0; j < expandRows; ++j) {
7✔
1045
          TAOS_CHECK_GOTO(colDataSetVal(pDest, startRow + j, src, false), &lino, _exit);
6!
1046
        }
1047
      }
1048
    }
1049
  }
1050

1051
  output->info.rows = numOfRows;
27,753✔
1052
_exit:
27,753✔
1053
  if (code != 0) {
27,753!
1054
    fnError("failed to convert scalar param to data block, code:%d, line:%d", code, lino);
×
1055
  }
1056
  return code;
27,753✔
1057
}
1058

1059
int32_t convertDataBlockToScalarParm(SSDataBlock *input, SScalarParam *output) {
27,726✔
1060
  if (taosArrayGetSize(input->pDataBlock) != 1) {
27,726!
1061
    fnError("scalar function only support one column");
×
1062
    return 0;
×
1063
  }
1064
  output->numOfRows = input->info.rows;
27,727✔
1065

1066
  output->columnData = taosMemoryMalloc(sizeof(SColumnInfoData));
27,727✔
1067
  if (output->columnData == NULL) {
27,733!
1068
    return terrno;
×
1069
  }
1070
  memcpy(output->columnData, taosArrayGet(input->pDataBlock, 0), sizeof(SColumnInfoData));
27,733✔
1071
  output->colAlloced = true;
27,730✔
1072

1073
  return 0;
27,730✔
1074
}
1075

1076
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
1077
// memory layout |---SUdfAggRes----|-----final result-----|---inter result----|
1078
typedef struct SUdfAggRes {
1079
  int8_t  finalResNum;
1080
  int8_t  interResNum;
1081
  int32_t interResBufLen;
1082
  char   *finalResBuf;
1083
  char   *interResBuf;
1084
} SUdfAggRes;
1085

1086
void    onUdfcPipeClose(uv_handle_t *handle);
1087
int32_t udfcGetUdfTaskResultFromUvTask(SClientUdfTask *task, SClientUvTaskNode *uvTask);
1088
void    udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf);
1089
bool    isUdfcUvMsgComplete(SClientConnBuf *connBuf);
1090
void    udfcUvHandleRsp(SClientUvConn *conn);
1091
void    udfcUvHandleError(SClientUvConn *conn);
1092
void    onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf);
1093
void    onUdfcPipeWrite(uv_write_t *write, int32_t status);
1094
void    onUdfcPipeConnect(uv_connect_t *connect, int32_t status);
1095
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask);
1096
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask);
1097
int32_t udfcStartUvTask(SClientUvTaskNode *uvTask);
1098
void    udfcAsyncTaskCb(uv_async_t *async);
1099
void    cleanUpUvTasks(SUdfcProxy *udfc);
1100
void    udfStopAsyncCb(uv_async_t *async);
1101
void    constructUdfService(void *argsThread);
1102
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType);
1103
int32_t doSetupUdf(char udfName[], UdfcFuncHandle *funcHandle);
1104
int32_t compareUdfcFuncSub(const void *elem1, const void *elem2);
1105
int32_t doTeardownUdf(UdfcFuncHandle handle);
1106

1107
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
1108
                SSDataBlock *output, SUdfInterBuf *newState);
1109
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf);
1110
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState);
1111
int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
1112
                          SUdfInterBuf *resultBuf);
1113
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData);
1114
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1115
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1116

1117
int32_t udfcOpen();
1118
int32_t udfcClose();
1119

1120
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle);
1121
void    releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle);
1122
int32_t cleanUpUdfs();
1123

1124
bool    udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv);
1125
int32_t udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo);
1126
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx);
1127
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock);
1128

1129
void    cleanupNotExpiredUdfs();
1130
void    cleanupExpiredUdfs();
1131
int32_t compareUdfcFuncSub(const void *elem1, const void *elem2) {
108,949✔
1132
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
108,949✔
1133
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
108,949✔
1134
  return strcmp(stub1->udfName, stub2->udfName);
108,949✔
1135
}
1136

1137
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle) {
33,049✔
1138
  int32_t code = 0, line = 0;
33,049✔
1139
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
33,049✔
1140
  SUdfcFuncStub key = {0};
33,079✔
1141
  tstrncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
33,079✔
1142
  int32_t stubIndex = taosArraySearchIdx(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
33,079✔
1143
  if (stubIndex != -1) {
33,079✔
1144
    SUdfcFuncStub *foundStub = taosArrayGet(gUdfcProxy.udfStubs, stubIndex);
32,017✔
1145
    UdfcFuncHandle handle = foundStub->handle;
32,017✔
1146
    int64_t        currUs = taosGetTimestampUs();
32,017✔
1147
    bool           expired = (currUs - foundStub->createTime) >= 10 * 1000 * 1000;
32,017✔
1148
    if (!expired) {
32,017✔
1149
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
31,998!
1150
        *pHandle = foundStub->handle;
31,998✔
1151
        ++foundStub->refCount;
31,998✔
1152
        uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
31,998✔
1153
        return 0;
31,998✔
1154
      } else {
1155
        fnInfo("udf invalid handle for %s, refCount: %d, create time: %" PRId64 ". remove it from cache", udfName,
×
1156
               foundStub->refCount, foundStub->createTime);
1157
        taosArrayRemove(gUdfcProxy.udfStubs, stubIndex);
×
1158
      }
1159
    } else {
1160
      fnDebug("udf handle expired for %s, will setup udf. move it to expired list", udfName);
19!
1161
      if (taosArrayPush(gUdfcProxy.expiredUdfStubs, foundStub) == NULL) {
38!
1162
        fnError("acquireUdfFuncHandle: failed to push udf stub to array");
×
1163
      } else {
1164
        taosArrayRemove(gUdfcProxy.udfStubs, stubIndex);
19✔
1165
        taosArraySort(gUdfcProxy.expiredUdfStubs, compareUdfcFuncSub);
19✔
1166
      }
1167
    }
1168
  }
1169
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
1,081✔
1170
  *pHandle = NULL;
1,081✔
1171
  code = doSetupUdf(udfName, pHandle);
1,081✔
1172
  if (code == TSDB_CODE_SUCCESS) {
1,081✔
1173
    SUdfcFuncStub stub = {0};
972✔
1174
    tstrncpy(stub.udfName, udfName, TSDB_FUNC_NAME_LEN);
972✔
1175
    stub.handle = *pHandle;
972✔
1176
    ++stub.refCount;
972✔
1177
    stub.createTime = taosGetTimestampUs();
972✔
1178
    uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
972✔
1179
    if (taosArrayPush(gUdfcProxy.udfStubs, &stub) == NULL) {
1,944!
1180
      fnError("acquireUdfFuncHandle: failed to push udf stub to array");
×
1181
      uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
×
1182
      goto _exit;
×
1183
    } else {
1184
      taosArraySort(gUdfcProxy.udfStubs, compareUdfcFuncSub);
972✔
1185
    }
1186
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
972✔
1187
  } else {
1188
    *pHandle = NULL;
109✔
1189
  }
1190

1191
_exit:
1,081✔
1192
  return code;
1,081✔
1193
}
1194

1195
void releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle) {
32,949✔
1196
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
32,949✔
1197
  SUdfcFuncStub key = {0};
32,970✔
1198
  tstrncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
32,970✔
1199
  SUdfcFuncStub *foundStub = taosArraySearch(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
32,970✔
1200
  SUdfcFuncStub *expiredStub = taosArraySearch(gUdfcProxy.expiredUdfStubs, &key, compareUdfcFuncSub, TD_EQ);
32,970✔
1201
  if (!foundStub && !expiredStub) {
32,970!
1202
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
×
1203
    return;
×
1204
  }
1205
  if (foundStub != NULL && foundStub->handle == handle && foundStub->refCount > 0) {
32,970!
1206
    --foundStub->refCount;
32,921✔
1207
  }
1208
  if (expiredStub != NULL && expiredStub->handle == handle && expiredStub->refCount > 0) {
32,970!
1209
    --expiredStub->refCount;
×
1210
  }
1211
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
32,970✔
1212
}
1213

1214
void cleanupExpiredUdfs() {
9,858✔
1215
  int32_t i = 0;
9,858✔
1216
  SArray *expiredUdfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
9,858✔
1217
  if (expiredUdfStubs == NULL) {
9,858!
1218
    fnError("cleanupExpiredUdfs: failed to init array");
×
1219
    return;
×
1220
  }
1221
  while (i < taosArrayGetSize(gUdfcProxy.expiredUdfStubs)) {
53,758✔
1222
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.expiredUdfStubs, i);
43,900✔
1223
    if (stub->refCount == 0) {
43,900!
1224
      fnInfo("tear down udf. expired. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle,
×
1225
             stub->refCount);
1226
      (void)doTeardownUdf(stub->handle);
×
1227
    } else {
1228
      fnInfo("udf still in use. expired. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p",
43,900!
1229
             stub->udfName, stub->refCount, stub->createTime, stub->handle);
1230
      UdfcFuncHandle handle = stub->handle;
43,900✔
1231
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
43,900!
1232
        if (taosArrayPush(expiredUdfStubs, stub) == NULL) {
43,900!
1233
          fnError("cleanupExpiredUdfs: failed to push udf stub to array");
×
1234
        }
1235
      } else {
1236
        fnInfo("udf invalid handle for %s, expired. refCount: %d, create time: %" PRId64 ". remove it from cache",
×
1237
               stub->udfName, stub->refCount, stub->createTime);
1238
      }
1239
    }
1240
    ++i;
43,900✔
1241
  }
1242
  taosArrayDestroy(gUdfcProxy.expiredUdfStubs);
9,858✔
1243
  gUdfcProxy.expiredUdfStubs = expiredUdfStubs;
9,858✔
1244
}
1245

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

1277
int32_t cleanUpUdfs() {
8,990,949✔
1278
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
8,990,949✔
1279
  if (!initialized) {
8,991,326✔
1280
    return TSDB_CODE_SUCCESS;
90,186✔
1281
  }
1282

1283
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
8,901,140✔
1284
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
8,903,618!
1285
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
8,893,760!
1286
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
8,893,760✔
1287
    return TSDB_CODE_SUCCESS;
8,893,741✔
1288
  }
1289

1290
  cleanupNotExpiredUdfs();
9,858✔
1291
  cleanupExpiredUdfs();
9,858✔
1292

1293
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
9,858✔
1294
  return 0;
9,858✔
1295
}
1296

1297
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
27,809✔
1298
  UdfcFuncHandle handle = NULL;
27,809✔
1299
  int32_t        code = acquireUdfFuncHandle(udfName, &handle);
27,809✔
1300
  if (code != 0) {
27,838✔
1301
    return code;
84✔
1302
  }
1303

1304
  SUdfcUvSession *session = handle;
27,754✔
1305
  code = doCallUdfScalarFunc(handle, input, numOfCols, output);
27,754✔
1306
  if (code != TSDB_CODE_SUCCESS) {
27,744✔
1307
    fnError("udfc scalar function execution failure");
18✔
1308
    releaseUdfFuncHandle(udfName, handle);
18✔
1309
    return code;
16✔
1310
  }
1311

1312
  if (output->columnData == NULL) {
27,726!
1313
    fnError("udfc scalar function calculate error. no column data");
×
1314
    code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1315
  } else {
1316
    if (session->outputType != output->columnData->info.type || session->bytes != output->columnData->info.bytes) {
27,726!
1317
      fnError("udfc scalar function calculate error. type mismatch. session type: %d(%d), output type: %d(%d)",
×
1318
              session->outputType, session->bytes, output->columnData->info.type, output->columnData->info.bytes);
1319
      code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1320
    }
1321
  }
1322
  releaseUdfFuncHandle(udfName, handle);
27,728✔
1323
  return code;
27,737✔
1324
}
1325

1326
bool udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv) {
599✔
1327
  if (fmIsScalarFunc(pFunc->funcId)) {
599!
1328
    return false;
×
1329
  }
1330
  pEnv->calcMemSize = sizeof(SUdfAggRes) + pFunc->node.resType.bytes + pFunc->udfBufSize;
599✔
1331
  return true;
599✔
1332
}
1333

1334
int32_t udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo) {
1,129✔
1335
  if (pResultCellInfo->initialized) {
1,129!
1336
    return TSDB_CODE_SUCCESS;
×
1337
  }
1338
  if (functionSetup(pCtx, pResultCellInfo) != TSDB_CODE_SUCCESS) {
1,129!
1339
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1340
  }
1341
  UdfcFuncHandle handle;
1342
  int32_t        udfCode = 0;
1,129✔
1343
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
1,129✔
1344
    fnError("udfAggInit error. step doSetupUdf. udf code: %d", udfCode);
25!
1345
    return TSDB_CODE_FUNC_SETUP_ERROR;
25✔
1346
  }
1347
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
1,104✔
1348
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(pResultCellInfo);
1,104✔
1349
  int32_t         envSize = sizeof(SUdfAggRes) + session->bytes + session->bufSize;
1,104✔
1350
  memset(udfRes, 0, envSize);
1,104✔
1351

1352
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
1,104✔
1353
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
1,104✔
1354

1355
  SUdfInterBuf buf = {0};
1,104✔
1356
  if ((udfCode = doCallUdfAggInit(handle, &buf)) != 0) {
1,104✔
1357
    fnError("udfAggInit error. step doCallUdfAggInit. udf code: %d", udfCode);
19!
1358
    releaseUdfFuncHandle(pCtx->udfName, handle);
19✔
1359
    return TSDB_CODE_FUNC_SETUP_ERROR;
19✔
1360
  }
1361
  if (buf.bufLen <= session->bufSize) {
1,085!
1362
    memcpy(udfRes->interResBuf, buf.buf, buf.bufLen);
1,085✔
1363
    udfRes->interResBufLen = buf.bufLen;
1,085✔
1364
    udfRes->interResNum = buf.numOfResult;
1,085✔
1365
  } else {
1366
    fnError("udfc inter buf size %d is greater than function bufSize %d", buf.bufLen, session->bufSize);
×
1367
    releaseUdfFuncHandle(pCtx->udfName, handle);
×
1368
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1369
  }
1370
  releaseUdfFuncHandle(pCtx->udfName, handle);
1,085✔
1371
  freeUdfInterBuf(&buf);
1,085✔
1372
  return TSDB_CODE_SUCCESS;
1,085✔
1373
}
1374

1375
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx) {
3,029✔
1376
  int32_t        udfCode = 0;
3,029✔
1377
  UdfcFuncHandle handle = 0;
3,029✔
1378
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
3,029!
1379
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
×
1380
    return udfCode;
×
1381
  }
1382

1383
  SUdfcUvSession *session = handle;
3,029✔
1384
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,029✔
1385
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
3,029✔
1386
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
3,029✔
1387

1388
  SInputColumnInfoData *pInput = &pCtx->input;
3,029✔
1389
  int32_t               numOfCols = pInput->numOfInputCols;
3,029✔
1390
  int32_t               start = pInput->startRowIndex;
3,029✔
1391
  int32_t               numOfRows = pInput->numOfRows;
3,029✔
1392
  SSDataBlock          *pTempBlock = NULL;
3,029✔
1393
  int32_t               code = createDataBlock(&pTempBlock);
3,029✔
1394

1395
  if (code) {
3,029!
1396
    return code;
×
1397
  }
1398

1399
  pTempBlock->info.rows = pInput->totalRows;
3,029✔
1400
  pTempBlock->info.id.uid = pInput->uid;
3,029✔
1401
  for (int32_t i = 0; i < numOfCols; ++i) {
6,256✔
1402
    if ((udfCode = blockDataAppendColInfo(pTempBlock, pInput->pData[i])) != 0) {
3,227!
1403
      fnError("udfAggProcess error. step blockDataAppendColInfo. udf code: %d", udfCode);
×
1404
      blockDataDestroy(pTempBlock);
×
1405
      return udfCode;
×
1406
    }
1407
  }
1408

1409
  SSDataBlock *inputBlock = NULL;
3,029✔
1410
  code = blockDataExtractBlock(pTempBlock, start, numOfRows, &inputBlock);
3,029✔
1411
  if (code) {
3,029!
1412
    return code;
×
1413
  }
1414

1415
  SUdfInterBuf state = {
3,029✔
1416
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
3,029✔
1417
  SUdfInterBuf newState = {0};
3,029✔
1418

1419
  udfCode = doCallUdfAggProcess(session, inputBlock, &state, &newState);
3,029✔
1420
  if (udfCode != 0) {
3,029!
1421
    fnError("udfAggProcess error. code: %d", udfCode);
×
1422
    newState.numOfResult = 0;
×
1423
  } else {
1424
    if (newState.bufLen <= session->bufSize) {
3,029!
1425
      memcpy(udfRes->interResBuf, newState.buf, newState.bufLen);
3,029✔
1426
      udfRes->interResBufLen = newState.bufLen;
3,029✔
1427
      udfRes->interResNum = newState.numOfResult;
3,029✔
1428
    } else {
1429
      fnError("udfc inter buf size %d is greater than function bufSize %d", newState.bufLen, session->bufSize);
×
1430
      udfCode = TSDB_CODE_UDF_INVALID_BUFSIZE;
×
1431
    }
1432
  }
1433

1434
  GET_RES_INFO(pCtx)->numOfRes = udfRes->interResNum;
3,029✔
1435

1436
  blockDataDestroy(inputBlock);
3,029✔
1437

1438
  taosArrayDestroy(pTempBlock->pDataBlock);
3,029✔
1439
  taosMemoryFree(pTempBlock);
3,029✔
1440

1441
  releaseUdfFuncHandle(pCtx->udfName, handle);
3,029✔
1442
  freeUdfInterBuf(&newState);
3,029✔
1443
  return udfCode;
3,029✔
1444
}
1445

1446
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock) {
1,083✔
1447
  int32_t        udfCode = 0;
1,083✔
1448
  UdfcFuncHandle handle = 0;
1,083✔
1449
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
1,083!
1450
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
×
1451
    return udfCode;
×
1452
  }
1453

1454
  SUdfcUvSession *session = handle;
1,083✔
1455
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,083✔
1456
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
1,083✔
1457
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
1,083✔
1458

1459
  SUdfInterBuf resultBuf = {0};
1,083✔
1460
  SUdfInterBuf state = {
1,083✔
1461
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
1,083✔
1462
  int32_t udfCallCode = 0;
1,083✔
1463
  udfCallCode = doCallUdfAggFinalize(session, &state, &resultBuf);
1,083✔
1464
  if (udfCallCode != 0) {
1,083!
1465
    fnError("udfAggFinalize error. doCallUdfAggFinalize step. udf code:%d", udfCallCode);
×
1466
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1467
  } else {
1468
    if (resultBuf.numOfResult == 0) {
1,083✔
1469
      udfRes->finalResNum = 0;
15✔
1470
      GET_RES_INFO(pCtx)->numOfRes = 0;
15✔
1471
    } else {
1472
      if (resultBuf.bufLen <= session->bytes) {
1,068!
1473
        memcpy(udfRes->finalResBuf, resultBuf.buf, resultBuf.bufLen);
1,068✔
1474
        udfRes->finalResNum = resultBuf.numOfResult;
1,068✔
1475
        GET_RES_INFO(pCtx)->numOfRes = udfRes->finalResNum;
1,068✔
1476
      } else {
1477
        fnError("udfc inter buf size %d is greater than function output size %d", resultBuf.bufLen, session->bytes);
×
1478
        GET_RES_INFO(pCtx)->numOfRes = 0;
×
1479
        udfCallCode = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1480
      }
1481
    }
1482
  }
1483

1484
  freeUdfInterBuf(&resultBuf);
1,083✔
1485

1486
  int32_t numOfResults = functionFinalizeWithResultBuf(pCtx, pBlock, udfRes->finalResBuf);
1,083✔
1487
  releaseUdfFuncHandle(pCtx->udfName, handle);
1,083✔
1488
  return udfCallCode == 0 ? numOfResults : udfCallCode;
1,083!
1489
}
1490

1491
void onUdfcPipeClose(uv_handle_t *handle) {
924✔
1492
  SClientUvConn *conn = handle->data;
924✔
1493
  if (!QUEUE_EMPTY(&conn->taskQueue)) {
924✔
1494
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
923✔
1495
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
923✔
1496
    task->errCode = 0;
923✔
1497
    QUEUE_REMOVE(&task->procTaskQueue);
923✔
1498
    uv_sem_post(&task->taskSem);
923✔
1499
  }
1500
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
924✔
1501
  if (conn->session != NULL) {
924!
1502
    conn->session->udfUvPipe = NULL;
924✔
1503
  }
1504
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
924✔
1505
  taosMemoryFree(conn->readBuf.buf);
924✔
1506
  taosMemoryFree(conn);
924✔
1507
  taosMemoryFree((uv_pipe_t *)handle);
924✔
1508
}
924✔
1509

1510
int32_t udfcGetUdfTaskResultFromUvTask(SClientUdfTask *task, SClientUvTaskNode *uvTask) {
36,803✔
1511
  int32_t code = 0;
36,803✔
1512
  fnDebug("udfc get uv task result. task: %p, uvTask: %p", task, uvTask);
36,803✔
1513
  if (uvTask->type == UV_TASK_REQ_RSP) {
36,828✔
1514
    if (uvTask->rspBuf.base != NULL) {
34,824!
1515
      SUdfResponse rsp = {0};
34,848✔
1516
      void        *buf = decodeUdfResponse(uvTask->rspBuf.base, &rsp);
34,848✔
1517
      code = rsp.code;
34,826✔
1518
      if (code != 0) {
34,826✔
1519
        fnError("udfc get udf task result failure. code: %d", code);
52!
1520
      }
1521

1522
      switch (task->type) {
34,848!
1523
        case UDF_TASK_SETUP: {
989✔
1524
          task->_setup.rsp = rsp.setupRsp;
989✔
1525
          break;
989✔
1526
        }
1527
        case UDF_TASK_CALL: {
32,936✔
1528
          task->_call.rsp = rsp.callRsp;
32,936✔
1529
          break;
32,936✔
1530
        }
1531
        case UDF_TASK_TEARDOWN: {
923✔
1532
          task->_teardown.rsp = rsp.teardownRsp;
1533
          break;
923✔
1534
        }
1535
        default: {
×
1536
          break;
×
1537
        }
1538
      }
1539

1540
      // TODO: the call buffer is setup and freed by udf invocation
1541
      taosMemoryFree(uvTask->rspBuf.base);
34,848✔
1542
    } else {
1543
      code = uvTask->errCode;
×
1544
      if (code != 0) {
×
1545
        fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1546
      }
1547
    }
1548
  } else if (uvTask->type == UV_TASK_CONNECT) {
2,004✔
1549
    code = uvTask->errCode;
1,081✔
1550
    if (code != 0) {
1,081✔
1551
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
92!
1552
    }
1553
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
923!
1554
    code = uvTask->errCode;
923✔
1555
    if (code != 0) {
923!
1556
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1557
    }
1558
  }
1559
  return code;
36,878✔
1560
}
1561

1562
void udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
97,809✔
1563
  SClientUvConn  *conn = handle->data;
97,809✔
1564
  SClientConnBuf *connBuf = &conn->readBuf;
97,809✔
1565

1566
  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
97,809✔
1567
  if (connBuf->cap == 0) {
97,809✔
1568
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
35,871✔
1569
    if (connBuf->buf) {
35,871!
1570
      connBuf->len = 0;
35,871✔
1571
      connBuf->cap = msgHeadSize;
35,871✔
1572
      connBuf->total = -1;
35,871✔
1573

1574
      buf->base = connBuf->buf;
35,871✔
1575
      buf->len = connBuf->cap;
35,871✔
1576
    } else {
1577
      fnError("udfc allocate buffer failure. size: %d", msgHeadSize);
×
1578
      buf->base = NULL;
×
1579
      buf->len = 0;
×
1580
    }
1581
  } else if (connBuf->total == -1 && connBuf->len < msgHeadSize) {
61,938!
1582
    buf->base = connBuf->buf + connBuf->len;
27,056✔
1583
    buf->len = msgHeadSize - connBuf->len;
27,056✔
1584
  } else {
1585
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
34,882✔
1586
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
34,882✔
1587
    if (resultBuf) {
34,882!
1588
      connBuf->buf = resultBuf;
34,882✔
1589
      buf->base = connBuf->buf + connBuf->len;
34,882✔
1590
      buf->len = connBuf->cap - connBuf->len;
34,882✔
1591
    } else {
1592
      fnError("udfc re-allocate buffer failure. size: %d", connBuf->cap);
×
1593
      buf->base = NULL;
×
1594
      buf->len = 0;
×
1595
    }
1596
  }
1597

1598
  fnDebug("udfc uv alloc buffer: cap - len - total : %d - %d - %d", connBuf->cap, connBuf->len, connBuf->total);
97,809✔
1599
}
97,809✔
1600

1601
bool isUdfcUvMsgComplete(SClientConnBuf *connBuf) {
69,764✔
1602
  if (connBuf->total == -1 && connBuf->len >= sizeof(int32_t)) {
69,764!
1603
    connBuf->total = *(int32_t *)(connBuf->buf);
34,882✔
1604
  }
1605
  if (connBuf->len == connBuf->cap && connBuf->total == connBuf->cap) {
69,764!
1606
    fnDebug("udfc complete message is received, now handle it");
34,882✔
1607
    return true;
34,882✔
1608
  }
1609
  return false;
34,882✔
1610
}
1611

1612
void udfcUvHandleRsp(SClientUvConn *conn) {
34,882✔
1613
  SClientConnBuf *connBuf = &conn->readBuf;
34,882✔
1614
  int64_t         seqNum = *(int64_t *)(connBuf->buf + sizeof(int32_t));  // msglen then seqnum
34,882✔
1615

1616
  if (QUEUE_EMPTY(&conn->taskQueue)) {
34,882!
1617
    fnError("udfc no task waiting on connection. response seqnum:%" PRId64, seqNum);
×
1618
    return;
×
1619
  }
1620
  bool               found = false;
34,882✔
1621
  SClientUvTaskNode *taskFound = NULL;
34,882✔
1622
  QUEUE             *h = QUEUE_NEXT(&conn->taskQueue);
34,882✔
1623
  SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
34,882✔
1624

1625
  while (h != &conn->taskQueue) {
108,971✔
1626
    fnDebug("udfc handle response iterate through queue. uvTask:%" PRId64 "-%p", task->seqNum, task);
74,089✔
1627
    if (task->seqNum == seqNum) {
74,089✔
1628
      if (found == false) {
34,882!
1629
        found = true;
34,882✔
1630
        taskFound = task;
34,882✔
1631
      } else {
1632
        fnError("udfc more than one task waiting for the same response");
×
1633
        continue;
×
1634
      }
1635
    }
1636
    h = QUEUE_NEXT(h);
74,089✔
1637
    task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
74,089✔
1638
  }
1639

1640
  if (taskFound) {
34,882!
1641
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
34,882✔
1642
    QUEUE_REMOVE(&taskFound->connTaskQueue);
34,882✔
1643
    QUEUE_REMOVE(&taskFound->procTaskQueue);
34,882✔
1644
    uv_sem_post(&taskFound->taskSem);
34,882✔
1645
  } else {
1646
    fnError("no task is waiting for the response.");
×
1647
  }
1648
  connBuf->buf = NULL;
34,882✔
1649
  connBuf->total = -1;
34,882✔
1650
  connBuf->len = 0;
34,882✔
1651
  connBuf->cap = 0;
34,882✔
1652
}
1653

1654
void udfcUvHandleError(SClientUvConn *conn) {
1✔
1655
  fnDebug("handle error on conn: %p, pipe: %p", conn, conn->pipe);
1!
1656
  while (!QUEUE_EMPTY(&conn->taskQueue)) {
1!
1657
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
×
1658
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
×
1659
    task->errCode = TSDB_CODE_UDF_PIPE_READ_ERR;
×
1660
    QUEUE_REMOVE(&task->connTaskQueue);
×
1661
    QUEUE_REMOVE(&task->procTaskQueue);
×
1662
    uv_sem_post(&task->taskSem);
×
1663
  }
1664
  if (!uv_is_closing((uv_handle_t *)conn->pipe)) {
1!
1665
    uv_close((uv_handle_t *)conn->pipe, onUdfcPipeClose);
1✔
1666
  }
1667
}
1✔
1668

1669
void onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
97,809✔
1670
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
97,809✔
1671
  if (nread == 0) return;
97,809✔
1672

1673
  SClientUvConn  *conn = client->data;
69,765✔
1674
  SClientConnBuf *connBuf = &conn->readBuf;
69,765✔
1675
  if (nread > 0) {
69,765✔
1676
    connBuf->len += nread;
69,764✔
1677
    if (isUdfcUvMsgComplete(connBuf)) {
69,764✔
1678
      udfcUvHandleRsp(conn);
34,882✔
1679
    }
1680
  }
1681
  if (nread < 0) {
69,765✔
1682
    fnError("udfc client pipe %p read error: %zd(%s).", client, nread, uv_strerror(nread));
1!
1683
    if (nread == UV_EOF) {
1!
1684
      fnError("\tudfc client pipe %p closed", client);
1!
1685
    }
1686
    udfcUvHandleError(conn);
1✔
1687
  }
1688
}
1689

1690
void onUdfcPipeWrite(uv_write_t *write, int32_t status) {
34,882✔
1691
  SClientUvConn *conn = write->data;
34,882✔
1692
  if (status < 0) {
34,882!
1693
    fnError("udfc client connection %p write failed. status: %d(%s)", conn, status, uv_strerror(status));
×
1694
    udfcUvHandleError(conn);
×
1695
  } else {
1696
    fnDebug("udfc client connection %p write succeed", conn);
34,882✔
1697
  }
1698
  taosMemoryFree(write);
34,882✔
1699
}
34,882✔
1700

1701
void onUdfcPipeConnect(uv_connect_t *connect, int32_t status) {
1,081✔
1702
  SClientUvTaskNode *uvTask = connect->data;
1,081✔
1703
  if (status != 0) {
1,081✔
1704
    fnError("client connect error, task seq: %" PRId64 ", code: %s", uvTask->seqNum, uv_strerror(status));
92!
1705
  }
1706
  uvTask->errCode = status;
1,081✔
1707

1708
  int32_t code = uv_read_start((uv_stream_t *)uvTask->pipe, udfcAllocateBuffer, onUdfcPipeRead);
1,081✔
1709
  if (code != 0) {
1,081✔
1710
    fnError("udfc client connection %p read start failed. code: %d(%s)", uvTask->pipe, code, uv_strerror(code));
92!
1711
    uvTask->errCode = code;
92✔
1712
  }
1713
  taosMemoryFree(connect);
1,081✔
1714
  QUEUE_REMOVE(&uvTask->procTaskQueue);
1,081✔
1715
  uv_sem_post(&uvTask->taskSem);
1,081✔
1716
}
1,081✔
1717

1718
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask) {
36,878✔
1719
  uvTask->type = uvTaskType;
36,878✔
1720
  uvTask->udfc = task->session->udfc;
36,878✔
1721

1722
  if (uvTaskType == UV_TASK_CONNECT) {
36,878✔
1723
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
35,799✔
1724
    uvTask->pipe = task->session->udfUvPipe;
34,878✔
1725
    SUdfRequest request;
1726
    request.type = task->type;
34,878✔
1727
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
34,878✔
1728

1729
    if (task->type == UDF_TASK_SETUP) {
34,879✔
1730
      request.setup = task->_setup.req;
988✔
1731
      request.type = UDF_TASK_SETUP;
988✔
1732
    } else if (task->type == UDF_TASK_CALL) {
33,891✔
1733
      request.call = task->_call.req;
32,968✔
1734
      request.type = UDF_TASK_CALL;
32,968✔
1735
    } else if (task->type == UDF_TASK_TEARDOWN) {
923!
1736
      request.teardown = task->_teardown.req;
923✔
1737
      request.type = UDF_TASK_TEARDOWN;
923✔
1738
    } else {
1739
      fnError("udfc create uv task, invalid task type : %d", task->type);
×
1740
    }
1741
    int32_t bufLen = encodeUdfRequest(NULL, &request);
34,879✔
1742
    if (bufLen <= 0) {
34,866!
1743
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1744
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1745
    }
1746
    request.msgLen = bufLen;
34,866✔
1747
    void *bufBegin = taosMemoryMalloc(bufLen);
34,866✔
1748
    if (bufBegin == NULL) {
34,873!
1749
      fnError("udfc create uv task, malloc buffer failed. size: %d", bufLen);
×
1750
      return terrno;
×
1751
    }
1752
    void *buf = bufBegin;
34,873✔
1753
    if (encodeUdfRequest(&buf, &request) <= 0) {
34,873!
1754
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1755
      taosMemoryFree(bufBegin);
×
1756
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1757
    }
1758

1759
    uvTask->reqBuf = uv_buf_init(bufBegin, bufLen);
34,861✔
1760
    uvTask->seqNum = request.seqNum;
34,851✔
1761
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
921!
1762
    uvTask->pipe = task->session->udfUvPipe;
923✔
1763
  }
1764
  if (uv_sem_init(&uvTask->taskSem, 0) != 0) {
36,851✔
1765
    if (uvTaskType == UV_TASK_REQ_RSP) {
7!
1766
      taosMemoryFree(uvTask->reqBuf.base);
×
1767
    }
1768
    fnError("udfc create uv task, init semaphore failed.");
7!
1769
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1770
  }
1771

1772
  return 0;
36,856✔
1773
}
1774

1775
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask) {
36,856✔
1776
  fnDebug("queue uv task to event loop, uvTask: %d-%p", uvTask->type, uvTask);
36,856✔
1777
  SUdfcProxy *udfc = uvTask->udfc;
36,856✔
1778
  uv_mutex_lock(&udfc->taskQueueMutex);
36,856✔
1779
  QUEUE_INSERT_TAIL(&udfc->taskQueue, &uvTask->recvTaskQueue);
36,886✔
1780
  uv_mutex_unlock(&udfc->taskQueueMutex);
36,886✔
1781
  int32_t code = uv_async_send(&udfc->loopTaskAync);
36,886✔
1782
  if (code != 0) {
36,860!
1783
    fnError("udfc queue uv task to event loop failed. code: %s", uv_strerror(code));
×
1784
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1785
  }
1786

1787
  uv_sem_wait(&uvTask->taskSem);
36,860✔
1788
  fnDebug("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
36,826✔
1789
  uv_sem_destroy(&uvTask->taskSem);
36,826✔
1790

1791
  return 0;
36,809✔
1792
}
1793

1794
int32_t udfcStartUvTask(SClientUvTaskNode *uvTask) {
36,886✔
1795
  fnDebug("event loop start uv task. uvTask: %" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
36,886✔
1796
  int32_t code = 0;
36,886✔
1797

1798
  switch (uvTask->type) {
36,886!
1799
    case UV_TASK_CONNECT: {
1,081✔
1800
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
1,081✔
1801
      if (pipe == NULL) {
1,081!
1802
        fnError("udfc event loop start connect task malloc pipe failed.");
×
1803
        return terrno;
×
1804
      }
1805
      if (uv_pipe_init(&uvTask->udfc->uvLoop, pipe, 0) != 0) {
1,081!
1806
        fnError("udfc event loop start connect task uv_pipe_init failed.");
×
1807
        taosMemoryFree(pipe);
×
1808
        return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1809
      }
1810
      uvTask->pipe = pipe;
1,081✔
1811

1812
      SClientUvConn *conn = taosMemoryCalloc(1, sizeof(SClientUvConn));
1,081✔
1813
      if (conn == NULL) {
1,081!
1814
        fnError("udfc event loop start connect task malloc conn failed.");
×
1815
        taosMemoryFree(pipe);
×
1816
        return terrno;
×
1817
      }
1818
      conn->pipe = pipe;
1,081✔
1819
      conn->readBuf.len = 0;
1,081✔
1820
      conn->readBuf.cap = 0;
1,081✔
1821
      conn->readBuf.buf = 0;
1,081✔
1822
      conn->readBuf.total = -1;
1,081✔
1823
      QUEUE_INIT(&conn->taskQueue);
1,081✔
1824

1825
      pipe->data = conn;
1,081✔
1826

1827
      uv_connect_t *connReq = taosMemoryMalloc(sizeof(uv_connect_t));
1,081✔
1828
      if (connReq == NULL) {
1,081!
1829
        fnError("udfc event loop start connect task malloc connReq failed.");
×
1830
        taosMemoryFree(pipe);
×
1831
        taosMemoryFree(conn);
×
1832
        return terrno;
×
1833
      }
1834
      connReq->data = uvTask;
1,081✔
1835
      uv_pipe_connect(connReq, pipe, uvTask->udfc->udfdPipeName, onUdfcPipeConnect);
1,081✔
1836
      code = 0;
1,081✔
1837
      break;
1,081✔
1838
    }
1839
    case UV_TASK_REQ_RSP: {
34,882✔
1840
      uv_pipe_t *pipe = uvTask->pipe;
34,882✔
1841
      if (pipe == NULL) {
34,882!
1842
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1843
      } else {
1844
        uv_write_t *write = taosMemoryMalloc(sizeof(uv_write_t));
34,882✔
1845
        if (write == NULL) {
34,882!
1846
          fnError("udfc event loop start req_rsp task malloc write failed.");
×
1847
          return terrno;
×
1848
        }
1849
        write->data = pipe->data;
34,882✔
1850
        QUEUE *connTaskQueue = &((SClientUvConn *)pipe->data)->taskQueue;
34,882✔
1851
        QUEUE_INSERT_TAIL(connTaskQueue, &uvTask->connTaskQueue);
34,882✔
1852
        int32_t err = uv_write(write, (uv_stream_t *)pipe, &uvTask->reqBuf, 1, onUdfcPipeWrite);
34,882✔
1853
        if (err != 0) {
34,882!
1854
          taosMemoryFree(write);
×
1855
          fnError("udfc event loop start req_rsp task uv_write failed. uvtask: %p, code: %s", uvTask, uv_strerror(err));
×
1856
        }
1857
        code = err;
34,882✔
1858
      }
1859
      break;
34,882✔
1860
    }
1861
    case UV_TASK_DISCONNECT: {
923✔
1862
      uv_pipe_t *pipe = uvTask->pipe;
923✔
1863
      if (pipe == NULL) {
923!
1864
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
1865
      } else {
1866
        SClientUvConn *conn = pipe->data;
923✔
1867
        QUEUE_INSERT_TAIL(&conn->taskQueue, &uvTask->connTaskQueue);
923✔
1868
        if (!uv_is_closing((uv_handle_t *)uvTask->pipe)) {
923!
1869
          uv_close((uv_handle_t *)uvTask->pipe, onUdfcPipeClose);
923✔
1870
        }
1871
        code = 0;
923✔
1872
      }
1873
      break;
923✔
1874
    }
1875
    default: {
×
1876
      fnError("udfc event loop unknown task type.") break;
×
1877
    }
1878
  }
1879

1880
  return code;
36,886✔
1881
}
1882

1883
void udfcAsyncTaskCb(uv_async_t *async) {
33,833✔
1884
  SUdfcProxy *udfc = async->data;
33,833✔
1885
  QUEUE       wq;
1886

1887
  uv_mutex_lock(&udfc->taskQueueMutex);
33,833✔
1888
  QUEUE_MOVE(&udfc->taskQueue, &wq);
33,833✔
1889
  uv_mutex_unlock(&udfc->taskQueueMutex);
33,833✔
1890

1891
  while (!QUEUE_EMPTY(&wq)) {
70,719✔
1892
    QUEUE *h = QUEUE_HEAD(&wq);
36,886✔
1893
    QUEUE_REMOVE(h);
36,886✔
1894
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
36,886✔
1895
    int32_t            code = udfcStartUvTask(task);
36,886✔
1896
    if (code == 0) {
36,886!
1897
      QUEUE_INSERT_TAIL(&udfc->uvProcTaskQueue, &task->procTaskQueue);
36,886✔
1898
    } else {
1899
      task->errCode = code;
×
1900
      uv_sem_post(&task->taskSem);
×
1901
    }
1902
  }
1903
}
33,833✔
1904

1905
void cleanUpUvTasks(SUdfcProxy *udfc) {
2,370✔
1906
  fnDebug("clean up uv tasks") QUEUE wq;
2,370✔
1907

1908
  uv_mutex_lock(&udfc->taskQueueMutex);
2,370✔
1909
  QUEUE_MOVE(&udfc->taskQueue, &wq);
2,370!
1910
  uv_mutex_unlock(&udfc->taskQueueMutex);
2,370✔
1911

1912
  while (!QUEUE_EMPTY(&wq)) {
2,370!
1913
    QUEUE *h = QUEUE_HEAD(&wq);
×
1914
    QUEUE_REMOVE(h);
×
1915
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
×
1916
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
×
1917
      task->errCode = TSDB_CODE_UDF_STOPPING;
×
1918
    }
1919
    uv_sem_post(&task->taskSem);
×
1920
  }
1921

1922
  while (!QUEUE_EMPTY(&udfc->uvProcTaskQueue)) {
2,370!
1923
    QUEUE *h = QUEUE_HEAD(&udfc->uvProcTaskQueue);
×
1924
    QUEUE_REMOVE(h);
×
1925
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, procTaskQueue);
×
1926
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
×
1927
      task->errCode = TSDB_CODE_UDF_STOPPING;
×
1928
    }
1929
    uv_sem_post(&task->taskSem);
×
1930
  }
1931
}
2,370✔
1932

1933
void udfStopAsyncCb(uv_async_t *async) {
2,370✔
1934
  SUdfcProxy *udfc = async->data;
2,370✔
1935
  cleanUpUvTasks(udfc);
2,370✔
1936
  if (udfc->udfcState == UDFC_STATE_STOPPING) {
2,370!
1937
    uv_stop(&udfc->uvLoop);
2,370✔
1938
  }
1939
}
2,370✔
1940

1941
void constructUdfService(void *argsThread) {
2,370✔
1942
  int32_t     code = 0, lino = 0;
2,370✔
1943
  SUdfcProxy *udfc = (SUdfcProxy *)argsThread;
2,370✔
1944
  code = uv_loop_init(&udfc->uvLoop);
2,370✔
1945
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1946

1947
  code = uv_async_init(&udfc->uvLoop, &udfc->loopTaskAync, udfcAsyncTaskCb);
2,370✔
1948
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1949
  udfc->loopTaskAync.data = udfc;
2,370✔
1950
  code = uv_async_init(&udfc->uvLoop, &udfc->loopStopAsync, udfStopAsyncCb);
2,370✔
1951
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1952
  udfc->loopStopAsync.data = udfc;
2,370✔
1953
  code = uv_mutex_init(&udfc->taskQueueMutex);
2,370✔
1954
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1955
  QUEUE_INIT(&udfc->taskQueue);
2,370✔
1956
  QUEUE_INIT(&udfc->uvProcTaskQueue);
2,370✔
1957
  (void)uv_barrier_wait(&udfc->initBarrier);
2,370✔
1958
  // TODO return value of uv_run
1959
  int32_t num = uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
2,370✔
1960
  fnInfo("udfc uv loop exit. active handle num: %d", num);
2,370!
1961
  (void)uv_loop_close(&udfc->uvLoop);
2,370✔
1962

1963
  uv_walk(&udfc->uvLoop, udfUdfdCloseWalkCb, NULL);
2,370✔
1964
  num = uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
2,370✔
1965
  fnInfo("udfc uv loop exit. active handle num: %d", num);
2,370!
1966

1967
  (void)uv_loop_close(&udfc->uvLoop);
2,370✔
1968
_exit:
2,370✔
1969
  if (code != 0) {
2,370!
1970
    fnError("udfc construct error. code: %d, line: %d", code, lino);
×
1971
  }
1972
  fnInfo("udfc construct finished");
2,370!
1973
}
2,370✔
1974

1975
int32_t udfcOpen() {
2,939✔
1976
  int32_t code = 0, lino = 0;
2,939✔
1977
  int8_t  old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 0, 1);
2,939✔
1978
  if (old == 1) {
2,939✔
1979
    return 0;
569✔
1980
  }
1981
  SUdfcProxy *proxy = &gUdfcProxy;
2,370✔
1982
  getUdfdPipeName(proxy->udfdPipeName, sizeof(proxy->udfdPipeName));
2,370✔
1983
  proxy->udfcState = UDFC_STATE_STARTNG;
2,370✔
1984
  code = uv_barrier_init(&proxy->initBarrier, 2);
2,370✔
1985
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1986
  code = uv_thread_create(&proxy->loopThread, constructUdfService, proxy);
2,370✔
1987
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1988
  atomic_store_8(&proxy->udfcState, UDFC_STATE_READY);
2,370✔
1989
  proxy->udfcState = UDFC_STATE_READY;
2,370✔
1990
  (void)uv_barrier_wait(&proxy->initBarrier);
2,370✔
1991
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1992
  code = uv_mutex_init(&proxy->udfStubsMutex);
2,370✔
1993
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
1994
  proxy->udfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
2,370✔
1995
  if (proxy->udfStubs == NULL) {
2,370!
1996
    fnError("udfc init failed. udfStubs: %p", proxy->udfStubs);
×
1997
    return -1;
×
1998
  }
1999
  proxy->expiredUdfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
2,370✔
2000
  if (proxy->expiredUdfStubs == NULL) {
2,370!
2001
    taosArrayDestroy(proxy->udfStubs);
×
2002
    fnError("udfc init failed. expiredUdfStubs: %p", proxy->expiredUdfStubs);
×
2003
    return -1;
×
2004
  }
2005
  code = uv_mutex_init(&proxy->udfcUvMutex);
2,370✔
2006
  TAOS_CHECK_GOTO(code, &lino, _exit);
2,370!
2007
_exit:
2,370✔
2008
  if (code != 0) {
2,370!
2009
    fnError("udfc open error. code: %d, line: %d", code, lino);
×
2010
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
2011
  }
2012
  fnInfo("udfc initialized");
2,370!
2013
  return 0;
2,370✔
2014
}
2015

2016
int32_t udfcClose() {
2,404✔
2017
  int8_t old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 1, 0);
2,404✔
2018
  if (old == 0) {
2,404✔
2019
    return 0;
34✔
2020
  }
2021

2022
  SUdfcProxy *udfc = &gUdfcProxy;
2,370✔
2023
  udfc->udfcState = UDFC_STATE_STOPPING;
2,370✔
2024
  if (uv_async_send(&udfc->loopStopAsync) != 0) {
2,370!
2025
    fnError("udfc close error to send stop async");
×
2026
  }
2027
  if (uv_thread_join(&udfc->loopThread) != 0) {
2,370!
2028
    fnError("udfc close errir to join loop thread");
×
2029
  }
2030
  uv_mutex_destroy(&udfc->taskQueueMutex);
2,370✔
2031
  uv_barrier_destroy(&udfc->initBarrier);
2,370✔
2032
  taosArrayDestroy(udfc->expiredUdfStubs);
2,370✔
2033
  taosArrayDestroy(udfc->udfStubs);
2,370✔
2034
  uv_mutex_destroy(&udfc->udfStubsMutex);
2,370✔
2035
  uv_mutex_destroy(&udfc->udfcUvMutex);
2,370✔
2036
  udfc->udfcState = UDFC_STATE_INITAL;
2,370✔
2037
  fnInfo("udfc is cleaned up");
2,370!
2038
  return 0;
2,370✔
2039
}
2040

2041
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType) {
36,880✔
2042
  int32_t            code = 0, lino = 0;
36,880✔
2043
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
36,880✔
2044
  if (uvTask == NULL) {
36,879!
2045
    fnError("udfc client task: %p failed to allocate memory for uvTask", task);
×
2046
    return terrno;
×
2047
  }
2048
  fnDebug("udfc client task: %p created uvTask: %p. pipe: %p", task, uvTask, task->session->udfUvPipe);
36,879✔
2049

2050
  code = udfcInitializeUvTask(task, uvTaskType, uvTask);
36,879✔
2051
  TAOS_CHECK_GOTO(code, &lino, _exit);
36,860!
2052
  code = udfcQueueUvTask(uvTask);
36,860✔
2053
  TAOS_CHECK_GOTO(code, &lino, _exit);
36,802!
2054
  code = udfcGetUdfTaskResultFromUvTask(task, uvTask);
36,802✔
2055
  TAOS_CHECK_GOTO(code, &lino, _exit);
36,878✔
2056
  if (uvTaskType == UV_TASK_CONNECT) {
36,734✔
2057
    task->session->udfUvPipe = uvTask->pipe;
989✔
2058
    SClientUvConn *conn = uvTask->pipe->data;
989✔
2059
    conn->session = task->session;
989✔
2060
  }
2061

2062
_exit:
35,745✔
2063
  if (code != 0) {
36,878✔
2064
    fnError("udfc run udf uv task failure. task: %p, uvTask: %p, err: %d, line: %d", task, uvTask, code, lino);
144!
2065
  }
2066
  taosMemoryFree(uvTask->reqBuf.base);
36,878✔
2067
  uvTask->reqBuf.base = NULL;
36,878✔
2068
  taosMemoryFree(uvTask);
36,878✔
2069
  uvTask = NULL;
36,881✔
2070
  return code;
36,881✔
2071
}
2072

2073
int32_t doSetupUdf(char udfName[], UdfcFuncHandle *funcHandle) {
1,081✔
2074
  int32_t         code = TSDB_CODE_SUCCESS, lino = 0;
1,081✔
2075
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
1,081✔
2076
  if (task == NULL) {
1,081!
2077
    fnError("doSetupUdf, failed to allocate memory for task");
×
2078
    return terrno;
×
2079
  }
2080
  task->session = taosMemoryCalloc(1, sizeof(SUdfcUvSession));
1,081✔
2081
  if (task->session == NULL) {
1,081!
2082
    fnError("doSetupUdf, failed to allocate memory for session");
×
2083
    taosMemoryFree(task);
×
2084
    return terrno;
×
2085
  }
2086
  task->session->udfc = &gUdfcProxy;
1,081✔
2087
  task->type = UDF_TASK_SETUP;
1,081✔
2088

2089
  SUdfSetupRequest *req = &task->_setup.req;
1,081✔
2090
  tstrncpy(req->udfName, udfName, TSDB_FUNC_NAME_LEN);
1,081✔
2091

2092
  code = udfcRunUdfUvTask(task, UV_TASK_CONNECT);
1,081✔
2093
  TAOS_CHECK_GOTO(code, &lino, _exit);
1,081✔
2094

2095
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
989✔
2096
  TAOS_CHECK_GOTO(code, &lino, _exit);
989✔
2097

2098
  SUdfSetupResponse *rsp = &task->_setup.rsp;
972✔
2099
  task->session->severHandle = rsp->udfHandle;
972✔
2100
  task->session->outputType = rsp->outputType;
972✔
2101
  task->session->bytes = rsp->bytes;
972✔
2102
  task->session->bufSize = rsp->bufSize;
972✔
2103
  tstrncpy(task->session->udfName, udfName, TSDB_FUNC_NAME_LEN);
972✔
2104
  fnInfo("successfully setup udf func handle. udfName: %s, handle: %p", udfName, task->session);
972!
2105
  *funcHandle = task->session;
972✔
2106
  taosMemoryFree(task);
972✔
2107
  return 0;
972✔
2108

2109
_exit:
109✔
2110
  if (code != 0) {
109!
2111
    fnError("failed to setup udf. udfname: %s, err: %d line:%d", udfName, code, lino);
109!
2112
  }
2113
  taosMemoryFree(task->session);
109✔
2114
  taosMemoryFree(task);
109✔
2115
  return code;
109✔
2116
}
2117

2118
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
32,967✔
2119
                SSDataBlock *output, SUdfInterBuf *newState) {
2120
  fnDebug("udfc call udf. callType: %d, funcHandle: %p", callType, handle);
32,967✔
2121
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
32,967✔
2122
  if (session->udfUvPipe == NULL) {
32,967!
2123
    fnError("No pipe to udfd");
×
2124
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2125
  }
2126
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
32,967✔
2127
  if (task == NULL) {
32,966!
2128
    fnError("udfc call udf. failed to allocate memory for task");
×
2129
    return terrno;
×
2130
  }
2131
  task->session = (SUdfcUvSession *)handle;
32,966✔
2132
  task->type = UDF_TASK_CALL;
32,966✔
2133

2134
  SUdfCallRequest *req = &task->_call.req;
32,966✔
2135
  req->udfHandle = task->session->severHandle;
32,966✔
2136
  req->callType = callType;
32,966✔
2137

2138
  switch (callType) {
32,966!
2139
    case TSDB_UDF_CALL_AGG_INIT: {
1,104✔
2140
      req->initFirst = 1;
1,104✔
2141
      break;
1,104✔
2142
    }
2143
    case TSDB_UDF_CALL_AGG_PROC: {
3,029✔
2144
      req->block = *input;
3,029✔
2145
      req->interBuf = *state;
3,029✔
2146
      break;
3,029✔
2147
    }
2148
    case TSDB_UDF_CALL_AGG_MERGE: {
×
2149
      req->interBuf = *state;
×
2150
      req->interBuf2 = *state2;
×
2151
      break;
×
2152
    }
2153
    case TSDB_UDF_CALL_AGG_FIN: {
1,083✔
2154
      req->interBuf = *state;
1,083✔
2155
      break;
1,083✔
2156
    }
2157
    case TSDB_UDF_CALL_SCALA_PROC: {
27,748✔
2158
      req->block = *input;
27,748✔
2159
      break;
27,748✔
2160
    }
2161
  }
2162

2163
  int32_t code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
32,966✔
2164
  if (code != 0) {
32,963✔
2165
    fnError("call udf failure. udfcRunUdfUvTask err: %d", code);
35!
2166
  } else {
2167
    SUdfCallResponse *rsp = &task->_call.rsp;
32,928✔
2168
    switch (callType) {
32,928!
2169
      case TSDB_UDF_CALL_AGG_INIT: {
1,085✔
2170
        *newState = rsp->resultBuf;
1,085✔
2171
        break;
1,085✔
2172
      }
2173
      case TSDB_UDF_CALL_AGG_PROC: {
3,029✔
2174
        *newState = rsp->resultBuf;
3,029✔
2175
        break;
3,029✔
2176
      }
2177
      case TSDB_UDF_CALL_AGG_MERGE: {
×
2178
        *newState = rsp->resultBuf;
×
2179
        break;
×
2180
      }
2181
      case TSDB_UDF_CALL_AGG_FIN: {
1,083✔
2182
        *newState = rsp->resultBuf;
1,083✔
2183
        break;
1,083✔
2184
      }
2185
      case TSDB_UDF_CALL_SCALA_PROC: {
27,732✔
2186
        *output = rsp->resultData;
27,732✔
2187
        break;
27,732✔
2188
      }
2189
    }
2190
  };
2191
  taosMemoryFree(task);
32,963✔
2192
  return code;
32,968✔
2193
}
2194

2195
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf) {
1,104✔
2196
  int8_t callType = TSDB_UDF_CALL_AGG_INIT;
1,104✔
2197

2198
  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);
1,104✔
2199

2200
  return err;
1,104✔
2201
}
2202

2203
// input: block, state
2204
// output: interbuf,
2205
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
3,029✔
2206
  int8_t  callType = TSDB_UDF_CALL_AGG_PROC;
3,029✔
2207
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
3,029✔
2208
  return err;
3,029✔
2209
}
2210

2211
// input: interbuf1, interbuf2
2212
// output: resultBuf
2213
int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
×
2214
                          SUdfInterBuf *resultBuf) {
2215
  int8_t  callType = TSDB_UDF_CALL_AGG_MERGE;
×
2216
  int32_t err = callUdf(handle, callType, NULL, interBuf1, interBuf2, NULL, resultBuf);
×
2217
  return err;
×
2218
}
2219

2220
// input: interBuf
2221
// output: resultData
2222
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData) {
1,083✔
2223
  int8_t  callType = TSDB_UDF_CALL_AGG_FIN;
1,083✔
2224
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
1,083✔
2225
  return err;
1,083✔
2226
}
2227

2228
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
27,754✔
2229
  int8_t      callType = TSDB_UDF_CALL_SCALA_PROC;
27,754✔
2230
  SSDataBlock inputBlock = {0};
27,754✔
2231
  int32_t     code = convertScalarParamToDataBlock(input, numOfCols, &inputBlock);
27,754✔
2232
  if (code != 0) {
27,754!
2233
    fnError("doCallUdfScalarFunc, convertScalarParamToDataBlock failed. code: %d", code);
×
2234
    return code;
×
2235
  }
2236
  SSDataBlock resultBlock = {0};
27,754✔
2237
  int32_t     err = callUdf(handle, callType, &inputBlock, NULL, NULL, &resultBlock, NULL);
27,754✔
2238
  if (err == 0) {
27,742✔
2239
    err = convertDataBlockToScalarParm(&resultBlock, output);
27,733✔
2240
    taosArrayDestroy(resultBlock.pDataBlock);
27,730✔
2241
  }
2242

2243
  blockDataFreeRes(&inputBlock);
27,737✔
2244
  return err;
27,745✔
2245
}
2246

2247
int32_t doTeardownUdf(UdfcFuncHandle handle) {
923✔
2248
  int32_t         code = TSDB_CODE_SUCCESS, lino = 0;
923✔
2249
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
923✔
2250

2251
  if (session->udfUvPipe == NULL) {
923!
2252
    fnError("tear down udf. pipe to udfd does not exist. udf name: %s", session->udfName);
×
2253
    taosMemoryFree(session);
×
2254
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2255
  }
2256

2257
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
923✔
2258
  if (task == NULL) {
923!
2259
    fnError("doTeardownUdf, failed to allocate memory for task");
×
2260
    taosMemoryFree(session);
×
2261
    return terrno;
×
2262
  }
2263
  task->session = session;
923✔
2264
  task->type = UDF_TASK_TEARDOWN;
923✔
2265

2266
  SUdfTeardownRequest *req = &task->_teardown.req;
923✔
2267
  req->udfHandle = task->session->severHandle;
923✔
2268

2269
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
923✔
2270
  TAOS_CHECK_GOTO(code, &lino, _exit);
923!
2271

2272
  code = udfcRunUdfUvTask(task, UV_TASK_DISCONNECT);
923✔
2273
  TAOS_CHECK_GOTO(code, &lino, _exit);
923!
2274

2275
  fnInfo("tear down udf. udf name: %s, udf func handle: %p", session->udfName, handle);
923!
2276
  // TODO: synchronization refactor between libuv event loop and request thread
2277
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
923✔
2278
  if (session->udfUvPipe != NULL && session->udfUvPipe->data != NULL) {
923!
2279
    SClientUvConn *conn = session->udfUvPipe->data;
×
2280
    conn->session = NULL;
×
2281
  }
2282
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
923✔
2283

2284
_exit:
923✔
2285
  if (code != 0) {
923!
2286
    fnError("failed to teardown udf. udf name: %s, err: %d, line: %d", session->udfName, code, lino);
×
2287
  }
2288
  taosMemoryFree(session);
923✔
2289
  taosMemoryFree(task);
923✔
2290

2291
  return code;
923✔
2292
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc