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

taosdata / TDengine / #3849

18 Apr 2025 06:24AM UTC coverage: 62.513% (-0.1%) from 62.61%
#3849

push

travis-ci

GitHub
feat: taosBenchmark restore RESTFUL (3.0) (#30699)

154684 of 316122 branches covered (48.93%)

Branch coverage included in aggregate %.

240354 of 315808 relevant lines covered (76.11%)

10508512.55 hits per line

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

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

18
#include "os.h"
19

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

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

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

49
  int32_t dnodeId;
50
} SUdfdData;
51

52
SUdfdData udfdGlobal = {0};
53

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

57
extern char **environ;
58

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

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

84
static int32_t udfSpawnUdfd(SUdfdData *pData) {
2,352✔
85
  fnInfo("start to init udfd");
2,352!
86
  TAOS_UDF_CHECK_PTR_RCODE(pData);
4,704!
87

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

91
  char path[PATH_MAX] = {0};
2,352✔
92
  if (tsProcPath == NULL) {
2,352✔
93
    path[0] = '.';
16✔
94
#ifdef WINDOWS
95
    GetModuleFileName(NULL, path, PATH_MAX);
96
    TAOS_DIRNAME(path);
97
#elif defined(_TD_DARWIN_64)
98
    uint32_t pathSize = sizeof(path);
99
    _NSGetExecutablePath(path, &pathSize);
100
    TAOS_DIRNAME(path);
101
#endif
102
  } else {
103
    TAOS_STRNCPY(path, tsProcPath, PATH_MAX);
2,336✔
104
    TAOS_DIRNAME(path);
2,336✔
105
  }
106

107
#ifdef WINDOWS
108
  if (strlen(path) == 0) {
109
    TAOS_STRCAT(path, "C:\\TDengine");
110
  }
111
  TAOS_STRCAT(path, "\\" CUS_PROMPT "udf.exe");
112
#else
113
  if (strlen(path) == 0) {
2,352!
114
    TAOS_STRCAT(path, "/usr/bin");
×
115
  }
116
  TAOS_STRCAT(path, "/" CUS_PROMPT "udf");
2,352✔
117
#endif
118
  char *argsUdfd[] = {path, "-c", configDir, NULL};
2,352✔
119
  options.args = argsUdfd;
2,352✔
120
  options.file = path;
2,352✔
121

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

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

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

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

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

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

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

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

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

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

186
  char *envUdfd[] = {dnodeIdEnvItem, thrdPoolSizeEnvItem, ldLibPathEnvItem, taosFqdnEnvItem, NULL};
2,352✔
187

188
  char **envUdfdWithPEnv = NULL;
2,352✔
189
  if (environ != NULL) {
2,352!
190
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
2,352✔
191
    int32_t numEnviron = 0;
2,352✔
192
    while (environ[numEnviron] != NULL) {
47,900✔
193
      numEnviron++;
45,548✔
194
    }
195

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

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

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

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

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

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

232
  err = uv_spawn(&pData->loop, &pData->process, &options);
2,352✔
233
  pData->process.data = (void *)pData;
2,352✔
234

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

254
  if (err != 0) {
2,352✔
255
    fnError("can not spawn udfd. path: %s, error: %s", path, uv_strerror(err));
16!
256
  } else {
257
    fnInfo("udfd is initialized");
2,336!
258
  }
259

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

265
  if (envUdfdWithPEnv != NULL) {
2,352!
266
    int32_t i = 0;
2,352✔
267
    while (envUdfdWithPEnv[i] != NULL) {
54,956✔
268
      taosMemoryFree(envUdfdWithPEnv[i]);
52,604!
269
      i++;
52,604✔
270
    }
271
    taosMemoryFree(envUdfdWithPEnv);
2,352!
272
  }
273

274
  return err;
2,352✔
275
}
276

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

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

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

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

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

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

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

364
void udfStopUdfd() {
2,284✔
365
  SUdfdData *pData = &udfdGlobal;
2,284✔
366
  fnInfo("udfd start to stop, need cleanup:%d, spawn err:%d", pData->needCleanUp, pData->spawnErr);
2,284!
367
  if (!pData->needCleanUp || atomic_load_32(&pData->stopCalled)) {
2,284!
368
    return;
8✔
369
  }
370
  atomic_store_32(&pData->stopCalled, 1);
2,276✔
371
  pData->needCleanUp = false;
2,276✔
372
  uv_barrier_destroy(&pData->barrier);
2,276✔
373
  if (uv_async_send(&pData->stopAsync) != 0) {
2,276!
374
    fnError("stop udfd: failed to send stop async");
×
375
  }
376
  if (uv_thread_join(&pData->thread) != 0) {
2,276!
377
    fnError("stop udfd: failed to join udfd thread");
×
378
  }
379

380
#ifdef WINDOWS
381
  if (pData->jobHandle != NULL) CloseHandle(pData->jobHandle);
382
#endif
383
  fnInfo("udfd is cleaned up");
2,276!
384
  return;
2,276✔
385
}
386

387
/*
388
int32_t udfGetUdfdPid(int32_t* pUdfdPid) {
389
  SUdfdData *pData = &udfdGlobal;
390
  if (pData->spawnErr) {
391
    return pData->spawnErr;
392
  }
393
  uv_pid_t pid = uv_process_get_pid(&pData->process);
394
  if (pUdfdPid) {
395
    *pUdfdPid = (int32_t)pid;
396
  }
397
  return TSDB_CODE_SUCCESS;
398
}
399
*/
400

401
//==============================================================================================
402
/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl>
403
 * The QUEUE is copied from queue.h under libuv
404
 * */
405

406
typedef void *QUEUE[2];
407

408
/* Private macros. */
409
#define QUEUE_NEXT(q)      (*(QUEUE **)&((*(q))[0]))
410
#define QUEUE_PREV(q)      (*(QUEUE **)&((*(q))[1]))
411
#define QUEUE_PREV_NEXT(q) (QUEUE_NEXT(QUEUE_PREV(q)))
412
#define QUEUE_NEXT_PREV(q) (QUEUE_PREV(QUEUE_NEXT(q)))
413

414
/* Public macros. */
415
#define QUEUE_DATA(ptr, type, field) ((type *)((char *)(ptr) - offsetof(type, field)))
416

417
/* Important note: mutating the list while QUEUE_FOREACH is
418
 * iterating over its elements results in undefined behavior.
419
 */
420
#define QUEUE_FOREACH(q, h) for ((q) = QUEUE_NEXT(h); (q) != (h); (q) = QUEUE_NEXT(q))
421

422
#define QUEUE_EMPTY(q) ((const QUEUE *)(q) == (const QUEUE *)QUEUE_NEXT(q))
423

424
#define QUEUE_HEAD(q) (QUEUE_NEXT(q))
425

426
#define QUEUE_INIT(q)    \
427
  do {                   \
428
    QUEUE_NEXT(q) = (q); \
429
    QUEUE_PREV(q) = (q); \
430
  } while (0)
431

432
#define QUEUE_ADD(h, n)                 \
433
  do {                                  \
434
    QUEUE_PREV_NEXT(h) = QUEUE_NEXT(n); \
435
    QUEUE_NEXT_PREV(n) = QUEUE_PREV(h); \
436
    QUEUE_PREV(h) = QUEUE_PREV(n);      \
437
    QUEUE_PREV_NEXT(h) = (h);           \
438
  } while (0)
439

440
#define QUEUE_SPLIT(h, q, n)       \
441
  do {                             \
442
    QUEUE_PREV(n) = QUEUE_PREV(h); \
443
    QUEUE_PREV_NEXT(n) = (n);      \
444
    QUEUE_NEXT(n) = (q);           \
445
    QUEUE_PREV(h) = QUEUE_PREV(q); \
446
    QUEUE_PREV_NEXT(h) = (h);      \
447
    QUEUE_PREV(q) = (n);           \
448
  } while (0)
449

450
#define QUEUE_MOVE(h, n)        \
451
  do {                          \
452
    if (QUEUE_EMPTY(h))         \
453
      QUEUE_INIT(n);            \
454
    else {                      \
455
      QUEUE *q = QUEUE_HEAD(h); \
456
      QUEUE_SPLIT(h, q, n);     \
457
    }                           \
458
  } while (0)
459

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

468
#define QUEUE_INSERT_TAIL(h, q)    \
469
  do {                             \
470
    QUEUE_NEXT(q) = (h);           \
471
    QUEUE_PREV(q) = QUEUE_PREV(h); \
472
    QUEUE_PREV_NEXT(q) = (q);      \
473
    QUEUE_PREV(h) = (q);           \
474
  } while (0)
475

476
#define QUEUE_REMOVE(q)                 \
477
  do {                                  \
478
    QUEUE_PREV_NEXT(q) = QUEUE_NEXT(q); \
479
    QUEUE_NEXT_PREV(q) = QUEUE_PREV(q); \
480
  } while (0)
481

482
enum { UV_TASK_CONNECT = 0, UV_TASK_REQ_RSP = 1, UV_TASK_DISCONNECT = 2 };
483

484
int64_t gUdfTaskSeqNum = 0;
485
typedef struct SUdfcFuncStub {
486
  char           udfName[TSDB_FUNC_NAME_LEN + 1];
487
  UdfcFuncHandle handle;
488
  int32_t        refCount;
489
  int64_t        createTime;
490
} SUdfcFuncStub;
491

492
typedef struct SUdfcProxy {
493
  char         udfdPipeName[PATH_MAX + UDF_LISTEN_PIPE_NAME_LEN + 2];
494
  uv_barrier_t initBarrier;
495

496
  uv_loop_t   uvLoop;
497
  uv_thread_t loopThread;
498
  uv_async_t  loopTaskAync;
499

500
  uv_async_t loopStopAsync;
501

502
  uv_mutex_t taskQueueMutex;
503
  int8_t     udfcState;
504
  QUEUE      taskQueue;
505
  QUEUE      uvProcTaskQueue;
506

507
  uv_mutex_t udfStubsMutex;
508
  SArray    *udfStubs;         // SUdfcFuncStub
509
  SArray    *expiredUdfStubs;  // SUdfcFuncStub
510

511
  uv_mutex_t udfcUvMutex;
512
  int8_t     initialized;
513
} SUdfcProxy;
514

515
SUdfcProxy gUdfcProxy = {0};
516

517
typedef struct SUdfcUvSession {
518
  SUdfcProxy *udfc;
519
  int64_t     severHandle;
520
  uv_pipe_t  *udfUvPipe;
521

522
  int8_t  outputType;
523
  int32_t bytes;
524
  int32_t bufSize;
525

526
  char udfName[TSDB_FUNC_NAME_LEN + 1];
527
} SUdfcUvSession;
528

529
typedef struct SClientUvTaskNode {
530
  SUdfcProxy *udfc;
531
  int8_t      type;
532
  int32_t     errCode;
533

534
  uv_pipe_t *pipe;
535

536
  int64_t  seqNum;
537
  uv_buf_t reqBuf;
538

539
  uv_sem_t taskSem;
540
  uv_buf_t rspBuf;
541

542
  QUEUE recvTaskQueue;
543
  QUEUE procTaskQueue;
544
  QUEUE connTaskQueue;
545
} SClientUvTaskNode;
546

547
typedef struct SClientUdfTask {
548
  int8_t type;
549

550
  SUdfcUvSession *session;
551

552
  union {
553
    struct {
554
      SUdfSetupRequest  req;
555
      SUdfSetupResponse rsp;
556
    } _setup;
557
    struct {
558
      SUdfCallRequest  req;
559
      SUdfCallResponse rsp;
560
    } _call;
561
    struct {
562
      SUdfTeardownRequest  req;
563
      SUdfTeardownResponse rsp;
564
    } _teardown;
565
  };
566

567
} SClientUdfTask;
568

569
typedef struct SClientConnBuf {
570
  char   *buf;
571
  int32_t len;
572
  int32_t cap;
573
  int32_t total;
574
} SClientConnBuf;
575

576
typedef struct SClientUvConn {
577
  uv_pipe_t      *pipe;
578
  QUEUE           taskQueue;
579
  SClientConnBuf  readBuf;
580
  SUdfcUvSession *session;
581
} SClientUvConn;
582

583
enum {
584
  UDFC_STATE_INITAL = 0,  // initial state
585
  UDFC_STATE_STARTNG,     // starting after udfcOpen
586
  UDFC_STATE_READY,       // started and begin to receive quests
587
  UDFC_STATE_STOPPING,    // stopping after udfcClose
588
};
589

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

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

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

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

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

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

661
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
54,312✔
662
  int32_t len = 0;
54,312✔
663
  len += taosEncodeFixedI64(buf, call->udfHandle);
54,312✔
664
  len += taosEncodeFixedI8(buf, call->callType);
54,312✔
665
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
54,312✔
666
    len += tEncodeDataBlock(buf, &call->block);
54,080✔
667
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
232✔
668
    len += taosEncodeFixedI8(buf, call->initFirst);
156✔
669
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
154✔
670
    len += tEncodeDataBlock(buf, &call->block);
92✔
671
    len += encodeUdfInterBuf(buf, &call->interBuf);
92✔
672
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
62!
673
    // len += encodeUdfInterBuf(buf, &call->interBuf);
674
    // len += encodeUdfInterBuf(buf, &call->interBuf2);
675
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
78!
676
    len += encodeUdfInterBuf(buf, &call->interBuf);
78✔
677
  }
