stream.c 16.8 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
/*
 * stream.c: APIs for managing client streams
 *
 * Copyright (C) 2009 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */


#include <config.h>

#include "stream.h"
#include "memory.h"
#include "dispatch.h"
#include "logging.h"
30 31 32
#include "virterror_internal.h"

#define VIR_FROM_THIS VIR_FROM_STREAMS
33

34 35 36 37
static int
remoteStreamHandleWrite(struct qemud_client *client,
                        struct qemud_client_stream *stream);
static int
38 39 40
remoteStreamHandleRead(struct qemud_client *client,
                       struct qemud_client_stream *stream);
static int
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
remoteStreamHandleFinish(struct qemud_client *client,
                         struct qemud_client_stream *stream,
                         struct qemud_client_message *msg);
static int
remoteStreamHandleAbort(struct qemud_client *client,
                        struct qemud_client_stream *stream,
                        struct qemud_client_message *msg);



static void
remoteStreamUpdateEvents(struct qemud_client_stream *stream)
{
    int newEvents = 0;
    if (stream->rx)
        newEvents |= VIR_STREAM_EVENT_WRITABLE;
57 58
    if (stream->tx && !stream->recvEOF)
        newEvents |= VIR_STREAM_EVENT_READABLE;
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

    virStreamEventUpdateCallback(stream->st, newEvents);
}


/*
 * Callback that gets invoked when a stream becomes writable/readable
 */
static void
remoteStreamEvent(virStreamPtr st, int events, void *opaque)
{
    struct qemud_client *client = opaque;
    struct qemud_client_stream *stream;

    /* XXX sub-optimal - we really should be taking the server lock
     * first, but we have no handle to the server object
     * We're lucky to get away with it for now, due to this callback
     * executing in the main thread, but this should really be fixed
     */
    virMutexLock(&client->lock);

    stream = remoteFindClientStream(client, st);

    if (!stream) {
        VIR_WARN("event for client=%p stream st=%p, but missing stream state", client, st);
        virStreamEventRemoveCallback(st);
        goto cleanup;
    }

88
    VIR_DEBUG("st=%p events=%d", st, events);
89 90 91 92 93 94 95 96 97

    if (events & VIR_STREAM_EVENT_WRITABLE) {
        if (remoteStreamHandleWrite(client, stream) < 0) {
            remoteRemoveClientStream(client, stream);
            qemudDispatchClientFailure(client);
            goto cleanup;
        }
    }

98 99 100 101 102 103 104 105 106 107
    if (!stream->recvEOF &&
        (events & (VIR_STREAM_EVENT_READABLE | VIR_STREAM_EVENT_HANGUP))) {
        events = events & ~(VIR_STREAM_EVENT_READABLE | VIR_STREAM_EVENT_HANGUP);
        if (remoteStreamHandleRead(client, stream) < 0) {
            remoteRemoveClientStream(client, stream);
            qemudDispatchClientFailure(client);
            goto cleanup;
        }
    }

108 109 110 111 112 113
    if (!stream->closed &&
        (events & (VIR_STREAM_EVENT_ERROR | VIR_STREAM_EVENT_HANGUP))) {
        int ret;
        remote_error rerr;
        memset(&rerr, 0, sizeof rerr);
        stream->closed = 1;
114
        virStreamEventRemoveCallback(stream->st);
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        virStreamAbort(stream->st);
        if (events & VIR_STREAM_EVENT_HANGUP)
            remoteDispatchFormatError(&rerr, "%s", _("stream had unexpected termination"));
        else
            remoteDispatchFormatError(&rerr, "%s", _("stream had I/O failure"));
        ret = remoteSerializeStreamError(client, &rerr, stream->procedure, stream->serial);
        remoteRemoveClientStream(client, stream);
        if (ret < 0)
            qemudDispatchClientFailure(client);
        goto cleanup;
    }

    if (stream->closed) {
        remoteRemoveClientStream(client, stream);
    } else {
        remoteStreamUpdateEvents(stream);
    }

cleanup:
    virMutexUnlock(&client->lock);
}

137 138 139 140 141 142 143 144 145 146

/*
 * @client: a locked client object
 *
 * Invoked by the main loop when filtering incoming messages.
 *
 * Returns 1 if the message was processed, 0 if skipped,
 * -1 on fatal client error
 */
static int
147 148
remoteStreamFilter(struct qemud_client *client,
                   struct qemud_client_message *msg, void *opaque)
