udfd.c 10.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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
shenglian zhou 已提交
18 19
#include "tlog.h"

20 21 22 23 24
#include "tudf.h"
#include "tudfInt.h"


static uv_loop_t *loop;
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

typedef struct SUdfdUvConn {
    uv_stream_t *client;
    char *inputBuf;
    int32_t inputLen;
    int32_t inputCap;
    int32_t inputTotal;
} SUdfdUvConn;

typedef struct SUvUdfWork {
    uv_stream_t *client;
    uv_buf_t input;
    uv_buf_t output;
} SUvUdfWork;

typedef struct SUdf {
    int32_t refCount;

    char name[16];
    int8_t type;

    uv_lib_t lib;
47
    TUdfFunc normalFunc;
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
} SUdf;

//TODO: low priority: change name onxxx to xxxCb, and udfc or udfd as prefix
//TODO: add private udf structure.
typedef struct SUdfHandle {
    SUdf *udf;
} SUdfHandle;


void udfdProcessRequest(uv_work_t *req) {
    SUvUdfWork *uvUdf = (SUvUdfWork *) (req->data);
    SUdfRequest *request = NULL;
    decodeRequest(uvUdf->input.base, uvUdf->input.len, &request);

    switch (request->type) {
        case UDF_TASK_SETUP: {
S
shenglian zhou 已提交
64
            debugPrint("%s", "process setup request");
65 66 67 68 69 70
            SUdf *udf = malloc(sizeof(SUdf));
            udf->refCount = 0;
            SUdfSetupRequest *setup = request->subReq;
            strcpy(udf->name, setup->udfName);
            int err = uv_dlopen(setup->path, &udf->lib);
            if (err != 0) {
S
shenglian zhou 已提交
71
                debugPrint("can not load library %s. error: %s", setup->path, uv_strerror(err));
72 73 74 75 76
                //TODO set error
            }

            char normalFuncName[32] = {0};
            strcpy(normalFuncName, setup->udfName);
77
	    //TODO error,
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
	    //TODO find all functions normal, init, destroy, normal, merge, finalize
            uv_dlsym(&udf->lib, normalFuncName, (void **) (&udf->normalFunc));

            SUdfHandle *handle = malloc(sizeof(SUdfHandle));
            handle->udf = udf;
            udf->refCount++;
            //TODO: allocate private structure and call init function and set it to handle
            SUdfResponse *rsp = malloc(sizeof(SUdfResponse));
            rsp->seqNum = request->seqNum;
            rsp->type = request->type;
            rsp->code = 0;
            SUdfSetupResponse *subRsp = malloc(sizeof(SUdfSetupResponse));
            subRsp->udfHandle = (int64_t) (handle);
            rsp->subRsp = subRsp;
            char *buf;
            int32_t len;
            encodeResponse(&buf, &len, rsp);

            uvUdf->output = uv_buf_init(buf, len);

            free(rsp->subRsp);
            free(rsp);
            free(request->subReq);
            free(request);
            free(uvUdf->input.base);
            break;
        }

        case UDF_TASK_CALL: {
S
shenglian zhou 已提交
107
            debugPrint("%s", "process call request");
108 109 110 111 112
            SUdfCallRequest *call = request->subReq;
            SUdfHandle *handle = (SUdfHandle *) (call->udfHandle);
            SUdf *udf = handle->udf;
            char *newState;
            int32_t newStateSize;
113 114
            SUdfDataBlock input = {.data = call->input, .size= call->inputBytes};
            SUdfDataBlock output;
115
	    //TODO: call different functions according to the step 
116
            udf->normalFunc(call->step, call->state, call->stateBytes, input, &newState, &newStateSize, &output);
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

            SUdfResponse *rsp = malloc(sizeof(SUdfResponse));
            rsp->seqNum = request->seqNum;
            rsp->type = request->type;
            rsp->code = 0;
            SUdfCallResponse *subRsp = malloc(sizeof(SUdfCallResponse));
            subRsp->outputBytes = output.size;
            subRsp->output = output.data;
            subRsp->newStateBytes = newStateSize;
            subRsp->newState = newState;
            rsp->subRsp = subRsp;

            char *buf;
            int32_t len;
            encodeResponse(&buf, &len, rsp);
            uvUdf->output = uv_buf_init(buf, len);

            free(rsp->subRsp);
            free(rsp);
            free(newState);
            free(output.data);
            free(request->subReq);
            free(request);
            free(uvUdf->input.base);
            break;
        }
        case UDF_TASK_TEARDOWN: {
S
shenglian zhou 已提交
144
            debugPrint("%s", "process teardown request");
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

            SUdfTeardownRequest *teardown = request->subReq;
            SUdfHandle *handle = (SUdfHandle *) (teardown->udfHandle);
            SUdf *udf = handle->udf;
            udf->refCount--;
            if (udf->refCount == 0) {
                uv_dlclose(&udf->lib);
            }
            free(udf);
	    //TODO: call destroy and free udf private 
            free(handle);

            SUdfResponse *rsp = malloc(sizeof(SUdfResponse));
            rsp->seqNum = request->seqNum;
            rsp->type = request->type;
            rsp->code = 0;
            SUdfTeardownResponse *subRsp = malloc(sizeof(SUdfTeardownResponse));
            rsp->subRsp = subRsp;
            char *buf;
            int32_t len;
            encodeResponse(&buf, &len, rsp);
            uvUdf->output = uv_buf_init(buf, len);

            free(rsp->subRsp);
            free(rsp);
            free(request->subReq);
            free(request);
            free(uvUdf->input.base);
            break;
        }
        default: {
            break;
        }

    }

}