678
  return len;
54,279✔
679
}
680

681
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
27,164✔
682
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
27,164!
683
  buf = taosDecodeFixedI8(buf, &call->callType);
27,164✔
684
  switch (call->callType) {
27,164!
685
    case TSDB_UDF_CALL_SCALA_PROC:
27,045✔
686
      buf = tDecodeDataBlock(buf, &call->block);
27,045✔
687
      break;
27,023✔
688
    case TSDB_UDF_CALL_AGG_INIT:
39✔
689
      buf = taosDecodeFixedI8(buf, &call->initFirst);
39✔
690
      break;
39✔
691
    case TSDB_UDF_CALL_AGG_PROC:
46✔
692
      buf = tDecodeDataBlock(buf, &call->block);
46✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
46✔
694
      break;
62✔
695
    // case TSDB_UDF_CALL_AGG_MERGE:
696
    //   buf = decodeUdfInterBuf(buf, &call->interBuf);
697
    //   buf = decodeUdfInterBuf(buf, &call->interBuf2);
698
    //   break;
699
    case TSDB_UDF_CALL_AGG_FIN:
39✔
700
      buf = decodeUdfInterBuf(buf, &call->interBuf);
39✔
701
      break;
39✔
702
  }
703
  return (void *)buf;
27,158✔
704
}
705

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

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

