tudf.c 37.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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"
#include "os.h"
S
slzhou 已提交
17
#include "fnLog.h"
18
#include "tudf.h"
19
#include "tudfInt.h"
S
shenglian zhou 已提交
20
#include "tarray.h"
S
slzhou 已提交
21
#include "tdatablock.h"
22

23 24
//TODO: network error processing.
//TODO: add unit test
S
shenglian zhou 已提交
25
//TODO: include all global variable under context struct
S
slzhou 已提交
26

S
shenglian zhou 已提交
27 28 29 30
/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl>
 * The QUEUE is copied from queue.h under libuv
 * */

S
shenglian zhou 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
typedef void *QUEUE[2];

/* Private macros. */
#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)))

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

/* Important note: mutating the list while QUEUE_FOREACH is
 * iterating over its elements results in undefined behavior.
 */
#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)


119 120 121 122 123 124
enum {
  UV_TASK_CONNECT = 0,
  UV_TASK_REQ_RSP = 1,
  UV_TASK_DISCONNECT = 2
};

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
int64_t gUdfTaskSeqNum = 0;
typedef struct SUdfdProxy {
  int32_t dnodeId;
  uv_barrier_t gUdfInitBarrier;

  uv_loop_t gUdfdLoop;
  uv_thread_t gUdfLoopThread;
  uv_async_t gUdfLoopTaskAync;

  uv_async_t gUdfLoopStopAsync;

  uv_mutex_t gUdfTaskQueueMutex;
  int8_t gUdfcState;
  QUEUE gUdfTaskQueue;
  QUEUE gUvProcTaskQueue;
  //  int8_t gUdfcState = UDFC_STATE_INITAL;
  //  QUEUE gUdfTaskQueue = {0};
  //  QUEUE gUvProcTaskQueue = {0};
} SUdfdProxy;


146
typedef struct SUdfUvSession {
147
  SUdfdProxy *udfc;
148 149 150 151 152
  int64_t severHandle;
  uv_pipe_t *udfSvcPipe;
} SUdfUvSession;

typedef struct SClientUvTaskNode {
153
  SUdfdProxy *udfc;
154 155 156 157 158 159 160 161 162 163 164
  int8_t type;
  int errCode;

  uv_pipe_t *pipe;

  int64_t seqNum;
  uv_buf_t reqBuf;

  uv_sem_t taskSem;
  uv_buf_t rspBuf;

S
shenglian zhou 已提交
165 166 167
  QUEUE recvTaskQueue;
  QUEUE procTaskQueue;
  QUEUE connTaskQueue;
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
} SClientUvTaskNode;

typedef struct SClientUdfTask {
  int8_t type;

  SUdfUvSession *session;

  int32_t errCode;

  union {
    struct {
      SUdfSetupRequest req;
      SUdfSetupResponse rsp;
    } _setup;
    struct {
      SUdfCallRequest req;
      SUdfCallResponse rsp;
    } _call;
    struct {
      SUdfTeardownRequest req;
      SUdfTeardownResponse rsp;
    } _teardown;
  };

} SClientUdfTask;

typedef struct SClientConnBuf {
  char *buf;
  int32_t len;
  int32_t cap;
  int32_t total;
} SClientConnBuf;

typedef struct SClientUvConn {
  uv_pipe_t *pipe;
S
shenglian zhou 已提交
203
  QUEUE taskQueue;
204 205 206
  SClientConnBuf readBuf;
} SClientUvConn;

207 208
enum {
  UDFC_STATE_INITAL = 0, // initial state
209
  UDFC_STATE_STARTNG, // starting after udfcOpen
210
  UDFC_STATE_READY, // started and begin to receive quests
211
  UDFC_STATE_STOPPING, // stopping after udfcClose
212 213
  UDFC_STATUS_FINAL, // stopped
};
214

215 216 217 218
int32_t encodeUdfSetupRequest(void **buf, const SUdfSetupRequest *setup) {
  int32_t len = 0;
  len += taosEncodeBinary(buf, setup->udfName, TSDB_FUNC_NAME_LEN);
  len += taosEncodeSEpSet(buf, &setup->epSet);
S
shenglian zhou 已提交
219 220
  return len;
}
221

222 223 224 225
void* decodeUdfSetupRequest(const void* buf, SUdfSetupRequest *request) {
  buf = taosDecodeBinaryTo(buf, request->udfName, TSDB_FUNC_NAME_LEN);
  buf = taosDecodeSEpSet((void*)buf, &request->epSet);
  return (void*)buf;
S
shenglian zhou 已提交
226
}
227

228 229 230 231
int32_t encodeUdfInterBuf(void **buf, const SUdfInterBuf* state) {
  int32_t len = 0;
  len += taosEncodeFixedI32(buf, state->bufLen);
  len += taosEncodeBinary(buf, state->buf, state->bufLen);
S
shenglian zhou 已提交
232 233
  return len;
}
234

235 236 237 238
void* decodeUdfInterBuf(const void* buf, SUdfInterBuf* state) {
  buf = taosDecodeFixedI32(buf, &state->bufLen);
  buf = taosDecodeBinary(buf, (void**)&state->buf, state->bufLen);
  return (void*)buf;
S
shenglian zhou 已提交
239 240
}

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
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);
257
  }
258
  return len;
259 260
}

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
void* decodeUdfCallRequest(const void* buf, SUdfCallRequest* call) {
  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;
282
  }
283
  return (void*)buf;
S
shenglian zhou 已提交
284 285
}

286 287 288 289
int32_t encodeUdfTeardownRequest(void **buf, const SUdfTeardownRequest *teardown) {
  int32_t len = 0;
  len += taosEncodeFixedI64(buf, teardown->udfHandle);
  return len;
S
shenglian zhou 已提交
290 291
}

