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

taosdata / TDengine / #5060

17 May 2026 01:15AM UTC coverage: 73.425% (-0.02%) from 73.443%
#5060

push

travis-ci

web-flow
feat (TDgpt): Dynamic Model Synchronization Enhancements (#35344)

* refactor: do some internal refactor.

* fix: fix multiprocess sync issue.

* feat: add dynamic anomaly detection and forecasting services

* fix: log error message for undeploying model in exception handling

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* fix: handle undeploy when model exists only on disk

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/286aafa0-c3ce-4c27-b803-2707571e9dc1

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: guard dynamic registry concurrent access

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/5e4db858-6458-40f4-ac28-d1b1b7f97c18

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: tighten service list locking scope

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/5e4db858-6458-40f4-ac28-d1b1b7f97c18

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: restore prophet support and update tests per review feedback

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/92298ae1-7da6-4d07-b20e-101c7cd0b26b

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: improve test name and move copy inside lock scope

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/92298ae1-7da6-4d07-b20e-101c7cd0b26b

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* Potential fix for pull request finding

Co-au... (continued)

281800 of 383795 relevant lines covered (73.42%)

134332207.97 hits per line

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

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

18
#include "os.h"
19

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

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

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

49
  int32_t dnodeId;
50
} SUdfdData;
51

52
SUdfdData udfdGlobal = {0};
53

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

57
extern char **environ;
58

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

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

84
static int32_t udfSpawnUdfd(SUdfdData *pData) {
740,311✔
85
  fnInfo("start to init udfd");
740,311✔
86
  TAOS_UDF_CHECK_PTR_RCODE(pData);
1,480,622✔
87

88
  int32_t              err = 0;
740,311✔
89
  uv_process_options_t options = {0};
740,311✔
90

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

122
  options.exit_cb = udfUdfdExit;
740,311✔
123

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

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

135
  options.flags = UV_PROCESS_DETACHED;
740,311✔
136

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

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

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

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

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

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

188
  char **envUdfdWithPEnv = NULL;
740,311✔
189
  if (environ != NULL) {
740,311✔
190
    int32_t lenEnvUdfd = ARRAY_SIZE(envUdfd);
740,311✔
191
    int32_t numEnviron = 0;
740,311✔
192
    while (environ[numEnviron] != NULL) {
22,390,787✔
193
      numEnviron++;
21,650,476✔
194
    }
195

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

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

210
      tstrncpy(envUdfdWithPEnv[i], environ[i], len);
21,650,476✔
211
    }
212

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

222
        tstrncpy(envUdfdWithPEnv[numEnviron + i], envUdfd[i], len);
2,220,933✔
223
      }
224
    }
225
    envUdfdWithPEnv[numEnviron + lenEnvUdfd - 1] = NULL;
740,311✔
226

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

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

260
_OVER:
738,427✔
261
  if (taosFqdnEnvItem) {
740,311✔
262
    taosMemoryFree(taosFqdnEnvItem);
×
263
  }
264

265
  if (envUdfdWithPEnv != NULL) {
740,311✔
266
    int32_t i = 0;
740,311✔
267
    while (envUdfdWithPEnv[i] != NULL) {
24,611,720✔
268
      taosMemoryFree(envUdfdWithPEnv[i]);
23,871,409✔
269
      i++;
23,871,409✔
270
    }
271
    taosMemoryFree(envUdfdWithPEnv);
740,311✔
272
  }
273

274
  return err;
740,311✔
275
}
276

277
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
3,687,403✔
278
  TAOS_UDF_CHECK_PTR_RVOID(handle);
7,374,806✔
279
  if (!uv_is_closing(handle)) {
3,687,403✔
280
    uv_close(handle, NULL);
3,687,403✔
281
  }
282
}
283

284
static void udfUdfdStopAsyncCb(uv_async_t *async) {
738,711✔
285
  TAOS_UDF_CHECK_PTR_RVOID(async);
1,477,422✔
286
  SUdfdData *pData = async->data;
738,711✔
287
  uv_stop(&pData->loop);
738,711✔
288
}
289

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

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

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

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

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

364
void udfStopUdfd() {
740,096✔
365
  SUdfdData *pData = &udfdGlobal;
740,096✔
366
  fnInfo("udfd start to stop, need cleanup:%d, spawn err:%d", pData->needCleanUp, pData->spawnErr);
740,096✔
367
  if (!pData->needCleanUp || atomic_load_32(&pData->stopCalled)) {
740,096✔
368
    return;
1,385✔
369
  }
370
  atomic_store_32(&pData->stopCalled, 1);
738,711✔
371
  pData->needCleanUp = false;
738,711✔
372
  uv_barrier_destroy(&pData->barrier);
738,711✔
373
  if (uv_async_send(&pData->stopAsync) != 0) {
738,711✔
374
    fnError("stop udfd: failed to send stop async");
×
375
  }
376
  if (uv_thread_join(&pData->thread) != 0) {
738,711✔
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");
738,711✔
384
  return;
738,711✔
385
}
386

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

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

406
typedef void *QUEUE[2];
407

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

500
  uv_async_t loopStopAsync;
501

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

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

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

515
SUdfcProxy gUdfcProxy = {0};
516

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

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

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

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

534
  uv_pipe_t *pipe;
535

536
  int64_t  seqNum;
537
  uv_buf_t reqBuf;
538

539
  uv_sem_t taskSem;
540
  uv_buf_t rspBuf;
541

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

547
typedef struct SClientUdfTask {
548
  int8_t type;
549

550
  SUdfcUvSession *session;
551

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

567
} SClientUdfTask;
568

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

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

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

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

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

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

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

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

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

661
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
1,237,978✔
662
  int32_t len = 0;
1,237,978✔
663
  len += taosEncodeFixedI64(buf, call->udfHandle);
1,237,978✔
664
  len += taosEncodeFixedI8(buf, call->callType);
1,237,978✔
665
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
1,237,978✔
666
    len += tEncodeDataBlock(buf, &call->block);
206,680✔
667
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
1,031,298✔
668
    len += taosEncodeFixedI8(buf, call->initFirst);
493,820✔
669
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
784,388✔
670
    len += tEncodeDataBlock(buf, &call->block);
537,478✔
671
    len += encodeUdfInterBuf(buf, &call->interBuf);
537,478✔
672
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
246,910✔
673
    // len += encodeUdfInterBuf(buf, &call->interBuf);
674
    // len += encodeUdfInterBuf(buf, &call->interBuf2);
675
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
246,910✔
676
    len += encodeUdfInterBuf(buf, &call->interBuf);
246,910✔
677
  }