717
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
54,886✔
718
  int32_t len = 0;
54,886✔
719
  if (buf == NULL) {
54,886✔
720
    len += sizeof(request->msgLen);
27,460✔
721
  } else {
722
    *(int32_t *)(*buf) = request->msgLen;
27,426✔
723
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
27,426✔
724
  }
725
  len += taosEncodeFixedI64(buf, request->seqNum);
54,886✔
726
  len += taosEncodeFixedI8(buf, request->type);
54,886✔
727
  if (request->type == UDF_TASK_SETUP) {
54,886✔
728
    len += encodeUdfSetupRequest(buf, &request->setup);
316✔
729
  } else if (request->type == UDF_TASK_CALL) {
54,570✔
730
    len += encodeUdfCallRequest(buf, &request->call);
54,330✔
731
  } else if (request->type == UDF_TASK_TEARDOWN) {
240!
732
    len += encodeUdfTeardownRequest(buf, &request->teardown);
268✔
733
  }
734
  return len;
54,836✔
735
}
736

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

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

744
  if (request->type == UDF_TASK_SETUP) {
27,462✔
745
    buf = decodeUdfSetupRequest(buf, &request->setup);
158✔
746
  } else if (request->type == UDF_TASK_CALL) {
27,304✔
747
    buf = decodeUdfCallRequest(buf, &request->call);
27,177✔
748
  } else if (request->type == UDF_TASK_TEARDOWN) {
127!
749
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
134✔
750
  }