149
{
150 151 152 153 154
    struct qemud_client_stream *stream = opaque;

    if (msg->hdr.serial == stream->serial &&
        msg->hdr.proc == stream->procedure &&
        msg->hdr.type == REMOTE_STREAM) {
155
        VIR_DEBUG("Incoming rx=%p serial=%d proc=%d status=%d",
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
              stream->rx, msg->hdr.proc, msg->hdr.serial, msg->hdr.status);

        /* If there are queued packets, we need to queue all further
         * messages, since they must be processed strictly in order.
         * If there are no queued packets, then OK/ERROR messages
         * should be processed immediately. Data packets are still
         * queued to only be processed when the stream is marked as
         * writable.
         */
        if (stream->rx) {
            qemudClientMessageQueuePush(&stream->rx, msg);
            remoteStreamUpdateEvents(stream);
        } else {
            int ret = 0;
            switch (msg->hdr.status) {
            case REMOTE_OK:
                ret = remoteStreamHandleFinish(client, stream, msg);
                if (ret == 0)
                    qemudClientMessageRelease(client, msg);
                break;

            case REMOTE_CONTINUE:
                qemudClientMessageQueuePush(&stream->rx, msg);
                remoteStreamUpdateEvents(stream);
                break;

            case REMOTE_ERROR:
            default:
                ret = remoteStreamHandleAbort(client, stream, msg);
                if (ret == 0)
                    qemudClientMessageRelease(client, msg);
                break;
            }

            if (ret < 0)
                return -1;
        }
        return 1;
    }
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    return 0;
}


/*
 * @conn: a connection object to associate the stream with
 * @hdr: the method call to associate with the stram
 *
 * Creates a new stream for this conn
 *
 * Returns a new stream object, or NULL upon OOM
 */
