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

17
#include "os.h"
H
Hongze Cheng 已提交
18 19

#include "builtinsimpl.h"
S
slzhou 已提交
20
#include "fnLog.h"
H
Hongze Cheng 已提交
21 22
#include "functionMgt.h"
#include "querynodes.h"
S
shenglian zhou 已提交
23
#include "tarray.h"
S
slzhou 已提交
24
#include "tdatablock.h"
H
Hongze Cheng 已提交
25 26 27
#include "tglobal.h"
#include "tudf.h"
#include "tudfInt.h"
28

29
typedef struct SUdfdData {
H
Hongze Cheng 已提交
30 31 32 33 34 35
  bool         startCalled;
  bool         needCleanUp;
  uv_loop_t    loop;
  uv_thread_t  thread;
  uv_barrier_t barrier;
  uv_process_t process;
36
#ifdef WINDOWS
H
Hongze Cheng 已提交
37
  HANDLE jobHandle;
38
#endif
H
Hongze Cheng 已提交
39 40 41 42
  int        spawnErr;
  uv_pipe_t  ctrlPipe;
  uv_async_t stopAsync;
  int32_t    stopCalled;
43

H
Hongze Cheng 已提交
44
  int32_t dnodeId;
45 46 47 48
} SUdfdData;

SUdfdData udfdGlobal = {0};

S
shenglian zhou 已提交
49 50 51
int32_t udfStartUdfd(int32_t startDnodeId);
int32_t udfStopUdfd();

52
static int32_t udfSpawnUdfd(SUdfdData *pData);
H
Hongze Cheng 已提交
53 54 55 56 57
void           udfUdfdExit(uv_process_t *process, int64_t exitStatus, int termSignal);
static int32_t udfSpawnUdfd(SUdfdData *pData);
static void    udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg);
static void    udfUdfdStopAsyncCb(uv_async_t *async);
static void    udfWatchUdfd(void *args);
58 59 60 61 62 63 64 65 66 67 68 69

void udfUdfdExit(uv_process_t *process, int64_t exitStatus, int termSignal) {
  fnInfo("udfd process exited with status %" PRId64 ", signal %d", exitStatus, termSignal);
  SUdfdData *pData = process->data;
  if (exitStatus == 0 && termSignal == 0 || atomic_load_32(&pData->stopCalled)) {
    fnInfo("udfd process exit due to SIGINT or dnode-mgmt called stop");
  } else {
    fnInfo("udfd process restart");
    udfSpawnUdfd(pData);
  }
}

H
Hongze Cheng 已提交
70
static int32_t udfSpawnUdfd(SUdfdData *pData) {
S
Shengliang Guan 已提交
71
  fnInfo("start to init udfd");
72 73 74 75 76
  uv_process_options_t options = {0};

  char path[PATH_MAX] = {0};
  if (tsProcPath == NULL) {
    path[0] = '.';
H
Hongze Cheng 已提交
77
#ifdef WINDOWS
wafwerar's avatar
wafwerar 已提交
78 79
    GetModuleFileName(NULL, path, PATH_MAX);
    taosDirName(path);
H
Hongze Cheng 已提交
80
#elif defined(_TD_DARWIN_64)
wafwerar's avatar
wafwerar 已提交
81 82 83
    uint32_t pathSize = sizeof(path);
    _NSGetExecutablePath(path, &pathSize);
    taosDirName(path);
H
Hongze Cheng 已提交
84
#endif
85
  } else {
86
    strncpy(path, tsProcPath, PATH_MAX);
87 88 89
    taosDirName(path);
  }
#ifdef WINDOWS
H
Hongze Cheng 已提交
90
  if (strlen(path) == 0) {
91
    strcat(path, "C:\\TDengine");
wafwerar's avatar
wafwerar 已提交
92
  }
93
  strcat(path, "\\udfd.exe");
94
#else
95 96 97
  if (strlen(path) == 0) {
    strcat(path, "/usr/bin");
  }
98 99
  strcat(path, "/udfd");
#endif
H
Hongze Cheng 已提交
100
  char *argsUdfd[] = {path, "-c", configDir, NULL};
101 102 103 104 105 106 107 108 109
  options.args = argsUdfd;
  options.file = path;

  options.exit_cb = udfUdfdExit;

  uv_pipe_init(&pData->loop, &pData->ctrlPipe, 1);

  uv_stdio_container_t child_stdio[3];
  child_stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE;
H
Hongze Cheng 已提交
110
  child_stdio[0].data.stream = (uv_stream_t *)&pData->ctrlPipe;
111 112 113 114 115 116 117 118 119 120 121
  child_stdio[1].flags = UV_IGNORE;
  child_stdio[2].flags = UV_INHERIT_FD;
  child_stdio[2].data.fd = 2;
  options.stdio_count = 3;
  options.stdio = child_stdio;

  options.flags = UV_PROCESS_DETACHED;

  char dnodeIdEnvItem[32] = {0};
  char thrdPoolSizeEnvItem[32] = {0};
  snprintf(dnodeIdEnvItem, 32, "%s=%d", "DNODE_ID", pData->dnodeId);
122

123 124
  float numCpuCores = 4;
  taosGetCpuCores(&numCpuCores);
H
Hongze Cheng 已提交
125
  snprintf(thrdPoolSizeEnvItem, 32, "%s=%d", "UV_THREADPOOL_SIZE", (int)numCpuCores * 2);
126

dengyihao's avatar
dengyihao 已提交
127
  char   pathTaosdLdLib[512] = {0};
128
  size_t taosdLdLibPathLen = sizeof(pathTaosdLdLib);
129 130 131 132
  int ret = uv_os_getenv("LD_LIBRARY_PATH", pathTaosdLdLib, &taosdLdLibPathLen);
  if (ret != UV_ENOBUFS) {
    taosdLdLibPathLen = strlen(pathTaosdLdLib);
  }
133

dengyihao's avatar
dengyihao 已提交
134
  char   udfdPathLdLib[1024] = {0};
135
  size_t udfdLdLibPathLen = strlen(tsUdfdLdLibPath);
H
Haojun Liao 已提交
136 137
  strncpy(udfdPathLdLib, tsUdfdLdLibPath, tListLen(udfdPathLdLib));

138
  udfdPathLdLib[udfdLdLibPathLen] = ':';
S
slzhou 已提交
139
  strncpy(udfdPathLdLib + udfdLdLibPathLen + 1, pathTaosdLdLib, sizeof(udfdPathLdLib) - udfdLdLibPathLen - 1);
140 141 142 143 144 145
  if (udfdLdLibPathLen + taosdLdLibPathLen < 1024) {
    fnInfo("udfd LD_LIBRARY_PATH: %s", udfdPathLdLib);
  } else {
    fnError("can not set correct udfd LD_LIBRARY_PATH");
  }
  char ldLibPathEnvItem[1024 + 32] = {0};
S
slzhou 已提交
146
  snprintf(ldLibPathEnvItem, 1024 + 32, "%s=%s", "LD_LIBRARY_PATH", udfdPathLdLib);
147 148

  char *envUdfd[] = {dnodeIdEnvItem, thrdPoolSizeEnvItem, ldLibPathEnvItem, NULL};
149 150 151
  options.env = envUdfd;

  int err = uv_spawn(&pData->loop, &pData->process, &options);
H
Hongze Cheng 已提交
152
  pData->process.data = (void *)pData;
153

154 155 156 157 158 159 160 161 162 163 164
#ifdef WINDOWS
  // End udfd.exe by Job.
  if (pData->jobHandle != NULL) CloseHandle(pData->jobHandle);
  pData->jobHandle = CreateJobObject(NULL, NULL);
  bool add_job_ok = AssignProcessToJobObject(pData->jobHandle, pData->process.process_handle);
  if (!add_job_ok) {
    fnError("Assign udfd to job failed.");
  } else {
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info;
    memset(&limit_info, 0x0, sizeof(limit_info));
    limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
H
Hongze Cheng 已提交
165 166
    bool set_auto_kill_ok =
        SetInformationJobObject(pData->jobHandle, JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info));
167 168 169 170 171 172
    if (!set_auto_kill_ok) {
      fnError("Set job auto kill udfd failed.");
    }
  }
#endif

173 174
  if (err != 0) {
    fnError("can not spawn udfd. path: %s, error: %s", path, uv_strerror(err));
S
Shengliang Guan 已提交
175 176
  } else {
    fnInfo("udfd is initialized");
177 178 179 180
  }
  return err;
}

H
Hongze Cheng 已提交
181
static void udfUdfdCloseWalkCb(uv_handle_t *handle, void *arg) {
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  if (!uv_is_closing(handle)) {
    uv_close(handle, NULL);
  }
}

static void udfUdfdStopAsyncCb(uv_async_t *async) {
  SUdfdData *pData = async->data;
  uv_stop(&pData->loop);
}

static void udfWatchUdfd(void *args) {
  SUdfdData *pData = args;
  uv_loop_init(&pData->loop);
  uv_async_init(&pData->loop, &pData->stopAsync, udfUdfdStopAsyncCb);
  pData->stopAsync.data = pData;
  int32_t err = udfSpawnUdfd(pData);
  atomic_store_32(&pData->spawnErr, err);
  uv_barrier_wait(&pData->barrier);
  uv_run(&pData->loop, UV_RUN_DEFAULT);
  uv_loop_close(&pData->loop);

  uv_walk(&pData->loop, udfUdfdCloseWalkCb, NULL);
  uv_run(&pData->loop, UV_RUN_DEFAULT);
  uv_loop_close(&pData->loop);
  return;
}

int32_t udfStartUdfd(int32_t startDnodeId) {
S
slzhou 已提交
210
  if (!tsStartUdfd) {
H
Hongze Cheng 已提交
211
    fnInfo("start udfd is disabled.") return 0;
S
slzhou 已提交
212
  }
213 214
  SUdfdData *pData = &udfdGlobal;
  if (pData->startCalled) {
S
Shengliang Guan 已提交
215
    fnInfo("dnode start udfd already called");
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    return 0;
  }
  pData->startCalled = true;
  char dnodeId[8] = {0};
  snprintf(dnodeId, sizeof(dnodeId), "%d", startDnodeId);
  uv_os_setenv("DNODE_ID", dnodeId);
  pData->dnodeId = startDnodeId;

  uv_barrier_init(&pData->barrier, 2);
  uv_thread_create(&pData->thread, udfWatchUdfd, pData);
  uv_barrier_wait(&pData->barrier);
  int32_t err = atomic_load_32(&pData->spawnErr);
  if (err != 0) {
    uv_barrier_destroy(&pData->barrier);
    uv_async_send(&pData->stopAsync);
    uv_thread_join(&pData->thread);
    pData->needCleanUp = false;
S
Shengliang Guan 已提交
233
    fnInfo("udfd is cleaned up after spawn err");
234 235 236 237 238 239 240 241
  } else {
    pData->needCleanUp = true;
  }
  return err;
}

int32_t udfStopUdfd() {
  SUdfdData *pData = &udfdGlobal;
H
Hongze Cheng 已提交
242
  fnInfo("udfd start to stop, need cleanup:%d, spawn err:%d", pData->needCleanUp, pData->spawnErr);
243 244 245 246 247 248 249 250
  if (!pData->needCleanUp || atomic_load_32(&pData->stopCalled)) {
    return 0;
  }
  atomic_store_32(&pData->stopCalled, 1);
  pData->needCleanUp = false;
  uv_barrier_destroy(&pData->barrier);
  uv_async_send(&pData->stopAsync);
  uv_thread_join(&pData->thread);
251 252 253
#ifdef WINDOWS
  if (pData->jobHandle != NULL) CloseHandle(pData->jobHandle);
#endif
S
Shengliang Guan 已提交
254
  fnInfo("udfd is cleaned up");
255 256 257
  return 0;
}

258 259 260 261 262 263 264 265 266 267 268 269
int32_t udfGetUdfdPid(int32_t* pUdfdPid) {
  SUdfdData *pData = &udfdGlobal;
  if (pData->spawnErr) {
    return pData->spawnErr;
  }
  uv_pid_t pid = uv_process_get_pid(&pData->process);
  if (pUdfdPid) {
    *pUdfdPid = (int32_t)pid;
  }
  return TSDB_CODE_SUCCESS;
}

270
//==============================================================================================
S
shenglian zhou 已提交
271 272 273 274
/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl>
 * The QUEUE is copied from queue.h under libuv
 * */

S
shenglian zhou 已提交
275 276 277
typedef void *QUEUE[2];

/* Private macros. */
H
Hongze Cheng 已提交
278 279 280 281
#define QUEUE_NEXT(q)      (*(QUEUE **)&((*(q))[0]))
#define QUEUE_PREV(q)      (*(QUEUE **)&((*(q))[1]))
#define QUEUE_PREV_NEXT(q) (QUEUE_NEXT(QUEUE_PREV(q)))
#define QUEUE_NEXT_PREV(q) (QUEUE_PREV(QUEUE_NEXT(q)))
S
shenglian zhou 已提交
282 283