292 293 294
void* decodeUdfTeardownRequest(const void* buf, SUdfTeardownRequest *teardown) {
  buf = taosDecodeFixedI64(buf, &teardown->udfHandle);
  return (void*)buf;
S
shenglian zhou 已提交
295 296
}

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
int32_t encodeUdfRequest(void** buf, const SUdfRequest* request) {
  int32_t len = 0;
  if (buf == NULL) {
    len += sizeof(request->msgLen);
  } else {
    *(int32_t*)(*buf) = request->msgLen;
    *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 已提交
315 316
}

317 318
void* decodeUdfRequest(const void* buf, SUdfRequest* request) {
  request->msgLen = *(int32_t*)(buf);
S
slzhou 已提交
319
  buf = POINTER_SHIFT(buf, sizeof(request->msgLen));
S
shenglian zhou 已提交
320

321 322
  buf = taosDecodeFixedI64(buf, &request->seqNum);
  buf = taosDecodeFixedI8(buf, &request->type);
S
shenglian zhou 已提交
323 324

  if (request->type == UDF_TASK_SETUP) {
325
    buf = decodeUdfSetupRequest(buf, &request->setup);
S
shenglian zhou 已提交
326
  } else if (request->type == UDF_TASK_CALL) {
327 328 329
    buf = decodeUdfCallRequest(buf, &request->call);
  } else if (request->type == UDF_TASK_TEARDOWN) {
    buf = decodeUdfTeardownRequest(buf, &request->teardown);
S
shenglian zhou 已提交
330
  }
331
  return (void*)buf;
S
shenglian zhou 已提交
332
}
333

334 335 336 337 338
int32_t encodeUdfSetupResponse(void **buf, const SUdfSetupResponse *setupRsp) {
  int32_t len = 0;
  len += taosEncodeFixedI64(buf, setupRsp->udfHandle);
  return len;
}
339

340 341 342
void* decodeUdfSetupResponse(const void* buf, SUdfSetupResponse* setupRsp) {
  buf = taosDecodeFixedI64(buf, &setupRsp->udfHandle);
  return (void*)buf;
S
shenglian zhou 已提交
343
}
344

345 346 347 348 349 350
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);
351
      break;
352
    case TSDB_UDF_CALL_AGG_INIT:
S
slzhou 已提交
353
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
354 355
      break;
    case TSDB_UDF_CALL_AGG_PROC:
S
slzhou 已提交
356
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
357 358
      break;
    case TSDB_UDF_CALL_AGG_MERGE:
S
slzhou 已提交
359
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
360 361
      break;
    case TSDB_UDF_CALL_AGG_FIN:
S
slzhou 已提交
362
      len += encodeUdfInterBuf(buf, &callRsp->resultBuf);
363 364
      break;
  }
365
  return len;
S
shenglian zhou 已提交
366 367
}

368 369 370 371 372 373 374
void* decodeUdfCallResponse(const void* buf, SUdfCallResponse* callRsp) {
  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 已提交
375
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
376 377
      break;
    case TSDB_UDF_CALL_AGG_PROC:
S
slzhou 已提交
378
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
379 380
      break;
    case TSDB_UDF_CALL_AGG_MERGE:
S
slzhou 已提交
381
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
382 383
      break;
    case TSDB_UDF_CALL_AGG_FIN:
S
slzhou 已提交
384
      buf = decodeUdfInterBuf(buf, &callRsp->resultBuf);
385
      break;
S
shenglian zhou 已提交
386
  }
387
  return (void*)buf;
S
shenglian zhou 已提交
388 389
}

390 391
int32_t encodeUdfTeardownResponse(void** buf, const SUdfTeardownResponse* teardownRsp) {
  return 0;
S
shenglian zhou 已提交
392 393
}

394 395
void* decodeUdfTeardownResponse(const void* buf, SUdfTeardownResponse* teardownResponse) {
  return (void*)buf;
S
shenglian zhou 已提交
396 397
}

398 399 400 401 402 403 404
int32_t encodeUdfResponse(void** buf, const SUdfResponse* rsp) {
  int32_t len = 0;
  if (buf == NULL) {
    len += sizeof(rsp->msgLen);
  } else {
    *(int32_t*)(*buf) = rsp->msgLen;
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->msgLen));
S
shenglian zhou 已提交
405 406
  }

S
slzhou 已提交
407 408 409 410 411 412 413
  if (buf == NULL) {
    len += sizeof(rsp->seqNum);
  } else {
    *(int64_t*)(*buf) = rsp->seqNum;
    *buf = POINTER_SHIFT(*buf, sizeof(rsp->seqNum));
  }

414 415 416
  len += taosEncodeFixedI64(buf, rsp->seqNum);
  len += taosEncodeFixedI8(buf, rsp->type);
  len += taosEncodeFixedI32(buf, rsp->code);
S
shenglian zhou 已提交
417

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
  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:
      //TODO: log error
      break;
  }
  return len;
S
shenglian zhou 已提交
433 434
}

435 436
void* decodeUdfResponse(const void* buf, SUdfResponse* rsp) {
  rsp->msgLen = *(int32_t*)(buf);
S
slzhou 已提交
437
  buf = POINTER_SHIFT(buf, sizeof(rsp->msgLen));
S
slzhou 已提交
438 439
  rsp->seqNum = *(int64_t*)(buf);
  buf = POINTER_SHIFT(buf, sizeof(rsp->seqNum));
440 441 442
  buf = taosDecodeFixedI64(buf, &rsp->seqNum);
  buf = taosDecodeFixedI8(buf, &rsp->type);
  buf = taosDecodeFixedI32(buf, &rsp->code);
S
shenglian zhou 已提交
443

444 445 446 447 448 449 450 451 452 453 454 455 456
  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:
      //TODO: log error
      break;
457
  }