751
  return (void *)buf;
27,463✔
752
}
753

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

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

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

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

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

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

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

828
  len += sizeof(rsp->seqNum);
54,589✔
829
  if (buf != NULL) {
54,589✔
830
    *(int64_t *)(*buf) = rsp->seqNum;
27,415✔
831
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
27,415✔
832
  }
833

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

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

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

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

886
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
54,109✔
887
  TAOS_UDF_CHECK_PTR_RVOID(data, meta);
162,331!
888
  if (IS_VAR_DATA_TYPE(meta->type)) {
54,109!
889
    taosMemoryFree(data->varLenCol.varOffsets);
173!
890
    data->varLenCol.varOffsets = NULL;
2✔
891
    taosMemoryFree(data->varLenCol.payload);
2!
892
    data->varLenCol.payload = NULL;
2✔
893
  } else {
894
    taosMemoryFree(data->fixLenCol.nullBitmap);
53,936!
895
    data->fixLenCol.nullBitmap = NULL;
53,688✔
896
    taosMemoryFree(data->fixLenCol.data);
53,688!
897
    data->fixLenCol.data = NULL;
54,069✔
898
  }
899
}
900

901
void freeUdfColumn(SUdfColumn *col) {
54,088✔
902
  TAOS_UDF_CHECK_PTR_RVOID(col);
108,191!
903
  freeUdfColumnData(&col->colData, &col->colMeta);
54,088✔
904
}
905

906
void freeUdfDataDataBlock(SUdfDataBlock *block) {
26,698✔
907
  TAOS_UDF_CHECK_PTR_RVOID(block);
53,525!
908
  for (int32_t i = 0; i < block->numOfCols; ++i) {
53,795✔
909
    freeUdfColumn(block->udfCols[i]);
26,877✔
910
    taosMemoryFree(block->udfCols[i]);
27,064!
911
    block->udfCols[i] = NULL;
27,097✔
912
  }
913
  taosMemoryFree(block->udfCols);
26,918!
914
  block->udfCols = NULL;
27,061✔
915
}
916

917
void freeUdfInterBuf(SUdfInterBuf *buf) {
333✔
918
  TAOS_UDF_CHECK_PTR_RVOID(buf);
666!
919
  taosMemoryFree(buf->buf);
333!
920
  buf->buf = NULL;
333✔
921
}
922

923
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
26,887✔
924
  TAOS_UDF_CHECK_PTR_RCODE(block, udfBlock);
80,809!
925
  int32_t code = blockDataCheck(block);
26,887✔
926
  if (code != TSDB_CODE_SUCCESS) {
26,989!
927
    return code;
×
928
  }
929
  udfBlock->numOfRows = block->info.rows;