/* Public macros. */
H
Hongze Cheng 已提交
284
#define QUEUE_DATA(ptr, type, field) ((type *)((char *)(ptr)-offsetof(type, field)))
S
shenglian zhou 已提交
285 286 287 288

/* Important note: mutating the list while QUEUE_FOREACH is
 * iterating over its elements results in undefined behavior.
 */
H
Hongze Cheng 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
#define QUEUE_FOREACH(q, h) for ((q) = QUEUE_NEXT(h); (q) != (h); (q) = QUEUE_NEXT(q))

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

#define QUEUE_HEAD(q) (QUEUE_NEXT(q))

#define QUEUE_INIT(q)    \
  do {                   \
    QUEUE_NEXT(q) = (q); \
    QUEUE_PREV(q) = (q); \
  } while (0)

#define QUEUE_ADD(h, n)                 \
  do {                                  \
    QUEUE_PREV_NEXT(h) = QUEUE_NEXT(n); \
    QUEUE_NEXT_PREV(n) = QUEUE_PREV(h); \
    QUEUE_PREV(h) = QUEUE_PREV(n);      \
    QUEUE_PREV_NEXT(h) = (h);           \
  } while (0)

#define QUEUE_SPLIT(h, q, n)       \
  do {                             \
    QUEUE_PREV(n) = QUEUE_PREV(h); \
    QUEUE_PREV_NEXT(n) = (n);      \
    QUEUE_NEXT(n) = (q);           \
    QUEUE_PREV(h) = QUEUE_PREV(q); \
    QUEUE_PREV_NEXT(h) = (h);      \
    QUEUE_PREV(q) = (n);           \
  } while (0)

#define QUEUE_MOVE(h, n)        \
  do {                          \
    if (QUEUE_EMPTY(h))         \
      QUEUE_INIT(n);            \
    else {                      \
      QUEUE *q = QUEUE_HEAD(h); \
      QUEUE_SPLIT(h, q, n);     \
    }                           \
  } while (0)

#define QUEUE_INSERT_HEAD(h, q)    \
  do {                             \
    QUEUE_NEXT(q) = QUEUE_NEXT(h); \
    QUEUE_PREV(q) = (h);           \
    QUEUE_NEXT_PREV(q) = (q);      \
    QUEUE_NEXT(h) = (q);           \
  } while (0)

#define QUEUE_INSERT_TAIL(h, q)    \
  do {                             \
    QUEUE_NEXT(q) = (h);           \
    QUEUE_PREV(q) = QUEUE_PREV(h); \
    QUEUE_PREV_NEXT(q) = (q);      \
    QUEUE_PREV(h) = (q);           \
  } while (0)

#define QUEUE_REMOVE(q)                 \
  do {                                  \
    QUEUE_PREV_NEXT(q) = QUEUE_NEXT(q); \
    QUEUE_NEXT_PREV(q) = QUEUE_PREV(q); \
  } while (0)

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

353
int64_t gUdfTaskSeqNum = 0;
354
typedef struct SUdfcFuncStub {
S
slzhou 已提交
355
  char           udfName[TSDB_FUNC_NAME_LEN + 1];
356
  UdfcFuncHandle handle;
H
Hongze Cheng 已提交
357
  int32_t        refCount;
358
  int64_t        createTime;
359 360
} SUdfcFuncStub;

361
typedef struct SUdfcProxy {
H
Hongze Cheng 已提交
362
  char         udfdPipeName[PATH_MAX + UDF_LISTEN_PIPE_NAME_LEN + 2];
363
  uv_barrier_t initBarrier;
364

365 366 367
  uv_loop_t   uvLoop;
  uv_thread_t loopThread;
  uv_async_t  loopTaskAync;
368

369
  uv_async_t loopStopAsync;
370

371 372 373 374
  uv_mutex_t taskQueueMutex;
  int8_t     udfcState;
  QUEUE      taskQueue;
  QUEUE      uvProcTaskQueue;
375

376
  uv_mutex_t udfStubsMutex;
H
Hongze Cheng 已提交
377
  SArray    *udfStubs;  // SUdfcFuncStub
378
  SArray    *expiredUdfStubs; //SUdfcFuncStub
379

380
  uv_mutex_t udfcUvMutex;
dengyihao's avatar
dengyihao 已提交
381
  int8_t     initialized;
382
} SUdfcProxy;
383

384
SUdfcProxy gUdfcProxy = {0};
385

S
slzhou 已提交
386
typedef struct SUdfcUvSession {
387
  SUdfcProxy *udfc;
H
Hongze Cheng 已提交
388 389
  int64_t     severHandle;
  uv_pipe_t  *udfUvPipe;
S
shenglian zhou 已提交
390 391

  int8_t  outputType;
S
slzhou 已提交
392
  int32_t bytes;
S
shenglian zhou 已提交
393
  int32_t bufSize;
S
slzhou 已提交
394

S
slzhou 已提交
395
  char udfName[TSDB_FUNC_NAME_LEN + 1];
S
slzhou 已提交
396
} SUdfcUvSession;
397 398

typedef struct SClientUvTaskNode {
399
  SUdfcProxy *udfc;
H
Hongze Cheng 已提交
400 401
  int8_t      type;
  int         errCode;
402 403 404

  uv_pipe_t *pipe;

H
Hongze Cheng 已提交
405
  int64_t  seqNum;
406 407 408 409 410
  uv_buf_t reqBuf;

  uv_sem_t taskSem;
  uv_buf_t rspBuf;

S
shenglian zhou 已提交
411 412 413
  QUEUE recvTaskQueue;
  QUEUE procTaskQueue;
  QUEUE connTaskQueue;
414 415 416 417 418
} SClientUvTaskNode;

typedef struct SClientUdfTask {
  int8_t type;

S
slzhou 已提交
419
  SUdfcUvSession *session;
420 421 422 423 424

  int32_t errCode;

  union {
    struct {
H
Hongze Cheng 已提交
425
      SUdfSetupRequest  req;
426 427 428
      SUdfSetupResponse rsp;
    } _setup;
    struct {
H
Hongze Cheng 已提交
429
      SUdfCallRequest  req;
430 431 432
      SUdfCallResponse rsp;
    } _call;
    struct {
H
Hongze Cheng 已提交
433
      SUdfTeardownRequest  req;
434 435 436 437 438 439 440
      SUdfTeardownResponse rsp;
    } _teardown;
  };

} SClientUdfTask;

typedef struct SClientConnBuf {
H
Hongze Cheng 已提交
441
  char   *buf;
442 443 444 445 446 447
  int32_t len;
  int32_t cap;
  int32_t total;
} SClientConnBuf;

typedef struct SClientUvConn {
H
Hongze Cheng 已提交
448 449 450
  uv_pipe_t      *pipe;
  QUEUE           taskQueue;
  SClientConnBuf  readBuf;
S
slzhou 已提交
451
  SUdfcUvSession *session;
452 453
} SClientUvConn;

454
enum {
H
Hongze Cheng 已提交
455 456 457 458
  UDFC_STATE_INITAL = 0,  // initial state
  UDFC_STATE_STARTNG,     // starting after udfcOpen
  UDFC_STATE_READY,       // started and begin to receive quests
  UDFC_STATE_STOPPING,    // stopping after udfcClose
459
};
460

H
Hongze Cheng 已提交
461
int32_t getUdfdPipeName(char *pipeName, int32_t size);
S
shenglian zhou 已提交
462
int32_t encodeUdfSetupRequest(void **buf, const SUdfSetupRequest *setup);
H
Hongze Cheng 已提交
463 464 465
void   *decodeUdfSetupRequest(const void *buf, SUdfSetupRequest *request);
int32_t encodeUdfInterBuf(void **buf, const SUdfInterBuf *state);
void   *decodeUdfInterBuf(const void *buf, SUdfInterBuf *state);
S
shenglian zhou 已提交
466
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call);
H
Hongze Cheng 已提交
467
void   *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call);
S
shenglian zhou 已提交
468
int32_t encodeUdfTeardownRequest(void **buf, const SUdfTeardownRequest *teardown);
H
Hongze Cheng 已提交
469 470 471
void   *decodeUdfTeardownRequest(const void *buf, SUdfTeardownRequest *teardown);
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request);
void   *decodeUdfRequest(const void *buf, SUdfRequest *request);
S
shenglian zhou 已提交
472
int32_t encodeUdfSetupResponse(void **buf, const SUdfSetupResponse *setupRsp);
H
Hongze Cheng 已提交
473
void   *decodeUdfSetupResponse(const void *buf, SUdfSetupResponse *setupRsp);
S
shenglian zhou 已提交
474
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp);
H
Hongze Cheng 已提交
475 476 477 478 479 480 481 482 483
void   *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp);
int32_t encodeUdfTeardownResponse(void **buf, const SUdfTeardownResponse *teardownRsp);
void   *decodeUdfTeardownResponse(const void *buf, SUdfTeardownResponse *teardownResponse);
int32_t encodeUdfResponse(void **buf, const SUdfResponse *rsp);
void   *decodeUdfResponse(const void *buf, SUdfResponse *rsp);
void    freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta);
void    freeUdfColumn(SUdfColumn *col);
void    freeUdfDataDataBlock(SUdfDataBlock *block);
void    freeUdfInterBuf(SUdfInterBuf *buf);
S
shenglian zhou 已提交
484 485 486 487 488
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock);
int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block);
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output);
int32_t convertDataBlockToScalarParm(SSDataBlock *input, SScalarParam *output);

H
Hongze Cheng 已提交
489
int32_t getUdfdPipeName(char *pipeName, int32_t size) {
490
  char    dnodeId[8] = {0};
wafwerar's avatar
wafwerar 已提交
491
  size_t  dnodeIdSize = sizeof(dnodeId);
492 493
  int32_t err = uv_os_getenv(UDF_DNODE_ID_ENV_NAME, dnodeId, &dnodeIdSize);
  if (err != 0) {
S
Shengliang Guan 已提交
494
    fnError("failed to get dnodeId from env since %s", uv_err_name(err));
495 496
    dnodeId[0] = '1';
  }
497
#ifdef _WIN32
H
Hongze Cheng 已提交
498 499
  snprintf(pipeName, size, "%s.%x.%s", UDF_LISTEN_PIPE_NAME_PREFIX, MurmurHash3_32(tsDataDir, strlen(tsDataDir)),
           dnodeId);
500 501 502
#else
  snprintf(pipeName, size, "%s/%s%s", tsDataDir, UDF_LISTEN_PIPE_NAME_PREFIX, dnodeId);
#endif
S
Shengliang Guan 已提交
503
  fnInfo("get dnodeId:%s from env, pipe path:%s", dnodeId, pipeName);
504 505 506
  return 0;
}

507 508 509
int32_t encodeUdfSetupRequest(void **buf, const SUdfSetupRequest *setup) {
  int32_t len = 0;
  len += taosEncodeBinary(buf, setup->udfName, TSDB_FUNC_NAME_LEN);
S
shenglian zhou 已提交
510 511
  return len;
}
512

H
Hongze Cheng 已提交
513
void *decodeUdfSetupRequest(const void *buf, SUdfSetupRequest *request) {
514
  buf = taosDecodeBinaryTo(buf, request->udfName, TSDB_FUNC_NAME_LEN);
H
Hongze Cheng 已提交
515
  return (void *)buf;
S
shenglian zhou 已提交
516
}
517

H
Hongze Cheng 已提交
518
int32_t encodeUdfInterBuf(void **buf, const SUdfInterBuf *state) {
519
  int32_t len = 0;
520
  len += taosEncodeFixedI8(buf, state->numOfResult);
521 522
  len += taosEncodeFixedI32(buf, state->bufLen);
  len += taosEncodeBinary(buf, state->buf, state->bufLen);
S
shenglian zhou 已提交
523 524
  return len;
}
525

H
Hongze Cheng 已提交
526
void *decodeUdfInterBuf(const void *buf, SUdfInterBuf *state) {
527
  buf = taosDecodeFixedI8(buf, &state->numOfResult);
528
  buf = taosDecodeFixedI32(buf, &state->bufLen);
H
Hongze Cheng 已提交
529 530
  buf = taosDecodeBinary(buf, (void **)&state->buf, state->bufLen);
  return (void *)buf;
S
shenglian zhou 已提交
531 532
}

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
int32_t encodeUdfCallRequest(void **buf, const SUdfCallRequest *call) {
  int32_t len = 0;
  len += taosEncodeFixedI64(buf, call->udfHandle);
  len += taosEncodeFixedI8(buf, call->callType);
  if (call->callType == TSDB_UDF_CALL_SCALA_PROC) {
    len += tEncodeDataBlock(buf, &call->block);
  } else if (call->callType == TSDB_UDF_CALL_AGG_INIT) {
    len += taosEncodeFixedI8(buf, call->initFirst);
  } else if (call->callType == TSDB_UDF_CALL_AGG_PROC) {
    len += tEncodeDataBlock(buf, &call->block);
    len += encodeUdfInterBuf(buf, &call->interBuf);
  } else if (call->callType == TSDB_UDF_CALL_AGG_MERGE) {
    len += encodeUdfInterBuf(buf, &call->interBuf);
    len += encodeUdfInterBuf(buf, &call->interBuf2);
  } else if (call->callType == TSDB_UDF_CALL_AGG_FIN) {
    len += encodeUdfInterBuf(buf, &call->interBuf);
549
  }
550
  return len;
551 552
}