458
  return (void*)buf;
459
}
460

S
shenglian zhou 已提交
461 462
void freeUdfColumnData(SUdfColumnData *data) {
  if (data->varLengthColumn) {
S
slzhou 已提交
463 464 465 466
    taosMemoryFree(data->varLenCol.varOffsets);
    data->varLenCol.varOffsets = NULL;
    taosMemoryFree(data->varLenCol.payload);
    data->varLenCol.payload = NULL;
S
shenglian zhou 已提交
467
  } else {
S
slzhou 已提交
468 469 470 471
    taosMemoryFree(data->fixLenCol.nullBitmap);
    data->fixLenCol.nullBitmap = NULL;
    taosMemoryFree(data->fixLenCol.data);
    data->fixLenCol.data = NULL;
S
shenglian zhou 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
  }
}

void freeUdfColumn(SUdfColumn* col) {
  freeUdfColumnData(&col->colData);
}

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 已提交
494 495 496 497

int32_t convertDataBlockToUdfDataBlock(SSDataBlock *block, SUdfDataBlock *udfBlock) {
  udfBlock->numOfRows = block->info.rows;
  udfBlock->numOfCols = block->info.numOfCols;
S
slzhou 已提交
498
  udfBlock->udfCols = taosMemoryCalloc(udfBlock->numOfCols, sizeof(SUdfColumn*));
S
slzhou 已提交
499
  for (int32_t i = 0; i < udfBlock->numOfCols; ++i) {
S
slzhou 已提交
500
    udfBlock->udfCols[i] = taosMemoryCalloc(1, sizeof(SUdfColumn));
S
slzhou 已提交
501 502 503 504 505 506 507 508 509
    SColumnInfoData *col= (SColumnInfoData*)taosArrayGet(block->pDataBlock, i);
    SUdfColumn *udfCol = udfBlock->udfCols[i];
    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;
    udfCol->colData.varLengthColumn = IS_VAR_DATA_TYPE(udfCol->colMeta.type);
    if (udfCol->colData.varLengthColumn) {
S
slzhou 已提交
510 511 512 513 514 515
      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);
      memcpy(udfCol->colData.varLenCol.payload, col->pData, udfCol->colData.varLenCol.payloadLen);
S
slzhou 已提交
516
    } else {
S
slzhou 已提交
517 518 519 520 521 522 523 524 525 526
      udfCol->colData.fixLenCol.nullBitmapLen = BitmapLen(udfCol->colData.numOfRows);
      int32_t bitmapLen = udfCol->colData.fixLenCol.nullBitmapLen;
      udfCol->colData.fixLenCol.nullBitmap = taosMemoryMalloc(udfCol->colData.fixLenCol.nullBitmapLen);
      char* bitmap = udfCol->colData.fixLenCol.nullBitmap;
      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);
      char* data = udfCol->colData.fixLenCol.data;
      memcpy(data, col->pData, dataLen);
S
slzhou 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    }
  }
  return 0;
}

int32_t convertUdfColumnToDataBlock(SUdfColumn *udfCol, SSDataBlock *block) {
  block->info.numOfCols = 1;
  block->info.rows = udfCol->colData.numOfRows;
  block->info.hasVarCol = udfCol->colData.varLengthColumn;

  block->pDataBlock = taosArrayInit(1, sizeof(SColumnInfoData));
  taosArraySetSize(block->pDataBlock, 1);
  SColumnInfoData *col = taosArrayGet(block->pDataBlock, 0);
  SUdfColumnMeta *meta = &udfCol->colMeta;
  col->info.precision = meta->precision;
  col->info.bytes = meta->bytes;
  col->info.scale = meta->scale;
  col->info.type = meta->type;
  SUdfColumnData *data = &udfCol->colData;

  if (!IS_VAR_DATA_TYPE(meta->type)) {
S
slzhou 已提交
548 549 550 551
    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 已提交
552
  } else {
S
slzhou 已提交
553 554 555 556
    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 已提交
557 558 559 560
  }
  return 0;
}

S
slzhou 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
int32_t convertScalarParamToDataBlock(SScalarParam *input, int32_t numOfCols, SSDataBlock *output) {
  output->info.rows = input->numOfRows;
  output->info.numOfCols = numOfCols;
  bool hasVarCol = false;
  for (int32_t i = 0; i < numOfCols; ++i) {
    if (IS_VAR_DATA_TYPE((input+i)->columnData->info.type)) {
      hasVarCol = true;
      break;
    }
  }
  output->info.hasVarCol = hasVarCol;

  //TODO: free the array output->pDataBlock
  output->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
  taosArrayPush(output->pDataBlock, input->columnData);
  return 0;
}

int32_t convertDataBlockToScalarParm(SSDataBlock *input, SScalarParam *output) {
  if (input->info.numOfCols != 1) {
    fnError("scalar function only support one column");
    return -1;
  }
  output->numOfRows = input->info.rows;
  //TODO: memory
  output->columnData = taosArrayGet(input->pDataBlock, 0);
  return 0;
}
S
slzhou 已提交
589

590 591
void onUdfcPipeClose(uv_handle_t *handle) {
  SClientUvConn *conn = handle->data;
S
shenglian zhou 已提交
592 593 594
  if (!QUEUE_EMPTY(&conn->taskQueue)) {
    QUEUE* h = QUEUE_HEAD(&conn->taskQueue);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
595 596
    task->errCode = 0;
    uv_sem_post(&task->taskSem);
S
shenglian zhou 已提交
597
    QUEUE_REMOVE(&task->procTaskQueue);
598 599
  }

wafwerar's avatar
wafwerar 已提交
600 601 602
  taosMemoryFree(conn->readBuf.buf);
  taosMemoryFree(conn);
  taosMemoryFree((uv_pipe_t *) handle);
603 604 605 606

}