26,989✔
930
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
26,989✔
931
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
27,025!
932
  if ((udfBlock->udfCols) == NULL) {
27,061!
933
    return terrno;
×
934
  }
935
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
54,170✔
936
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
27,015!
937
    if (udfBlock->udfCols[i] == NULL) {
27,038!
938
      return terrno;
×
939
    }
940
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
27,038✔
941
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
27,001✔
942
    udfCol->colMeta.type = col->info.type;
27,001✔
943
    udfCol->colMeta.bytes = col->info.bytes;
27,001✔
944
    udfCol->colMeta.scale = col->info.scale;
27,001✔
945
    udfCol->colMeta.precision = col->info.precision;
27,001✔
946
    udfCol->colData.numOfRows = udfBlock->numOfRows;
27,001✔
947
    udfCol->hasNull = col->hasNull;
27,001✔
948
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
27,001!
949
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
×
950
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
×
951
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
2!
952
        return terrno;
×
953
      }
954
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
2✔
955
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
2✔
956
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
2!
957
      if (udfCol->colData.varLenCol.payload == NULL) {
2!
958
        return terrno;
×
959
      }
960
      if (col->reassigned) {
2!
961
        for (int32_t row = 0; row < udfCol->colData.numOfRows; ++row) {
×
962
          char   *pColData = col->pData + col->varmeta.offset[row];
×
963
          int32_t colSize = 0;
×
964
          if (col->info.type == TSDB_DATA_TYPE_JSON) {
×
965
            colSize = getJsonValueLen(pColData);
×
966
          } else {
967
            colSize = varDataTLen(pColData);
×
968
          }
969
          memcpy(udfCol->colData.varLenCol.payload, pColData, colSize);
×
970
          udfCol->colData.varLenCol.payload += colSize;
×
971
        }
972
      } else {
973
        memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
2✔
974
      }
975
    } else {
976
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
27,069✔
977
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
27,069✔
978
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
27,069!
979
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
27,068!
980
        return terrno;
×
981
      }
982
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
27,068✔
983
      memcpy(bitmap, col->nullbitmap, bitmapLen);
27,068✔
984
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
27,068✔
985
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
27,100✔
986
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
27,100!
987
      if (NULL == udfCol->colData.fixLenCol.data) {
27,107!
988
        return terrno;
×
989
      }
990
      char *data = udfCol->colData.fixLenCol.data;
27,107✔
991
      memcpy(data, col->pData, dataLen);
27,107✔
992
    }
993
  }
994
  return TSDB_CODE_SUCCESS;
27,155✔
995
}
996

997
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
26,675✔
998
  TAOS_UDF_CHECK_PTR_RCODE(udfCol, block);
80,290!
999
  int32_t         code = 0, lino = 0;
26,675✔
1000
  SUdfColumnMeta *meta = &udfCol->colMeta;
26,675✔
1001

1002
  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
26,675✔
1003
  code = blockDataAppendColInfo(block, &colInfoData);
26,788✔
1004
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,020!
1005

1006
  code = blockDataEnsureCapacity(block, udfCol->colData.numOfRows);
27,020✔
1007
  TAOS_CHECK_GOTO(code, &lino, _exit);
26,807!
1008

1009
  SColumnInfoData *col = NULL;
26,807✔
1010
  code = bdGetColumnInfoData(block, 0, &col);
26,807✔
1011
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,006!
1012

1013
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
5,774,050✔
1014
    if (udfColDataIsNull(udfCol, i)) {
5,720,739✔
1015
      colDataSetNULL(col, i);
34!
1016
    } else {
1017
      char *data = udfColDataGetData(udfCol, i);
5,720,705✔
1018
      code = colDataSetVal(col, i, data, false);
5,720,705✔
1019
      TAOS_CHECK_GOTO(code, &lino, _exit);
5,747,010!
1020
    }
1021
  }
1022
  block->info.rows = udfCol->colData.numOfRows;
53,311✔
1023

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

1033
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
27,058✔
1034
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
81,174!
1035
  int32_t code = 0, lino = 0;
27,058✔
1036
  int32_t numOfRows = 0;
27,058✔
1037
  for (int32_t i = 0; i < numOfCols; ++i) {
54,138✔
1038
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
27,080✔
1039
  }
1040

1041
  // create the basic block info structure
1042
  for (int32_t i = 0; i < numOfCols; ++i) {
54,135✔
1043
    SColumnInfoData *pInfo = input[i].columnData;
27,080✔
1044
    SColumnInfoData  d = {0};
27,080✔
1045
    d.info = pInfo->info;
27,080✔
1046

1047
    TAOS_CHECK_GOTO(blockDataAppendColInfo(output, &d), &lino, _exit);
27,080!
1048
  }
1049