H
Hongze Cheng 已提交
553
void *decodeUdfCallRequest(const void *buf, SUdfCallRequest *call) {
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  buf = taosDecodeFixedI64(buf, &call->udfHandle);
  buf = taosDecodeFixedI8(buf, &call->callType);
  switch (call->callType) {
    case TSDB_UDF_CALL_SCALA_PROC:
      buf = tDecodeDataBlock(buf, &call->block);
      break;
    case TSDB_UDF_CALL_AGG_INIT:
      buf = taosDecodeFixedI8(buf, &call->initFirst);
      break;
    case TSDB_UDF_CALL_AGG_PROC:
      buf = tDecodeDataBlock(buf, &call->block);
      buf = decodeUdfInterBuf(buf, &call->interBuf);
      break;
    case TSDB_UDF_CALL_AGG_MERGE:
      buf = decodeUdfInterBuf(buf, &call->interBuf);
      buf = decodeUdfInterBuf(buf, &call->interBuf2);
      break;
    case TSDB_UDF_CALL_AGG_FIN:
      buf = decodeUdfInterBuf(buf, &call->interBuf);
      break;
574
  }
H
Hongze Cheng 已提交
575
  return (void *)buf;
S
shenglian zhou 已提交
576 577
}

578 579 580 581
int32_t encodeUdfTeardownRequest(void **buf, const SUdfTeardownRequest *teardown) {
  int32_t len = 0;
  len += taosEncodeFixedI64(buf, teardown->udfHandle);
  return len;
S
shenglian zhou 已提交
582 583
}

H
Hongze Cheng 已提交
584
void *decodeUdfTeardownRequest(const void *buf, SUdfTeardownRequest *teardown) {
585
  buf = taosDecodeFixedI64(buf, &teardown->udfHandle);
H
Hongze Cheng 已提交
586
  return (void *)buf;
S
shenglian zhou 已提交
587 588
}

H
Hongze Cheng 已提交
589
int32_t encodeUdfRequest(void **buf, const SUdfRequest *request) {
590 591 592 593
  int32_t len = 0;
  if (buf == NULL) {
    len += sizeof(request->msgLen);
  } else {
H
Hongze Cheng 已提交
594
    *(int32_t *)(*buf) = request->msgLen;
595 596 597 598 599 600 601 602 603 604 605 606
    *buf = POINTER_SHIFT(*buf, sizeof(request->msgLen));
  }
  len += taosEncodeFixedI64(buf, request->seqNum);
  len += taosEncodeFixedI8(buf, request->type);
  if (request->type == UDF_TASK_SETUP) {
    len += encodeUdfSetupRequest(buf, &request->setup);
  } else if (request->type == UDF_TASK_CALL) {
    len += encodeUdfCallRequest(buf, &request->call);
  } else if (request->type == UDF_TASK_TEARDOWN) {
    len += encodeUdfTeardownRequest(buf, &request->teardown);
  }
  return len;
S
shenglian zhou 已提交
607 608
}

H
Hongze Cheng 已提交
609 610
void *decodeUdfRequest(const void *buf, SUdfRequest *request) {
  request->msgLen = *(int32_t *)(buf);
S
slzhou 已提交
611
  buf = POINTER_SHIFT(buf, sizeof(request->msgLen));
S
shenglian zhou 已提交
612

613 614
  buf = taosDecodeFixedI64(buf, &request->seqNum);
  buf = taosDecodeFixedI8(buf, &request->type);
S
shenglian zhou 已提交
615 616

  if (request->type == UDF_TASK_SETUP) {
617
    buf = decodeUdfSetupRequest(buf, &request->setup);
S
shenglian zhou 已提交
618
  } else if (request->type == UDF_TASK_CALL) {
619 620 621
    buf = decodeUdfCallRequest(buf, &request->call);
  } else if (request->type == UDF_TASK_TEARDOWN) {
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
S
shenglian zhou 已提交
622
  }
H
Hongze Cheng 已提交
623
  return (void *)buf;
S
shenglian zhou 已提交
624
}
625

626 627 628
int32_t encodeUdfSetupResponse(void **buf, const SUdfSetupResponse *setupRsp) {
  int32_t len = 0;
  len += taosEncodeFixedI64(buf, setupRsp->udfHandle);
S
shenglian zhou 已提交
629
  len += taosEncodeFixedI8(buf, setupRsp->outputType);
S
slzhou 已提交
630
  len += taosEncodeFixedI32(buf, setupRsp->bytes);
S
shenglian zhou 已提交
631
  len += taosEncodeFixedI32(buf, setupRsp->bufSize);
632 633
  return len;
}
634

H
Hongze Cheng 已提交
635
void *decodeUdfSetupResponse(const void *buf, SUdfSetupResponse *setupRsp) {
636
  buf = taosDecodeFixedI64(buf, &setupRsp->udfHandle);
S
shenglian zhou 已提交
637
  buf = taosDecodeFixedI8(buf, &setupRsp->outputType);
S
slzhou 已提交
638
  buf = taosDecodeFixedI32(buf, &setupRsp->bytes);
S
shenglian zhou 已提交
639
  buf = taosDecodeFixedI32(buf, &setupRsp->bufSize);
H
Hongze Cheng 已提交
640
  return (void *)buf;
S
shenglian zhou 已提交
641
}
642

643 644 645 646 647 648
int32_t encodeUdfCallResponse(void **buf, const SUdfCallResponse *callRsp) {
  int32_t len = 0;
  len += taosEncodeFixedI8(buf, callRsp->callType);
  switch (callRsp->callType) {
    case TSDB_UDF_CALL_SCALA_PROC:
      len += tEncodeDataBlock(buf, &callRsp->resultData);
649
      break;
650
    case TSDB_UDF_CALL_AGG_INIT:
S
slzhou 已提交
651
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
652 653
      break;
    case TSDB_UDF_CALL_AGG_PROC:
S
slzhou 已提交
654
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
655 656
      break;
    case TSDB_UDF_CALL_AGG_MERGE:
S
slzhou 已提交
657
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
658 659
      break;
    case TSDB_UDF_CALL_AGG_FIN:
S
slzhou 已提交
660
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
661 662
      break;
  }
663
  return len;
S
shenglian zhou 已提交
664 665
}

H
Hongze Cheng 已提交
666
void *decodeUdfCallResponse(const void *buf, SUdfCallResponse *callRsp) {
667 668 669 670 671 672
  buf = taosDecodeFixedI8(buf, &callRsp->callType);
  switch (callRsp->callType) {
    case TSDB_UDF_CALL_SCALA_PROC:
      buf = tDecodeDataBlock(buf, &callRsp->resultData);
      break;
    case TSDB_UDF_CALL_AGG_INIT:
S
slzhou 已提交
673
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
674 675
      break;
    case TSDB_UDF_CALL_AGG_PROC:
S
slzhou 已提交
676
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
677 678
      break;
    case TSDB_UDF_CALL_AGG_MERGE:
S
slzhou 已提交
679
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
680 681
      break;
    case TSDB_UDF_CALL_AGG_FIN:
S
slzhou 已提交
682
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
683
      break;
S
shenglian zhou 已提交
684
  }
H
Hongze Cheng 已提交
685
  return (void *)buf;
S
shenglian zhou 已提交
686 687
}

H
Hongze Cheng 已提交
688
int32_t encodeUdfTeardownResponse(void **buf, const SUdfTeardownResponse *teardownRsp) { return 0; }
S
shenglian zhou 已提交
689

H
Hongze Cheng 已提交
690
void *decodeUdfTeardownResponse(const void *buf, SUdfTeardownResponse *teardownResponse) { return (void *)buf; }
S
shenglian zhou 已提交
691

H
Hongze Cheng 已提交
692
int32_t encodeUdfResponse(void **buf, const SUdfResponse *rsp) {
693 694 695 696
  int32_t len = 0;
  if (buf == NULL) {
    len += sizeof(rsp->msgLen);
  } else {
H
Hongze Cheng 已提交
697
    *(int32_t *)(*buf) = rsp->msgLen;
698
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->msgLen));
S
shenglian zhou 已提交
699 700
  }

S
slzhou 已提交
701 702 703
  if (buf == NULL) {
    len += sizeof(rsp->seqNum);
  } else {
H
Hongze Cheng 已提交
704
    *(int64_t *)(*buf) = rsp->seqNum;
S
slzhou 已提交
705 706 707
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
  }

708 709 710
  len += taosEncodeFixedI64(buf, rsp->seqNum);
  len += taosEncodeFixedI8(buf, rsp->type);
  len += taosEncodeFixedI32(buf, rsp->code);
S
shenglian zhou 已提交
711

712 713 714 715 716 717 718 719 720 721 722
  switch (rsp->type) {
    case UDF_TASK_SETUP:
      len += encodeUdfSetupResponse(buf, &rsp->setupRsp);
      break;
    case UDF_TASK_CALL:
      len += encodeUdfCallResponse(buf, &rsp->callRsp);
      break;
    case UDF_TASK_TEARDOWN:
      len += encodeUdfTeardownResponse(buf, &rsp->teardownRsp);
      break;
    default:
S
shenglian zhou 已提交
723
      fnError("encode udf response, invalid udf response type %d", rsp->type);
724 725 726
      break;
  }
  return len;
S
shenglian zhou 已提交
727 728
}

H
Hongze Cheng 已提交
729 730
void *decodeUdfResponse(const void *buf, SUdfResponse *rsp) {
  rsp->msgLen = *(int32_t *)(buf);
S
slzhou 已提交
731
  buf = POINTER_SHIFT(buf, sizeof(rsp->msgLen));
H
Hongze Cheng 已提交
732
  rsp->seqNum = *(int64_t *)(buf);
S
slzhou 已提交
733
  buf = POINTER_SHIFT(buf, sizeof(rsp->seqNum));
734 735 736
  buf = taosDecodeFixedI64(buf, &rsp->seqNum);
  buf = taosDecodeFixedI8(buf, &rsp->type);
  buf = taosDecodeFixedI32(buf, &rsp->code);
S
shenglian zhou 已提交
737

738 739 740 741 742 743 744 745 746 747 748
  switch (rsp->type) {
    case UDF_TASK_SETUP:
      buf = decodeUdfSetupResponse(buf, &rsp->setupRsp);
      break;
    case UDF_TASK_CALL:
      buf = decodeUdfCallResponse(buf, &rsp->callRsp);
      break;
    case UDF_TASK_TEARDOWN:
      buf = decodeUdfTeardownResponse(buf, &rsp->teardownRsp);
      break;
    default:
S
shenglian zhou 已提交
749
      fnError("decode udf response, invalid udf response type %d", rsp->type);
750
      break;
751
  }
H
Hongze Cheng 已提交
752
  return (void *)buf;
753
}
754

S
shenglian zhou 已提交
755 756
void freeUdfColumnData(SUdfColumnData *data, SUdfColumnMeta *meta) {
  if (IS_VAR_DATA_TYPE(meta->type)) {
S
slzhou 已提交
757 758 759 760
    taosMemoryFree(data->varLenCol.varOffsets);
    data->varLenCol.varOffsets = NULL;
    taosMemoryFree(data->varLenCol.payload);
    data->varLenCol.payload = NULL;
S
shenglian zhou 已提交
761
  } else {
S
slzhou 已提交
762 763 764 765
    taosMemoryFree(data->fixLenCol.nullBitmap);
    data->fixLenCol.nullBitmap = NULL;
    taosMemoryFree(data->fixLenCol.data);
    data->fixLenCol.data = NULL;
S
shenglian zhou 已提交
766 767 768
  }
}

H
Hongze Cheng 已提交
769
void freeUdfColumn(SUdfColumn *col) { freeUdfColumnData(&col->colData, &col->colMeta); }
S
shenglian zhou 已提交
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785

void freeUdfDataDataBlock(SUdfDataBlock *block) {
  for (int32_t i = 0; i < block->numOfCols; ++i) {
    freeUdfColumn(block->udfCols[i]);
    taosMemoryFree(block->udfCols[i]);
    block->udfCols[i] = NULL;
  }
  taosMemoryFree(block->udfCols);
  block->udfCols = NULL;
}

void freeUdfInterBuf(SUdfInterBuf *buf) {
  taosMemoryFree(buf->buf);
  buf->buf = NULL;
}