int32_t udfcGetUvTaskResponseResult(SClientUdfTask *task, SClientUvTaskNode *uvTask) {
S
shenglian zhou 已提交
607
  debugPrint("%s", "get uv task result");
608 609
  if (uvTask->type == UV_TASK_REQ_RSP) {
    if (uvTask->rspBuf.base != NULL) {
S
shenglian zhou 已提交
610
      SUdfResponse rsp;
611 612
      void* buf = decodeUdfResponse(uvTask->rspBuf.base, &rsp);
      assert(uvTask->rspBuf.len == POINTER_DISTANCE(buf, uvTask->rspBuf.base));
S
shenglian zhou 已提交
613
      task->errCode = rsp.code;
614 615 616

      switch (task->type) {
        case UDF_TASK_SETUP: {
S
shenglian zhou 已提交
617
          //TODO: copy or not
S
shenglian zhou 已提交
618
          task->_setup.rsp = rsp.setupRsp;
619 620 621
          break;
        }
        case UDF_TASK_CALL: {
S
shenglian zhou 已提交
622
          task->_call.rsp = rsp.callRsp;
S
shenglian zhou 已提交
623
          //TODO: copy or not
624 625 626
          break;
        }
        case UDF_TASK_TEARDOWN: {
S
shenglian zhou 已提交
627
          task->_teardown.rsp = rsp.teardownRsp;
628 629 630 631 632 633 634 635 636
          //TODO: copy or not?
          break;
        }
        default: {
          break;
        }
      }

      // TODO: the call buffer is setup and freed by udf invocation
wafwerar's avatar
wafwerar 已提交
637
      taosMemoryFree(uvTask->rspBuf.base);
638 639
    } else {
      task->errCode = uvTask->errCode;
640
    }
641 642 643 644
  } else if (uvTask->type == UV_TASK_CONNECT) {
    task->errCode = uvTask->errCode;
  } else if (uvTask->type == UV_TASK_DISCONNECT) {
    task->errCode = uvTask->errCode;
645
  }
646 647 648 649
  return 0;
}

void udfcAllocateBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
S
shenglian zhou 已提交
650
  debugPrint("%s", "client allocate buffer to receive from pipe");
651 652 653 654 655
  SClientUvConn *conn = handle->data;
  SClientConnBuf *connBuf = &conn->readBuf;

  int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
  if (connBuf->cap == 0) {
wafwerar's avatar
wafwerar 已提交
656
    connBuf->buf = taosMemoryMalloc(msgHeadSize);
657 658 659 660 661 662 663 664 665 666 667 668 669 670
    if (connBuf->buf) {
      connBuf->len = 0;
      connBuf->cap = msgHeadSize;
      connBuf->total = -1;

      buf->base = connBuf->buf;
      buf->len = connBuf->cap;
    } else {
      //TODO: log error
      buf->base = NULL;
      buf->len = 0;
    }
  } else {
    connBuf->cap = connBuf->total > connBuf->cap ? connBuf->total : connBuf->cap;
wafwerar's avatar
wafwerar 已提交
671
    void *resultBuf = taosMemoryRealloc(connBuf->buf, connBuf->cap);
672 673 674 675 676 677 678 679 680 681 682
    if (resultBuf) {
      connBuf->buf = resultBuf;
      buf->base = connBuf->buf + connBuf->len;
      buf->len = connBuf->cap - connBuf->len;
    } else {
      //TODO: log error free connBuf->buf
      buf->base = NULL;
      buf->len = 0;
    }
  }

S
shenglian zhou 已提交
683
  debugPrint("\tconn buf cap - len - total : %d - %d - %d", connBuf->cap, connBuf->len, connBuf->total);
684 685 686

}

687 688 689 690 691 692
bool isUdfcUvMsgComplete(SClientConnBuf *connBuf) {
  if (connBuf->total == -1 && connBuf->len >= sizeof(int32_t)) {
    connBuf->total = *(int32_t *) (connBuf->buf);
  }
  if (connBuf->len == connBuf->cap && connBuf->total == connBuf->cap) {
    return true;
693
  }
694 695 696 697 698 699
  return false;
}

void udfcUvHandleRsp(SClientUvConn *conn) {
  SClientConnBuf *connBuf = &conn->readBuf;
  int64_t seqNum = *(int64_t *) (connBuf->buf + sizeof(int32_t)); // msglen int32_t then seqnum
700

S
shenglian zhou 已提交
701
  if (QUEUE_EMPTY(&conn->taskQueue)) {
702 703 704 705 706
    //LOG error
    return;
  }
  bool found = false;
  SClientUvTaskNode *taskFound = NULL;
S
shenglian zhou 已提交
707 708 709 710
  QUEUE* h = QUEUE_NEXT(&conn->taskQueue);
  SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);

  while (h != &conn->taskQueue) {
711 712 713 714 715 716 717 718
    if (task->seqNum == seqNum) {
      if (found == false) {
        found = true;
        taskFound = task;
      } else {
        //LOG error;
        continue;
      }
719
    }
S
shenglian zhou 已提交
720 721
    h = QUEUE_NEXT(h);
    task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
722 723
  }

724 725
  if (taskFound) {
    taskFound->rspBuf = uv_buf_init(connBuf->buf, connBuf->len);
S
shenglian zhou 已提交
726
    QUEUE_REMOVE(&taskFound->connTaskQueue);
727
    uv_sem_post(&taskFound->taskSem);
S
shenglian zhou 已提交
728
    QUEUE_REMOVE(&taskFound->procTaskQueue);
729
  } else {
730
    //TODO: LOG error
731 732 733 734 735 736
  }
  connBuf->buf = NULL;
  connBuf->total = -1;
  connBuf->len = 0;
  connBuf->cap = 0;
}
737

