udfd.c 10.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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 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 144 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 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 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 238 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 277 278 279 280 281 282 283 284 285 286 287 288 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
#include <udf.h>
#include <stdbool.h>

uv_loop_t *loop;

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 void (*TUdfNormalFunc)(char *state, int32_t stateSize, char **newstate, int32_t *newStateSize,
                               SSDataBlock input, SSDataBlock *output);


typedef struct SUdf {
    int32_t refCount;

    char name[16];
    int8_t type;

    uv_lib_t lib;
    TUdfNormalFunc normalFunc;

} 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;


typedef void (*TUdfNormalFunc)(char *state, int32_t stateSize, char **newstate, int32_t *newStateSize,
                               SSDataBlock input, SSDataBlock *output);


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: {
            debugPrint(stdout, "%s\n", "process setup request");
            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) {
                debugPrint(stderr, "can not load library %s. error: %s", setup->path, uv_strerror(err));
                //TODO set error
            }

            char normalFuncName[32] = {0};
            strcpy(normalFuncName, setup->udfName);
            strcat(normalFuncName, "_normal");
	    //TODO error, 
	    //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: {
            debugPrint(stdout, "%s\n", "process call request");
            SUdfCallRequest *call = request->subReq;
            SUdfHandle *handle = (SUdfHandle *) (call->udfHandle);
            SUdf *udf = handle->udf;
            char *newState;
            int32_t newStateSize;
            SSDataBlock input = {.data = call->input, .size= call->inputBytes};
            SSDataBlock output;
	    //TODO: call different functions according to the step 
            udf->normalFunc(call->state, call->stateBytes, &newState, &newStateSize, input, &output);

            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: {
            debugPrint(stdout, "%s\n", "process teardown request");

            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) {
    debugPrint(stdout, "%s\n", "after writing to pipe");
    if (status < 0) {
        debugPrint(stderr, "Write error %s\n", uv_err_name(status));
    }
    SUvUdfWork *work = (SUvUdfWork *) req->data;
    debugPrint(stdout, "\tlength: %zu\n", work->output.len);
    free(work->output.base);
    free(work);
    free(req);
}


void udfdSendResponse(uv_work_t *work, int status) {
    debugPrint(stdout, "%s\n", "send response");
    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) {
    debugPrint(stdout, "%s\n", "allocate buffer for read");
    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;
        }
    }
    debugPrint(stdout, "\tinput buf cap - len - total : %d - %d - %d\n", ctx->inputCap, ctx->inputLen, ctx->inputTotal);

}

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) {
    debugPrint(stdout, "%s, nread: %zd\n", "read from pipe", nread);

    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) {
        debugPrint(stderr, "Read error %s\n", uv_err_name(nread));
        if (nread == UV_EOF) {
            //TODO check more when close
        } else {
        }
        udfdUvHandleError(conn);
    }
}

void udfdOnNewConnection(uv_stream_t *server, int status) {
    debugPrint(stdout, "%s\n", "on new connection");
    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() {
    debugPrint(stderr, "libuv version: %x\n", UV_VERSION_HEX);

    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"))) {
        debugPrint(stderr, "Bind error %s\n", uv_err_name(r));
        removeListeningPipe(0);
        return 1;
    }
    if ((r = uv_listen((uv_stream_t *) &server, 128, udfdOnNewConnection))) {
        debugPrint(stderr, "Listen error %s\n", uv_err_name(r));
        return 2;
    }
    uv_run(loop, UV_RUN_DEFAULT);
    uv_loop_close(loop);
}