S
slzhou 已提交
786 787
int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
  udfBlock->numOfRows = block->info.rows;
788
  udfBlock->numOfCols = taosArrayGetSize(block->pDataBlock);
H
Hongze Cheng 已提交
789
  udfBlock->udfCols = taosMemoryCalloc(taosArrayGetSize(block->pDataBlock), sizeof(SUdfColumn *));
S
slzhou 已提交
790
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
S
slzhou 已提交
791
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
H
Hongze Cheng 已提交
792 793
    SColumnInfoData *col = (SColumnInfoData *)taosArrayGet(block->pDataBlock, i);
    SUdfColumn      *udfCol = udfBlock->udfCols[i];
S
slzhou 已提交
794 795 796 797 798
    udfCol->colMeta.type = col->info.type;
    udfCol->colMeta.bytes = col->info.bytes;
    udfCol->colMeta.scale = col->info.scale;
    udfCol->colMeta.precision = col->info.precision;
    udfCol->colData.numOfRows = udfBlock->numOfRows;
S
slzhou@taodata.com 已提交
799
    udfCol->hasNull = col->hasNull;
S
shenglian zhou 已提交
800
    if (IS_VAR_DATA_TYPE(udfCol->colMeta.type)) {
S
slzhou 已提交
801 802 803 804 805
      udfCol->colData.varLenCol.varOffsetsLen = sizeof(int32_t) * udfBlock->numOfRows;
      udfCol->colData.varLenCol.varOffsets = taosMemoryMalloc(udfCol->colData.varLenCol.varOffsetsLen);
      memcpy(udfCol->colData.varLenCol.varOffsets, col->varmeta.offset, udfCol->colData.varLenCol.varOffsetsLen);
      udfCol->colData.varLenCol.payloadLen = colDataGetLength(col, udfBlock->numOfRows);
      udfCol->colData.varLenCol.payload = taosMemoryMalloc(udfCol->colData.varLenCol.payloadLen);
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
      if (col->reassigned) {
        for (int32_t row = 0; row < udfCol->colData.numOfRows; ++row) {
          char* pColData = col->pData + col->varmeta.offset[row];
          int32_t colSize = 0;
          if (col->info.type == TSDB_DATA_TYPE_JSON) {
            colSize = getJsonValueLen(pColData);
          } else {
            colSize = varDataTLen(pColData);
          }
          memcpy(udfCol->colData.varLenCol.payload, pColData, colSize);
          udfCol->colData.varLenCol.payload += colSize;
        }
      } else {
        memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
      }
S
slzhou 已提交
821
    } else {
S
slzhou 已提交
822 823 824
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
H
Hongze Cheng 已提交
825
      char *bitmap = udfCol->colData.fixLenCol.nullBitmap;
S
slzhou 已提交
826 827 828 829
      memcpy(bitmap, col->nullbitmap, bitmapLen);
      udfCol->colData.fixLenCol.dataLen = colDataGetLength(col, udfBlock->numOfRows);
      int32_t dataLen = udfCol->colData.fixLenCol.dataLen;
      udfCol->colData.fixLenCol.data = taosMemoryMalloc(udfCol->colData.fixLenCol.dataLen);
H
Hongze Cheng 已提交
830
      char *data = udfCol->colData.fixLenCol.data;
S
slzhou 已提交
831
      memcpy(data, col->pData, dataLen);
S
slzhou 已提交
832 833 834 835 836 837
    }
  }
  return 0;
}

int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
S
slzhou 已提交
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
  SUdfColumnMeta* meta = &udfCol->colMeta;

  SColumnInfoData colInfoData = createColumnInfoData(meta->type, meta->bytes, 1);
  blockDataAppendColInfo(block, &colInfoData);
  blockDataEnsureCapacity(block, udfCol->colData.numOfRows);

  SColumnInfoData *col = bdGetColumnInfoData(block, 0);
  for (int i = 0; i < udfCol->colData.numOfRows; ++i) {
    if (udfColDataIsNull(udfCol, i)) {
      colDataSetNULL(col, i);
    } else {
      char* data = udfColDataGetData(udfCol, i);
      colDataSetVal(col, i, data, false);
    }
  }
  block->info.rows = udfCol->colData.numOfRows;
  return 0;
}

int32_t convertUdfColumnToDataBlock2(SUdfColumn *udfCol, SSDataBlock *block) {
S
slzhou 已提交
858
  block->info.rows = udfCol->colData.numOfRows;
S
shenglian zhou 已提交
859
  block->info.hasVarCol = IS_VAR_DATA_TYPE(udfCol->colMeta.type);
S
slzhou 已提交
860 861

  block->pDataBlock = taosArrayInit(1, sizeof(SColumnInfoData));
H
Haojun Liao 已提交
862
  taosArrayPush(block->pDataBlock, &(SColumnInfoData){0});
S
slzhou 已提交
863
  SColumnInfoData *col = taosArrayGet(block->pDataBlock, 0);
H
Hongze Cheng 已提交
864
  SUdfColumnMeta  *meta = &udfCol->colMeta;
S
slzhou 已提交
865 866 867 868
  col->info.precision = meta->precision;
  col->info.bytes = meta->bytes;
  col->info.scale = meta->scale;
  col->info.type = meta->type;
S
slzhou@taodata.com 已提交
869
  col->hasNull = udfCol->hasNull;
S
slzhou 已提交
870 871 872
  SUdfColumnData *data = &udfCol->colData;

  if (!IS_VAR_DATA_TYPE(meta->type)) {
S
slzhou 已提交
873 874 875 876
    col->nullbitmap = taosMemoryMalloc(data->fixLenCol.nullBitmapLen);
    memcpy(col->nullbitmap, data->fixLenCol.nullBitmap, data->fixLenCol.nullBitmapLen);
    col->pData = taosMemoryMalloc(data->fixLenCol.dataLen);
    memcpy(col->pData, data->fixLenCol.data, data->fixLenCol.dataLen);
S
slzhou 已提交
877
  } else {
S
slzhou 已提交
878 879 880 881
    col->varmeta.offset = taosMemoryMalloc(data->varLenCol.varOffsetsLen);
    memcpy(col->varmeta.offset, data->varLenCol.varOffsets, data->varLenCol.varOffsetsLen);
    col->pData = taosMemoryMalloc(data->varLenCol.payloadLen);
    memcpy(col->pData, data->varLenCol.payload, data->varLenCol.payloadLen);
S
slzhou 已提交
882 883 884 885
  }
  return 0;
}

S
slzhou 已提交
886
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
887 888 889 890
  int32_t numOfRows = 0;
  for (int32_t i = 0; i < numOfCols; ++i) {
    numOfRows = (input[i].numOfRows > numOfRows) ? input[i].numOfRows : numOfRows;
  }
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

  // create the basic block info structure
  for(int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pInfo = input[i].columnData;
    SColumnInfoData d = {0};
    d.info = pInfo->info;

    blockDataAppendColInfo(output, &d);
  }

  blockDataEnsureCapacity(output, numOfRows);

  for(int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pDest = taosArrayGet(output->pDataBlock, i);

    SColumnInfoData* pColInfoData = input[i].columnData;
    colDataAssign(pDest, pColInfoData, input[i].numOfRows, &output->info);

    if (input[i].numOfRows < numOfRows) {
      int32_t startRow = input[i].numOfRows;
      int expandRows = numOfRows - startRow;
912 913
      bool isNull = colDataIsNull_s(pColInfoData, (input+i)->numOfRows - 1);
      if (isNull) {
914
        colDataSetNNULL(pDest, startRow, expandRows);
915
      } else {
916 917
        char* src = colDataGetData(pColInfoData, (input + i)->numOfRows - 1);
        for (int j = 0; j < expandRows; ++j) {
918
          colDataSetVal(pDest, startRow+j, src, false);
919
        }
920
        //colDataSetNItems(pColInfoData, startRow, data, expandRows);
921 922
      }
    }
923
  }
924

S
shenglian zhou 已提交
925 926
  output->info.rows = numOfRows;

S
slzhou 已提交
927 928 929 930
  return 0;
}

int32_t convertDataBlockToScalarParm(SSDataBlock *input, SScalarParam *output) {
931
  if (taosArrayGetSize(input->pDataBlock) != 1) {
S
slzhou 已提交
932 933 934 935
    fnError("scalar function only support one column");
    return -1;
  }
  output->numOfRows = input->info.rows;
S
slzhou 已提交
936 937

  output->columnData = taosMemoryMalloc(sizeof(SColumnInfoData));
H
Hongze Cheng 已提交
938 939
  memcpy(output->columnData, taosArrayGet(input->pDataBlock, 0), sizeof(SColumnInfoData));
  output->colAlloced = true;
S
slzhou 已提交
940

S
slzhou 已提交
941 942
  return 0;
}
S
slzhou 已提交
943

S
shenglian zhou 已提交
944
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
H
Hongze Cheng 已提交
945
// memory layout |---SUdfAggRes----|-----final result-----|---inter result----|
S
shenglian zhou 已提交
946 947 948
typedef struct SUdfAggRes {
  int8_t finalResNum;
  int8_t interResNum;
949
  int32_t interResBufLen;
H
Hongze Cheng 已提交
950 951
  char  *finalResBuf;
  char  *interResBuf;
S
shenglian zhou 已提交
952
} SUdfAggRes;
953

H
Hongze Cheng 已提交
954
void    onUdfcPipeClose(uv_handle_t *handle);
S
shenglian zhou 已提交
955
int32_t udfcGetUdfTaskResultFromUvTask(SClientUdfTask *task, SClientUvTaskNode *uvTask);
H
Hongze Cheng 已提交
956 957 958 959 960 961 962
void    udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf);
bool    isUdfcUvMsgComplete(SClientConnBuf *connBuf);
void    udfcUvHandleRsp(SClientUvConn *conn);
void    udfcUvHandleError(SClientUvConn *conn);
void    onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf);
void    onUdfcPipeWrite(uv_write_t *write, int status);
void    onUdfcPipeConnect(uv_connect_t *connect, int status);
S
shenglian zhou 已提交
963
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask);
S
shenglian zhou 已提交
964 965
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask);
int32_t udfcStartUvTask(SClientUvTaskNode *uvTask);
H
Hongze Cheng 已提交
966 967 968 969
void    udfcAsyncTaskCb(uv_async_t *async);
void    cleanUpUvTasks(SUdfcProxy *udfc);
void    udfStopAsyncCb(uv_async_t *async);
void    constructUdfService(void *argsThread);
S
shenglian zhou 已提交
970 971
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType);
int32_t doSetupUdf(char udfName[], UdfcFuncHandle *funcHandle);
H
Hongze Cheng 已提交
972
int     compareUdfcFuncSub(const void *elem1, const void *elem2);
S
shenglian zhou 已提交
973
int32_t doTeardownUdf(UdfcFuncHandle handle);
974

S
shenglian zhou 已提交
975
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
H
Hongze Cheng 已提交
976
                SSDataBlock *output, SUdfInterBuf *newState);
S
shenglian zhou 已提交
977 978
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf);
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState);
H
Hongze Cheng 已提交
979 980
int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
                          SUdfInterBuf *resultBuf);
S
shenglian zhou 已提交
981
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData);
H
Hongze Cheng 已提交
982
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output);
S
shenglian zhou 已提交
983 984 985 986 987
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output);

int32_t udfcOpen();
int32_t udfcClose();

H
Hongze Cheng 已提交
988
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle);
S
slzhou 已提交
989
void    releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle);
S
shenglian zhou 已提交
990 991
int32_t cleanUpUdfs();

H
Hongze Cheng 已提交
992 993
bool    udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv);
bool    udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo);
S
shenglian zhou 已提交
994
int32_t udfAggProcess(struct SqlFunctionCtx *pCtx);
H
Hongze Cheng 已提交
995
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock);
996

997 998
void cleanupNotExpiredUdfs();
void cleanupExpiredUdfs();
H
Hongze Cheng 已提交
999
int compareUdfcFuncSub(const void *elem1, const void *elem2) {
S
shenglian zhou 已提交
1000 1001 1002
  SUdfcFuncStub *stub1 = (SUdfcFuncStub *)elem1;
  SUdfcFuncStub *stub2 = (SUdfcFuncStub *)elem2;
  return strcmp(stub1->udfName, stub2->udfName);
1003 1004
}