738
void udfcUvHandleError(SClientUvConn *conn) {
S
shenglian zhou 已提交
739 740 741 742 743 744 745 746 747 748 749 750
  while (!QUEUE_EMPTY(&conn->taskQueue)) {
    QUEUE* h = QUEUE_HEAD(&conn->taskQueue);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, connTaskQueue);
    task->errCode = UDFC_CODE_PIPE_READ_ERR;
    uv_sem_post(&task->taskSem);
    QUEUE_REMOVE(&task->procTaskQueue);
  }

  uv_close((uv_handle_t *) conn->pipe, NULL);
  taosMemoryFree(conn->pipe);
  taosMemoryFree(conn->readBuf.buf);
  taosMemoryFree(conn);
751 752 753
}

void onUdfcRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
S
shenglian zhou 已提交
754
  debugPrint("%s, nread: %zd", "client read from pipe", nread);
755 756 757 758 759 760 761 762 763 764 765 766
  if (nread == 0) return;

  SClientUvConn *conn = client->data;
  SClientConnBuf *connBuf = &conn->readBuf;
  if (nread > 0) {
    connBuf->len += nread;
    if (isUdfcUvMsgComplete(connBuf)) {
      udfcUvHandleRsp(conn);
    }

  }
  if (nread < 0) {
S
shenglian zhou 已提交
767
    debugPrint("\tclient read error: %s", uv_strerror(nread));
768 769 770 771
    if (nread == UV_EOF) {
      //TODO:
    }
    udfcUvHandleError(conn);
772 773 774 775
  }

}

776
void onUdfClientWrite(uv_write_t *write, int status) {
S
shenglian zhou 已提交
777
  debugPrint("%s", "after writing to pipe");
778 779 780 781
  SClientUvTaskNode *uvTask = write->data;
  if (status == 0) {
    uv_pipe_t *pipe = uvTask->pipe;
    SClientUvConn *conn = pipe->data;
S
shenglian zhou 已提交
782
    QUEUE_INSERT_TAIL(&conn->taskQueue, &uvTask->connTaskQueue);
783 784 785
  } else {
    //TODO Log error;
  }
S
shenglian zhou 已提交
786
  debugPrint("\tlength:%zu", uvTask->reqBuf.len);
wafwerar's avatar
wafwerar 已提交
787 788
  taosMemoryFree(write);
  taosMemoryFree(uvTask->reqBuf.base);
789
}
H
Haojun Liao 已提交
790

791 792 793 794 795
void onUdfClientConnect(uv_connect_t *connect, int status) {
  SClientUvTaskNode *uvTask = connect->data;
  uvTask->errCode = status;
  if (status != 0) {
    //TODO: LOG error
H
Haojun Liao 已提交
796
  }
797
  uv_read_start((uv_stream_t *) uvTask->pipe, udfcAllocateBuffer, onUdfcRead);
wafwerar's avatar
wafwerar 已提交
798
  taosMemoryFree(connect);
799
  uv_sem_post(&uvTask->taskSem);
S
shenglian zhou 已提交
800
  QUEUE_REMOVE(&uvTask->procTaskQueue);
801
}
H
Haojun Liao 已提交
802

803
int32_t createUdfcUvTask(SClientUdfTask *task, int8_t uvTaskType, SClientUvTaskNode **pUvTask) {
wafwerar's avatar
wafwerar 已提交
804
  SClientUvTaskNode *uvTask = taosMemoryCalloc(1, sizeof(SClientUvTaskNode));
805
  uvTask->type = uvTaskType;
806
  uvTask->udfc = task->session->udfc;
807 808 809 810 811 812

  if (uvTaskType == UV_TASK_CONNECT) {
  } else if (uvTaskType == UV_TASK_REQ_RSP) {
    uvTask->pipe = task->session->udfSvcPipe;
    SUdfRequest request;
    request.type = task->type;
813
    request.seqNum =   atomic_fetch_add_64(&gUdfTaskSeqNum, 1);
814 815

    if (task->type == UDF_TASK_SETUP) {
S
shenglian zhou 已提交
816
      request.setup = task->_setup.req;
817 818
      request.type = UDF_TASK_SETUP;
    } else if (task->type == UDF_TASK_CALL) {
S
shenglian zhou 已提交
819
      request.call = task->_call.req;
820 821
      request.type = UDF_TASK_CALL;
    } else if (task->type == UDF_TASK_TEARDOWN) {
S
shenglian zhou 已提交
822
      request.teardown = task->_teardown.req;
823 824 825 826
      request.type = UDF_TASK_TEARDOWN;
    } else {
      //TODO log and return error
    }
827 828
    int32_t bufLen = encodeUdfRequest(NULL, &request);
    request.msgLen = bufLen;
S
slzhou 已提交
829 830
    void *bufBegin = taosMemoryMalloc(bufLen);
    void *buf = bufBegin;
831
    encodeUdfRequest(&buf, &request);
S
slzhou 已提交
832
    uvTask->reqBuf = uv_buf_init(bufBegin, bufLen);
833 834 835 836 837
    uvTask->seqNum = request.seqNum;
  } else if (uvTaskType == UV_TASK_DISCONNECT) {
    uvTask->pipe = task->session->udfSvcPipe;
  }
  uv_sem_init(&uvTask->taskSem, 0);
H
Haojun Liao 已提交
838

839 840 841
  *pUvTask = uvTask;
  return 0;
}
H
Haojun Liao 已提交
842