1050
  TAOS_CHECK_GOTO(blockDataEnsureCapacity(output, numOfRows), &lino, _exit);
27,055!
1051

1052
  for (int32_t i = 0; i < numOfCols; ++i) {
54,134✔
1053
    SColumnInfoData *pDest = taosArrayGet(output->pDataBlock, i);
27,074✔
1054

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

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

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

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

1089
  output->columnData = taosMemoryMalloc(sizeof(SColumnInfoData));
27,034!
1090
  if (output->columnData == NULL) {
27,044!
1091
    return terrno;
×
1092
  }
1093
  memcpy(output->columnData, taosArrayGet(input->pDataBlock, 0), sizeof(SColumnInfoData));
27,044✔
1094
  output->colAlloced = true;
27,025✔
1095

1096
  return 0;
27,025✔
1097
}
1098

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

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

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

1141
int32_t udfcOpen();
1142
int32_t udfcClose();
1143

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

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

1153
void    cleanupNotExpiredUdfs();
1154
void    cleanupExpiredUdfs();
1155
int32_t compareUdfcFuncSub(const void *elem1, const void *elem2) {
78,689✔
1156
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
78,689✔
1157
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
78,689✔
1158
  return strcmp(stub1->udfName, stub2->udfName);
78,689✔
1159
}
1160

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

1216
_exit:
158✔
1217
  return code;
158✔
1218
}
1219

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

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

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

1303
int32_t cleanUpUdfs() {
2,914,341✔
1304
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
2,914,341✔
1305
  if (!initialized) {
2,914,631✔
1306
    return TSDB_CODE_SUCCESS;
73,580✔
1307
  }
1308

1309
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
2,841,051✔
1310
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
2,842,182!
1311
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
2,833,697!
1312
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
2,833,697✔
1313
    return TSDB_CODE_SUCCESS;
2,833,692✔
1314
  }
1315

1316
  cleanupNotExpiredUdfs();
8,485✔
1317
  cleanupExpiredUdfs();
8,485✔
1318

1319
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
8,485✔
1320
  return 0;
8,485✔
1321
}
1322

1323
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
27,007✔
1324
  TAOS_UDF_CHECK_PTR_RCODE(udfName, input, output);
108,062!
1325
  UdfcFuncHandle handle = NULL;
27,007✔
1326
  int32_t        code = acquireUdfFuncHandle(udfName, &handle);
27,007✔
1327
  if (code != 0) {
27,058!
1328
    return code;
×
1329
  }
1330

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

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

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

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

1384
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
39✔
1385
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
39✔
1386

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

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

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

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

1428
  if (code) {
46!
1429
    return code;
×
1430
  }
1431

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

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

1448
  SUdfInterBuf state = {
46✔
1449
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
46✔
1450
  SUdfInterBuf newState = {0};
46✔
1451

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

1467
  GET_RES_INFO(pCtx)->numOfRes = udfRes->interResNum;
46✔
1468

1469
  blockDataDestroy(inputBlock);
46✔
1470

1471
  taosArrayDestroy(pTempBlock->pDataBlock);
46✔
1472
  taosMemoryFree(pTempBlock);
46!
1473

1474
  releaseUdfFuncHandle(pCtx->udfName, handle);
46✔
1475
  freeUdfInterBuf(&newState);
46✔
1476
  return udfCode;
46✔
1477
}
1478

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

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

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

1518
  freeUdfInterBuf(&resultBuf);
39✔
1519

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

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

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

1556
      switch (task->type) {
27,441!
1557
        case UDF_TASK_SETUP: {
158✔
1558
          task->_setup.rsp = rsp.setupRsp;
158✔
1559
          break;
158✔
1560
        }
1561
        case UDF_TASK_CALL: {
27,149✔
1562
          task->_call.rsp = rsp.callRsp;
27,149✔
1563
          break;
27,149✔
1564
        }
1565
        case UDF_TASK_TEARDOWN: {
134✔
1566
          task->_teardown.rsp = rsp.teardownRsp;
1567
          break;
134✔
1568
        }
1569
        default: {
×
1570
          break;
×
1571
        }
1572
      }
1573

1574
      // TODO: the call buffer is setup and freed by udf invocation
1575
      taosMemoryFreeClear(uvTask->rspBuf.base);
27,441!
1576
    } else {
1577
      code = uvTask->errCode;
×
1578
      if (code != 0) {
×
1579
        fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1580
      }
1581
    }
1582
  } else if (uvTask->type == UV_TASK_CONNECT) {
292✔
1583
    code = uvTask->errCode;
158✔
1584
    if (code != 0) {
158!
1585
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1586
    }
1587
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
134!
1588
    code = uvTask->errCode;
134✔
1589
    if (code != 0) {
134!
1590
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1591
    }
1592
  }
1593
  return code;
27,732✔
1594
}
1595