void udfdOnWrite(uv_write_t *req, int status) {
S
shenglian zhou 已提交
184
    debugPrint("%s", "after writing to pipe");
185
    if (status < 0) {
S
shenglian zhou 已提交
186
        debugPrint("Write error %s", uv_err_name(status));
187 188
    }
    SUvUdfWork *work = (SUvUdfWork *) req->data;
S
shenglian zhou 已提交
189
    debugPrint("\tlength: %zu", work->output.len);
190 191 192 193 194 195 196
    free(work->output.base);
    free(work);
    free(req);
}


void udfdSendResponse(uv_work_t *work, int status) {
S
shenglian zhou 已提交
197
    debugPrint("%s", "send response");
198 199 200 201 202 203 204 205 206 207
    SUvUdfWork *udfWork = (SUvUdfWork *) (work->data);

    uv_write_t *write_req = malloc(sizeof(uv_write_t));
    write_req->data = udfWork;
    uv_write(write_req, udfWork->client, &udfWork->output, 1, udfdOnWrite);

    free(work);
}

void udfdAllocBuffer(uv_handle_t *handle, size_t suggestedSize, uv_buf_t *buf) {
S
shenglian zhou 已提交
208
    debugPrint("%s", "allocate buffer for read");
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    SUdfdUvConn *ctx = handle->data;
    int32_t msgHeadSize = sizeof(int32_t) + sizeof(int64_t);
    if (ctx->inputCap == 0) {
        ctx->inputBuf = malloc(msgHeadSize);
        if (ctx->inputBuf) {
            ctx->inputLen = 0;
            ctx->inputCap = msgHeadSize;
            ctx->inputTotal = -1;

            buf->base = ctx->inputBuf;
            buf->len = ctx->inputCap;
        } else {
            //TODO: log error
            buf->base = NULL;
            buf->len = 0;
        }
    } else {
        ctx->inputCap = ctx->inputTotal > ctx->inputCap ? ctx->inputTotal : ctx->inputCap;
        void *inputBuf = realloc(ctx->inputBuf, ctx->inputCap);
        if (inputBuf) {
            ctx->inputBuf = inputBuf;
            buf->base = ctx->inputBuf + ctx->inputLen;
            buf->len = ctx->inputCap - ctx->inputLen;
        } else {
            //TODO: log error
            buf->base = NULL;
            buf->len = 0;
        }
    }
S
shenglian zhou 已提交
238
    debugPrint("\tinput buf cap - len - total : %d - %d - %d", ctx->inputCap, ctx->inputLen, ctx->inputTotal);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

}