H
Hongze Cheng 已提交
1005
int32_t acquireUdfFuncHandle(char *udfName, UdfcFuncHandle *pHandle) {
S
shenglian zhou 已提交
1006
  int32_t code = 0;
1007
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
S
shenglian zhou 已提交
1008
  SUdfcFuncStub key = {0};
S
slzhou 已提交
1009
  strncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
1010
  int32_t stubIndex = taosArraySearchIdx(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
S
shenglian zhou 已提交
1011
  if (stubIndex != -1) {
1012
    SUdfcFuncStub *foundStub = taosArrayGet(gUdfcProxy.udfStubs, stubIndex);
S
shenglian zhou 已提交
1013
    UdfcFuncHandle handle = foundStub->handle;
1014
    int64_t currUs = taosGetTimestampUs();
1015 1016 1017 1018 1019 1020 1021 1022
    bool expired = (currUs - foundStub->createTime) >= 10 * 1000 * 1000;
    if (!expired) {
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
        *pHandle = foundStub->handle;
        ++foundStub->refCount;
        uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
        return 0;
      } else {
S
slzhou 已提交
1023
        fnInfo("udf invalid handle for %s, refCount: %d, create time: %" PRId64 ". remove it from cache", udfName,
1024 1025 1026
               foundStub->refCount, foundStub->createTime);
        taosArrayRemove(gUdfcProxy.udfStubs, stubIndex);
      }
1027
    } else {
S
slzhou 已提交
1028
      fnInfo("udf handle expired for %s, will setup udf. move it to expired list", udfName);
1029
      taosArrayRemove(gUdfcProxy.udfStubs, stubIndex);
1030 1031
      taosArrayPush(gUdfcProxy.expiredUdfStubs, foundStub);
      taosArraySort(gUdfcProxy.expiredUdfStubs, compareUdfcFuncSub);
1032
    }
S
shenglian zhou 已提交
1033 1034 1035 1036 1037
  }
  *pHandle = NULL;
  code = doSetupUdf(udfName, pHandle);
  if (code == TSDB_CODE_SUCCESS) {
    SUdfcFuncStub stub = {0};
S
shenglian zhou 已提交
1038
    strncpy(stub.udfName, udfName, TSDB_FUNC_NAME_LEN);
S
shenglian zhou 已提交
1039 1040
    stub.handle = *pHandle;
    ++stub.refCount;
1041
    stub.createTime = taosGetTimestampUs();
1042 1043
    taosArrayPush(gUdfcProxy.udfStubs, &stub);
    taosArraySort(gUdfcProxy.udfStubs, compareUdfcFuncSub);
1044
  } else {
S
shenglian zhou 已提交
1045
    *pHandle = NULL;
1046 1047
  }

1048
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
S
shenglian zhou 已提交
1049
  return code;
1050 1051
}

S
slzhou 已提交
1052
void releaseUdfFuncHandle(char *udfName, UdfcFuncHandle handle) {
1053
  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
S
shenglian zhou 已提交
1054
  SUdfcFuncStub key = {0};
S
slzhou 已提交
1055
  strncpy(key.udfName, udfName, TSDB_FUNC_NAME_LEN);
1056
  SUdfcFuncStub *foundStub = taosArraySearch(gUdfcProxy.udfStubs, &key, compareUdfcFuncSub, TD_EQ);
1057 1058
  SUdfcFuncStub *expiredStub = taosArraySearch(gUdfcProxy.expiredUdfStubs, &key, compareUdfcFuncSub, TD_EQ);
  if (!foundStub && !expiredStub) {
1059
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
S
shenglian zhou 已提交
1060
    return;
1061
  }
S
slzhou 已提交
1062
  if (foundStub != NULL && foundStub->handle == handle && foundStub->refCount > 0) {
S
shenglian zhou 已提交
1063
    --foundStub->refCount;
1064
  }
S
slzhou 已提交
1065
  if (expiredStub != NULL && expiredStub->handle == handle && expiredStub->refCount > 0) {
1066 1067
    --expiredStub->refCount;
  }
1068
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
1069 1070
}

1071
void cleanupExpiredUdfs() {
1072
  int32_t i = 0;
1073 1074 1075
  SArray *expiredUdfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
  while (i < taosArrayGetSize(gUdfcProxy.expiredUdfStubs)) {
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.expiredUdfStubs, i);
S
shenglian zhou 已提交
1076
    if (stub->refCount == 0) {
1077
      fnInfo("tear down udf. expired. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle, stub->refCount);
S
shenglian zhou 已提交
1078 1079
      doTeardownUdf(stub->handle);
    } else {
1080
      fnInfo("udf still in use. expired. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p", stub->udfName,
1081
             stub->refCount, stub->createTime, stub->handle);
S
shenglian zhou 已提交
1082
      UdfcFuncHandle handle = stub->handle;
H
Hongze Cheng 已提交
1083
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
1084
        taosArrayPush(expiredUdfStubs, stub);
1085
      } else {
1086
        fnInfo("udf invalid handle for %s, expired. refCount: %d, create time: %" PRId64 ". remove it from cache",
1087
               stub->udfName, stub->refCount, stub->createTime);
1088
      }
1089
    }
S
shenglian zhou 已提交
1090
    ++i;
1091
  }
1092 1093 1094
  taosArrayDestroy(gUdfcProxy.expiredUdfStubs);
  gUdfcProxy.expiredUdfStubs = expiredUdfStubs;
}
1095

1096 1097 1098 1099 1100
void cleanupNotExpiredUdfs() {
  SArray *udfStubs = taosArrayInit(16, sizeof(SUdfcFuncStub));
  int32_t i = 0;
  while (i < taosArrayGetSize(gUdfcProxy.udfStubs)) {
    SUdfcFuncStub *stub = taosArrayGet(gUdfcProxy.udfStubs, i);
1101
    if (stub->refCount == 0) {
1102
      fnInfo("tear down udf. udf name: %s, handle: %p, ref count: %d", stub->udfName, stub->handle, stub->refCount);
1103 1104
      doTeardownUdf(stub->handle);
    } else {
1105
      fnInfo("udf still in use. udf name: %s, ref count: %d, create time: %" PRId64 ", handle: %p", stub->udfName,
1106 1107 1108
             stub->refCount, stub->createTime, stub->handle);
      UdfcFuncHandle handle = stub->handle;
      if (handle != NULL && ((SUdfcUvSession *)handle)->udfUvPipe != NULL) {
1109
        taosArrayPush(udfStubs, stub);
1110
      } else {
1111
        fnInfo("udf invalid handle for %s, refCount: %d, create time: %" PRId64 ". remove it from cache",
1112 1113 1114 1115 1116
               stub->udfName, stub->refCount, stub->createTime);
      }
    }
    ++i;
  }
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  taosArrayDestroy(gUdfcProxy.udfStubs);
  gUdfcProxy.udfStubs = udfStubs;
}

int32_t cleanUpUdfs() {
  int8_t initialized = atomic_load_8(&gUdfcProxy.initialized);
  if (!initialized) {
    return TSDB_CODE_SUCCESS;
  }

  uv_mutex_lock(&gUdfcProxy.udfStubsMutex);
  if ((gUdfcProxy.udfStubs == NULL || taosArrayGetSize(gUdfcProxy.udfStubs) == 0) &&
      (gUdfcProxy.expiredUdfStubs == NULL || taosArrayGetSize(gUdfcProxy.expiredUdfStubs) == 0)) {
    uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
    return TSDB_CODE_SUCCESS;
  }

  cleanupNotExpiredUdfs();
  cleanupExpiredUdfs();

1137
  uv_mutex_unlock(&gUdfcProxy.udfStubsMutex);
S
shenglian zhou 已提交
1138 1139
  return 0;
}
1140

S
shenglian zhou 已提交
1141 1142
int32_t callUdfScalarFunc(char *udfName, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
  UdfcFuncHandle handle = NULL;
H
Hongze Cheng 已提交
1143
  int32_t        code = acquireUdfFuncHandle(udfName, &handle);
S
shenglian zhou 已提交
1144 1145 1146
  if (code != 0) {
    return code;
  }
1147

S
shenglian zhou 已提交
1148 1149
  SUdfcUvSession *session = handle;
  code = doCallUdfScalarFunc(handle, input, numOfCols, output);
1150 1151
  if (code != TSDB_CODE_SUCCESS) {
    fnError("udfc scalar function execution failure");
S
slzhou 已提交
1152
    releaseUdfFuncHandle(udfName, handle);
1153 1154 1155
    return code;
  }

S
shenglian zhou 已提交
1156 1157 1158
  if (output->columnData == NULL) {
    fnError("udfc scalar function calculate error. no column data");
    code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
1159
  } else {
S
slzhou 已提交
1160
    if (session->outputType != output->columnData->info.type || session->bytes != output->columnData->info.bytes) {
H
Hongze Cheng 已提交
1161
      fnError("udfc scalar function calculate error. type mismatch. session type: %d(%d), output type: %d(%d)",
S
slzhou 已提交
1162
              session->outputType, session->bytes, output->columnData->info.type, output->columnData->info.bytes);
S
shenglian zhou 已提交
1163 1164
      code = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
    }
1165
  }
S
slzhou 已提交
1166
  releaseUdfFuncHandle(udfName, handle);
S
shenglian zhou 已提交
1167
  return code;
1168
}
1169

H
Hongze Cheng 已提交
1170
bool udfAggGetEnv(struct SFunctionNode *pFunc, SFuncExecEnv *pEnv) {
S
shenglian zhou 已提交
1171 1172
  if (fmIsScalarFunc(pFunc->funcId)) {
    return false;
S
shenglian zhou 已提交
1173
  }
S
shenglian zhou 已提交
1174 1175
  pEnv->calcMemSize = sizeof(SUdfAggRes) + pFunc->node.resType.bytes + pFunc->udfBufSize;
  return true;
1176 1177
}

H
Hongze Cheng 已提交
1178
bool udfAggInit(struct SqlFunctionCtx *pCtx, struct SResultRowEntryInfo *pResultCellInfo) {
S
shenglian zhou 已提交
1179 1180 1181 1182
  if (functionSetup(pCtx, pResultCellInfo) != true) {
    return false;
  }
  UdfcFuncHandle handle;
H
Hongze Cheng 已提交
1183
  int32_t        udfCode = 0;
S
shenglian zhou 已提交
1184 1185 1186 1187 1188
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
    fnError("udfAggInit error. step doSetupUdf. udf code: %d", udfCode);
    return false;
  }
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
H
Hongze Cheng 已提交
1189
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(pResultCellInfo);
S
slzhou 已提交
1190
  int32_t         envSize = sizeof(SUdfAggRes) + session->bytes + session->bufSize;
S
shenglian zhou 已提交
1191 1192
  memset(udfRes, 0, envSize);

H
Hongze Cheng 已提交
1193
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
S
slzhou 已提交
1194
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
S
shenglian zhou 已提交
1195 1196 1197 1198

  SUdfInterBuf buf = {0};
  if ((udfCode = doCallUdfAggInit(handle, &buf)) != 0) {
    fnError("udfAggInit error. step doCallUdfAggInit. udf code: %d", udfCode);
S
slzhou 已提交
1199
    releaseUdfFuncHandle(pCtx->udfName, handle);
S
shenglian zhou 已提交
1200 1201 1202 1203
    return false;
  }
  if (buf.bufLen <= session->bufSize) {
    memcpy(udfRes->interResBuf, buf.buf, buf.bufLen);
1204 1205
    udfRes->interResBufLen = buf.bufLen;
    udfRes->interResNum = buf.numOfResult;
S
shenglian zhou 已提交
1206 1207
  } else {
    fnError("udfc inter buf size %d is greater than function bufSize %d", buf.bufLen, session->bufSize);
S
slzhou 已提交
1208
    releaseUdfFuncHandle(pCtx->udfName, handle);
S
shenglian zhou 已提交
1209 1210
    return false;
  }
S
slzhou 已提交
1211
  releaseUdfFuncHandle(pCtx->udfName, handle);
S
shenglian zhou 已提交
1212 1213 1214 1215 1216
  freeUdfInterBuf(&buf);
  return true;
}

int32_t udfAggProcess(struct SqlFunctionCtx *pCtx) {
H
Hongze Cheng 已提交
1217
  int32_t        udfCode = 0;
S
shenglian zhou 已提交
1218 1219 1220 1221 1222 1223 1224
  UdfcFuncHandle handle = 0;
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
    return udfCode;
  }

  SUdfcUvSession *session = handle;
H
Hongze Cheng 已提交
1225 1226
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
S
slzhou 已提交
1227
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
S
shenglian zhou 已提交
1228

H
Hongze Cheng 已提交
1229 1230 1231 1232
  SInputColumnInfoData *pInput = &pCtx->input;
  int32_t               numOfCols = pInput->numOfInputCols;
  int32_t               start = pInput->startRowIndex;
  int32_t               numOfRows = pInput->numOfRows;
S
shenglian zhou 已提交
1233

H
Hongze Cheng 已提交
1234
  SSDataBlock *pTempBlock = createDataBlock();
1235
  pTempBlock->info.rows = pInput->totalRows;
H
Haojun Liao 已提交
1236
  pTempBlock->info.id.uid = pInput->uid;
S
shenglian zhou 已提交
1237
  for (int32_t i = 0; i < numOfCols; ++i) {
1238
    blockDataAppendColInfo(pTempBlock, pInput->pData[i]);
S
shenglian zhou 已提交
1239 1240
  }