678
  return len;
1,237,978✔
679
}
680

681
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
1,241,903✔
682
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
1,241,903✔
683
  buf = taosDecodeFixedI8(buf, &call->callType);
1,241,903✔
684
  switch (call->callType) {
1,241,903✔
685
    case TSDB_UDF_CALL_SCALA_PROC:
518,750✔
686
      buf = tDecodeDataBlock(buf, &call->block);
518,750✔
687
      break;
518,444✔
688
    case TSDB_UDF_CALL_AGG_INIT:
164,639✔
689
      buf = taosDecodeFixedI8(buf, &call->initFirst);
164,639✔
690
      break;
164,639✔
691
    case TSDB_UDF_CALL_AGG_PROC:
395,129✔
692
      buf = tDecodeDataBlock(buf, &call->block);
395,129✔
693
      buf = decodeUdfInterBuf(buf, &call->interBuf);
395,129✔
694
      break;
395,189✔
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:
163,385✔
700
      buf = decodeUdfInterBuf(buf, &call->interBuf);
163,385✔
701
      break;
163,385✔
702
  }
703
  return (void *)buf;
1,241,657✔
704
}
705

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

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

717
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
1,611,382✔
718
  int32_t len = 0;
1,611,382✔
719
  if (buf == NULL) {
1,611,382✔
720
    len += sizeof(request->msgLen);
805,691✔
721
  } else {
722
    *(int32_t *)(*buf) = request->msgLen;
805,691✔
723
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
805,691✔
724
  }
725
  len += taosEncodeFixedI64(buf, request->seqNum);
1,611,382✔
726
  len += taosEncodeFixedI8(buf, request->type);
1,611,382✔
727
  if (request->type == UDF_TASK_SETUP) {
1,611,382✔
728
    len += encodeUdfSetupRequest(buf, &request->setup);
186,702✔
729
  } else if (request->type == UDF_TASK_CALL) {
1,424,680✔
730
    len += encodeUdfCallRequest(buf, &request->call);
1,237,978✔
731
  } else if (request->type == UDF_TASK_TEARDOWN) {
186,702✔
732
    len += encodeUdfTeardownRequest(buf, &request->teardown);
186,702✔
733
  }
734
  return len;
1,611,382✔
735
}
736

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

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

744
  if (request->type == UDF_TASK_SETUP) {
1,586,771✔
745
    buf = decodeUdfSetupRequest(buf, &request->setup);
172,995✔
746
  } else if (request->type == UDF_TASK_CALL) {
1,413,776✔
747
    buf = decodeUdfCallRequest(buf, &request->call);
1,241,903✔
748
  } else if (request->type == UDF_TASK_TEARDOWN) {
171,873✔
749
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
171,873✔
750
  }
751
  return (void *)buf;
1,586,591✔
752
}
753

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

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

771
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp) {
2,483,320✔
772
  int32_t len = 0;
2,483,320✔
773
  len += taosEncodeFixedI8(buf, callRsp->callType);
2,483,320✔
774
  switch (callRsp->callType) {
2,483,320✔
775
    case TSDB_UDF_CALL_SCALA_PROC:
1,036,840✔
776
      len += tEncodeDataBlock(buf, &callRsp->resultData);
1,036,840✔
777
      break;
1,036,294✔
778
    case TSDB_UDF_CALL_AGG_INIT:
329,278✔
779
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
329,278✔
780
      break;
329,278✔
781
    case TSDB_UDF_CALL_AGG_PROC:
790,258✔
782
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
790,258✔
783
      break;
790,258✔
784
    // case TSDB_UDF_CALL_AGG_MERGE:
785
    //   len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
786
    //   break;
787
    case TSDB_UDF_CALL_AGG_FIN:
326,770✔
788
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
326,770✔
789
      break;
326,770✔
790
  }
791
  return len;
2,482,774✔
792
}
793

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

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

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

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

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

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

838
  switch (rsp->type) {
3,172,882✔
839
    case UDF_TASK_SETUP:
345,990✔
840
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
345,990✔
841
      break;
345,990✔
842
    case UDF_TASK_CALL:
2,483,326✔
843
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
2,483,326✔
844
      break;
2,482,300✔
845
    case UDF_TASK_TEARDOWN:
343,746✔
846
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
343,746✔
847
      break;
343,746✔
848
    default:
×
849
      fnError("encode udf response, invalid udf response type %d", rsp->type);
×
850
      break;
×
851
  }
852
  return len;
3,172,036✔
853
}
854

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

864
  switch (rsp->type) {
805,691✔
865
    case UDF_TASK_SETUP:
93,351✔
866
      buf = decodeUdfSetupResponse(buf, &rsp->setupRsp);
93,351✔
867
      break;
93,351✔
868
    case UDF_TASK_CALL:
618,989✔
869
      if (rsp->code) {
618,989✔
870
        fnError("udf response failed, code:0x%x", rsp->code);
×
871

872
        return NULL;
×
873
      }
874

875
      buf = decodeUdfCallResponse(buf, &rsp->callRsp);
618,989✔
876
      break;
618,989✔
877
    case UDF_TASK_TEARDOWN:
93,351✔
878
      buf = decodeUdfTeardownResponse(buf, &rsp->teardownRsp);
93,351✔
879
      break;
93,351✔
880
    default:
×
881
      rsp->code = TSDB_CODE_UDF_INTERNAL_ERROR;
×
882
      fnError("decode udf response, invalid udf response type %d", rsp->type);
×
883
      break;
×
884
  }
885
  if (buf == NULL) {
805,691✔
886
    rsp->code = terrno;
×
887
    fnError("decode udf response failed, code:0x%x", rsp->code);
×
888
  }
889
  return (void *)buf;
805,691✔
890
}
891