bool isUdfdUvMsgComplete(SUdfdUvConn *pipe) {
    if (pipe->inputTotal == -1 && pipe->inputLen >= sizeof(int32_t)) {
        pipe->inputTotal = *(int32_t *) (pipe->inputBuf);
    }
    if (pipe->inputLen == pipe->inputCap && pipe->inputTotal == pipe->inputCap) {
        return true;
    }
    return false;
}

void udfdHandleRequest(SUdfdUvConn *conn) {
    uv_work_t *work = malloc(sizeof(uv_work_t));
    SUvUdfWork *udfWork = malloc(sizeof(SUvUdfWork));
    udfWork->client = conn->client;
    udfWork->input = uv_buf_init(conn->inputBuf, conn->inputLen);
    conn->inputBuf = NULL;
    conn->inputLen = 0;
    conn->inputCap = 0;
    conn->inputTotal = -1;
    work->data = udfWork;
    uv_queue_work(loop, work, udfdProcessRequest, udfdSendResponse);
}

void udfdPipeCloseCb(uv_handle_t *pipe) {
    SUdfdUvConn *conn = pipe->data;
    free(conn->client);
    free(conn->inputBuf);
    free(conn);
}

void udfdUvHandleError(SUdfdUvConn *conn) {
    uv_close((uv_handle_t *) conn->client, udfdPipeCloseCb);
}

void udfdPipeRead(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
S
shenglian zhou 已提交
277
    debugPrint("%s, nread: %zd", "read from pipe", nread);
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

    if (nread == 0) return;

    SUdfdUvConn *conn = client->data;

    if (nread > 0) {
        conn->inputLen += nread;
        if (isUdfdUvMsgComplete(conn)) {
            udfdHandleRequest(conn);
        } else {
            //log error or continue;
        }
        return;
    }

    if (nread < 0) {
S
shenglian zhou 已提交
294
        debugPrint("Read error %s", uv_err_name(nread));
295 296 297 298 299 300 301 302 303
        if (nread == UV_EOF) {
            //TODO check more when close
        } else {
        }
        udfdUvHandleError(conn);
    }
}

void udfdOnNewConnection(uv_stream_t *server, int status) {
S
shenglian zhou 已提交
304
    debugPrint("%s", "on new connection");
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
    if (status < 0) {
        // TODO
        return;
    }

    uv_pipe_t *client = (uv_pipe_t *) malloc(sizeof(uv_pipe_t));
    uv_pipe_init(loop, client, 0);
    if (uv_accept(server, (uv_stream_t *) client) == 0) {
        SUdfdUvConn *ctx = malloc(sizeof(SUdfdUvConn));
        ctx->client = (uv_stream_t *) client;
        ctx->inputBuf = 0;
        ctx->inputLen = 0;
        ctx->inputCap = 0;
        client->data = ctx;
        ctx->client = (uv_stream_t *) client;
        uv_read_start((uv_stream_t *) client, udfdAllocBuffer, udfdPipeRead);
    } else {
        uv_close((uv_handle_t *) client, NULL);
    }
}

void removeListeningPipe(int sig) {
    uv_fs_t req;
    uv_fs_unlink(loop, &req, "udf.sock", NULL);
    exit(0);
}

int main() {
S
shenglian zhou 已提交
333
    debugPrint("libuv version: %x", UV_VERSION_HEX);
334 335 336 337 338 339 340 341 342 343 344 345

    loop = uv_default_loop();
    uv_fs_t req;
    uv_fs_unlink(loop, &req, "udf.sock", NULL);

    uv_pipe_t server;
    uv_pipe_init(loop, &server, 0);

    signal(SIGINT, removeListeningPipe);

    int r;
    if ((r = uv_pipe_bind(&server, "udf.sock"))) {
S
shenglian zhou 已提交
346
        debugPrint("Bind error %s\n", uv_err_name(r));
347 348 349 350
        removeListeningPipe(0);
        return 1;
    }
    if ((r = uv_listen((uv_stream_t *) &server, 128, udfdOnNewConnection))) {
S
shenglian zhou 已提交
351
        debugPrint("Listen error %s", uv_err_name(r));
352 353 354 355 356
        return 2;
    }
    uv_run(loop, UV_RUN_DEFAULT);
    uv_loop_close(loop);
}