1241
  SSDataBlock *inputBlock = blockDataExtractBlock(pTempBlock, start, numOfRows);
S
shenglian zhou 已提交
1242

1243
  SUdfInterBuf state = {.buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
S
shenglian zhou 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252
  SUdfInterBuf newState = {0};

  udfCode = doCallUdfAggProcess(session, inputBlock, &state, &newState);
  if (udfCode != 0) {
    fnError("udfAggProcess error. code: %d", udfCode);
    newState.numOfResult = 0;
  } else {
    if (newState.bufLen <= session->bufSize) {
      memcpy(udfRes->interResBuf, newState.buf, newState.bufLen);
1253 1254
      udfRes->interResBufLen = newState.bufLen;
      udfRes->interResNum = newState.numOfResult;
S
shenglian zhou 已提交
1255 1256 1257 1258 1259
    } else {
      fnError("udfc inter buf size %d is greater than function bufSize %d", newState.bufLen, session->bufSize);
      udfCode = TSDB_CODE_UDF_INVALID_BUFSIZE;
    }
  }
1260 1261

  GET_RES_INFO(pCtx)->numOfRes = udfRes->interResNum;
S
shenglian zhou 已提交
1262 1263

  blockDataDestroy(inputBlock);
1264 1265 1266

  taosArrayDestroy(pTempBlock->pDataBlock);
  taosMemoryFree(pTempBlock);
S
shenglian zhou 已提交
1267

S
slzhou 已提交
1268
  releaseUdfFuncHandle(pCtx->udfName, handle);
S
shenglian zhou 已提交
1269 1270 1271 1272
  freeUdfInterBuf(&newState);
  return udfCode;
}

H
Hongze Cheng 已提交
1273 1274
int32_t udfAggFinalize(struct SqlFunctionCtx *pCtx, SSDataBlock *pBlock) {
  int32_t        udfCode = 0;
S
shenglian zhou 已提交
1275 1276 1277 1278 1279 1280 1281
  UdfcFuncHandle handle = 0;
  if ((udfCode = acquireUdfFuncHandle((char *)pCtx->udfName, &handle)) != 0) {
    fnError("udfAggProcess  error. step acquireUdfFuncHandle. udf code: %d", udfCode);
    return udfCode;
  }

  SUdfcUvSession *session = handle;
H
Hongze Cheng 已提交
1282 1283
  SUdfAggRes     *udfRes = (SUdfAggRes *)GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  udfRes->finalResBuf = (char *)udfRes + sizeof(SUdfAggRes);
S
slzhou 已提交
1284
  udfRes->interResBuf = (char *)udfRes + sizeof(SUdfAggRes) + session->bytes;
S
shenglian zhou 已提交
1285 1286

  SUdfInterBuf resultBuf = {0};
1287
  SUdfInterBuf state = {.buf = udfRes->interResBuf, .bufLen = udfRes->interResBufLen, .numOfResult = udfRes->interResNum};
H
Hongze Cheng 已提交
1288 1289
  int32_t      udfCallCode = 0;
  udfCallCode = doCallUdfAggFinalize(session, &state, &resultBuf);
S
shenglian zhou 已提交
1290 1291 1292 1293
  if (udfCallCode != 0) {
    fnError("udfAggFinalize error. doCallUdfAggFinalize step. udf code:%d", udfCallCode);
    GET_RES_INFO(pCtx)->numOfRes = 0;
  } else {
1294 1295
    if (resultBuf.numOfResult == 0) {
      udfRes->finalResNum = 0;
S
shenglian zhou 已提交
1296
      GET_RES_INFO(pCtx)->numOfRes = 0;
1297
    } else {
S
shenglian zhou 已提交
1298
      if (resultBuf.bufLen <= session->bytes) {
1299 1300 1301 1302 1303 1304 1305 1306
        memcpy(udfRes->finalResBuf, resultBuf.buf, resultBuf.bufLen);
        udfRes->finalResNum = resultBuf.numOfResult;
        GET_RES_INFO(pCtx)->numOfRes = udfRes->finalResNum;
      } else {
        fnError("udfc inter buf size %d is greater than function output size %d", resultBuf.bufLen, session->bytes);
        GET_RES_INFO(pCtx)->numOfRes = 0;
        udfCallCode = TSDB_CODE_UDF_INVALID_OUTPUT_TYPE;
      }
S
shenglian zhou 已提交
1307 1308 1309 1310 1311 1312
    }
  }

  freeUdfInterBuf(&resultBuf);

  int32_t numOfResults = functionFinalizeWithResultBuf(pCtx, pBlock, udfRes->finalResBuf);
S
slzhou 已提交
1313
  releaseUdfFuncHandle(pCtx->udfName, handle);
S
shenglian zhou 已提交
1314 1315 1316 1317 1318 1319
  return udfCallCode == 0 ? numOfResults : udfCallCode;
}

void onUdfcPipeClose(uv_handle_t *handle) {
  SClientUvConn *conn = handle->data;
  if (!QUEUE_EMPTY(&conn->taskQueue)) {
H
Hongze Cheng 已提交
1320
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
S
shenglian zhou 已提交
1321 1322 1323 1324 1325
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
    task->errCode = 0;
    QUEUE_REMOVE(&task->procTaskQueue);
    uv_sem_post(&task->taskSem);
  }
1326
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
1327 1328 1329
  if (conn->session != NULL) {
    conn->session->udfUvPipe = NULL;
  }
1330
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
S
shenglian zhou 已提交
1331 1332
  taosMemoryFree(conn->readBuf.buf);
  taosMemoryFree(conn);
H
Hongze Cheng 已提交
1333
  taosMemoryFree((uv_pipe_t *)handle);
S
shenglian zhou 已提交
1334 1335 1336 1337 1338 1339 1340
}

int32_t udfcGetUdfTaskResultFromUvTask(SClientUdfTask *task, SClientUvTaskNode *uvTask) {
  fnDebug("udfc get uv task result. task: %p, uvTask: %p", task, uvTask);
  if (uvTask->type == UV_TASK_REQ_RSP) {
    if (uvTask->rspBuf.base != NULL) {
      SUdfResponse rsp = {0};
H
Hongze Cheng 已提交
1341
      void        *buf = decodeUdfResponse(uvTask->rspBuf.base, &rsp);
S
shenglian zhou 已提交
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
      task->errCode = rsp.code;

      switch (task->type) {
        case UDF_TASK_SETUP: {
          task->_setup.rsp = rsp.setupRsp;
          break;
        }
        case UDF_TASK_CALL: {
          task->_call.rsp = rsp.callRsp;
          break;
        }
        case UDF_TASK_TEARDOWN: {
          task->_teardown.rsp = rsp.teardownRsp;
          break;
        }
        default: {
          break;
        }
      }

      // TODO: the call buffer is setup and freed by udf invocation
      taosMemoryFree(uvTask->rspBuf.base);
    } else {
      task->errCode = uvTask->errCode;
    }
  } else if (uvTask->type == UV_TASK_CONNECT) {
    task->errCode = uvTask->errCode;
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
    task->errCode = uvTask->errCode;
  }
  return 0;
}

void udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
1376
  SClientUvConn  *conn = handle->data;
S
shenglian zhou 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
  SClientConnBuf *connBuf = &conn->readBuf;

  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
  if (connBuf->cap == 0) {
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
    if (connBuf->buf) {
      connBuf->len = 0;
      connBuf->cap = msgHeadSize;
      connBuf->total = -1;

      buf->base = connBuf->buf;
      buf->len = connBuf->cap;
    } else {
      fnError("udfc allocate buffer failure. size: %d", msgHeadSize);
      buf->base = NULL;
      buf->len = 0;
    }
1394 1395 1396
  } else if (connBuf->total == -1 && connBuf->len < msgHeadSize) {
    buf->base = connBuf->buf + connBuf->len;
    buf->len = msgHeadSize - connBuf->len;
S
shenglian zhou 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
  } else {
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
    if (resultBuf) {
      connBuf->buf = resultBuf;
      buf->base = connBuf->buf + connBuf->len;
      buf->len = connBuf->cap - connBuf->len;
    } else {
      fnError("udfc re-allocate buffer failure. size: %d", connBuf->cap);
      buf->base = NULL;
      buf->len = 0;
    }
  }

1411
  fnDebug("udfc uv alloc buffer: cap - len - total : %d - %d - %d", connBuf->cap, connBuf->len, connBuf->total);
S
shenglian zhou 已提交
1412 1413 1414 1415
}

bool isUdfcUvMsgComplete(SClientConnBuf *connBuf) {
  if (connBuf->total == -1 && connBuf->len >= sizeof(int32_t)) {
H
Hongze Cheng 已提交
1416
    connBuf->total = *(int32_t *)(connBuf->buf);
S
shenglian zhou 已提交
1417 1418
  }
  if (connBuf->len == connBuf->cap && connBuf->total == connBuf->cap) {
1419
    fnDebug("udfc complete message is received, now handle it");
S
shenglian zhou 已提交
1420 1421 1422 1423 1424 1425 1426
    return true;
  }
  return false;
}

void udfcUvHandleRsp(SClientUvConn *conn) {
  SClientConnBuf *connBuf = &conn->readBuf;
H
Hongze Cheng 已提交
1427
  int64_t         seqNum = *(int64_t *)(connBuf->buf + sizeof(int32_t));  // msglen then seqnum
S
shenglian zhou 已提交
1428 1429

  if (QUEUE_EMPTY(&conn->taskQueue)) {
H
Hongze Cheng 已提交
1430
    fnError("udfc no task waiting on connection. response seqnum:%" PRId64, seqNum);
S
shenglian zhou 已提交
1431 1432
    return;
  }
H
Hongze Cheng 已提交
1433
  bool               found = false;
S
shenglian zhou 已提交
1434
  SClientUvTaskNode *taskFound = NULL;
H
Hongze Cheng 已提交
1435
  QUEUE             *h = QUEUE_NEXT(&conn->taskQueue);
S
shenglian zhou 已提交
1436 1437 1438
  SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);

  while (h != &conn->taskQueue) {
1439
    fnDebug("udfc handle response iterate through queue. uvTask:%" PRId64 "-%p", task->seqNum, task);
S
shenglian zhou 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
    if (task->seqNum == seqNum) {
      if (found == false) {
        found = true;
        taskFound = task;
      } else {
        fnError("udfc more than one task waiting for the same response");
        continue;
      }
    }
    h = QUEUE_NEXT(h);
    task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
  }

  if (taskFound) {
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
    QUEUE_REMOVE(&taskFound->connTaskQueue);
    QUEUE_REMOVE(&taskFound->procTaskQueue);
    uv_sem_post(&taskFound->taskSem);
  } else {
    fnError("no task is waiting for the response.");
  }
  connBuf->buf = NULL;
  connBuf->total = -1;
  connBuf->len = 0;
  connBuf->cap = 0;
}

void udfcUvHandleError(SClientUvConn *conn) {
1468
  fnDebug("handle error on conn: %p, pipe: %p", conn, conn->pipe);
S
shenglian zhou 已提交
1469
  while (!QUEUE_EMPTY(&conn->taskQueue)) {
H
Hongze Cheng 已提交
1470
    QUEUE             *h = QUEUE_HEAD(&conn->taskQueue);
S
shenglian zhou 已提交
1471 1472 1473 1474 1475 1476
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
    task->errCode = TSDB_CODE_UDF_PIPE_READ_ERR;
    QUEUE_REMOVE(&task->connTaskQueue);
    QUEUE_REMOVE(&task->procTaskQueue);
    uv_sem_post(&task->taskSem);
  }
S
slzhou 已提交
1477
  if (!uv_is_closing((uv_handle_t *)conn->pipe)) {
1478 1479
    uv_close((uv_handle_t *)conn->pipe, onUdfcPipeClose);
  }
S
shenglian zhou 已提交
1480 1481 1482
}

void onUdfcPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
1483
  fnDebug("udfc client %p, client read from pipe. nread: %zd", client, nread);
S
shenglian zhou 已提交
1484 1485
  if (nread == 0) return;

H
Hongze Cheng 已提交
1486
  SClientUvConn  *conn = client->data;
S
shenglian zhou 已提交
1487 1488 1489 1490 1491 1492 1493 1494
  SClientConnBuf *connBuf = &conn->readBuf;
  if (nread > 0) {
    connBuf->len += nread;
    if (isUdfcUvMsgComplete(connBuf)) {
      udfcUvHandleRsp(conn);
    }
  }
  if (nread < 0) {
1495
    fnError("udfc client pipe %p read error: %zd(%s).", client, nread, uv_strerror(nread));
S
shenglian zhou 已提交
1496 1497 1498 1499
    if (nread == UV_EOF) {
      fnError("\tudfc client pipe %p closed", client);
    }
    udfcUvHandleError(conn);
1500 1501 1502
  }
}