843
int32_t queueUvUdfTask(SClientUvTaskNode *uvTask) {
S
shenglian zhou 已提交
844
  debugPrint("%s, %d", "queue uv task", uvTask->type);
845 846 847 848 849
  SUdfdProxy *udfc = uvTask->udfc;
  uv_mutex_lock(&udfc->gUdfTaskQueueMutex);
  QUEUE_INSERT_TAIL(&udfc->gUdfTaskQueue, &uvTask->recvTaskQueue);
  uv_mutex_unlock(&udfc->gUdfTaskQueueMutex);
  uv_async_send(&udfc->gUdfLoopTaskAync);
H
Haojun Liao 已提交
850

851 852
  uv_sem_wait(&uvTask->taskSem);
  uv_sem_destroy(&uvTask->taskSem);
H
Haojun Liao 已提交
853

854 855
  return 0;
}
H
Haojun Liao 已提交
856

857
int32_t startUvUdfTask(SClientUvTaskNode *uvTask) {
S
shenglian zhou 已提交
858
  debugPrint("%s, type %d", "start uv task ", uvTask->type);
859 860
  switch (uvTask->type) {
    case UV_TASK_CONNECT: {
wafwerar's avatar
wafwerar 已提交
861
      uv_pipe_t *pipe = taosMemoryMalloc(sizeof(uv_pipe_t));
862
      uv_pipe_init(&uvTask->udfc->gUdfdLoop, pipe, 0);
863
      uvTask->pipe = pipe;
H
Haojun Liao 已提交
864

wafwerar's avatar
wafwerar 已提交
865
      SClientUvConn *conn = taosMemoryMalloc(sizeof(SClientUvConn));
866 867 868 869 870
      conn->pipe = pipe;
      conn->readBuf.len = 0;
      conn->readBuf.cap = 0;
      conn->readBuf.buf = 0;
      conn->readBuf.total = -1;
S
shenglian zhou 已提交
871
      QUEUE_INIT(&conn->taskQueue);
H
Haojun Liao 已提交
872

873 874
      pipe->data = conn;

wafwerar's avatar
wafwerar 已提交
875
      uv_connect_t *connReq = taosMemoryMalloc(sizeof(uv_connect_t));
876
      connReq->data = uvTask;
H
Haojun Liao 已提交
877

878
      uv_pipe_connect(connReq, pipe, "udf.sock", onUdfClientConnect);
H
Haojun Liao 已提交
879
      break;
880 881 882
    }
    case UV_TASK_REQ_RSP: {
      uv_pipe_t *pipe = uvTask->pipe;
wafwerar's avatar
wafwerar 已提交
883
      uv_write_t *write = taosMemoryMalloc(sizeof(uv_write_t));
884 885 886 887 888 889
      write->data = uvTask;
      uv_write(write, (uv_stream_t *) pipe, &uvTask->reqBuf, 1, onUdfClientWrite);
      break;
    }
    case UV_TASK_DISCONNECT: {
      SClientUvConn *conn = uvTask->pipe->data;
S
shenglian zhou 已提交
890
      QUEUE_INSERT_TAIL(&conn->taskQueue, &uvTask->connTaskQueue);
891 892 893 894 895 896 897
      uv_close((uv_handle_t *) uvTask->pipe, onUdfcPipeClose);
      break;
    }
    default: {
      break;
    }
  }
H
Haojun Liao 已提交
898

899 900
  return 0;
}
H
Haojun Liao 已提交
901

902
void udfClientAsyncCb(uv_async_t *async) {
903
  SUdfdProxy *udfc = async->data;
S
shenglian zhou 已提交
904
  QUEUE wq;
905

906 907 908
  uv_mutex_lock(&udfc->gUdfTaskQueueMutex);
  QUEUE_MOVE(&udfc->gUdfTaskQueue, &wq);
  uv_mutex_unlock(&udfc->gUdfTaskQueueMutex);
909

S
shenglian zhou 已提交
910 911 912 913
  while (!QUEUE_EMPTY(&wq)) {
    QUEUE* h = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(h);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
914
    startUvUdfTask(task);
915
    QUEUE_INSERT_TAIL(&udfc->gUvProcTaskQueue, &task->procTaskQueue);
916 917 918 919
  }

}

920
void cleanUpUvTasks(SUdfdProxy *udfc) {
S
shenglian zhou 已提交
921
  QUEUE wq;
922

923 924 925
  uv_mutex_lock(&udfc->gUdfTaskQueueMutex);
  QUEUE_MOVE(&udfc->gUdfTaskQueue, &wq);
  uv_mutex_unlock(&udfc->gUdfTaskQueueMutex);
926

S
shenglian zhou 已提交
927 928 929 930
  while (!QUEUE_EMPTY(&wq)) {
    QUEUE* h = QUEUE_HEAD(&wq);
    QUEUE_REMOVE(h);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, recvTaskQueue);
931
    if (udfc->gUdfcState == UDFC_STATE_STOPPING) {
932 933 934 935 936 937
      task->errCode = UDFC_CODE_STOPPING;
    }
    uv_sem_post(&task->taskSem);
  }

  // TODO: deal with tasks that are waiting result.
938 939
  while (!QUEUE_EMPTY(&udfc->gUvProcTaskQueue)) {
    QUEUE* h = QUEUE_HEAD(&udfc->gUvProcTaskQueue);
S
shenglian zhou 已提交
940 941
    QUEUE_REMOVE(h);
    SClientUvTaskNode *task = QUEUE_DATA(h, SClientUvTaskNode, procTaskQueue);
942
    if (udfc->gUdfcState == UDFC_STATE_STOPPING) {
S
shenglian zhou 已提交
943 944 945 946 947
      task->errCode = UDFC_CODE_STOPPING;
    }
    uv_sem_post(&task->taskSem);
  }
}
948