892
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
1,498,279✔
893
  TAOS_UDF_CHECK_PTR_RVOID(data, meta);
4,494,957✔
894
  if (IS_VAR_DATA_TYPE(meta->type)) {
1,498,279✔
895
    taosMemoryFree(data->varLenCol.varOffsets);
17,510✔
896
    data->varLenCol.varOffsets = NULL;
17,510✔
897
    taosMemoryFree(data->varLenCol.payload);
17,510✔
898
    data->varLenCol.payload = NULL;
17,510✔
899
  } else {
900
    taosMemoryFree(data->fixLenCol.nullBitmap);
1,480,769✔
901
    data->fixLenCol.nullBitmap = NULL;
1,480,889✔
902
    taosMemoryFree(data->fixLenCol.data);
1,480,889✔
903
    data->fixLenCol.data = NULL;
1,480,949✔
904
  }
905
}
906

907
void freeUdfColumn(SUdfColumn *col) {
1,498,159✔
908
  TAOS_UDF_CHECK_PTR_RVOID(col);
2,996,378✔
909
  freeUdfColumnData(&col->colData, &col->colMeta);
1,498,159✔
910
}
911

912
void freeUdfDataDataBlock(SUdfDataBlock *block) {
913,699✔
913
  TAOS_UDF_CHECK_PTR_RVOID(block);
1,827,398✔
914
  for (int32_t i = 0; i < block->numOfCols; ++i) {
1,893,528✔
915
    freeUdfColumn(block->udfCols[i]);
979,769✔
916
    taosMemoryFree(block->udfCols[i]);
979,889✔
917
    block->udfCols[i] = NULL;
979,829✔
918
  }
919
  taosMemoryFree(block->udfCols);
913,759✔
920
  block->udfCols = NULL;
913,819✔
921
}
922

923
void freeUdfInterBuf(SUdfInterBuf *buf) {
1,797,316✔
924
  TAOS_UDF_CHECK_PTR_RVOID(buf);
3,594,632✔
925
  taosMemoryFree(buf->buf);
1,797,316✔
926
  buf->buf = NULL;
1,797,316✔
927
}
928

929
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
913,693✔
930
  TAOS_UDF_CHECK_PTR_RCODE(block, udfBlock);
2,740,653✔
931
  int32_t code = blockDataCheck(block);
913,693✔
932
  if (code != TSDB_CODE_SUCCESS) {
913,459✔
933
    return code;
×
934
  }
935
  udfBlock->numOfRows = block->info.rows;
913,459✔
936
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
913,459✔
937
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
913,579✔
938
  if ((udfBlock->udfCols) == NULL) {
913,819✔
939
    return terrno;
×
940
  }
941
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
1,893,642✔
942
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
979,703✔
943
    if (udfBlock->udfCols[i] == NULL) {
979,763✔
944
      return terrno;
×
945
    }
946
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
979,763✔
947
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
979,589✔
948
    udfCol->colMeta.type = col->info.type;
979,589✔
949
    udfCol->colMeta.bytes = col->info.bytes;
979,589✔
950
    udfCol->colMeta.scale = col->info.scale;
979,589✔
951
    udfCol->colMeta.precision = col->info.precision;
979,589✔
952
    udfCol->colData.numOfRows = udfBlock->numOfRows;
979,589✔
953
    udfCol->hasNull = col->hasNull;
979,589✔
954
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
979,589✔
955
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
10,922✔
956
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
10,922✔
957
      if (udfCol->colData.varLenCol.varOffsets == NULL) {
10,910✔
958
        return terrno;
×
959
      }
960
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
10,910✔
961
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
10,910✔
962
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
10,910✔
963
      if (udfCol->colData.varLenCol.payload == NULL) {
10,910✔
964
        return terrno;
×
965
      }
966
      if (col->reassigned) {
10,910✔
967
        for (int32_t row = 0; row < udfCol->colData.numOfRows; ++row) {
×
968
          char   *pColData = col->pData + col->varmeta.offset[row];
×
969
          int32_t colSize = 0;
×
970
          if (col->info.type == TSDB_DATA_TYPE_JSON) {
×
971
            colSize = getJsonValueLen(pColData);
×
972
          } else if (IS_STR_DATA_BLOB(col->info.type)) {
×
973
            colSize = blobDataTLen(pColData);
×
974
          } else {
975
            colSize = varDataTLen(pColData);
×
976
          }
977
          memcpy(udfCol->colData.varLenCol.payload, pColData, colSize);
×
978
          udfCol->colData.varLenCol.payload += colSize;
×
979
        }
980
      } else {
981
        memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
10,910✔
982
      }
983
    } else {
984
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
968,667✔
985
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
968,667✔
986
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
968,667✔
987
      if (udfCol->colData.fixLenCol.nullBitmap == NULL) {
968,913✔
988
        return terrno;
×
989
      }
990
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
968,913✔
991
      memcpy(bitmap, col->nullbitmap, bitmapLen);
968,913✔
992
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
968,913✔
993
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
968,733✔
994
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
968,733✔
995
      if (NULL == udfCol->colData.fixLenCol.data) {
968,913✔
996
        return terrno;
×
997
      }
998
      char *data = udfCol->colData.fixLenCol.data;
968,913✔
999
      memcpy(data, col->pData, dataLen);
968,913✔
1000
    }
1001
  }
1002
  return TSDB_CODE_SUCCESS;
913,939✔
1003
}
1004

1005
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
517,334✔
1006
  TAOS_UDF_CHECK_PTR_RCODE(udfCol, block);
1,552,182✔
1007
  int32_t         code = 0, lino = 0;
517,334✔
1008
  SUdfColumnMeta *meta = &udfCol->colMeta;
517,334✔
1009

1010
  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
517,334✔
1011
  code = blockDataAppendColInfo(block, &colInfoData);
517,274✔
1012
  TAOS_CHECK_GOTO(code, &lino, _exit);
517,514✔
1013

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

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