struct qemud_client_stream *
remoteCreateClientStream(virConnectPtr conn,
                         remote_message_header *hdr)
{
    struct qemud_client_stream *stream;

213
    VIR_DEBUG("proc=%d serial=%d", hdr->proc, hdr->serial);
214

215 216
    if (VIR_ALLOC(stream) < 0) {
        virReportOOMError();
217
        return NULL;
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

    stream->procedure = hdr->proc;
    stream->serial = hdr->serial;

    stream->st = virStreamNew(conn, VIR_STREAM_NONBLOCK);
    if (!stream->st) {
        VIR_FREE(stream);
        return NULL;
    }

    stream->filter.query = remoteStreamFilter;
    stream->filter.opaque = stream;

    return stream;
}

/*
 * @stream: an unused client stream
 *
 * Frees the memory associated with this inactive client
 * stream
 */
void remoteFreeClientStream(struct qemud_client *client,
                            struct qemud_client_stream *stream)
{
    struct qemud_client_message *msg;

    if (!stream)
        return;

249
    VIR_DEBUG("proc=%d serial=%d", stream->procedure, stream->serial);
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267

    msg = stream->rx;
    while (msg) {
        struct qemud_client_message *tmp = msg->next;
        qemudClientMessageRelease(client, msg);
        msg = tmp;
    }

    virStreamFree(stream->st);
    VIR_FREE(stream);
}


/*
 * @client: a locked client to add the stream to
 * @stream: a stream to add
 */
int remoteAddClientStream(struct qemud_client *client,
268 269
                          struct qemud_client_stream *stream,
                          int transmit)
270 271 272
{
    struct qemud_client_stream *tmp = client->streams;

273
    VIR_DEBUG("client=%p proc=%d serial=%d", client, stream->procedure, stream->serial);
274

275 276 277 278
    if (virStreamEventAddCallback(stream->st, 0,
                                  remoteStreamEvent, client, NULL) < 0)
        return -1;

279 280 281 282 283 284 285 286 287 288 289
    if (tmp) {
        while (tmp->next)
            tmp = tmp->next;
        tmp->next = stream;
    } else {
        client->streams = stream;
    }

    stream->filter.next = client->filters;
    client->filters = &stream->filter;

290 291
    if (transmit)
        stream->tx = 1;
292

293 294
    remoteStreamUpdateEvents(stream);

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


/*
 * @client: a locked client object
 * @procedure: procedure associated with the stream
 * @serial: serial number associated with the stream
 *
 * Finds a existing active stream
 *
 * Returns a stream object matching the procedure+serial number, or NULL
 */
struct qemud_client_stream *
remoteFindClientStream(struct qemud_client *client,
                       virStreamPtr st)
{
    struct qemud_client_stream *stream = client->streams;

    while (stream) {
        if (stream->st == st)
            return stream;
        stream = stream->next;
    }

    return NULL;
}


/*
 * @client: a locked client object
 * @stream: an inactive, closed stream object
 *
 * Removes a stream from the list of active streams for the client
 *
 * Returns 0 if the stream was removd, -1 if it doesn't exist
 */
int
remoteRemoveClientStream(struct qemud_client *client,
                         struct qemud_client_stream *stream)
{
336
    VIR_DEBUG("client=%p proc=%d serial=%d", client, stream->procedure, stream->serial);
337 338 339 340 341 342 343 344 345 346 347 348 349 350

    struct qemud_client_stream *curr = client->streams;
    struct qemud_client_stream *prev = NULL;
    struct qemud_client_filter *filter = NULL;

    if (client->filters == &stream->filter) {
        client->filters = client->filters->next;
    } else {
        filter = client->filters;
        while (filter) {
            if (filter->next == &stream->filter) {
                filter->next = filter->next->next;
                break;
            }
351
            filter = filter->next;
352 353 354
        }
    }

355 356
    if (!stream->closed) {
        virStreamEventRemoveCallback(stream->st);
357
        virStreamAbort(stream->st);
358
    }
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

    while (curr) {
        if (curr == stream) {
            if (prev)
                prev->next = curr->next;
            else
                client->streams = curr->next;
            remoteFreeClientStream(client, stream);
            return 0;
        }
        prev = curr;
        curr = curr->next;
    }
    return -1;
}
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389


/*
 * Returns:
 *   -1  if fatal error occurred
 *    0  if message was fully processed
 *    1  if message is still being processed
 */
static int
remoteStreamHandleWriteData(struct qemud_client *client,
                            struct qemud_client_stream *stream,
                            struct qemud_client_message *msg)
{
    remote_error rerr;
    int ret;

390
    VIR_DEBUG("stream=%p proc=%d serial=%d len=%d offset=%d",
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
          stream, msg->hdr.proc, msg->hdr.serial, msg->bufferLength, msg->bufferOffset);

    memset(&rerr, 0, sizeof rerr);

    ret = virStreamSend(stream->st,
                        msg->buffer + msg->bufferOffset,
                        msg->bufferLength - msg->bufferOffset);

    if (ret > 0) {
        msg->bufferOffset += ret;

        /* Partial write, so indicate we have more todo later */
        if (msg->bufferOffset < msg->bufferLength)
            return 1;
    } else if (ret == -2) {
        /* Blocking, so indicate we have more todo later */
        return 1;
    } else {
409
        VIR_INFO("Stream send failed");
410
        stream->closed = 1;
411
        remoteDispatchError(&rerr);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        return remoteSerializeReplyError(client, &rerr, &msg->hdr);
    }

    return 0;
}


/*
 * Process an finish handshake from the client.
 *
 * Returns a REMOTE_OK confirmation if successful, or a REMOTE_ERROR
 * if there was a stream error
 *
 * Returns 0 if successfully sent RPC reply, -1 upon fatal error
 */
static int
remoteStreamHandleFinish(struct qemud_client *client,
                         struct qemud_client_stream *stream,
                         struct qemud_client_message *msg)
{
    remote_error rerr;
    int ret;

435
    VIR_DEBUG("stream=%p proc=%d serial=%d",
436 437 438 439 440
          stream, msg->hdr.proc, msg->hdr.serial);

    memset(&rerr, 0, sizeof rerr);

    stream->closed = 1;
441
    virStreamEventRemoveCallback(stream->st);
442 443 444
    ret = virStreamFinish(stream->st);

    if (ret < 0) {
445
        remoteDispatchError(&rerr);
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
        return remoteSerializeReplyError(client, &rerr, &msg->hdr);
    } else {
        /* Send zero-length confirm */
        if (remoteSendStreamData(client, stream, NULL, 0) < 0)
            return -1;
    }

    return 0;
}


/*
 * Process an abort request from the client.
 *
 * Returns 0 if successfully aborted, -1 upon error
 */
static int
remoteStreamHandleAbort(struct qemud_client *client,
                        struct qemud_client_stream *stream,
                        struct qemud_client_message *msg)
{
    remote_error rerr;

469
    VIR_DEBUG("stream=%p proc=%d serial=%d",
470 471 472 473 474
          stream, msg->hdr.proc, msg->hdr.serial);

    memset(&rerr, 0, sizeof rerr);

    stream->closed = 1;
475
    virStreamEventRemoveCallback(stream->st);
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    virStreamAbort(stream->st);

    if (msg->hdr.status == REMOTE_ERROR)
        remoteDispatchFormatError(&rerr, "%s", _("stream aborted at client request"));
    else {
        VIR_WARN("unexpected stream status %d", msg->hdr.status);
        remoteDispatchFormatError(&rerr, _("stream aborted with unexpected status %d"),
                                  msg->hdr.status);
    }

    return remoteSerializeReplyError(client, &rerr, &msg->hdr);
}



/*
 * Called when the stream is signalled has being able to accept
 * data writes. Will process all pending incoming messages
 * until they're all gone, or I/O blocks
 *
 * Returns 0 on success, or -1 upon fatal error
 */
static int
remoteStreamHandleWrite(struct qemud_client *client,
                        struct qemud_client_stream *stream)
{
    struct qemud_client_message *msg, *tmp;

504
    VIR_DEBUG("stream=%p", stream);
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

    msg = stream->rx;
    while (msg && !stream->closed) {
        int ret;
        switch (msg->hdr.status) {
        case REMOTE_OK:
            ret = remoteStreamHandleFinish(client, stream, msg);
            break;

        case REMOTE_CONTINUE:
            ret = remoteStreamHandleWriteData(client, stream, msg);
            break;

        case REMOTE_ERROR:
        default:
            ret = remoteStreamHandleAbort(client, stream, msg);
            break;
        }

        if (ret == 0)
            qemudClientMessageQueueServe(&stream->rx);
        else if (ret < 0)
            return -1;
        else
            break; /* still processing data */

        tmp = msg->next;
        qemudClientMessageRelease(client, msg);
        msg = tmp;
    }

    return 0;
}
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558



/*
 * Invoked when a stream is signalled as having data
 * available to read. This reads upto one message
 * worth of data, and then queues that for transmission
 * to the client.
 *
 * Returns 0 if data was queued for TX, or a error RPC
 * was sent, or -1 on fatal error, indicating client should
 * be killed
 */
static int
remoteStreamHandleRead(struct qemud_client *client,
                       struct qemud_client_stream *stream)
{
    char *buffer;
    size_t bufferLen = REMOTE_MESSAGE_PAYLOAD_MAX;
    int ret;

559
    VIR_DEBUG("stream=%p", stream);
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

    /* Shouldn't ever be called unless we're marked able to
     * transmit, but doesn't hurt to check */
    if (!stream->tx)
        return 0;

    if (VIR_ALLOC_N(buffer, bufferLen) < 0)
        return -1;

    ret = virStreamRecv(stream->st, buffer, bufferLen);
    if (ret == -2) {
        /* Should never get this, since we're only called when we know
         * we're readable, but hey things change... */
        ret = 0;
    } else if (ret < 0) {
        remote_error rerr;
        memset(&rerr, 0, sizeof rerr);
577
        remoteDispatchError(&rerr);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

        ret = remoteSerializeStreamError(client, &rerr, stream->procedure, stream->serial);
    } else {
        stream->tx = 0;
        if (ret == 0)
            stream->recvEOF = 1;
        ret = remoteSendStreamData(client, stream, buffer, ret);
    }

    VIR_FREE(buffer);
    return ret;
}


/*
 * Invoked when an outgoing data packet message has been fully sent.
 * This simply re-enables TX of further data.
 *
 * The idea is to stop the daemon growing without bound due to
 * fast stream, but slow client
 */
void
remoteStreamMessageFinished(struct qemud_client *client,
                            struct qemud_client_message *msg)
{
    struct qemud_client_stream *stream = client->streams;

    while (stream) {
        if (msg->hdr.proc == stream->procedure &&
            msg->hdr.serial == stream->serial)
            break;
        stream = stream->next;
    }

612
    VIR_DEBUG("Message client=%p stream=%p proc=%d serial=%d", client, stream, msg->hdr.proc, msg->hdr.serial);
613 614 615 616 617 618

    if (stream) {
        stream->tx = 1;
        remoteStreamUpdateEvents(stream);
    }
}