S
shenglian zhou 已提交
949
void udfStopAsyncCb(uv_async_t *async) {
950 951 952 953
  SUdfdProxy *udfc = async->data;
  cleanUpUvTasks(udfc);
  if (udfc->gUdfcState == UDFC_STATE_STOPPING) {
    uv_stop(&udfc->gUdfdLoop);
S
shenglian zhou 已提交
954
  }
955
}
S
shenglian zhou 已提交
956

S
shenglian zhou 已提交
957
void constructUdfService(void *argsThread) {
958 959 960 961 962 963 964 965 966 967 968
  SUdfdProxy *udfc = (SUdfdProxy*)argsThread;
  uv_loop_init(&udfc->gUdfdLoop);

  uv_async_init(&udfc->gUdfdLoop, &udfc->gUdfLoopTaskAync, udfClientAsyncCb);
  udfc->gUdfLoopTaskAync.data = udfc;
  uv_async_init(&udfc->gUdfdLoop, &udfc->gUdfLoopStopAsync, udfStopAsyncCb);
  udfc->gUdfLoopStopAsync.data = udfc;
  uv_mutex_init(&udfc->gUdfTaskQueueMutex);
  QUEUE_INIT(&udfc->gUdfTaskQueue);
  QUEUE_INIT(&udfc->gUvProcTaskQueue);
  uv_barrier_wait(&udfc->gUdfInitBarrier);
969
  //TODO return value of uv_run
970 971
  uv_run(&udfc->gUdfdLoop, UV_RUN_DEFAULT);
  uv_loop_close(&udfc->gUdfdLoop);
972 973
}

974 975 976 977 978 979 980 981 982
int32_t udfcOpen(int32_t dnodeId, UdfcHandle *udfc) {
  SUdfdProxy *proxy = taosMemoryCalloc(1, sizeof(SUdfdProxy));
  proxy->dnodeId = dnodeId;
  proxy->gUdfcState = UDFC_STATE_STARTNG;
  uv_barrier_init(&proxy->gUdfInitBarrier, 2);
  uv_thread_create(&proxy->gUdfLoopThread, constructUdfService, proxy);
  uv_barrier_wait(&proxy->gUdfInitBarrier);
  proxy->gUdfcState = UDFC_STATE_READY;
  *udfc = proxy;
983 984 985
  return 0;
}

986 987 988 989 990 991 992 993 994
int32_t udfcClose(UdfcHandle udfcHandle) {
  SUdfdProxy *udfc = udfcHandle;
  udfc->gUdfcState = UDFC_STATE_STOPPING;
  uv_async_send(&udfc->gUdfLoopStopAsync);
  uv_thread_join(&udfc->gUdfLoopThread);
  uv_mutex_destroy(&udfc->gUdfTaskQueueMutex);
  uv_barrier_destroy(&udfc->gUdfInitBarrier);
  udfc->gUdfcState = UDFC_STATUS_FINAL;
  taosMemoryFree(udfc);
995 996 997
  return 0;
}

998 999 1000 1001 1002 1003 1004 1005
int32_t udfcRunUvTask(SClientUdfTask *task, int8_t uvTaskType) {
  SClientUvTaskNode *uvTask = NULL;

  createUdfcUvTask(task, uvTaskType, &uvTask);
  queueUvUdfTask(uvTask);
  udfcGetUvTaskResponseResult(task, uvTask);
  if (uvTaskType == UV_TASK_CONNECT) {
    task->session->udfSvcPipe = uvTask->pipe;
S
slzhou 已提交
1006 1007
  }
  taosMemoryFree(uvTask);
1008 1009 1010 1011
  uvTask = NULL;
  return task->errCode;
}

1012
int32_t setupUdf(UdfcHandle udfc, char udfName[], SEpSet *epSet, UdfcFuncHandle *funcHandle) {
S
shenglian zhou 已提交
1013
  debugPrint("%s", "client setup udf");
wafwerar's avatar
wafwerar 已提交
1014
  SClientUdfTask *task = taosMemoryMalloc(sizeof(SClientUdfTask));
1015
  task->errCode = 0;
wafwerar's avatar
wafwerar 已提交
1016
  task->session = taosMemoryMalloc(sizeof(SUdfUvSession));
1017
  task->session->udfc = udfc;
1018 1019 1020
  task->type = UDF_TASK_SETUP;

  SUdfSetupRequest *req = &task->_setup.req;
S
shenglian zhou 已提交
1021
  memcpy(req->udfName, udfName, TSDB_FUNC_NAME_LEN);
1022 1023 1024 1025 1026

  int32_t errCode = udfcRunUvTask(task, UV_TASK_CONNECT);
  if (errCode != 0) {
    //TODO: log error
    return -1;
H
Haojun Liao 已提交
1027
  }
1028 1029 1030 1031 1032

  udfcRunUvTask(task, UV_TASK_REQ_RSP);

  SUdfSetupResponse *rsp = &task->_setup.rsp;
  task->session->severHandle = rsp->udfHandle;
1033
  *funcHandle = task->session;
1034
  int32_t err = task->errCode;
wafwerar's avatar
wafwerar 已提交
1035
  taosMemoryFree(task);
1036
  return err;
H
Haojun Liao 已提交
1037 1038
}