1596
void udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
75,216✔
1597
  SClientUvConn  *conn = handle->data;
75,216✔
1598
  SClientConnBuf *connBuf = &conn->readBuf;
75,216✔
1599

1600
  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
75,216✔
1601
  if (connBuf->cap == 0) {
75,216✔
1602
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
27,632!
1603
    if (connBuf->buf) {
27,632!
1604
      connBuf->len = 0;
27,632✔
1605
      connBuf->cap = msgHeadSize;
27,632✔
1606
      connBuf->total = -1;
27,632✔
1607

1608
      buf->base = connBuf->buf;
27,632✔
1609
      buf->len = connBuf->cap;
27,632✔
1610
    } else {
1611
      fnError("udfc allocate buffer failure. size: %d", msgHeadSize);
×
1612
      buf->base = NULL;
×
1613
      buf->len = 0;
×
1614
    }
1615
  } else if (connBuf->total == -1 && connBuf->len < msgHeadSize) {
47,584!
1616
    buf->base = connBuf->buf + connBuf->len;
20,110✔
1617
    buf->len = msgHeadSize - connBuf->len;
20,110✔
1618
  } else {
1619
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
27,474✔
1620
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
27,474!
1621
    if (resultBuf) {
27,474!
1622
      connBuf->buf = resultBuf;
27,474✔
1623
      buf->base = connBuf->buf + connBuf->len;
27,474✔
1624
      buf->len = connBuf->cap - connBuf->len;
27,474✔
1625
    } else {
1626
      fnError("udfc re-allocate buffer failure. size: %d", connBuf->cap);
×
1627
      buf->base = NULL;
×
1628
      buf->len = 0;
×
1629
    }
1630
  }
1631

1632
  fnDebug("udfc uv alloc buffer: cap - len - total : %d - %d - %d", connBuf->cap, connBuf->len, connBuf->total);
75,216✔
1633
}
75,216✔
1634

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

1646
void udfcUvHandleRsp(SClientUvConn *conn) {
27,474✔
1647
  SClientConnBuf *connBuf = &conn->readBuf;
27,474✔
1648
  int64_t         seqNum = *(int64_t *)(connBuf->buf + sizeof(int32_t));  // msglen then seqnum
27,474✔
1649

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

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

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

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

1703
void onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
75,216✔
1704
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
75,216✔
1705
  if (nread == 0) return;
75,216✔
1706

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

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

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

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

1752
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask) {
27,747✔
1753
  uvTask->type = uvTaskType;
27,747✔
1754
  uvTask->udfc = task->session->udfc;
27,747✔
1755

1756
  if (uvTaskType == UV_TASK_CONNECT) {
27,747✔
1757
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
27,598✔
1758
    uvTask->pipe = task->session->udfUvPipe;
27,467✔
1759
    SUdfRequest request;
1760
    request.type = task->type;
27,467✔
1761
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
27,467✔
1762

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

1793
    uvTask->reqBuf = uv_buf_init(bufBegin, bufLen);
27,449✔
1794
    uvTask->seqNum = request.seqNum;
27,421✔
1795
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
131!
1796
    uvTask->pipe = task->session->udfUvPipe;
134✔
1797
  }
1798
  if (uv_sem_init(&uvTask->taskSem, 0) != 0) {
27,701✔
1799
    if (uvTaskType == UV_TASK_REQ_RSP) {
5!
1800
      taosMemoryFreeClear(uvTask->reqBuf.base);
×
1801
    }
1802
    fnError("udfc create uv task, init semaphore failed.");
5!
1803
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1804
  }
1805

1806
  return 0;
27,710✔
1807
}
1808

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

1821
  uv_sem_wait(&uvTask->taskSem);
27,742✔
1822
  fnDebug("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
27,681✔
1823
  uv_sem_destroy(&uvTask->taskSem);
27,681✔
1824

1825
  return 0;
27,678✔
1826
}
1827

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

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

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

1859
      pipe->data = conn;
158✔
1860

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

1914
  return code;
27,766✔
1915
}
1916

1917
void udfcAsyncTaskCb(uv_async_t *async) {
24,142✔
1918
  SUdfcProxy *udfc = async->data;
24,142✔
1919
  QUEUE       wq;
1920

1921
  uv_mutex_lock(&udfc->taskQueueMutex);
24,142✔
1922
  QUEUE_MOVE(&udfc->taskQueue, &wq);
24,142✔
1923
  uv_mutex_unlock(&udfc->taskQueueMutex);
24,142✔
1924

1925
  while (!QUEUE_EMPTY(&wq)) {
51,908✔
1926
    QUEUE *h = QUEUE_HEAD(&wq);
27,766✔
1927
    QUEUE_REMOVE(h);
27,766✔
1928
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
27,766✔
1929
    int32_t            code = udfcStartUvTask(task);
27,766✔
1930
    if (code == 0) {
27,766!
1931
      QUEUE_INSERT_TAIL(&udfc->uvProcTaskQueue, &task->procTaskQueue);
27,766✔
1932
    } else {
1933
      task->errCode = code;
×
1934
      uv_sem_post(&task->taskSem);
×
1935
    }
1936
  }
1937
}
24,142✔
1938