1503 1504 1505 1506
void onUdfcPipeWrite(uv_write_t *write, int status) {
  SClientUvConn *conn = write->data;
  if (status < 0) {
    fnError("udfc client connection %p write failed. status: %d(%s)", conn, status, uv_strerror(status));
1507
    udfcUvHandleError(conn);
1508 1509
  } else {
    fnDebug("udfc client connection %p write succeed", conn);
1510
  }
wafwerar's avatar
wafwerar 已提交
1511
  taosMemoryFree(write);
1512
}
H
Haojun Liao 已提交
1513

1514
void onUdfcPipeConnect(uv_connect_t *connect, int status) {
1515 1516
  SClientUvTaskNode *uvTask = connect->data;
  if (status != 0) {
H
Hongze Cheng 已提交
1517
    fnError("client connect error, task seq: %" PRId64 ", code: %s", uvTask->seqNum, uv_strerror(status));
H
Haojun Liao 已提交
1518
  }
1519 1520 1521
  uvTask->errCode = status;

  uv_read_start((uv_stream_t *)uvTask->pipe, udfcAllocateBuffer, onUdfcPipeRead);
wafwerar's avatar
wafwerar 已提交
1522
  taosMemoryFree(connect);
S
shenglian zhou 已提交
1523
  QUEUE_REMOVE(&uvTask->procTaskQueue);
1524
  uv_sem_post(&uvTask->taskSem);
1525
}
H
Haojun Liao 已提交
1526

S
shenglian zhou 已提交
1527
int32_t udfcInitializeUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode *uvTask) {
1528
  uvTask->type = uvTaskType;
1529
  uvTask->udfc = task->session->udfc;
1530 1531 1532

  if (uvTaskType == UV_TASK_CONNECT) {
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
S
slzhou 已提交
1533
    uvTask->pipe = task->session->udfUvPipe;
1534 1535
    SUdfRequest request;
    request.type = task->type;
H
Hongze Cheng 已提交
1536
    request.seqNum = atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
1537 1538

    if (task->type == UDF_TASK_SETUP) {
S
shenglian zhou 已提交
1539
      request.setup = task->_setup.req;
1540 1541
      request.type = UDF_TASK_SETUP;
    } else if (task->type == UDF_TASK_CALL) {
S
shenglian zhou 已提交
1542
      request.call = task->_call.req;
1543 1544
      request.type = UDF_TASK_CALL;
    } else if (task->type == UDF_TASK_TEARDOWN) {
S
shenglian zhou 已提交
1545
      request.teardown = task->_teardown.req;
1546 1547
      request.type = UDF_TASK_TEARDOWN;
    } else {
S
shenglian zhou 已提交
1548
      fnError("udfc create uv task, invalid task type : %d", task->type);
1549
    }
1550 1551
    int32_t bufLen = encodeUdfRequest(NULL, &request);
    request.msgLen = bufLen;
S
slzhou 已提交
1552 1553
    void *bufBegin = taosMemoryMalloc(bufLen);
    void *buf = bufBegin;
1554
    encodeUdfRequest(&buf, &request);
S
slzhou 已提交
1555
    uvTask->reqBuf = uv_buf_init(bufBegin, bufLen);
1556 1557
    uvTask->seqNum = request.seqNum;
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
S
slzhou 已提交
1558
    uvTask->pipe = task->session->udfUvPipe;
1559 1560
  }
  uv_sem_init(&uvTask->taskSem, 0);
H
Haojun Liao 已提交
1561

1562 1563
  return 0;
}
H
Haojun Liao 已提交
1564

S
slzhou 已提交
1565
int32_t udfcQueueUvTask(SClientUvTaskNode *uvTask) {
1566
  fnDebug("queue uv task to event loop, uvTask: %d-%p", uvTask->type, uvTask);
1567 1568 1569 1570 1571
  SUdfcProxy *udfc = uvTask->udfc;
  uv_mutex_lock(&udfc->taskQueueMutex);
  QUEUE_INSERT_TAIL(&udfc->taskQueue, &uvTask->recvTaskQueue);
  uv_mutex_unlock(&udfc->taskQueueMutex);
  uv_async_send(&udfc->loopTaskAync);
H
Haojun Liao 已提交
1572

1573
  uv_sem_wait(&uvTask->taskSem);
H
Hongze Cheng 已提交
1574
  fnInfo("udfc uvTask finished. uvTask:%" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
1575
  uv_sem_destroy(&uvTask->taskSem);
H
Haojun Liao 已提交
1576

1577 1578
  return 0;
}
H
Haojun Liao 已提交
1579

S
slzhou 已提交
1580
int32_t udfcStartUvTask(SClientUvTaskNode *uvTask) {
H
Hongze Cheng 已提交
1581
  fnDebug("event loop start uv task. uvTask: %" PRId64 "-%d-%p", uvTask->seqNum, uvTask->type, uvTask);
1582 1583
  int32_t code = 0;

1584 1585
  switch (uvTask->type) {
    case UV_TASK_CONNECT: {
wafwerar's avatar
wafwerar 已提交
1586
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
1587
      uv_pipe_init(&uvTask->udfc->uvLoop, pipe, 0);
1588
      uvTask->pipe = pipe;
H
Haojun Liao 已提交
1589

S
slzhou 已提交
1590
      SClientUvConn *conn = taosMemoryCalloc(1, sizeof(SClientUvConn));
1591 1592 1593 1594 1595
      conn->pipe = pipe;
      conn->readBuf.len = 0;
      conn->readBuf.cap = 0;
      conn->readBuf.buf = 0;
      conn->readBuf.total = -1;
S
shenglian zhou 已提交
1596
      QUEUE_INIT(&conn->taskQueue);
H
Haojun Liao 已提交
1597

1598 1599
      pipe->data = conn;

wafwerar's avatar
wafwerar 已提交
1600
      uv_connect_t *connReq = taosMemoryMalloc(sizeof(uv_connect_t));
1601
      connReq->data = uvTask;
1602
      uv_pipe_connect(connReq, pipe, uvTask->udfc->udfdPipeName, onUdfcPipeConnect);
1603
      code = 0;
H
Haojun Liao 已提交
1604
      break;
1605 1606 1607
    }
    case UV_TASK_REQ_RSP: {
      uv_pipe_t *pipe = uvTask->pipe;
1608
      if (pipe == NULL) {
S
shenglian zhou 已提交
1609
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
1610 1611
      } else {
        uv_write_t *write = taosMemoryMalloc(sizeof(uv_write_t));
1612
        write->data = pipe->data;
H
Hongze Cheng 已提交
1613
        QUEUE *connTaskQueue = &((SClientUvConn *)pipe->data)->taskQueue;
1614 1615
        QUEUE_INSERT_TAIL(connTaskQueue, &uvTask->connTaskQueue);
        int err = uv_write(write, (uv_stream_t *)pipe, &uvTask->reqBuf, 1, onUdfcPipeWrite);
1616
        if (err != 0) {
S
slzhou 已提交
1617
          taosMemoryFree(write);
1618
          fnError("udfc event loop start req_rsp task uv_write failed. uvtask: %p, code: %s", uvTask, uv_strerror(err));
1619 1620
        }
        code = err;
1621
      }
1622 1623 1624
      break;
    }
    case UV_TASK_DISCONNECT: {
1625 1626
      uv_pipe_t *pipe = uvTask->pipe;
      if (pipe == NULL) {
S
shenglian zhou 已提交
1627
        code = TSDB_CODE_UDF_PIPE_NOT_EXIST;
1628 1629 1630
      } else {
        SClientUvConn *conn = pipe->data;
        QUEUE_INSERT_TAIL(&conn->taskQueue, &uvTask->connTaskQueue);
S
slzhou 已提交
1631
        if (!uv_is_closing((uv_handle_t *)uvTask->pipe)) {
1632 1633
          uv_close((uv_handle_t *)uvTask->pipe, onUdfcPipeClose);
        }
1634 1635
        code = 0;
      }
1636 1637 1638
      break;
    }
    default: {
H
Hongze Cheng 已提交
1639
      fnError("udfc event loop unknown task type.") break;
1640 1641
    }
  }
H
Haojun Liao 已提交
1642

1643
  return code;
1644
}
H
Haojun Liao 已提交
1645

1646
void udfcAsyncTaskCb(uv_async_t *async) {
1647
  SUdfcProxy *udfc = async->data;
H
Hongze Cheng 已提交
1648
  QUEUE       wq;
1649

1650 1651 1652
  uv_mutex_lock(&udfc->taskQueueMutex);
  QUEUE_MOVE(&udfc->taskQueue, &wq);
  uv_mutex_unlock(&udfc->taskQueueMutex);
1653

S
shenglian zhou 已提交
1654
  while (!QUEUE_EMPTY(&wq)) {
H
Hongze Cheng 已提交
1655
    QUEUE *h = QUEUE_HEAD(&wq);
S
shenglian zhou 已提交
1656 1657
    QUEUE_REMOVE(h);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
H
Hongze Cheng 已提交
1658
    int32_t            code = udfcStartUvTask(task);
1659 1660
    if (code == 0) {
      QUEUE_INSERT_TAIL(&udfc->uvProcTaskQueue, &task->procTaskQueue);
1661 1662 1663
    } else {
      task->errCode = code;
      uv_sem_post(&task->taskSem);
1664
    }
1665 1666 1667
  }
}

1668
void cleanUpUvTasks(SUdfcProxy *udfc) {
H
Hongze Cheng 已提交
1669
  fnDebug("clean up uv tasks") QUEUE wq;
1670

1671 1672 1673
  uv_mutex_lock(&udfc->taskQueueMutex);
  QUEUE_MOVE(&udfc->taskQueue, &wq);
  uv_mutex_unlock(&udfc->taskQueueMutex);
1674

S
shenglian zhou 已提交
1675
  while (!QUEUE_EMPTY(&wq)) {
H
Hongze Cheng 已提交
1676
    QUEUE *h = QUEUE_HEAD(&wq);
S
shenglian zhou 已提交
1677 1678
    QUEUE_REMOVE(h);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
1679
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
1680
      task->errCode = TSDB_CODE_UDF_STOPPING;
1681 1682 1683 1684
    }
    uv_sem_post(&task->taskSem);
  }

1685
  while (!QUEUE_EMPTY(&udfc->uvProcTaskQueue)) {
H
Hongze Cheng 已提交
1686
    QUEUE *h = QUEUE_HEAD(&udfc->uvProcTaskQueue);
S
shenglian zhou 已提交
1687 1688
    QUEUE_REMOVE(h);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, procTaskQueue);
1689
    if (udfc->udfcState == UDFC_STATE_STOPPING) {
1690
      task->errCode = TSDB_CODE_UDF_STOPPING;
S
shenglian zhou 已提交
1691 1692 1693 1694
    }
    uv_sem_post(&task->taskSem);
  }
}
1695

S
shenglian zhou 已提交
1696
void udfStopAsyncCb(uv_async_t *async) {
1697
  SUdfcProxy *udfc = async->data;
1698
  cleanUpUvTasks(udfc);
1699 1700
  if (udfc->udfcState == UDFC_STATE_STOPPING) {
    uv_stop(&udfc->uvLoop);
S
shenglian zhou 已提交
1701
  }
1702
}
S
shenglian zhou 已提交
1703

S
shenglian zhou 已提交
1704
void constructUdfService(void *argsThread) {
1705 1706 1707
  SUdfcProxy *udfc = (SUdfcProxy *)argsThread;
  uv_loop_init(&udfc->uvLoop);

1708
  uv_async_init(&udfc->uvLoop, &udfc->loopTaskAync, udfcAsyncTaskCb);
1709 1710 1711 1712 1713 1714 1715
  udfc->loopTaskAync.data = udfc;
  uv_async_init(&udfc->uvLoop, &udfc->loopStopAsync, udfStopAsyncCb);
  udfc->loopStopAsync.data = udfc;
  uv_mutex_init(&udfc->taskQueueMutex);
  QUEUE_INIT(&udfc->taskQueue);
  QUEUE_INIT(&udfc->uvProcTaskQueue);
  uv_barrier_wait(&udfc->initBarrier);
H
Hongze Cheng 已提交
1716
  // TODO return value of uv_run
1717 1718
  uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
  uv_loop_close(&udfc->uvLoop);
S
slzhou 已提交
1719 1720 1721 1722

  uv_walk(&udfc->uvLoop, udfUdfdCloseWalkCb, NULL);
  uv_run(&udfc->uvLoop, UV_RUN_DEFAULT);
  uv_loop_close(&udfc->uvLoop);
1723 1724
}

1725
int32_t udfcOpen() {
1726
  int8_t old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 0, 1);
1727 1728 1729
  if (old == 1) {
    return 0;
  }
1730
  SUdfcProxy *proxy = &gUdfcProxy;
1731
  getUdfdPipeName(proxy->udfdPipeName, sizeof(proxy->udfdPipeName));