1021
  for (int32_t i = 0; i < udfCol->colData.numOfRows; ++i) {
446,183,920✔
1022
    if (udfColDataIsNull(udfCol, i)) {
447,142,052✔
1023
      colDataSetNULL(col, i);
46,338,824✔
1024
    } else {
1025
      char *data = udfColDataGetData(udfCol, i);
400,803,228✔
1026
      code = colDataSetVal(col, i, data, false);
400,803,228✔
1027
      TAOS_CHECK_GOTO(code, &lino, _exit);
399,328,062✔
1028
    }
1029
  }
1030
  block->info.rows = udfCol->colData.numOfRows;
108,368✔
1031

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

1041
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
103,340✔
1042
  TAOS_UDF_CHECK_PTR_RCODE(input, output);
310,020✔
1043
  int32_t code = 0, lino = 0;
103,340✔
1044
  int32_t numOfRows = 0;
103,340✔
1045
  for (int32_t i = 0; i < numOfCols; ++i) {
210,536✔
1046
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
107,196✔
1047
  }
1048

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

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

1058
  TAOS_CHECK_GOTO(blockDataEnsureCapacity(output, numOfRows), &lino, _exit);
103,340✔
1059

1060
  for (int32_t i = 0; i < numOfCols; ++i) {
210,536✔
1061
    SColumnInfoData *pDest = taosArrayGet(output->pDataBlock, i);
107,196✔
1062

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

1066
    if (input[i].numOfRows < numOfRows) {
107,196✔
1067
      int32_t startRow = input[i].numOfRows;
×
1068
      int32_t expandRows = numOfRows - startRow;
×
1069
      bool    isNull = colDataIsNull_s(pColInfoData, (input + i)->numOfRows - 1);
×
1070
      if (isNull) {
×
1071
        colDataSetNNULL(pDest, startRow, expandRows);
×
1072
      } else {
1073
        char *src = colDataGetData(pColInfoData, (input + i)->numOfRows - 1);
×
1074
        for (int32_t j = 0; j < expandRows; ++j) {
×
1075
          TAOS_CHECK_GOTO(colDataSetVal(pDest, startRow + j, src, false), &lino, _exit);
×
1076
        }
1077
      }
1078
    }
1079
  }
1080

1081
  output->info.rows = numOfRows;
103,340✔
1082
_exit:
103,340✔
1083
  if (code != 0) {
103,340✔
1084
    fnError("failed to convert scalar param to data block, code:%d, line:%d", code, lino);
×
1085
  }
1086
  return code;
103,340✔
1087
}
1088

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

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

1104
  return 0;
103,340✔
1105
}
1106

1107
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
1108
// memory layout |---SUdfAggRes----|-----final result-----|---inter result----|
1109
typedef struct SUdfAggRes {
1110
  int8_t  finalResNum;
1111
  int8_t  interResNum;
1112
  int32_t interResBufLen;
1113
  char   *finalResBuf;
1114
  char   *interResBuf;
1115
} SUdfAggRes;
1116

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

1138
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
1139
                SSDataBlock *output, SUdfInterBuf *newState);
1140
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf);
1141
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState);
1142
// udf todo:  aggmerge
1143
// int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
1144
//                           SUdfInterBuf *resultBuf);
1145
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData);
1146
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1147
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
1148

1149
int32_t udfcOpen();
1150
int32_t udfcClose();
1151

1152
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle);
1153
void    releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle);
1154
int32_t cleanUpUdfs();
1155

1156
bool    udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv);
1157
int32_t udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo);
1158
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx);
1159
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock);
1160

1161
void    cleanupNotExpiredUdfs();
1162
void    cleanupExpiredUdfs();
1163
int32_t compareUdfcFuncSub(const void *elem1, const void *elem2) {
1,685,431✔
1164
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
1,685,431✔
1165
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
1,685,431✔
1166
  return strcmp(stub1->udfName, stub2->udfName);
1,685,431✔
1167
}
1168

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

1223
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
93,351✔
1224

1225
_exit:
93,351✔
1226
  return code;
93,351✔
1227
}
1228

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

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

1281
void cleanupNotExpiredUdfs() {
82,354✔
1282
  SArray *udfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
82,354✔
1283
  if (udfStubs == NULL) {
82,354✔
1284
    fnError("cleanupNotExpiredUdfs: failed to init array");
×
1285
    return;
×
1286
  }
1287
  int32_t i = 0;
82,354✔
1288
  while (i < taosArrayGetSize(gUdfcProxy.udfStubs)) {
189,290✔
1289
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.udfStubs, i);
106,936✔
1290
    if (stub->refCount == 0) {
106,936✔
1291
      fnInfo("tear down udf. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle, stub->refCount);
93,351✔
1292
      (void)doTeardownUdf(stub->handle);
93,351✔
1293
    } else {
1294
      fnInfo("udf still in use. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p", stub->udfName,
13,585✔
1295
             stub->refCount, stub->createTime, stub->handle);
1296
      UdfcFuncHandle handle = stub->handle;
13,585✔
1297
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
13,585✔
1298
        if (taosArrayPush(udfStubs, stub) == NULL) {
13,585✔
1299
          fnError("cleanupNotExpiredUdfs: failed to push udf stub to array");
×
1300
        }
1301
      } else {
1302
        fnInfo("udf invalid handle for %s, refCount: %d, create time: %" PRId64 ". remove it from cache", stub->udfName,
×
1303
               stub->refCount, stub->createTime);
1304
      }
1305
    }
1306
    ++i;
106,936✔
1307
  }
1308
  taosArrayDestroy(gUdfcProxy.udfStubs);
82,354✔
1309
  gUdfcProxy.udfStubs = udfStubs;
82,354✔
1310
}
1311

1312
int32_t cleanUpUdfs() {
658,414,098✔
1313
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
658,414,098✔
1314
  if (!initialized) {
658,360,896✔
1315
    return TSDB_CODE_SUCCESS;
25,791✔
1316
  }
1317

1318
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
658,335,105✔
1319
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
658,443,851✔
1320
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
658,361,497✔
1321
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
658,361,497✔
1322
    return TSDB_CODE_SUCCESS;
658,361,497✔
1323
  }
1324

1325
  cleanupNotExpiredUdfs();
82,354✔
1326
  cleanupExpiredUdfs();
82,354✔
1327

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

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

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