1939
void cleanUpUvTasks(SUdfcProxy *udfc) {
2,252✔
1940
  fnDebug("clean up uv tasks") QUEUE wq;
2,252✔
1941

1942
  uv_mutex_lock(&udfc->taskQueueMutex);
2,252✔
1943
  QUEUE_MOVE(&udfc->taskQueue, &wq);
2,252!
1944
  uv_mutex_unlock(&udfc->taskQueueMutex);
2,252✔
1945

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

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

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

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

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

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

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

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

2050
int32_t udfcClose() {
2,284✔
2051
  int8_t old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 1, 0);
2,284✔
2052
  if (old == 0) {
2,284✔
2053
    return 0;
32✔
2054
  }
2055

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

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

2084
  code = udfcInitializeUvTask(task, uvTaskType, uvTask);
27,763✔
2085
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,716!
2086
  code = udfcQueueUvTask(uvTask);
27,716✔
2087
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,676!
2088
  code = udfcGetUdfTaskResultFromUvTask(task, uvTask);
27,676✔
2089
  TAOS_CHECK_GOTO(code, &lino, _exit);
27,748!
2090
  if (uvTaskType == UV_TASK_CONNECT) {
27,748✔
2091
    task->session->udfUvPipe = uvTask->pipe;
158✔
2092
    SClientUvConn *conn = uvTask->pipe->data;
158✔
2093
    conn->session = task->session;
158✔
2094
  }
2095

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

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

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

2133
  SUdfSetupRequest *req = &task->_setup.req;
158✔
2134
  tstrncpy(req->udfName, udfName, TSDB_FUNC_NAME_LEN);
158✔
2135

2136
  code = udfcRunUdfUvTask(task, UV_TASK_CONNECT);
158✔
2137
  TAOS_CHECK_GOTO(code, &lino, _exit);
158!
2138

2139
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
158✔
2140
  TAOS_CHECK_GOTO(code, &lino, _exit);
158!
2141

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

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

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

2178
  SUdfCallRequest *req = &task->_call.req;
27,176✔
2179
  req->udfHandle = task->session->severHandle;
27,176✔
2180
  req->callType = callType;
27,176✔
2181

2182
  switch (callType) {
27,176✔
2183
    case TSDB_UDF_CALL_AGG_INIT: {
39✔
2184
      req->initFirst = 1;
39✔
2185
      break;
39✔
2186
    }
2187
    case TSDB_UDF_CALL_AGG_PROC: {
46✔
2188
      req->block = *input;
46✔
2189
      req->interBuf = *state;
46✔
2190
      break;
46✔
2191
    }
2192
    // case TSDB_UDF_CALL_AGG_MERGE: {
2193
    //   req->interBuf = *state;
2194
    //   req->interBuf2 = *state2;
2195
    //   break;
2196
    // }
2197
    case TSDB_UDF_CALL_AGG_FIN: {
39✔
2198
      req->interBuf = *state;
39✔
2199
      break;
39✔
2200
    }
2201
    case TSDB_UDF_CALL_SCALA_PROC: {
27,044✔
2202
      req->block = *input;
27,044✔
2203
      break;
27,044✔
2204
    }
2205
  }
2206

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

2239
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf) {
39✔
2240
  int8_t callType = TSDB_UDF_CALL_AGG_INIT;
39✔
2241

2242
  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);
39✔
2243

2244
  return err;
39✔
2245
}
2246

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

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

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

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

2288
  blockDataFreeRes(&inputBlock);
27,039✔
2289
  return err;
27,022✔
2290
}
2291

2292
int32_t doTeardownUdf(UdfcFuncHandle handle) {
134✔
2293
  int32_t         code = TSDB_CODE_SUCCESS, lino = 0;
134✔
2294
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
134✔
2295

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

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

2311
  SUdfTeardownRequest *req = &task->_teardown.req;
134✔
2312
  req->udfHandle = task->session->severHandle;
134✔
2313

2314
  code = udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
134✔
2315
  TAOS_CHECK_GOTO(code, &lino, _exit);
134!
2316

2317
  code = udfcRunUdfUvTask(task, UV_TASK_DISCONNECT);
134✔
2318
  TAOS_CHECK_GOTO(code, &lino, _exit);
134!
2319

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

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

2336
  return code;
134✔
2337
}
2338
#else
2339
#include "tudf.h"
2340

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

© 2026 Coveralls, Inc