1039
int32_t callUdf(UdfcFuncHandle handle, int8_t callType, SSDataBlock *input, SUdfInterBuf *state, SUdfInterBuf *state2,
1040
                SSDataBlock* output, SUdfInterBuf *newState) {
S
shenglian zhou 已提交
1041
  debugPrint("%s", "client call udf");
1042

wafwerar's avatar
wafwerar 已提交
1043
  SClientUdfTask *task = taosMemoryMalloc(sizeof(SClientUdfTask));
1044 1045 1046 1047 1048
  task->errCode = 0;
  task->session = (SUdfUvSession *) handle;
  task->type = UDF_TASK_CALL;

  SUdfCallRequest *req = &task->_call.req;
S
slzhou 已提交
1049
  req->udfHandle = task->session->severHandle;
S
slzhou 已提交
1050
  req->callType = callType;
S
slzhou 已提交
1051

S
shenglian zhou 已提交
1052
  switch (callType) {
1053 1054 1055 1056
    case TSDB_UDF_CALL_AGG_INIT: {
      req->initFirst = 1;
      break;
    }
S
shenglian zhou 已提交
1057 1058 1059 1060 1061
    case TSDB_UDF_CALL_AGG_PROC: {
      req->block = *input;
      req->interBuf = *state;
      break;
    }
1062 1063 1064 1065 1066 1067
    case TSDB_UDF_CALL_AGG_MERGE: {
      req->interBuf = *state;
      req->interBuf2 = *state2;
      break;
    }
    case TSDB_UDF_CALL_AGG_FIN: {
S
shenglian zhou 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076
      req->interBuf = *state;
      break;
    }
    case TSDB_UDF_CALL_SCALA_PROC: {
      req->block = *input;
      break;
    }
  }

1077 1078 1079
  udfcRunUvTask(task, UV_TASK_REQ_RSP);

  SUdfCallResponse *rsp = &task->_call.rsp;
S
shenglian zhou 已提交
1080
  switch (callType) {
1081
    case TSDB_UDF_CALL_AGG_INIT: {
S
slzhou 已提交
1082
      *newState = rsp->resultBuf;
1083 1084
      break;
    }
S
shenglian zhou 已提交
1085
    case TSDB_UDF_CALL_AGG_PROC: {
S
slzhou 已提交
1086
      *newState = rsp->resultBuf;
S
shenglian zhou 已提交
1087 1088
      break;
    }
1089
    case TSDB_UDF_CALL_AGG_MERGE: {
S
slzhou 已提交
1090
      *newState = rsp->resultBuf;
1091 1092 1093
      break;
    }
    case TSDB_UDF_CALL_AGG_FIN: {
S
slzhou 已提交
1094
      *newState = rsp->resultBuf;
S
shenglian zhou 已提交
1095 1096 1097 1098 1099 1100 1101 1102
      break;
    }
    case TSDB_UDF_CALL_SCALA_PROC: {
      *output = rsp->resultData;
      break;
    }
  }

wafwerar's avatar
wafwerar 已提交
1103
  taosMemoryFree(task);
S
shenglian zhou 已提交
1104
  return task->errCode;
1105 1106
}

S
slzhou 已提交
1107
//TODO: translate these calls to callUdf
1108
int32_t callUdfAggInit(UdfcFuncHandle handle, SUdfInterBuf *interBuf) {
S
slzhou 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117
  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,
1118
int32_t callUdfAggProcess(UdfcFuncHandle handle, SSDataBlock *block, SUdfInterBuf *state, SUdfInterBuf *newState) {
S
slzhou 已提交
1119 1120 1121 1122 1123 1124 1125
  int8_t callType = TSDB_UDF_CALL_AGG_PROC;
  int32_t err = callUdf(handle, callType, block, state, NULL, NULL, newState);
  return err;
}

// input: interbuf1, interbuf2
// output: resultBuf
1126
int32_t callUdfAggMerge(UdfcFuncHandle handle, SUdfInterBuf *interBuf1, SUdfInterBuf *interBuf2, SUdfInterBuf *resultBuf) {
S
slzhou 已提交
1127 1128 1129 1130 1131 1132 1133
  int8_t callType = TSDB_UDF_CALL_AGG_MERGE;
  int32_t err = callUdf(handle, callType, NULL, interBuf1, interBuf2, NULL, resultBuf);
  return err;
}

// input: interBuf
// output: resultData
1134
int32_t callUdfAggFinalize(UdfcFuncHandle handle, SUdfInterBuf *interBuf, SUdfInterBuf *resultData) {
S
slzhou 已提交
1135 1136 1137 1138 1139
  int8_t callType = TSDB_UDF_CALL_AGG_PROC;
  int32_t err = callUdf(handle, callType, NULL, interBuf, NULL, NULL, resultData);
  return err;
}

S
slzhou 已提交
1140
int32_t callUdfScalarFunc(UdfcFuncHandle handle, SScalarParam *input, int32_t numOfCols, SScalarParam* output) {
S
slzhou 已提交
1141
  int8_t callType = TSDB_UDF_CALL_SCALA_PROC;
S
slzhou 已提交
1142 1143 1144 1145 1146
  SSDataBlock inputBlock = {0};
  convertScalarParamToDataBlock(input, numOfCols, &inputBlock);
  SSDataBlock resultBlock = {0};
  int32_t err = callUdf(handle, callType, &inputBlock, NULL, NULL, &resultBlock, NULL);
  convertDataBlockToScalarParm(&resultBlock, output);
S
slzhou 已提交
1147 1148 1149
  return err;
}

1150
int32_t teardownUdf(UdfcFuncHandle handle) {
S
shenglian zhou 已提交
1151
  debugPrint("%s", "client teardown udf");
1152

wafwerar's avatar
wafwerar 已提交
1153
  SClientUdfTask *task = taosMemoryMalloc(sizeof(SClientUdfTask));
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
  task->errCode = 0;
  task->session = (SUdfUvSession *) handle;
  task->type = UDF_TASK_TEARDOWN;

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

  udfcRunUvTask(task, UV_TASK_REQ_RSP);


  SUdfTeardownResponse *rsp = &task->_teardown.rsp;

  int32_t err = task->errCode;

  udfcRunUvTask(task, UV_TASK_DISCONNECT);

wafwerar's avatar
wafwerar 已提交
1170 1171
  taosMemoryFree(task->session);
  taosMemoryFree(task);
1172 1173 1174

  return err;
}