1348
  if (output->columnData == NULL) {
103,340✔
1349
    fnError("udfc scalar function calculate error. no column data");
×
1350
    code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1351
  } else {
1352
    if (session->outputType != output->columnData->info.type || session->bytes != output->columnData->info.bytes) {
103,340✔
1353
      fnError("udfc scalar function calculate error. type mismatch. session type: %d(%d), output type: %d(%d)",
×
1354
              session->outputType, session->bytes, output->columnData->info.type, output->columnData->info.bytes);
1355
      code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1356
    }
1357
  }
1358
  releaseUdfFuncHandle(udfName, handle);
103,340✔
1359
  return code;
103,340✔
1360
}
1361

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

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

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

1396
  SUdfInterBuf buf = {0};
123,455✔
1397
  if ((udfCode = doCallUdfAggInit(handle, &buf)) != 0) {
123,455✔
1398
    fnError("udfAggInit error. step doCallUdfAggInit. udf code: %d", udfCode);
×
1399
    releaseUdfFuncHandle(pCtx->udfName, handle);
×
1400
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1401
  }
1402
  if (buf.bufLen <= session->bufSize) {
123,455✔
1403
    memcpy(udfRes->interResBuf, buf.buf, buf.bufLen);
123,455✔
1404
    udfRes->interResBufLen = buf.bufLen;
123,455✔
1405
    udfRes->interResNum = buf.numOfResult;
123,455✔
1406
  } else {
1407
    fnError("udfc inter buf size %d is greater than function bufSize %d", buf.bufLen, session->bufSize);
×
1408
    releaseUdfFuncHandle(pCtx->udfName, handle);
×
1409
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1410
  }
1411
  releaseUdfFuncHandle(pCtx->udfName, handle);
123,455✔
1412
  freeUdfInterBuf(&buf);
123,455✔
1413
  return TSDB_CODE_SUCCESS;
123,455✔
1414
}
1415

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

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

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

1437
  if (code) {
268,739✔
1438
    return code;
×
1439
  }
1440

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

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

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

1461
  udfCode = doCallUdfAggProcess(session, inputBlock, &state, &newState);
268,739✔
1462
  if (udfCode != 0) {
268,739✔
1463
    fnError("udfAggProcess error. code: %d", udfCode);
×
1464
    newState.numOfResult = 0;
×
1465
  } else {
1466
    if (newState.bufLen <= session->bufSize) {
268,739✔
1467
      memcpy(udfRes->interResBuf, newState.buf, newState.bufLen);
268,739✔
1468
      udfRes->interResBufLen = newState.bufLen;
268,739✔
1469
      udfRes->interResNum = newState.numOfResult;
268,739✔
1470
    } else {
1471
      fnError("udfc inter buf size %d is greater than function bufSize %d", newState.bufLen, session->bufSize);
×
1472
      udfCode = TSDB_CODE_UDF_INVALID_BUFSIZE;
×
1473
    }
1474
  }
1475

1476
  GET_RES_INFO(pCtx)->numOfRes = udfRes->interResNum;
268,739✔
1477

1478
  blockDataDestroy(inputBlock);
268,739✔
1479

1480
  taosArrayDestroy(pTempBlock->pDataBlock);
268,739✔
1481
  taosMemoryFree(pTempBlock);
268,739✔
1482

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

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

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

1502
  SUdfInterBuf resultBuf = {0};
123,455✔
1503
  SUdfInterBuf state = {
123,455✔
1504
      .buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
123,455✔
1505
  int32_t udfCallCode = 0;
123,455✔
1506
  udfCallCode = doCallUdfAggFinalize(session, &state, &resultBuf);
123,455✔
1507
  if (udfCallCode != 0) {
123,455✔
1508
    fnError("udfAggFinalize error. doCallUdfAggFinalize step. udf code:%d", udfCallCode);
×
1509
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1510
  } else {
1511
    if (resultBuf.numOfResult == 0) {
123,455✔
1512
      udfRes->finalResNum = 0;
479✔
1513
      GET_RES_INFO(pCtx)->numOfRes = 0;
479✔
1514
    } else {
1515
      if (resultBuf.bufLen <= session->bytes) {
122,976✔
1516
        memcpy(udfRes->finalResBuf, resultBuf.buf, resultBuf.bufLen);
122,976✔
1517
        udfRes->finalResNum = resultBuf.numOfResult;
122,976✔
1518
        GET_RES_INFO(pCtx)->numOfRes = udfRes->finalResNum;
122,976✔
1519
      } else {
1520
        fnError("udfc inter buf size %d is greater than function output size %d", resultBuf.bufLen, session->bytes);
×
1521
        GET_RES_INFO(pCtx)->numOfRes = 0;
×
1522
        udfCallCode = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
×
1523
      }
1524
    }
1525
  }
1526

1527
  freeUdfInterBuf(&resultBuf);
123,455✔
1528

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

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

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

1565
      switch (task->type) {
805,691✔
1566
        case UDF_TASK_SETUP: {
93,351✔
1567
          task->_setup.rsp = rsp.setupRsp;
93,351✔
1568
          break;
93,351✔
1569
        }
1570
        case UDF_TASK_CALL: {
618,989✔
1571
          task->_call.rsp = rsp.callRsp;
618,989✔
1572
          break;
618,989✔
1573
        }
1574
        case UDF_TASK_TEARDOWN: {
93,351✔
1575
          task->_teardown.rsp = rsp.teardownRsp;
1576
          break;
93,351✔
1577
        }
1578
        default: {
×
1579
          break;
×
1580
        }
1581
      }
1582

1583
      // TODO: the call buffer is setup and freed by udf invocation
1584
      taosMemoryFreeClear(uvTask->rspBuf.base);
805,691✔
1585
    } else {
1586
      code = uvTask->errCode;
×
1587
      if (code != 0) {
×
1588
        fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1589
      }
1590
    }
1591
  } else if (uvTask->type == UV_TASK_CONNECT) {
186,702✔
1592
    code = uvTask->errCode;
93,351✔
1593
    if (code != 0) {
93,351✔
1594
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1595
    }
1596
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
93,351✔
1597
    code = uvTask->errCode;
93,351✔
1598
    if (code != 0) {
93,351✔
1599
      fnError("udfc get udf task result failure. code: %d, line:%d", code, __LINE__);
×
1600
    }
1601
  }