1732 1733 1734 1735 1736 1737
  proxy->udfcState = UDFC_STATE_STARTNG;
  uv_barrier_init(&proxy->initBarrier, 2);
  uv_thread_create(&proxy->loopThread, constructUdfService, proxy);
  atomic_store_8(&proxy->udfcState, UDFC_STATE_READY);
  proxy->udfcState = UDFC_STATE_READY;
  uv_barrier_wait(&proxy->initBarrier);
1738 1739
  uv_mutex_init(&proxy->udfStubsMutex);
  proxy->udfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
1740
  proxy->expiredUdfStubs = taosArrayInit(8, sizeof(SUdfcFuncStub));
1741
  uv_mutex_init(&proxy->udfcUvMutex);
H
Hongze Cheng 已提交
1742
  fnInfo("udfc initialized") return 0;
1743 1744
}

1745
int32_t udfcClose() {
1746
  int8_t old = atomic_val_compare_exchange_8(&gUdfcProxy.initialized, 1, 0);
1747 1748 1749 1750
  if (old == 0) {
    return 0;
  }

1751
  SUdfcProxy *udfc = &gUdfcProxy;
1752 1753 1754 1755 1756
  udfc->udfcState = UDFC_STATE_STOPPING;
  uv_async_send(&udfc->loopStopAsync);
  uv_thread_join(&udfc->loopThread);
  uv_mutex_destroy(&udfc->taskQueueMutex);
  uv_barrier_destroy(&udfc->initBarrier);
1757
  taosArrayDestroy(udfc->expiredUdfStubs);
1758 1759
  taosArrayDestroy(udfc->udfStubs);
  uv_mutex_destroy(&udfc->udfStubsMutex);
1760
  uv_mutex_destroy(&udfc->udfcUvMutex);
1761
  udfc->udfcState = UDFC_STATE_INITAL;
S
Shengliang Guan 已提交
1762
  fnInfo("udfc is cleaned up");
1763 1764 1765
  return 0;
}

S
slzhou 已提交
1766
int32_t udfcRunUdfUvTask(SClientUdfTask *task, int8_t uvTaskType) {
S
shenglian zhou 已提交
1767
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
1768
  fnDebug("udfc client task: %p created uvTask: %p. pipe: %p", task, uvTask, task->session->udfUvPipe);
S
shenglian zhou 已提交
1769 1770

  udfcInitializeUvTask(task, uvTaskType, uvTask);
S
slzhou 已提交
1771 1772
  udfcQueueUvTask(uvTask);
  udfcGetUdfTaskResultFromUvTask(task, uvTask);
1773
  if (uvTaskType == UV_TASK_CONNECT) {
S
slzhou 已提交
1774 1775 1776
    task->session->udfUvPipe = uvTask->pipe;
    SClientUvConn *conn = uvTask->pipe->data;
    conn->session = task->session;
S
slzhou 已提交
1777
  }
1778 1779
  taosMemoryFree(uvTask->reqBuf.base);
  uvTask->reqBuf.base = NULL;
S
shenglian zhou 已提交
1780
  taosMemoryFree(uvTask);
S
shenglian zhou 已提交
1781 1782
  fnDebug("udfc freed uvTask: %p", task);

S
shenglian zhou 已提交
1783 1784
  uvTask = NULL;
  return task->errCode;
S
slzhou 已提交
1785 1786
}

S
shenglian zhou 已提交
1787
int32_t doSetupUdf(char udfName[], UdfcFuncHandle *funcHandle) {
H
Hongze Cheng 已提交
1788
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
S
shenglian zhou 已提交
1789 1790
  task->errCode = 0;
  task->session = taosMemoryCalloc(1, sizeof(SUdfcUvSession));
1791
  task->session->udfc = &gUdfcProxy;
S
shenglian zhou 已提交
1792 1793 1794 1795 1796 1797 1798
  task->type = UDF_TASK_SETUP;

  SUdfSetupRequest *req = &task->_setup.req;
  strncpy(req->udfName, udfName, TSDB_FUNC_NAME_LEN);

  int32_t errCode = udfcRunUdfUvTask(task, UV_TASK_CONNECT);
  if (errCode != 0) {
1799
    fnError("failed to connect to pipe. udfName: %s, pipe: %s", udfName, (&gUdfcProxy)->udfdPipeName);
1800 1801
    taosMemoryFree(task->session);
    taosMemoryFree(task);
S
shenglian zhou 已提交
1802
    return TSDB_CODE_UDF_PIPE_CONNECT_ERR;
1803
  }
S
slzhou 已提交
1804

S
shenglian zhou 已提交
1805 1806 1807 1808 1809
  udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);

  SUdfSetupResponse *rsp = &task->_setup.rsp;
  task->session->severHandle = rsp->udfHandle;
  task->session->outputType = rsp->outputType;
S
slzhou 已提交
1810
  task->session->bytes = rsp->bytes;
S
shenglian zhou 已提交
1811
  task->session->bufSize = rsp->bufSize;
S
slzhou 已提交
1812
  strncpy(task->session->udfName, udfName, TSDB_FUNC_NAME_LEN);
S
shenglian zhou 已提交
1813 1814 1815
  if (task->errCode != 0) {
    fnError("failed to setup udf. udfname: %s, err: %d", udfName, task->errCode)
  } else {
1816
    fnInfo("successfully setup udf func handle. udfName: %s, handle: %p", udfName, task->session);
S
shenglian zhou 已提交
1817
    *funcHandle = task->session;
S
slzhou 已提交
1818
  }
S
shenglian zhou 已提交
1819 1820 1821
  int32_t err = task->errCode;
  taosMemoryFree(task);
  return err;
S
slzhou 已提交
1822 1823
}

1824
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
H
Hongze Cheng 已提交
1825
                SSDataBlock *output, SUdfInterBuf *newState) {
1826
  fnDebug("udfc call udf. callType: %d, funcHandle: %p", callType, handle);
H
Hongze Cheng 已提交
1827
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
S
slzhou 已提交
1828 1829
  if (session->udfUvPipe == NULL) {
    fnError("No pipe to udfd");
S
shenglian zhou 已提交
1830
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
S
slzhou 已提交
1831 1832
  }
  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
1833
  task->errCode = 0;
H
Hongze Cheng 已提交
1834
  task->session = (SUdfcUvSession *)handle;
1835 1836 1837
  task->type = UDF_TASK_CALL;

  SUdfCallRequest *req = &task->_call.req;
S
slzhou 已提交
1838
  req->udfHandle = task->session->severHandle;
S
slzhou 已提交
1839
  req->callType = callType;
S
slzhou 已提交
1840

S
shenglian zhou 已提交
1841
  switch (callType) {
1842 1843 1844 1845
    case TSDB_UDF_CALL_AGG_INIT: {
      req->initFirst = 1;
      break;
    }
S
shenglian zhou 已提交
1846 1847 1848 1849 1850
    case TSDB_UDF_CALL_AGG_PROC: {
      req->block = *input;
      req->interBuf = *state;
      break;
    }
1851 1852 1853 1854 1855 1856
    case TSDB_UDF_CALL_AGG_MERGE: {
      req->interBuf = *state;
      req->interBuf2 = *state2;
      break;
    }
    case TSDB_UDF_CALL_AGG_FIN: {
S
shenglian zhou 已提交
1857 1858 1859 1860 1861 1862 1863 1864 1865
      req->interBuf = *state;
      break;
    }
    case TSDB_UDF_CALL_SCALA_PROC: {
      req->block = *input;
      break;
    }
  }

S
slzhou 已提交
1866
  udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
1867

1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
  if (task->errCode != 0) {
    fnError("call udf failure. err: %d", task->errCode);
  } else {
    SUdfCallResponse *rsp = &task->_call.rsp;
    switch (callType) {
      case TSDB_UDF_CALL_AGG_INIT: {
        *newState = rsp->resultBuf;
        break;
      }
      case TSDB_UDF_CALL_AGG_PROC: {
        *newState = rsp->resultBuf;
        break;
      }
      case TSDB_UDF_CALL_AGG_MERGE: {
        *newState = rsp->resultBuf;
        break;
      }
      case TSDB_UDF_CALL_AGG_FIN: {
        *newState = rsp->resultBuf;
        break;
      }
      case TSDB_UDF_CALL_SCALA_PROC: {
        *output = rsp->resultData;
        break;
      }
S
shenglian zhou 已提交
1893
    }
S
slzhou 已提交
1894 1895
  };
  int err = task->errCode;
wafwerar's avatar
wafwerar 已提交
1896
  taosMemoryFree(task);
S
slzhou 已提交
1897
  return err;
1898 1899
}

1900
int32_t doCallUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf) {
S
slzhou 已提交
1901 1902 1903 1904 1905 1906 1907 1908 1909
  int8_t callType = TSDB_UDF_CALL_AGG_INIT;

  int32_t err = callUdf(handle, callType, NULL, NULL, NULL, NULL, interBuf);

  return err;
}

// input: block, state
// output: interbuf,
1910
int32_t doCallUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
H
Hongze Cheng 已提交
1911
  int8_t  callType = TSDB_UDF_CALL_AGG_PROC;
S
slzhou 已提交
1912 1913 1914 1915 1916 1917
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
  return err;
}

// input: interbuf1, interbuf2
// output: resultBuf
H
Hongze Cheng 已提交
1918 1919 1920
int32_t doCallUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2,
                          SUdfInterBuf *resultBuf) {
  int8_t  callType = TSDB_UDF_CALL_AGG_MERGE;
S
slzhou 已提交
1921 1922 1923 1924 1925 1926
  int32_t err = callUdf(handle, callType, NULL, interBuf1, interBuf2, NULL, resultBuf);
  return err;
}

// input: interBuf
// output: resultData
1927
int32_t doCallUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData) {
H
Hongze Cheng 已提交
1928
  int8_t  callType = TSDB_UDF_CALL_AGG_FIN;
S
slzhou 已提交
1929 1930 1931 1932
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
  return err;
}

H
Hongze Cheng 已提交
1933 1934
int32_t doCallUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam *output) {
  int8_t      callType = TSDB_UDF_CALL_SCALA_PROC;
S
slzhou 已提交
1935 1936 1937
  SSDataBlock inputBlock = {0};
  convertScalarParamToDataBlock(input, numOfCols, &inputBlock);
  SSDataBlock resultBlock = {0};
H
Hongze Cheng 已提交
1938
  int32_t     err = callUdf(handle, callType, &inputBlock, NULL, NULL, &resultBlock, NULL);
S
slzhou 已提交
1939 1940
  if (err == 0) {
    convertDataBlockToScalarParm(&resultBlock, output);
S
slzhou 已提交
1941
    taosArrayDestroy(resultBlock.pDataBlock);
S
slzhou 已提交
1942
  }
S
shenglian zhou 已提交
1943 1944
  
  blockDataFreeRes(&inputBlock);
S
slzhou 已提交
1945 1946 1947
  return err;
}

1948
int32_t doTeardownUdf(UdfcFuncHandle handle) {
H
Hongze Cheng 已提交
1949
  SUdfcUvSession *session = (SUdfcUvSession *)handle;
S
slzhou 已提交
1950

S
slzhou 已提交
1951
  if (session->udfUvPipe == NULL) {
S
slzhou 已提交
1952
    fnError("tear down udf. pipe to udfd does not exist. udf name: %s", session->udfName);
1953
    taosMemoryFree(session);
S
shenglian zhou 已提交
1954
    return TSDB_CODE_UDF_PIPE_NOT_EXIST;
S
slzhou 已提交
1955 1956 1957
  }

  SClientUdfTask *task = taosMemoryCalloc(1, sizeof(SClientUdfTask));
1958
  task->errCode = 0;
S
slzhou 已提交
1959
  task->session = session;
1960 1961 1962 1963 1964
  task->type = UDF_TASK_TEARDOWN;

  SUdfTeardownRequest *req = &task->_teardown.req;
  req->udfHandle = task->session->severHandle;

S
slzhou 已提交
1965
  udfcRunUdfUvTask(task, UV_TASK_REQ_RSP);
1966 1967 1968

  int32_t err = task->errCode;

S
slzhou 已提交
1969
  udfcRunUdfUvTask(task, UV_TASK_DISCONNECT);
1970

S
slzhou 已提交
1971
  fnInfo("tear down udf. udf name: %s, udf func handle: %p", session->udfName, handle);
H
Hongze Cheng 已提交
1972
  // TODO: synchronization refactor between libuv event loop and request thread
1973
  uv_mutex_lock(&gUdfcProxy.udfcUvMutex);
S
slzhou 已提交
1974
  if (session->udfUvPipe != NULL && session->udfUvPipe->data != NULL) {
1975 1976 1977
    SClientUvConn *conn = session->udfUvPipe->data;
    conn->session = NULL;
  }
1978
  uv_mutex_unlock(&gUdfcProxy.udfcUvMutex);
1979
  taosMemoryFree(session);
wafwerar's avatar
wafwerar 已提交
1980
  taosMemoryFree(task);
1981 1982 1983

  return err;
}