1602
  return code;
992,393✔
1603
}
1604

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

1609
  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
2,415,173✔
1610
  if (connBuf->cap == 0) {
2,415,173✔
1611
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
899,042✔
1612
    if (connBuf->buf) {
899,042✔
1613
      connBuf->len = 0;
899,042✔
1614
      connBuf->cap = msgHeadSize;
899,042✔
1615
      connBuf->total = -1;
899,042✔
1616

1617
      buf->base = connBuf->buf;
899,042✔
1618
      buf->len = connBuf->cap;
899,042✔
1619
    } else {
1620
      fnError("udfc allocate buffer failure. size: %d", msgHeadSize);
×
1621
      buf->base = NULL;
×
1622
      buf->len = 0;
×
1623
    }
1624
  } else if (connBuf->total == -1 && connBuf->len < msgHeadSize) {
1,516,131✔
1625
    buf->base = connBuf->buf + connBuf->len;
710,440✔
1626
    buf->len = msgHeadSize - connBuf->len;
710,440✔
1627
  } else {
1628
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
805,691✔
1629
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
805,691✔
1630
    if (resultBuf) {
805,691✔
1631
      connBuf->buf = resultBuf;
805,691✔
1632
      buf->base = connBuf->buf + connBuf->len;
805,691✔
1633
      buf->len = connBuf->cap - connBuf->len;
805,691✔
1634
    } else {
1635
      fnError("udfc re-allocate buffer failure. size: %d", connBuf->cap);
×
1636
      buf->base = NULL;
×
1637
      buf->len = 0;
×
1638
    }
1639
  }
1640

1641
  fnDebug("udfc uv alloc buffer: cap - len - total : %d - %d - %d", connBuf->cap, connBuf->len, connBuf->total);
2,415,173✔
1642
}
2,415,173✔
1643

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

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

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

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

1683
  if (taskFound) {
805,691✔
1684
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
805,691✔
1685
    QUEUE_REMOVE(&taskFound->connTaskQueue);
805,691✔
1686
    QUEUE_REMOVE(&taskFound->procTaskQueue);
805,691✔
1687
    uv_sem_post(&taskFound->taskSem);
805,691✔
1688
  } else {
1689
    fnError("no task is waiting for the response.");
×
1690
  }
1691
  connBuf->buf = NULL;
805,691✔
1692
  connBuf->total = -1;
805,691✔
1693
  connBuf->len = 0;
805,691✔
1694
  connBuf->cap = 0;
805,691✔
1695
}
1696

1697
void udfcUvHandleError(SClientUvConn *conn) {
×
1698
  fnDebug("handle error on conn: %p, pipe: %p", conn, conn->pipe);
×
1699
  while (!QUEUE_EMPTY(&conn->taskQueue)) {
×
1700
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
×
1701
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
×
1702
    task->errCode = TSDB_CODE_UDF_PIPE_READ_ERR;
×
1703
    QUEUE_REMOVE(&task->connTaskQueue);
×
1704
    QUEUE_REMOVE(&task->procTaskQueue);
×
1705
    uv_sem_post(&task->taskSem);
×
1706
  }
1707
  if (!uv_is_closing((uv_handle_t *)conn->pipe)) {
×
1708
    uv_close((uv_handle_t *)conn->pipe, onUdfcPipeClose);
×
1709
  }
1710
}
×
1711

1712
void onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
2,415,173✔
1713
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
2,415,173✔
1714
  if (nread == 0) return;
2,415,173✔
1715

1716
  SClientUvConn  *conn = client->data;
1,611,382✔
1717
  SClientConnBuf *connBuf = &conn->readBuf;
1,611,382✔
1718
  if (nread > 0) {
1,611,382✔
1719
    connBuf->len += nread;
1,611,382✔
1720
    if (isUdfcUvMsgComplete(connBuf)) {
1,611,382✔
1721
      udfcUvHandleRsp(conn);
805,691✔
1722
    }
1723
  }
1724
  if (nread < 0) {
1,611,382✔
1725
    fnError("udfc client pipe %p read error: %zd(%s).", client, nread, uv_strerror(nread));
×
1726
    if (nread == UV_EOF) {
×
1727
      fnError("\tudfc client pipe %p closed", client);
×
1728
    }
1729
    udfcUvHandleError(conn);
×
1730
  }
1731
}
1732

1733
void onUdfcPipeWrite(uv_write_t *write, int32_t status) {
805,691✔
1734
  SClientUvConn *conn = write->data;
805,691✔
1735
  if (status < 0) {
805,691✔
1736
    fnError("udfc client connection %p write failed. status: %d(%s)", conn, status, uv_strerror(status));
×
1737
    udfcUvHandleError(conn);
×
1738
  } else {
1739
    fnDebug("udfc client connection %p write succeed", conn);
805,691✔
1740
  }
1741
  taosMemoryFree(write);
805,691✔
1742
}
805,691✔
1743

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

1751
  int32_t code = uv_read_start((uv_stream_t *)uvTask->pipe, udfcAllocateBuffer, onUdfcPipeRead);
93,351✔
1752
  if (code != 0) {
93,351✔
1753
    fnError("udfc client connection %p read start failed. code: %d(%s)", uvTask->pipe, code, uv_strerror(code));
×
1754
    uvTask->errCode = code;
×
1755
  }
1756
  taosMemoryFree(connect);
93,351✔
1757
  QUEUE_REMOVE(&uvTask->procTaskQueue);
93,351✔
1758
  uv_sem_post(&uvTask->taskSem);
93,351✔
1759
}
93,351✔
1760

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

1765
  if (uvTaskType == UV_TASK_CONNECT) {
992,393✔
1766
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
899,042✔
1767
    uvTask->pipe = task->session->udfUvPipe;
805,691✔
1768
    SUdfRequest request;
805,691✔
1769
    request.type = task->type;
805,691✔
1770
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
805,691✔
1771

1772
    if (task->type == UDF_TASK_SETUP) {
805,691✔
1773
      request.setup = task->_setup.req;
93,351✔
1774
      request.type = UDF_TASK_SETUP;
93,351✔
1775
    } else if (task->type == UDF_TASK_CALL) {
712,340✔
1776
      request.call = task->_call.req;
618,989✔
1777
      request.type = UDF_TASK_CALL;
618,989✔
1778
    } else if (task->type == UDF_TASK_TEARDOWN) {
93,351✔
1779
      request.teardown = task->_teardown.req;
93,351✔
1780
      request.type = UDF_TASK_TEARDOWN;
93,351✔
1781
    } else {
1782
      fnError("udfc create uv task, invalid task type : %d", task->type);
×
1783
    }
1784
    int32_t bufLen = encodeUdfRequest(NULL, &request);
805,691✔
1785
    if (bufLen <= 0) {
805,691✔
1786
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1787
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1788
    }
1789
    request.msgLen = bufLen;
805,691✔
1790
    void *bufBegin = taosMemoryMalloc(bufLen);
805,691✔
1791
    if (bufBegin == NULL) {
805,691✔
1792
      fnError("udfc create uv task, malloc buffer failed. size: %d", bufLen);
×
1793
      return terrno;
×
1794
    }
1795
    void *buf = bufBegin;
805,691✔
1796
    if (encodeUdfRequest(&buf, &request) <= 0) {
805,691✔
1797
      fnError("udfc create uv task, encode request failed. size: %d", bufLen);
×
1798
      taosMemoryFree(bufBegin);
×
1799
      return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1800
    }
1801

1802
    uvTask->reqBuf = uv_buf_init(bufBegin, bufLen);
805,691✔
1803
    uvTask->seqNum = request.seqNum;
805,691✔
1804
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
93,351✔
1805
    uvTask->pipe = task->session->udfUvPipe;
93,351✔
1806
  }
1807
  if (uv_sem_init(&uvTask->taskSem, 0) != 0) {
992,393✔
1808
    if (uvTaskType == UV_TASK_REQ_RSP) {
×
1809
      taosMemoryFreeClear(uvTask->reqBuf.base);
×
1810
    }
1811
    fnError("udfc create uv task, init semaphore failed.");
×
1812
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1813
  }
1814

1815
  return 0;
992,393✔
1816
}
1817

1818
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask) {
992,393✔
1819
  fnDebug("queue uv task to event loop, uvTask: %d-%p", uvTask->type, uvTask);
992,393✔
1820
  SUdfcProxy *udfc = uvTask->udfc;
992,393✔
1821
  uv_mutex_lock(&udfc->taskQueueMutex);
992,393✔
1822
  QUEUE_INSERT_TAIL(&udfc->taskQueue, &uvTask->recvTaskQueue);
992,393✔
1823
  uv_mutex_unlock(&udfc->taskQueueMutex);
992,393✔
1824
  int32_t code = uv_async_send(&udfc->loopTaskAync);
992,393✔
1825
  if (code != 0) {
992,393✔
1826
    fnError("udfc queue uv task to event loop failed. code:%s", uv_strerror(code));
×
1827
    return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1828
  }
1829

1830
  uv_sem_wait(&uvTask->taskSem);
992,393✔
1831
  fnDebug("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
992,393✔
1832
  uv_sem_destroy(&uvTask->taskSem);
992,393✔
1833

1834
  return 0;
992,393✔
1835
}
1836

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

1841
  switch (uvTask->type) {
992,393✔
1842
    case UV_TASK_CONNECT: {
93,351✔
1843
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
93,351✔
1844
      if (pipe == NULL) {
93,351✔
1845
        fnError("udfc event loop start connect task malloc pipe failed.");
×
1846
        return terrno;
×
1847
      }
1848
      if (uv_pipe_init(&uvTask->udfc->uvLoop, pipe, 0) != 0) {
93,351✔
1849
        fnError("udfc event loop start connect task uv_pipe_init failed.");
×
1850
        taosMemoryFree(pipe);
×
1851
        return TSDB_CODE_UDF_UV_EXEC_FAILURE;
×
1852
      }
1853
      uvTask->pipe = pipe;
93,351✔
1854

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

1868
      pipe->data = conn;
93,351✔
1869

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

1923
  return code;
992,393✔
1924
}
1925

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

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

1949
void cleanUpUvTasks(SUdfcProxy *udfc) {
735,635✔
1950
  fnDebug("clean up uv tasks");
735,635✔
1951
  QUEUE wq;
734,551✔
1952
  QUEUE_INIT(&wq); 
735,635✔
1953

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

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

1968
  while (!QUEUE_EMPTY(&udfc->uvProcTaskQueue)) {
735,635✔
1969
    QUEUE *h = QUEUE_HEAD(&udfc->uvProcTaskQueue);
×
1970
    QUEUE_REMOVE(h);
×
1971
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, procTaskQueue);
×
1972
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
×
1973
      task->errCode = TSDB_CODE_UDF_STOPPING;
×
1974
    }
1975
    uv_sem_post(&task->taskSem);
×
1976
  }
1977
}
735,635✔
1978

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

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

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

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

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

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

2062
int32_t udfcClose() {
740,096✔
2063
  int8_t old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 1, 0);
740,096✔
2064
  if (old == 0) {
740,096✔
2065
    return 0;
4,461✔
2066
  }
2067

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

2087
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType) {
992,393✔
2088
  int32_t            code = 0, lino = 0;
992,393✔
2089
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
992,393✔
2090
  if (uvTask == NULL) {
992,393✔
2091
    fnError("udfc client task: %p failed to allocate memory for uvTask", task);
×
2092
    return terrno;
×
2093
  }
2094
  fnDebug("udfc client task: %p created uvTask: %p. pipe: %p", task, uvTask, task->session->udfUvPipe);
992,393✔
2095

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

2108
_exit:
992,393✔
2109
  if (code != 0) {
992,393✔
2110
    fnError("udfc run udf uv task failure. task: %p, uvTask: %p, err: %d, line: %d", task, uvTask, code, lino);
×
2111
  }
2112
  taosMemoryFree(uvTask->reqBuf.base);
992,393✔
2113
  uvTask->reqBuf.base = NULL;
992,393✔
2114
  taosMemoryFree(uvTask);
992,393✔
2115
  uvTask = NULL;
992,393✔
2116
  return code;
992,393✔
2117
}
2118

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

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

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

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

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

2154
  SUdfSetupResponse *rsp = &task->_setup.rsp;
93,351✔
2155
  task->session->severHandle = rsp->udfHandle;
93,351✔
2156
  task->session->outputType = rsp->outputType;
93,351✔
2157
  task->session->bytes = rsp->bytes;
93,351✔
2158
  task->session->bufSize = rsp->bufSize;
93,351✔
2159
  tstrncpy(task->session->udfName, udfName, TSDB_FUNC_NAME_LEN);
93,351✔
2160
  fnInfo("successfully setup udf func handle. udfName: %s, handle: %p", udfName, task->session);
93,351✔
2161
  *funcHandle = task->session;
93,351✔
2162
  taosMemoryFree(task);
93,351✔
2163
  return 0;
93,351✔
2164

2165
_exit:
×
2166
  if (code != 0) {
×
2167
    fnError("failed to setup udf. udfname: %s, err: %d line:%d", udfName, code, lino);
×
2168
  }
2169
  freeTaskSession(task);
×
2170
  taosMemoryFree(task);
×
2171
  return code;
×
2172
}
2173

2174
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
618,989✔
2175
                SSDataBlock *output, SUdfInterBuf *newState) {
2176
  fnDebug("udfc call udf. callType: %d, funcHandle: %p", callType, handle);
618,989✔
2177
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
618,989✔
2178
  if (session->udfUvPipe == NULL) {
618,989✔
2179
    fnError("No pipe to udfd");
×
2180
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2181
  }
2182
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
618,989✔
2183
  if (task == NULL) {
618,989✔
2184
    fnError("udfc call udf. failed to allocate memory for task");
×
2185
    return terrno;
×
2186
  }
2187
  task->session = (SUdfcUvSession *)handle;
618,989✔
2188
  task->type = UDF_TASK_CALL;
618,989✔
2189

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

2194
  switch (callType) {
618,989✔
2195
    case TSDB_UDF_CALL_AGG_INIT: {
123,455✔
2196
      req->initFirst = 1;
123,455✔
2197
      break;
123,455✔
2198
    }
2199
    case TSDB_UDF_CALL_AGG_PROC: {
268,739✔
2200
      req->block = *input;
268,739✔
2201
      req->interBuf = *state;
268,739✔
2202
      break;
268,739✔
2203
    }
2204
    // case TSDB_UDF_CALL_AGG_MERGE: {
2205
    //   req->interBuf = *state;
2206
    //   req->interBuf2 = *state2;
2207
    //   break;
2208
    // }
2209
    case TSDB_UDF_CALL_AGG_FIN: {
123,455✔
2210
      req->interBuf = *state;
123,455✔
2211
      break;
123,455✔
2212
    }
2213
    case TSDB_UDF_CALL_SCALA_PROC: {
103,340✔
2214
      req->block = *input;
103,340✔
2215
      break;
103,340✔
2216
    }
2217
  }
2218

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

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

2254
  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);
123,455✔
2255

2256
  return err;
123,455✔
2257
}
2258

2259
// input: block, state
2260
// output: interbuf,
2261
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
268,739✔
2262
  int8_t  callType = TSDB_UDF_CALL_AGG_PROC;
268,739✔
2263
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
268,739✔
2264
  return err;
268,739✔
2265
}
2266

2267
// input: interbuf1, interbuf2
2268
// output: resultBuf
2269
// udf todo:  aggmerge
2270
// int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
2271
//                           SUdfInterBuf *resultBuf) {
2272
//   int8_t  callType = TSDB_UDF_CALL_AGG_MERGE;
2273
//   int32_t err = callUdf(handle, callType, NULL, interBuf1, interBuf2, NULL, resultBuf);
2274
//   return err;
2275
// }
2276

2277
// input: interBuf
2278
// output: resultData
2279
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData) {
123,455✔
2280
  int8_t  callType = TSDB_UDF_CALL_AGG_FIN;
123,455✔
2281
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
123,455✔
2282
  return err;
123,455✔
2283
}
2284

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

2300
  blockDataFreeRes(&inputBlock);
103,340✔
2301
  return err;
103,340✔
2302
}
2303

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

2308
  if (session->udfUvPipe == NULL) {
93,351✔
2309
    fnError("tear down udf. pipe to udfd does not exist. udf name: %s", session->udfName);
×
2310
    taosMemoryFree(session);
×
2311
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
×
2312
  }
2313

2314
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
93,351✔
2315
  if (task == NULL) {
93,351✔
2316
    fnError("doTeardownUdf, failed to allocate memory for task");
×
2317
    taosMemoryFree(session);
×
2318
    return terrno;
×
2319
  }
2320
  task->session = session;
93,351✔
2321
  task->type = UDF_TASK_TEARDOWN;
93,351✔
2322

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

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

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

2332
  fnInfo("tear down udf. udf name: %s, udf func handle: %p", session->udfName, handle);
93,351✔
2333
  // TODO: synchronization refactor between libuv event loop and request thread
2334
  // uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
2335
  // if (session->udfUvPipe != NULL && session->udfUvPipe->data != NULL) {
2336
  //   SClientUvConn *conn = session->udfUvPipe->data;
2337
  //   conn->session = NULL;
2338
  // }
2339
  // uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
2340

2341
_exit:
93,351✔
2342
  if (code != 0) {
93,351✔
2343
    fnError("failed to teardown udf. udf name: %s, err: %d, line: %d", session->udfName, code, lino);
×
2344
  }
2345
  freeTaskSession(task);
93,351✔
2346
  taosMemoryFree(task);
93,351✔
2347

2348
  return code;
93,351✔
2349
}
2350
#else
2351
#include "tudf.h"
2352

2353
int32_t cleanUpUdfs() { return 0; }
2354
int32_t udfcOpen() { return 0; }
2355
int32_t udfcClose() { return 0; }
2356
int32_t udfStartUdfd(int32_t startDnodeId) { return 0; }
2357
void    udfStopUdfd() { return; }
2358
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
2359
  return TSDB_CODE_OPS_NOT_SUPPORT;
2360
}
2361
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc