qemu_agent.c 63.0 KB
Newer Older
D
Daniel P. Berrange 已提交
1
/*
2
 * qemu_agent.c: interaction with QEMU guest agent
D
Daniel P. Berrange 已提交
3
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
D
Daniel P. Berrange 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32
 */

#include <config.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>

#include "qemu_agent.h"
33
#include "viralloc.h"
34
#include "virlog.h"
35
#include "virerror.h"
36
#include "virjson.h"
D
Daniel P. Berrange 已提交
37
#include "virfile.h"
38
#include "virprocess.h"
39
#include "virtime.h"
40
#include "virobject.h"
41
#include "virstring.h"
42
#include "base64.h"
D
Daniel P. Berrange 已提交
43 44 45

#define VIR_FROM_THIS VIR_FROM_QEMU

46 47
VIR_LOG_INIT("qemu.qemu_agent");

D
Daniel P. Berrange 已提交
48 49 50 51 52
#define LINE_ENDING "\n"

#define DEBUG_IO 0
#define DEBUG_RAW_IO 0

53 54 55 56 57 58 59 60 61
/* We read from QEMU until seeing a \r\n pair to indicate a
 * completed reply or event. To avoid memory denial-of-service
 * though, we must have a size limit on amount of data we
 * buffer. 10 MB is large enough that it ought to cope with
 * normal QEMU replies, and small enough that we're not
 * consuming unreasonable mem.
 */
#define QEMU_AGENT_MAX_RESPONSE (10 * 1024 * 1024)

D
Daniel P. Berrange 已提交
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
/* When you are the first to uncomment this,
 * don't forget to uncomment the corresponding
 * part in qemuAgentIOProcessEvent as well.
 *
static struct {
    const char *type;
    void (*handler)(qemuAgentPtr mon, virJSONValuePtr data);
} eventHandlers[] = {
};
*/

typedef struct _qemuAgentMessage qemuAgentMessage;
typedef qemuAgentMessage *qemuAgentMessagePtr;

struct _qemuAgentMessage {
    char *txBuffer;
    int txOffset;
    int txLength;

    /* Used by the JSON monitor to hold reply / error */
    char *rxBuffer;
    int rxLength;
    void *rxObject;

    /* True if rxBuffer / rxObject are ready, or a
     * fatal error occurred on the monitor channel
     */
    bool finished;
90 91
    /* true for sync command */
    bool sync;
92 93
    /* id of the issued sync comand */
    unsigned long long id;
94
    bool first;
D
Daniel P. Berrange 已提交
95 96 97 98
};


struct _qemuAgent {
99
    virObjectLockable parent;
100

D
Daniel P. Berrange 已提交
101 102 103 104 105
    virCond notify;

    int fd;
    int watch;

106
    bool running;
D
Daniel P. Berrange 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    virDomainObjPtr vm;

    qemuAgentCallbacksPtr cb;

    /* If there's a command being processed this will be
     * non-NULL */
    qemuAgentMessagePtr msg;

    /* Buffer incoming data ready for Agent monitor
     * code to process & find message boundaries */
    size_t bufferOffset;
    size_t bufferLength;
    char *buffer;

    /* If anything went wrong, this will be fed back
     * the next monitor msg */
    virError lastError;
125 126 127 128 129

    /* Some guest agent commands don't return anything
     * but fire up an event on qemu monitor instead.
     * Take that as indication of successful completion */
    qemuAgentEvent await_event;
D
Daniel P. Berrange 已提交
130 131
};

132 133 134 135 136
static virClassPtr qemuAgentClass;
static void qemuAgentDispose(void *obj);

static int qemuAgentOnceInit(void)
{
137
    if (!VIR_CLASS_NEW(qemuAgent, virClassForObjectLockable()))
138 139 140 141 142 143 144 145
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(qemuAgent)


D
Daniel P. Berrange 已提交
146 147 148 149 150
#if DEBUG_RAW_IO
# include <c-ctype.h>
static char *
qemuAgentEscapeNonPrintable(const char *text)
{
151
    size_t i;
D
Daniel P. Berrange 已提交
152
    virBuffer buf = VIR_BUFFER_INITIALIZER;
153
    for (i = 0; text[i] != '\0'; i++) {
D
Daniel P. Berrange 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166
        if (text[i] == '\\')
            virBufferAddLit(&buf, "\\\\");
        else if (c_isprint(text[i]) || text[i] == '\n' ||
                 (text[i] == '\r' && text[i+1] == '\n'))
            virBufferAddChar(&buf, text[i]);
        else
            virBufferAsprintf(&buf, "\\x%02x", text[i]);
    }
    return virBufferContentAndReset(&buf);
}
#endif


167
static void qemuAgentDispose(void *obj)
D
Daniel P. Berrange 已提交
168
{
169
    qemuAgentPtr mon = obj;
D
Daniel P. Berrange 已提交
170 171 172
    VIR_DEBUG("mon=%p", mon);
    if (mon->cb && mon->cb->destroy)
        (mon->cb->destroy)(mon, mon->vm);
173
    virCondDestroy(&mon->notify);
D
Daniel P. Berrange 已提交
174
    VIR_FREE(mon->buffer);
175
    virResetError(&mon->lastError);
D
Daniel P. Berrange 已提交
176 177 178
}

static int
179
qemuAgentOpenUnix(const char *monitor)
D
Daniel P. Berrange 已提交
180 181 182
{
    struct sockaddr_un addr;
    int monfd;
183
    int ret = -1;
D
Daniel P. Berrange 已提交
184 185 186 187 188 189 190 191

    if ((monfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        virReportSystemError(errno,
                             "%s", _("failed to create socket"));
        return -1;
    }

    if (virSetNonBlock(monfd) < 0) {
192 193 194
        virReportSystemError(errno, "%s",
                             _("Unable to put monitor "
                               "into non-blocking mode"));
D
Daniel P. Berrange 已提交
195 196 197 198
        goto error;
    }

    if (virSetCloseExec(monfd) < 0) {
199 200 201
        virReportSystemError(errno, "%s",
                             _("Unable to set monitor "
                               "close-on-exec flag"));
D
Daniel P. Berrange 已提交
202 203 204 205 206
        goto error;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
207
    if (virStrcpyStatic(addr.sun_path, monitor) < 0) {
208 209
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Agent path %s too big for destination"), monitor);
D
Daniel P. Berrange 已提交
210 211 212
        goto error;
    }

213 214
    ret = connect(monfd, (struct sockaddr *)&addr, sizeof(addr));
    if (ret < 0) {
D
Daniel P. Berrange 已提交
215 216 217 218 219 220 221
        virReportSystemError(errno, "%s",
                             _("failed to connect to monitor socket"));
        goto error;
    }

    return monfd;

222
 error:
D
Daniel P. Berrange 已提交
223 224 225 226 227 228 229 230 231 232
    VIR_FORCE_CLOSE(monfd);
    return -1;
}

static int
qemuAgentOpenPty(const char *monitor)
{
    int monfd;

    if ((monfd = open(monitor, O_RDWR | O_NONBLOCK)) < 0) {
233 234
        virReportSystemError(errno,
                             _("Unable to open monitor path %s"), monitor);
D
Daniel P. Berrange 已提交
235 236 237 238
        return -1;
    }

    if (virSetCloseExec(monfd) < 0) {
239 240
        virReportSystemError(errno, "%s",
                             _("Unable to set monitor close-on-exec flag"));
D
Daniel P. Berrange 已提交
241 242 243 244 245
        goto error;
    }

    return monfd;

246
 error:
D
Daniel P. Berrange 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    VIR_FORCE_CLOSE(monfd);
    return -1;
}


static int
qemuAgentIOProcessEvent(qemuAgentPtr mon,
                        virJSONValuePtr obj)
{
    const char *type;
    VIR_DEBUG("mon=%p obj=%p", mon, obj);

    type = virJSONValueObjectGetString(obj, "event");
    if (!type) {
        VIR_WARN("missing event type in message");
        errno = EINVAL;
        return -1;
    }

/*
267
    for (i = 0; i < ARRAY_CARDINALITY(eventHandlers); i++) {
D
Daniel P. Berrange 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        if (STREQ(eventHandlers[i].type, type)) {
            virJSONValuePtr data = virJSONValueObjectGet(obj, "data");
            VIR_DEBUG("handle %s handler=%p data=%p", type,
                      eventHandlers[i].handler, data);
            (eventHandlers[i].handler)(mon, data);
            break;
        }
    }
*/
    return 0;
}

static int
qemuAgentIOProcessLine(qemuAgentPtr mon,
                       const char *line,
                       qemuAgentMessagePtr msg)
{
    virJSONValuePtr obj = NULL;
    int ret = -1;

    VIR_DEBUG("Line [%s]", line);

290
    if (!(obj = virJSONValueFromString(line))) {
291 292
        /* receiving garbage on first sync is regular situation */
        if (msg && msg->sync && msg->first) {
293 294 295 296 297
            VIR_DEBUG("Received garbage on sync");
            msg->finished = 1;
            return 0;
        }

D
Daniel P. Berrange 已提交
298
        goto cleanup;
299
    }
D
Daniel P. Berrange 已提交
300

301
    if (virJSONValueGetType(obj) != VIR_JSON_TYPE_OBJECT) {
302 303
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Parsed JSON reply '%s' isn't an object"), line);
D
Daniel P. Berrange 已提交
304 305 306 307 308 309 310 311 312 313
        goto cleanup;
    }

    if (virJSONValueObjectHasKey(obj, "QMP") == 1) {
        ret = 0;
    } else if (virJSONValueObjectHasKey(obj, "event") == 1) {
        ret = qemuAgentIOProcessEvent(mon, obj);
    } else if (virJSONValueObjectHasKey(obj, "error") == 1 ||
               virJSONValueObjectHasKey(obj, "return") == 1) {
        if (msg) {
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            if (msg->sync) {
                unsigned long long id;

                if (virJSONValueObjectGetNumberUlong(obj, "return", &id) < 0) {
                    VIR_DEBUG("Ignoring delayed reply on sync");
                    ret = 0;
                    goto cleanup;
                }

                VIR_DEBUG("Guest returned ID: %llu", id);

                if (msg->id != id) {
                    VIR_DEBUG("Guest agent returned ID: %llu instead of %llu",
                              id, msg->id);
                    ret = 0;
                    goto cleanup;
                }
            }
D
Daniel P. Berrange 已提交
332 333 334 335
            msg->rxObject = obj;
            msg->finished = 1;
            obj = NULL;
        } else {
336 337
            /* we are out of sync */
            VIR_DEBUG("Ignoring delayed reply");
D
Daniel P. Berrange 已提交
338
        }
339
        ret = 0;
D
Daniel P. Berrange 已提交
340
    } else {
341 342
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown JSON reply '%s'"), line);
D
Daniel P. Berrange 已提交
343 344
    }

345
 cleanup:
D
Daniel P. Berrange 已提交
346 347 348 349 350 351 352 353 354 355
    virJSONValueFree(obj);
    return ret;
}

static int qemuAgentIOProcessData(qemuAgentPtr mon,
                                  char *data,
                                  size_t len,
                                  qemuAgentMessagePtr msg)
{
    int used = 0;
356
    size_t i = 0;
D
Daniel P. Berrange 已提交
357 358 359
#if DEBUG_IO
# if DEBUG_RAW_IO
    char *str1 = qemuAgentEscapeNonPrintable(data);
360
    VIR_ERROR(_("[%s]"), str1);
D
Daniel P. Berrange 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373
    VIR_FREE(str1);
# else
    VIR_DEBUG("Data %zu bytes [%s]", len, data);
# endif
#endif

    while (used < len) {
        char *nl = strstr(data + used, LINE_ENDING);

        if (nl) {
            int got = nl - (data + used);
            for (i = 0; i < strlen(LINE_ENDING); i++)
                data[used + got + i] = '\0';
374
            if (qemuAgentIOProcessLine(mon, data + used, msg) < 0)
D
Daniel P. Berrange 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
                return -1;
            used += got + strlen(LINE_ENDING);
        } else {
            break;
        }
    }

    VIR_DEBUG("Total used %d bytes out of %zd available in buffer", used, len);
    return used;
}

/* This method processes data that has been received
 * from the monitor. Looking for async events and
 * replies/errors.
 */
static int
qemuAgentIOProcess(qemuAgentPtr mon)
{
    int len;
    qemuAgentMessagePtr msg = NULL;

    /* See if there's a message ready for reply; that is,
     * one that has completed writing all its data.
     */
    if (mon->msg && mon->msg->txOffset == mon->msg->txLength)
        msg = mon->msg;

#if DEBUG_IO
# if DEBUG_RAW_IO
    char *str1 = qemuAgentEscapeNonPrintable(msg ? msg->txBuffer : "");
    char *str2 = qemuAgentEscapeNonPrintable(mon->buffer);
    VIR_ERROR(_("Process %zu %p %p [[[%s]]][[[%s]]]"),
              mon->bufferOffset, mon->msg, msg, str1, str2);
    VIR_FREE(str1);
    VIR_FREE(str2);
# else
    VIR_DEBUG("Process %zu", mon->bufferOffset);
# endif
#endif

    len = qemuAgentIOProcessData(mon,
                                 mon->buffer, mon->bufferOffset,
                                 msg);

    if (len < 0)
        return -1;

    if (len < mon->bufferOffset) {
        memmove(mon->buffer, mon->buffer + len, mon->bufferOffset - len);
        mon->bufferOffset -= len;
    } else {
        VIR_FREE(mon->buffer);
        mon->bufferOffset = mon->bufferLength = 0;
    }
#if DEBUG_IO
    VIR_DEBUG("Process done %zu used %d", mon->bufferOffset, len);
#endif
    if (msg && msg->finished)
        virCondBroadcast(&mon->notify);
    return len;
}


/*
 * Called when the monitor is able to write data
 * Call this function while holding the monitor lock.
 */
static int
qemuAgentIOWrite(qemuAgentPtr mon)
{
    int done;

    /* If no active message, or fully transmitted, then no-op */
    if (!mon->msg || mon->msg->txOffset == mon->msg->txLength)
        return 0;

    done = safewrite(mon->fd,
                     mon->msg->txBuffer + mon->msg->txOffset,
                     mon->msg->txLength - mon->msg->txOffset);

    if (done < 0) {
        if (errno == EAGAIN)
            return 0;

        virReportSystemError(errno, "%s",
                             _("Unable to write to monitor"));
        return -1;
    }
    mon->msg->txOffset += done;
    return done;
}

/*
 * Called when the monitor has incoming data to read
 * Call this function while holding the monitor lock.
 *
 * Returns -1 on error, or number of bytes read
 */
static int
qemuAgentIORead(qemuAgentPtr mon)
{
    size_t avail = mon->bufferLength - mon->bufferOffset;
    int ret = 0;

    if (avail < 1024) {
480 481 482 483 484 485
        if (mon->bufferLength >= QEMU_AGENT_MAX_RESPONSE) {
            virReportSystemError(ERANGE,
                                 _("No complete agent response found in %d bytes"),
                                 QEMU_AGENT_MAX_RESPONSE);
            return -1;
        }
D
Daniel P. Berrange 已提交
486
        if (VIR_REALLOC_N(mon->buffer,
487
                          mon->bufferLength + 1024) < 0)
D
Daniel P. Berrange 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 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
            return -1;
        mon->bufferLength += 1024;
        avail += 1024;
    }

    /* Read as much as we can get into our buffer,
       until we block on EAGAIN, or hit EOF */
    while (avail > 1) {
        int got;
        got = read(mon->fd,
                   mon->buffer + mon->bufferOffset,
                   avail - 1);
        if (got < 0) {
            if (errno == EAGAIN)
                break;
            virReportSystemError(errno, "%s",
                                 _("Unable to read from monitor"));
            ret = -1;
            break;
        }
        if (got == 0)
            break;

        ret += got;
        avail -= got;
        mon->bufferOffset += got;
        mon->buffer[mon->bufferOffset] = '\0';
    }

#if DEBUG_IO
    VIR_DEBUG("Now read %zu bytes of data", mon->bufferOffset);
#endif

    return ret;
}


static void qemuAgentUpdateWatch(qemuAgentPtr mon)
{
    int events =
        VIR_EVENT_HANDLE_HANGUP |
        VIR_EVENT_HANDLE_ERROR;

531 532 533
    if (!mon->watch)
        return;

D
Daniel P. Berrange 已提交
534 535 536 537 538 539 540 541 542 543 544 545
    if (mon->lastError.code == VIR_ERR_OK) {
        events |= VIR_EVENT_HANDLE_READABLE;

        if (mon->msg && mon->msg->txOffset < mon->msg->txLength)
            events |= VIR_EVENT_HANDLE_WRITABLE;
    }

    virEventUpdateHandle(mon->watch, events);
}


static void
546 547
qemuAgentIO(int watch, int fd, int events, void *opaque)
{
D
Daniel P. Berrange 已提交
548 549 550 551
    qemuAgentPtr mon = opaque;
    bool error = false;
    bool eof = false;

552
    virObjectRef(mon);
D
Daniel P. Berrange 已提交
553
    /* lock access to the monitor and protect fd */
554
    virObjectLock(mon);
D
Daniel P. Berrange 已提交
555 556 557 558
#if DEBUG_IO
    VIR_DEBUG("Agent %p I/O on watch %d fd %d events %d", mon, watch, fd, events);
#endif

559 560 561 562 563 564
    if (mon->fd == -1 || mon->watch == 0) {
        virObjectUnlock(mon);
        virObjectUnref(mon);
        return;
    }

D
Daniel P. Berrange 已提交
565 566 567
    if (mon->fd != fd || mon->watch != watch) {
        if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR))
            eof = true;
568 569 570
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("event from unexpected fd %d!=%d / watch %d!=%d"),
                       mon->fd, fd, mon->watch, watch);
D
Daniel P. Berrange 已提交
571 572 573 574 575 576 577
        error = true;
    } else if (mon->lastError.code != VIR_ERR_OK) {
        if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR))
            eof = true;
        error = true;
    } else {
        if (events & VIR_EVENT_HANDLE_WRITABLE) {
578 579
            if (qemuAgentIOWrite(mon) < 0)
                error = true;
D
Daniel P. Berrange 已提交
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
            events &= ~VIR_EVENT_HANDLE_WRITABLE;
        }

        if (!error &&
            events & VIR_EVENT_HANDLE_READABLE) {
            int got = qemuAgentIORead(mon);
            events &= ~VIR_EVENT_HANDLE_READABLE;
            if (got < 0) {
                error = true;
            } else if (got == 0) {
                eof = true;
            } else {
                /* Ignore hangup/error events if we read some data, to
                 * give time for that data to be consumed */
                events = 0;

                if (qemuAgentIOProcess(mon) < 0)
                    error = true;
            }
        }

        if (!error &&
            events & VIR_EVENT_HANDLE_HANGUP) {
603
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
604
                           _("End of file from agent monitor"));
605
            eof = true;
D
Daniel P. Berrange 已提交
606 607 608 609 610
            events &= ~VIR_EVENT_HANDLE_HANGUP;
        }

        if (!error && !eof &&
            events & VIR_EVENT_HANDLE_ERROR) {
611 612
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Invalid file descriptor while waiting for monitor"));
613
            eof = true;
D
Daniel P. Berrange 已提交
614 615 616
            events &= ~VIR_EVENT_HANDLE_ERROR;
        }
        if (!error && events) {
617 618 619
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unhandled event %d for monitor fd %d"),
                           events, mon->fd);
620
            error = true;
D
Daniel P. Berrange 已提交
621 622 623 624 625 626 627 628
        }
    }

    if (error || eof) {
        if (mon->lastError.code != VIR_ERR_OK) {
            /* Already have an error, so clear any new error */
            virResetLastError();
        } else {
629
            if (virGetLastErrorCode() == VIR_ERR_OK)
630 631
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Error while processing monitor IO"));
D
Daniel P. Berrange 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
            virCopyLastError(&mon->lastError);
            virResetLastError();
        }

        VIR_DEBUG("Error on monitor %s", NULLSTR(mon->lastError.message));
        /* If IO process resulted in an error & we have a message,
         * then wakeup that waiter */
        if (mon->msg && !mon->msg->finished) {
            mon->msg->finished = 1;
            virCondSignal(&mon->notify);
        }
    }

    qemuAgentUpdateWatch(mon);

    /* We have to unlock to avoid deadlock against command thread,
     * but is this safe ?  I think it is, because the callback
     * will try to acquire the virDomainObjPtr mutex next */
    if (eof) {
        void (*eofNotify)(qemuAgentPtr, virDomainObjPtr)
            = mon->cb->eofNotify;
        virDomainObjPtr vm = mon->vm;

        /* Make sure anyone waiting wakes up now */
        virCondSignal(&mon->notify);
657
        virObjectUnlock(mon);
658
        virObjectUnref(mon);
D
Daniel P. Berrange 已提交
659 660 661 662 663 664 665 666 667
        VIR_DEBUG("Triggering EOF callback");
        (eofNotify)(mon, vm);
    } else if (error) {
        void (*errorNotify)(qemuAgentPtr, virDomainObjPtr)
            = mon->cb->errorNotify;
        virDomainObjPtr vm = mon->vm;

        /* Make sure anyone waiting wakes up now */
        virCondSignal(&mon->notify);
668
        virObjectUnlock(mon);
669
        virObjectUnref(mon);
D
Daniel P. Berrange 已提交
670 671 672
        VIR_DEBUG("Triggering error callback");
        (errorNotify)(mon, vm);
    } else {
673
        virObjectUnlock(mon);
674
        virObjectUnref(mon);
D
Daniel P. Berrange 已提交
675 676 677 678 679 680
    }
}


qemuAgentPtr
qemuAgentOpen(virDomainObjPtr vm,
681
              const virDomainChrSourceDef *config,
D
Daniel P. Berrange 已提交
682 683 684 685 686
              qemuAgentCallbacksPtr cb)
{
    qemuAgentPtr mon;

    if (!cb || !cb->eofNotify) {
687 688
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("EOF notify callback must be supplied"));
D
Daniel P. Berrange 已提交
689 690 691
        return NULL;
    }

692 693 694
    if (qemuAgentInitialize() < 0)
        return NULL;

695
    if (!(mon = virObjectLockableNew(qemuAgentClass)))
D
Daniel P. Berrange 已提交
696 697
        return NULL;

698
    mon->fd = -1;
D
Daniel P. Berrange 已提交
699
    if (virCondInit(&mon->notify) < 0) {
700 701
        virReportSystemError(errno, "%s",
                             _("cannot initialize monitor condition"));
702
        virObjectUnref(mon);
D
Daniel P. Berrange 已提交
703 704 705 706 707 708 709
        return NULL;
    }
    mon->vm = vm;
    mon->cb = cb;

    switch (config->type) {
    case VIR_DOMAIN_CHR_TYPE_UNIX:
710
        mon->fd = qemuAgentOpenUnix(config->data.nix.path);
D
Daniel P. Berrange 已提交
711 712 713 714 715 716 717
        break;

    case VIR_DOMAIN_CHR_TYPE_PTY:
        mon->fd = qemuAgentOpenPty(config->data.file.path);
        break;

    default:
718 719 720
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to handle monitor type: %s"),
                       virDomainChrTypeToString(config->type));
D
Daniel P. Berrange 已提交
721 722 723 724 725 726
        goto cleanup;
    }

    if (mon->fd == -1)
        goto cleanup;

727
    virObjectRef(mon);
D
Daniel P. Berrange 已提交
728 729 730
    if ((mon->watch = virEventAddHandle(mon->fd,
                                        VIR_EVENT_HANDLE_HANGUP |
                                        VIR_EVENT_HANDLE_ERROR |
731
                                        VIR_EVENT_HANDLE_READABLE,
D
Daniel P. Berrange 已提交
732
                                        qemuAgentIO,
733 734
                                        mon,
                                        virObjectFreeCallback)) < 0) {
735
        virObjectUnref(mon);
736 737
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unable to register monitor events"));
D
Daniel P. Berrange 已提交
738 739 740
        goto cleanup;
    }

741
    mon->running = true;
D
Daniel P. Berrange 已提交
742 743 744 745
    VIR_DEBUG("New mon %p fd =%d watch=%d", mon, mon->fd, mon->watch);

    return mon;

746
 cleanup:
D
Daniel P. Berrange 已提交
747 748 749 750 751 752 753 754 755 756 757
    /* We don't want the 'destroy' callback invoked during
     * cleanup from construction failure, because that can
     * give a double-unref on virDomainObjPtr in the caller,
     * so kill the callbacks now.
     */
    mon->cb = NULL;
    qemuAgentClose(mon);
    return NULL;
}


758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
static void
qemuAgentNotifyCloseLocked(qemuAgentPtr mon)
{
    if (mon) {
        mon->running = false;

        /* If there is somebody waiting for a message
         * wake him up. No message will arrive anyway. */
        if (mon->msg && !mon->msg->finished) {
            mon->msg->finished = 1;
            virCondSignal(&mon->notify);
        }
    }
}


void
qemuAgentNotifyClose(qemuAgentPtr mon)
{
    if (!mon)
        return;

    VIR_DEBUG("mon=%p", mon);

    virObjectLock(mon);
    qemuAgentNotifyCloseLocked(mon);
    virObjectUnlock(mon);
}


D
Daniel P. Berrange 已提交
788 789 790 791 792 793 794
void qemuAgentClose(qemuAgentPtr mon)
{
    if (!mon)
        return;

    VIR_DEBUG("mon=%p", mon);

795
    virObjectLock(mon);
D
Daniel P. Berrange 已提交
796 797

    if (mon->fd >= 0) {
798
        if (mon->watch) {
D
Daniel P. Berrange 已提交
799
            virEventRemoveHandle(mon->watch);
800 801
            mon->watch = 0;
        }
D
Daniel P. Berrange 已提交
802 803 804
        VIR_FORCE_CLOSE(mon->fd);
    }

805
    qemuAgentNotifyCloseLocked(mon);
806
    virObjectUnlock(mon);
807

808
    virObjectUnref(mon);
D
Daniel P. Berrange 已提交
809 810
}

811
#define QEMU_AGENT_WAIT_TIME 5
D
Daniel P. Berrange 已提交
812

813 814 815 816
/**
 * qemuAgentSend:
 * @mon: Monitor
 * @msg: Message
817 818
 * @seconds: number of seconds to wait for the result, it can be either
 *           -2, -1, 0 or positive.
819
 *
820 821 822 823
 * Send @msg to agent @mon. If @seconds is equal to
 * VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK(-2), this function will block forever
 * waiting for the result. The value of
 * VIR_DOMAIN_QEMU_AGENT_COMMAND_DEFAULT(-1) means use default timeout value
Y
Yuri Chornoivan 已提交
824
 * and VIR_DOMAIN_QEMU_AGENT_COMMAND_NOWAIT(0) makes this function return
825 826
 * immediately without waiting. Any positive value means the number of seconds
 * to wait for the result.
827 828 829 830 831
 *
 * Returns: 0 on success,
 *          -2 on timeout,
 *          -1 otherwise
 */
D
Daniel P. Berrange 已提交
832
static int qemuAgentSend(qemuAgentPtr mon,
833
                         qemuAgentMessagePtr msg,
834
                         int seconds)
D
Daniel P. Berrange 已提交
835 836
{
    int ret = -1;
837
    unsigned long long then = 0;
D
Daniel P. Berrange 已提交
838 839 840 841 842 843 844 845 846

    /* Check whether qemu quit unexpectedly */
    if (mon->lastError.code != VIR_ERR_OK) {
        VIR_DEBUG("Attempt to send command while error is set %s",
                  NULLSTR(mon->lastError.message));
        virSetError(&mon->lastError);
        return -1;
    }

847 848
    if (seconds > VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) {
        unsigned long long now;
849 850
        if (virTimeMillisNow(&now) < 0)
            return -1;
851 852 853
        if (seconds == VIR_DOMAIN_QEMU_AGENT_COMMAND_DEFAULT)
            seconds = QEMU_AGENT_WAIT_TIME;
        then = now + seconds * 1000ull;
854 855
    }

D
Daniel P. Berrange 已提交
856 857 858 859
    mon->msg = msg;
    qemuAgentUpdateWatch(mon);

    while (!mon->msg->finished) {
860 861
        if ((then && virCondWaitUntil(&mon->notify, &mon->parent.lock, then) < 0) ||
            (!then && virCondWait(&mon->notify, &mon->parent.lock) < 0)) {
862
            if (errno == ETIMEDOUT) {
863
                virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
864
                               _("Guest agent not available for now"));
865 866
                ret = -2;
            } else {
867
                virReportSystemError(errno, "%s",
868 869
                                     _("Unable to wait on agent monitor "
                                       "condition"));
870
            }
D
Daniel P. Berrange 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883
            goto cleanup;
        }
    }

    if (mon->lastError.code != VIR_ERR_OK) {
        VIR_DEBUG("Send command resulted in error %s",
                  NULLSTR(mon->lastError.message));
        virSetError(&mon->lastError);
        goto cleanup;
    }

    ret = 0;

884
 cleanup:
D
Daniel P. Berrange 已提交
885 886 887 888 889 890 891
    mon->msg = NULL;
    qemuAgentUpdateWatch(mon);

    return ret;
}


892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
/**
 * qemuAgentGuestSync:
 * @mon: Monitor
 *
 * Send guest-sync with unique ID
 * and wait for reply. If we get one, check if
 * received ID is equal to given.
 *
 * Returns: 0 on success,
 *          -1 otherwise
 */
static int
qemuAgentGuestSync(qemuAgentPtr mon)
{
    int ret = -1;
    int send_ret;
908
    unsigned long long id;
909 910 911
    qemuAgentMessage sync_msg;

    memset(&sync_msg, 0, sizeof(sync_msg));
912 913
    /* set only on first sync */
    sync_msg.first = true;
914

915
 retry:
916 917 918 919 920
    if (virTimeMillisNow(&id) < 0)
        return -1;

    if (virAsprintf(&sync_msg.txBuffer,
                    "{\"execute\":\"guest-sync\", "
921
                    "\"arguments\":{\"id\":%llu}}\n", id) < 0)
922 923 924
        return -1;

    sync_msg.txLength = strlen(sync_msg.txBuffer);
925
    sync_msg.sync = true;
926
    sync_msg.id = id;
927 928 929

    VIR_DEBUG("Sending guest-sync command with ID: %llu", id);

930
    send_ret = qemuAgentSend(mon, &sync_msg,
931
                             VIR_DOMAIN_QEMU_AGENT_COMMAND_DEFAULT);
932 933 934

    VIR_DEBUG("qemuAgentSend returned: %d", send_ret);

935
    if (send_ret < 0)
936 937 938
        goto cleanup;

    if (!sync_msg.rxObject) {
939 940 941 942 943
        if (sync_msg.first) {
            VIR_FREE(sync_msg.txBuffer);
            memset(&sync_msg, 0, sizeof(sync_msg));
            goto retry;
        } else {
944 945 946 947 948 949
            if (mon->running)
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing monitor reply object"));
            else
                virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                               _("Guest agent disappeared while executing command"));
950 951
            goto cleanup;
        }
952 953 954 955
    }

    ret = 0;

956
 cleanup:
957 958 959 960 961
    virJSONValueFree(sync_msg.rxObject);
    VIR_FREE(sync_msg.txBuffer);
    return ret;
}

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
static const char *
qemuAgentStringifyErrorClass(const char *klass)
{
    if (STREQ_NULLABLE(klass, "BufferOverrun"))
        return "Buffer overrun";
    else if (STREQ_NULLABLE(klass, "CommandDisabled"))
        return "The command has been disabled for this instance";
    else if (STREQ_NULLABLE(klass, "CommandNotFound"))
        return "The command has not been found";
    else if (STREQ_NULLABLE(klass, "FdNotFound"))
        return "File descriptor not found";
    else if (STREQ_NULLABLE(klass, "InvalidParameter"))
        return "Invalid parameter";
    else if (STREQ_NULLABLE(klass, "InvalidParameterType"))
        return "Invalid parameter type";
    else if (STREQ_NULLABLE(klass, "InvalidParameterValue"))
        return "Invalid parameter value";
    else if (STREQ_NULLABLE(klass, "OpenFileFailed"))
        return "Cannot open file";
    else if (STREQ_NULLABLE(klass, "QgaCommandFailed"))
        return "Guest agent command failed";
    else if (STREQ_NULLABLE(klass, "QMPBadInputObjectMember"))
        return "Bad QMP input object member";
    else if (STREQ_NULLABLE(klass, "QMPExtraInputObjectMember"))
        return "Unexpected extra object member";
    else if (STREQ_NULLABLE(klass, "UndefinedError"))
        return "An undefined error has occurred";
    else if (STREQ_NULLABLE(klass, "Unsupported"))
        return "this feature or command is not currently supported";
    else if (klass)
        return klass;
    else
        return "unknown QEMU command error";
}
D
Daniel P. Berrange 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005

/* Ignoring OOM in this method, since we're already reporting
 * a more important error
 *
 * XXX see qerror.h for different klasses & fill out useful params
 */
static const char *
qemuAgentStringifyError(virJSONValuePtr error)
{
    const char *klass = virJSONValueObjectGetString(error, "class");
1006
    const char *detail = virJSONValueObjectGetString(error, "desc");
D
Daniel P. Berrange 已提交
1007 1008

    /* The QMP 'desc' field is usually sufficient for our generic
1009 1010
     * error reporting needs. However, if not present, translate
     * the class into something readable.
D
Daniel P. Berrange 已提交
1011 1012
     */
    if (!detail)
1013
        detail = qemuAgentStringifyErrorClass(klass);
D
Daniel P. Berrange 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

    return detail;
}

static const char *
qemuAgentCommandName(virJSONValuePtr cmd)
{
    const char *name = virJSONValueObjectGetString(cmd, "execute");
    if (name)
        return name;
    else
        return "<unknown>";
}

static int
qemuAgentCheckError(virJSONValuePtr cmd,
                    virJSONValuePtr reply)
{
    if (virJSONValueObjectHasKey(reply, "error")) {
        virJSONValuePtr error = virJSONValueObjectGet(reply, "error");
1034 1035
        char *cmdstr = virJSONValueToString(cmd, false);
        char *replystr = virJSONValueToString(reply, false);
D
Daniel P. Berrange 已提交
1036 1037

        /* Log the full JSON formatted command & error */
1038
        VIR_DEBUG("unable to execute QEMU agent command %s: %s",
1039
                  NULLSTR(cmdstr), NULLSTR(replystr));
D
Daniel P. Berrange 已提交
1040 1041 1042

        /* Only send the user the command name + friendly error */
        if (!error)
1043
            virReportError(VIR_ERR_INTERNAL_ERROR,
1044
                           _("unable to execute QEMU agent command '%s'"),
1045
                           qemuAgentCommandName(cmd));
D
Daniel P. Berrange 已提交
1046
        else
1047
            virReportError(VIR_ERR_INTERNAL_ERROR,
1048
                           _("unable to execute QEMU agent command '%s': %s"),
1049 1050
                           qemuAgentCommandName(cmd),
                           qemuAgentStringifyError(error));
D
Daniel P. Berrange 已提交
1051 1052 1053 1054 1055

        VIR_FREE(cmdstr);
        VIR_FREE(replystr);
        return -1;
    } else if (!virJSONValueObjectHasKey(reply, "return")) {
1056 1057
        char *cmdstr = virJSONValueToString(cmd, false);
        char *replystr = virJSONValueToString(reply, false);
D
Daniel P. Berrange 已提交
1058 1059

        VIR_DEBUG("Neither 'return' nor 'error' is set in the JSON reply %s: %s",
1060
                  NULLSTR(cmdstr), NULLSTR(replystr));
1061
        virReportError(VIR_ERR_INTERNAL_ERROR,
1062
                       _("unable to execute QEMU agent command '%s'"),
1063
                       qemuAgentCommandName(cmd));
D
Daniel P. Berrange 已提交
1064 1065 1066 1067 1068 1069 1070
        VIR_FREE(cmdstr);
        VIR_FREE(replystr);
        return -1;
    }
    return 0;
}

1071 1072 1073 1074
static int
qemuAgentCommand(qemuAgentPtr mon,
                 virJSONValuePtr cmd,
                 virJSONValuePtr *reply,
1075
                 bool needReply,
1076 1077 1078 1079 1080 1081 1082 1083 1084
                 int seconds)
{
    int ret = -1;
    qemuAgentMessage msg;
    char *cmdstr = NULL;
    int await_event = mon->await_event;

    *reply = NULL;

1085 1086 1087 1088 1089 1090
    if (!mon->running) {
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                       _("Guest agent disappeared while executing command"));
        return -1;
    }

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    if (qemuAgentGuestSync(mon) < 0)
        return -1;

    memset(&msg, 0, sizeof(msg));

    if (!(cmdstr = virJSONValueToString(cmd, false)))
        goto cleanup;
    if (virAsprintf(&msg.txBuffer, "%s" LINE_ENDING, cmdstr) < 0)
        goto cleanup;
    msg.txLength = strlen(msg.txBuffer);

    VIR_DEBUG("Send command '%s' for write, seconds = %d", cmdstr, seconds);

    ret = qemuAgentSend(mon, &msg, seconds);

    VIR_DEBUG("Receive command reply ret=%d rxObject=%p",
              ret, msg.rxObject);

    if (ret == 0) {
        /* If we haven't obtained any reply but we wait for an
         * event, then don't report this as error */
        if (!msg.rxObject) {
1113
            if (await_event && !needReply) {
1114 1115
                VIR_DEBUG("Woken up by event %d", await_event);
            } else {
1116 1117 1118 1119 1120 1121
                if (mon->running)
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Missing monitor reply object"));
                else
                    virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                                   _("Guest agent disappeared while executing command"));
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
                ret = -1;
            }
        } else {
            *reply = msg.rxObject;
            ret = qemuAgentCheckError(cmd, *reply);
        }
    }

 cleanup:
    VIR_FREE(cmdstr);
    VIR_FREE(msg.txBuffer);

    return ret;
}

D
Daniel P. Berrange 已提交
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
static virJSONValuePtr ATTRIBUTE_SENTINEL
qemuAgentMakeCommand(const char *cmdname,
                     ...)
{
    virJSONValuePtr obj;
    virJSONValuePtr jargs = NULL;
    va_list args;

    va_start(args, cmdname);

    if (!(obj = virJSONValueNewObject()))
1148
        goto error;
D
Daniel P. Berrange 已提交
1149 1150

    if (virJSONValueObjectAppendString(obj, "execute", cmdname) < 0)
1151
        goto error;
D
Daniel P. Berrange 已提交
1152

1153 1154
    if (virJSONValueObjectCreateVArgs(&jargs, args) < 0)
        goto error;
D
Daniel P. Berrange 已提交
1155 1156 1157

    if (jargs &&
        virJSONValueObjectAppend(obj, "arguments", jargs) < 0)
1158
        goto error;
D
Daniel P. Berrange 已提交
1159 1160 1161 1162 1163

    va_end(args);

    return obj;

1164
 error:
D
Daniel P. Berrange 已提交
1165 1166 1167 1168 1169 1170
    virJSONValueFree(obj);
    virJSONValueFree(jargs);
    va_end(args);
    return NULL;
}

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
static virJSONValuePtr
qemuAgentMakeStringsArray(const char **strings, unsigned int len)
{
    size_t i;
    virJSONValuePtr ret = virJSONValueNewArray(), str;

    if (!ret)
        return NULL;

    for (i = 0; i < len; i++) {
        str = virJSONValueNewString(strings[i]);
        if (!str)
            goto error;

        if (virJSONValueArrayAppend(ret, str) < 0) {
            virJSONValueFree(str);
            goto error;
        }
    }
    return ret;

 error:
    virJSONValueFree(ret);
    return NULL;
}

1197 1198 1199
void qemuAgentNotifyEvent(qemuAgentPtr mon,
                          qemuAgentEvent event)
{
1200 1201
    virObjectLock(mon);

1202
    VIR_DEBUG("mon=%p event=%d await_event=%d", mon, event, mon->await_event);
1203 1204 1205 1206 1207 1208 1209 1210
    if (mon->await_event == event) {
        mon->await_event = QEMU_AGENT_EVENT_NONE;
        /* somebody waiting for this event, wake him up. */
        if (mon->msg && !mon->msg->finished) {
            mon->msg->finished = 1;
            virCondSignal(&mon->notify);
        }
    }
1211 1212

    virObjectUnlock(mon);
1213 1214
}

D
Daniel P. Berrange 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
VIR_ENUM_DECL(qemuAgentShutdownMode);

VIR_ENUM_IMPL(qemuAgentShutdownMode,
              QEMU_AGENT_SHUTDOWN_LAST,
              "powerdown", "reboot", "halt");

int qemuAgentShutdown(qemuAgentPtr mon,
                      qemuAgentShutdownMode mode)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

    cmd = qemuAgentMakeCommand("guest-shutdown",
                               "s:mode", qemuAgentShutdownModeTypeToString(mode),
                               NULL);
    if (!cmd)
        return -1;

1234 1235 1236 1237
    if (mode == QEMU_AGENT_SHUTDOWN_REBOOT)
        mon->await_event = QEMU_AGENT_EVENT_RESET;
    else
        mon->await_event = QEMU_AGENT_EVENT_SHUTDOWN;
1238
    ret = qemuAgentCommand(mon, cmd, &reply, false,
1239
                           VIR_DOMAIN_QEMU_AGENT_COMMAND_SHUTDOWN);
D
Daniel P. Berrange 已提交
1240 1241 1242 1243 1244

    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1245 1246 1247 1248

/*
 * qemuAgentFSFreeze:
 * @mon: Agent
1249 1250
 * @mountpoints: Array of mountpoint paths to be frozen, or NULL for all
 * @nmountpoints: Number of mountpoints to be frozen, or 0 for all
1251 1252
 *
 * Issue guest-fsfreeze-freeze command to guest agent,
1253 1254
 * which freezes file systems mounted on specified mountpoints
 * (or all file systems when @mountpoints is NULL), and returns
1255 1256 1257 1258 1259
 * number of frozen file systems on success.
 *
 * Returns: number of file system frozen on success,
 *          -1 on error.
 */
1260 1261
int qemuAgentFSFreeze(qemuAgentPtr mon, const char **mountpoints,
                      unsigned int nmountpoints)
1262 1263
{
    int ret = -1;
1264
    virJSONValuePtr cmd, arg = NULL;
1265 1266
    virJSONValuePtr reply = NULL;

1267 1268 1269 1270 1271
    if (mountpoints && nmountpoints) {
        arg = qemuAgentMakeStringsArray(mountpoints, nmountpoints);
        if (!arg)
            return -1;

1272
        cmd = qemuAgentMakeCommand("guest-fsfreeze-freeze-list",
1273
                                   "a:mountpoints", &arg, NULL);
1274 1275 1276
    } else {
        cmd = qemuAgentMakeCommand("guest-fsfreeze-freeze", NULL);
    }
1277 1278

    if (!cmd)
1279
        goto cleanup;
1280

1281
    if (qemuAgentCommand(mon, cmd, &reply, true,
1282
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
1283 1284 1285
        goto cleanup;

    if (virJSONValueObjectGetNumberInt(reply, "return", &ret) < 0) {
1286 1287
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed return value"));
1288 1289
    }

1290
 cleanup:
1291
    virJSONValueFree(arg);
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}

/*
 * qemuAgentFSThaw:
 * @mon: Agent
 *
 * Issue guest-fsfreeze-thaw command to guest agent,
 * which unfreezes all mounted file systems and returns
 * number of thawed file systems on success.
 *
 * Returns: number of file system thawed on success,
 *          -1 on error.
 */
int qemuAgentFSThaw(qemuAgentPtr mon)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

    cmd = qemuAgentMakeCommand("guest-fsfreeze-thaw", NULL);

    if (!cmd)
        return -1;

1319
    if (qemuAgentCommand(mon, cmd, &reply, true,
1320
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
1321 1322 1323
        goto cleanup;

    if (virJSONValueObjectGetNumberInt(reply, "return", &ret) < 0) {
1324 1325
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed return value"));
1326 1327
    }

1328
 cleanup:
1329 1330 1331 1332
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354

VIR_ENUM_DECL(qemuAgentSuspendMode);

VIR_ENUM_IMPL(qemuAgentSuspendMode,
              VIR_NODE_SUSPEND_TARGET_LAST,
              "guest-suspend-ram",
              "guest-suspend-disk",
              "guest-suspend-hybrid");

int
qemuAgentSuspend(qemuAgentPtr mon,
                 unsigned int target)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

    cmd = qemuAgentMakeCommand(qemuAgentSuspendModeTypeToString(target),
                               NULL);
    if (!cmd)
        return -1;

1355
    mon->await_event = QEMU_AGENT_EVENT_SUSPEND;
1356
    ret = qemuAgentCommand(mon, cmd, &reply, false,
1357
                           VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK);
1358 1359 1360 1361 1362

    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1363 1364 1365 1366 1367 1368 1369 1370

int
qemuAgentArbitraryCommand(qemuAgentPtr mon,
                          const char *cmd_str,
                          char **result,
                          int timeout)
{
    int ret = -1;
1371
    virJSONValuePtr cmd = NULL;
1372 1373 1374
    virJSONValuePtr reply = NULL;

    *result = NULL;
1375 1376 1377 1378 1379 1380 1381
    if (timeout < VIR_DOMAIN_QEMU_AGENT_COMMAND_MIN) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("guest agent timeout '%d' is "
                         "less than the minimum '%d'"),
                       timeout, VIR_DOMAIN_QEMU_AGENT_COMMAND_MIN);
        goto cleanup;
    }
1382

1383 1384 1385
    if (!(cmd = virJSONValueFromString(cmd_str)))
        goto cleanup;

1386
    if ((ret = qemuAgentCommand(mon, cmd, &reply, true, timeout)) < 0)
1387
        goto cleanup;
1388

1389 1390
    if (!(*result = virJSONValueToString(reply, false)))
        ret = -1;
1391

1392

1393
 cleanup:
1394 1395 1396 1397
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
M
Michal Privoznik 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412

int
qemuAgentFSTrim(qemuAgentPtr mon,
                unsigned long long minimum)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

    cmd = qemuAgentMakeCommand("guest-fstrim",
                               "U:minimum", minimum,
                               NULL);
    if (!cmd)
        return ret;

1413
    ret = qemuAgentCommand(mon, cmd, &reply, false,
M
Michal Privoznik 已提交
1414 1415 1416 1417 1418 1419
                           VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK);

    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1420 1421 1422 1423 1424 1425

int
qemuAgentGetVCPUs(qemuAgentPtr mon,
                  qemuAgentCPUInfoPtr *info)
{
    int ret = -1;
1426
    size_t i;
1427 1428 1429
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr data = NULL;
1430
    size_t ndata;
1431 1432 1433 1434

    if (!(cmd = qemuAgentMakeCommand("guest-get-vcpus", NULL)))
        return -1;

1435
    if (qemuAgentCommand(mon, cmd, &reply, true,
1436
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
1437 1438
        goto cleanup;

1439
    if (!(data = virJSONValueObjectGetArray(reply, "return"))) {
1440 1441 1442 1443 1444
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest-get-vcpus reply was missing return data"));
        goto cleanup;
    }

1445 1446 1447 1448 1449 1450
    if (!virJSONValueIsArray(data)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed guest-get-vcpus data array"));
        goto cleanup;
    }

1451 1452
    ndata = virJSONValueArraySize(data);

1453
    if (VIR_ALLOC_N(*info, ndata) < 0)
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
        goto cleanup;

    for (i = 0; i < ndata; i++) {
        virJSONValuePtr entry = virJSONValueArrayGet(data, i);
        qemuAgentCPUInfoPtr in = *info + i;

        if (!entry) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("array element missing in guest-get-vcpus return "
                             "value"));
            goto cleanup;
        }

        if (virJSONValueObjectGetNumberUint(entry, "logical-id", &in->id) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'logical-id' missing in reply of guest-get-vcpus"));
            goto cleanup;
        }

        if (virJSONValueObjectGetBoolean(entry, "online", &in->online) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'online' missing in reply of guest-get-vcpus"));
            goto cleanup;
        }

        if (virJSONValueObjectGetBoolean(entry, "can-offline",
                                         &in->offlinable) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'can-offline' missing in reply of guest-get-vcpus"));
            goto cleanup;
        }
    }

    ret = ndata;

1489
 cleanup:
1490 1491 1492 1493 1494
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}

1495 1496 1497 1498 1499 1500 1501

/* returns the value provided by the guest agent or -1 on internal error */
static int
qemuAgentSetVCPUsCommand(qemuAgentPtr mon,
                         qemuAgentCPUInfoPtr info,
                         size_t ninfo,
                         int *nmodified)
1502 1503 1504 1505 1506 1507 1508 1509
{
    int ret = -1;
    virJSONValuePtr cmd = NULL;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr cpus = NULL;
    virJSONValuePtr cpu = NULL;
    size_t i;

1510 1511
    *nmodified = 0;

1512 1513
    /* create the key data array */
    if (!(cpus = virJSONValueNewArray()))
1514
        goto cleanup;
1515 1516 1517 1518

    for (i = 0; i < ninfo; i++) {
        qemuAgentCPUInfoPtr in = &info[i];

1519 1520 1521 1522 1523 1524
        /* don't set state for cpus that were not touched */
        if (!in->modified)
            continue;

        (*nmodified)++;

1525 1526
        /* create single cpu object */
        if (!(cpu = virJSONValueNewObject()))
1527
            goto cleanup;
1528 1529

        if (virJSONValueObjectAppendNumberInt(cpu, "logical-id", in->id) < 0)
1530
            goto cleanup;
1531 1532

        if (virJSONValueObjectAppendBoolean(cpu, "online", in->online) < 0)
1533
            goto cleanup;
1534 1535

        if (virJSONValueArrayAppend(cpus, cpu) < 0)
1536
            goto cleanup;
1537 1538 1539 1540

        cpu = NULL;
    }

1541 1542 1543 1544 1545
    if (*nmodified == 0) {
        ret = 0;
        goto cleanup;
    }

1546
    if (!(cmd = qemuAgentMakeCommand("guest-set-vcpus",
1547
                                     "a:vcpus", &cpus,
1548 1549 1550
                                     NULL)))
        goto cleanup;

1551
    if (qemuAgentCommand(mon, cmd, &reply, true,
1552
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
1553 1554
        goto cleanup;

1555 1556 1557 1558 1559
    /* All negative values are invalid. Return of 0 is bogus since we wouldn't
     * call the guest agent so that 0 cpus would be set successfully. Reporting
     * more successfully set vcpus that we've asked for is invalid. */
    if (virJSONValueObjectGetNumberInt(reply, "return", &ret) < 0 ||
        ret <= 0 || ret > *nmodified) {
1560
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1561 1562
                       _("guest agent returned malformed or invalid return value"));
        ret = -1;
1563 1564
    }

1565
 cleanup:
1566 1567 1568 1569 1570 1571
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    virJSONValueFree(cpu);
    virJSONValueFree(cpus);
    return ret;
}
1572 1573


1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
/**
 * Set the VCPU state using guest agent.
 *
 * Attempts to set the guest agent state for all cpus or until a proper error is
 * reported by the guest agent. This may require multiple calls.
 *
 * Returns -1 on error, 0 on success.
 */
int
qemuAgentSetVCPUs(qemuAgentPtr mon,
                  qemuAgentCPUInfoPtr info,
                  size_t ninfo)
{
    int rv;
    int nmodified;
    size_t i;

    do {
        if ((rv = qemuAgentSetVCPUsCommand(mon, info, ninfo, &nmodified)) < 0)
            return -1;

        /* all vcpus were set successfully */
        if (rv == nmodified)
            return 0;

        /* un-mark vcpus that were already set */
        for (i = 0; i < ninfo && rv > 0; i++) {
            if (!info[i].modified)
                continue;

            info[i].modified = false;
            rv--;
        }
    } while (1);

    return 0;
}


1613 1614 1615 1616 1617 1618 1619 1620 1621
/* modify the cpu info structure to set the correct amount of cpus */
int
qemuAgentUpdateCPUInfo(unsigned int nvcpus,
                       qemuAgentCPUInfoPtr cpuinfo,
                       int ncpuinfo)
{
    size_t i;
    int nonline = 0;
    int nofflinable = 0;
1622
    ssize_t cpu0 = -1;
1623 1624 1625

    /* count the active and offlinable cpus */
    for (i = 0; i < ncpuinfo; i++) {
1626 1627 1628
        if (cpuinfo[i].id == 0)
            cpu0 = i;

1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
        if (cpuinfo[i].online)
            nonline++;

        if (cpuinfo[i].offlinable && cpuinfo[i].online)
            nofflinable++;

        /* This shouldn't happen, but we can't trust the guest agent */
        if (!cpuinfo[i].online && !cpuinfo[i].offlinable) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Invalid data provided by guest agent"));
            return -1;
        }
    }

1643 1644 1645 1646 1647 1648 1649 1650 1651
    /* CPU0 was made offlinable in linux a while ago, but certain parts (suspend
     * to ram) of the kernel still don't cope well with that. Make sure that if
     * all remaining vCPUs are offlinable, vCPU0 will not be selected to be
     * offlined automatically */
    if (nofflinable == nonline && cpu0 >= 0 && cpuinfo[cpu0].online) {
        cpuinfo[cpu0].offlinable = false;
        nofflinable--;
    }

1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    /* the guest agent reported less cpus than requested */
    if (nvcpus > ncpuinfo) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest agent reports less cpu than requested"));
        return -1;
    }

    /* not enough offlinable CPUs to support the request */
    if (nvcpus < nonline - nofflinable) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Cannot offline enough CPUs"));
        return -1;
    }

    for (i = 0; i < ncpuinfo; i++) {
        if (nvcpus < nonline) {
            /* unplug */
            if (cpuinfo[i].offlinable && cpuinfo[i].online) {
                cpuinfo[i].online = false;
1671
                cpuinfo[i].modified = true;
1672 1673 1674 1675 1676 1677
                nonline--;
            }
        } else if (nvcpus > nonline) {
            /* plug */
            if (!cpuinfo[i].online) {
                cpuinfo[i].online = true;
1678
                cpuinfo[i].modified = true;
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
                nonline++;
            }
        } else {
            /* done */
            break;
        }
    }

    return 0;
}
1689 1690


1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
int
qemuAgentGetHostname(qemuAgentPtr mon,
                     char **hostname)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr data = NULL;
    const char *result = NULL;

    cmd = qemuAgentMakeCommand("guest-get-host-name",
                               NULL);

    if (!cmd)
        return ret;

    if (qemuAgentCommand(mon, cmd, &reply, true,
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
        goto cleanup;

    if (!(data = virJSONValueObjectGet(reply, "return"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed return value"));
        goto cleanup;
    }

    if (!(result = virJSONValueObjectGetString(data, "host-name"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("'host-name' missing in guest-get-host-name reply"));
        goto cleanup;
    }

    if (VIR_STRDUP(*hostname, result) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}


1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
int
qemuAgentGetTime(qemuAgentPtr mon,
                 long long *seconds,
                 unsigned int *nseconds)
{
    int ret = -1;
    unsigned long long json_time;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

    cmd = qemuAgentMakeCommand("guest-get-time",
                               NULL);
    if (!cmd)
        return ret;

    if (qemuAgentCommand(mon, cmd, &reply, true,
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
        goto cleanup;

    if (virJSONValueObjectGetNumberUlong(reply, "return", &json_time) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed return value"));
        goto cleanup;
    }

    /* guest agent returns time in nanoseconds,
     * we need it in seconds here */
    *seconds = json_time / 1000000000LL;
    *nseconds = json_time % 1000000000LL;
    ret = 0;

 cleanup:
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}


/**
 * qemuAgentSetTime:
 * @setTime: time to set
 * @sync: let guest agent to read domain's RTC (@setTime is ignored)
 */
int
qemuAgentSetTime(qemuAgentPtr mon,
                long long seconds,
                unsigned int nseconds,
P
Pavel Hrdina 已提交
1782
                bool rtcSync)
1783 1784 1785 1786 1787
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

P
Pavel Hrdina 已提交
1788
    if (rtcSync) {
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
        cmd = qemuAgentMakeCommand("guest-set-time", NULL);
    } else {
        /* guest agent expect time with nanosecond granularity.
         * Impressing. */
        long long json_time;

        /* Check if we overflow. For some reason qemu doesn't handle unsigned
         * long long on the monitor well as it silently truncates numbers to
         * signed long long. Therefore we must check overflow against LLONG_MAX
         * not ULLONG_MAX. */
        if (seconds > LLONG_MAX / 1000000000LL) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Time '%lld' is too big for guest agent"),
                           seconds);
            return ret;
        }

        json_time = seconds * 1000000000LL;
        json_time += nseconds;
        cmd = qemuAgentMakeCommand("guest-set-time",
                                   "I:time", json_time,
                                   NULL);
    }

    if (!cmd)
        return ret;

    if (qemuAgentCommand(mon, cmd, &reply, true,
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1826 1827 1828 1829 1830 1831 1832 1833


int
qemuAgentGetFSInfo(qemuAgentPtr mon, virDomainFSInfoPtr **info,
                   virDomainDefPtr vmdef)
{
    size_t i, j, k;
    int ret = -1;
1834
    size_t ndata = 0, ndisk;
1835 1836 1837 1838 1839
    char **alias;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr data;
    virDomainFSInfoPtr *info_ret = NULL;
1840
    virPCIDeviceAddress pci_address;
1841
    const char *result = NULL;
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856

    cmd = qemuAgentMakeCommand("guest-get-fsinfo", NULL);
    if (!cmd)
        return ret;

    if (qemuAgentCommand(mon, cmd, &reply, true,
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
        goto cleanup;

    if (!(data = virJSONValueObjectGet(reply, "return"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest-get-fsinfo reply was missing return data"));
        goto cleanup;
    }

1857
    if (!virJSONValueIsArray(data)) {
1858
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1859
                       _("Malformed guest-get-fsinfo data array"));
1860 1861 1862 1863
        goto cleanup;
    }

    ndata = virJSONValueArraySize(data);
1864
    if (ndata == 0) {
1865
        ret = 0;
1866
        *info = NULL;
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
        goto cleanup;
    }
    if (VIR_ALLOC_N(info_ret, ndata) < 0)
        goto cleanup;

    for (i = 0; i < ndata; i++) {
        /* Reverse the order to arrange in mount order */
        virJSONValuePtr entry = virJSONValueArrayGet(data, ndata - 1 - i);

        if (!entry) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
1878
                           _("array element '%zd' of '%zd' missing in "
1879 1880 1881 1882 1883 1884 1885 1886
                             "guest-get-fsinfo return data"),
                           i, ndata);
            goto cleanup;
        }

        if (VIR_ALLOC(info_ret[i]) < 0)
            goto cleanup;

1887
        if (!(result = virJSONValueObjectGetString(entry, "mountpoint"))) {
1888 1889 1890 1891 1892 1893
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'mountpoint' missing in reply of "
                             "guest-get-fsinfo"));
            goto cleanup;
        }

1894 1895 1896 1897
        if (VIR_STRDUP(info_ret[i]->mountpoint, result) < 0)
            goto cleanup;

        if (!(result = virJSONValueObjectGetString(entry, "name"))) {
1898 1899 1900 1901 1902
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'name' missing in reply of guest-get-fsinfo"));
            goto cleanup;
        }

1903 1904 1905 1906
        if (VIR_STRDUP(info_ret[i]->name, result) < 0)
            goto cleanup;

        if (!(result = virJSONValueObjectGetString(entry, "type"))) {
1907 1908 1909 1910 1911
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'type' missing in reply of guest-get-fsinfo"));
            goto cleanup;
        }

1912 1913 1914
        if (VIR_STRDUP(info_ret[i]->fstype, result) < 0)
            goto cleanup;

1915 1916 1917 1918 1919 1920
        if (!(entry = virJSONValueObjectGet(entry, "disk"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'disk' missing in reply of guest-get-fsinfo"));
            goto cleanup;
        }

1921
        if (!virJSONValueIsArray(entry)) {
1922
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1923
                           _("Malformed guest-get-fsinfo 'disk' data array"));
1924 1925 1926 1927
            goto cleanup;
        }

        ndisk = virJSONValueArraySize(entry);
1928
        if (ndisk == 0)
1929 1930 1931 1932 1933 1934 1935 1936 1937
            continue;
        if (VIR_ALLOC_N(info_ret[i]->devAlias, ndisk) < 0)
            goto cleanup;

        alias = info_ret[i]->devAlias;
        info_ret[i]->ndevAlias = 0;
        for (j = 0; j < ndisk; j++) {
            virJSONValuePtr disk = virJSONValueArrayGet(entry, j);
            virJSONValuePtr pci;
1938
            int diskaddr[3], pciaddr[4];
1939 1940
            const char *diskaddr_comp[] = {"bus", "target", "unit"};
            const char *pciaddr_comp[] = {"domain", "bus", "slot", "function"};
1941
            virDomainDiskDefPtr diskDef;
1942 1943 1944

            if (!disk) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
1945
                               _("array element '%zd' of '%zd' missing in "
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
                                 "guest-get-fsinfo 'disk' data"),
                               j, ndisk);
                goto cleanup;
            }

            if (!(pci = virJSONValueObjectGet(disk, "pci-controller"))) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("'pci-controller' missing in guest-get-fsinfo "
                                 "'disk' data"));
                goto cleanup;
            }

            for (k = 0; k < 3; k++) {
                if (virJSONValueObjectGetNumberInt(
                        disk, diskaddr_comp[k], &diskaddr[k]) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("'%s' missing in guest-get-fsinfo "
                                     "'disk' data"), diskaddr_comp[k]);
                    goto cleanup;
                }
            }
            for (k = 0; k < 4; k++) {
                if (virJSONValueObjectGetNumberInt(
                        pci, pciaddr_comp[k], &pciaddr[k]) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("'%s' missing in guest-get-fsinfo "
                                     "'pci-address' data"), pciaddr_comp[k]);
                    goto cleanup;
                }
            }

            pci_address.domain = pciaddr[0];
            pci_address.bus = pciaddr[1];
            pci_address.slot = pciaddr[2];
            pci_address.function = pciaddr[3];
1981
            if (!(diskDef = virDomainDiskByAddress(
1982
                     vmdef, &pci_address,
1983
                     diskaddr[0], diskaddr[1], diskaddr[2])))
1984 1985
                continue;

1986
            if (VIR_STRDUP(*alias, diskDef->dst) < 0)
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
                goto cleanup;

            if (*alias) {
                alias++;
                info_ret[i]->ndevAlias++;
            }
        }
    }

    *info = info_ret;
    info_ret = NULL;
    ret = ndata;

 cleanup:
    if (info_ret) {
        for (i = 0; i < ndata; i++)
            virDomainFSInfoFree(info_ret[i]);
        VIR_FREE(info_ret);
    }
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045

/*
 * qemuAgentGetInterfaces:
 * @mon: Agent monitor
 * @ifaces: pointer to an array of pointers pointing to interface objects
 *
 * Issue guest-network-get-interfaces to guest agent, which returns a
 * list of interfaces of a running domain along with their IP and MAC
 * addresses.
 *
 * Returns: number of interfaces on success, -1 on error.
 */
int
qemuAgentGetInterfaces(qemuAgentPtr mon,
                       virDomainInterfacePtr **ifaces)
{
    int ret = -1;
    size_t i, j;
    virJSONValuePtr cmd = NULL;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr ret_array = NULL;
    size_t ifaces_count = 0;
    size_t addrs_count = 0;
    virDomainInterfacePtr *ifaces_ret = NULL;
    virHashTablePtr ifaces_store = NULL;
    char **ifname = NULL;

    /* Hash table to handle the interface alias */
    if (!(ifaces_store = virHashCreate(ifaces_count, NULL))) {
        virHashFree(ifaces_store);
        return -1;
    }

    if (!(cmd = qemuAgentMakeCommand("guest-network-get-interfaces", NULL)))
        goto cleanup;

2046 2047
    if (qemuAgentCommand(mon, cmd, &reply, false,
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
2048 2049 2050 2051 2052 2053 2054 2055
        goto cleanup;

    if (!(ret_array = virJSONValueObjectGet(reply, "return"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("qemu agent didn't provide 'return' field"));
        goto cleanup;
    }

2056
    if (!virJSONValueIsArray(ret_array)) {
2057 2058 2059 2060 2061
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("qemu agent didn't return an array of interfaces"));
        goto cleanup;
    }

2062
    for (i = 0; i < virJSONValueArraySize(ret_array); i++) {
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
        virJSONValuePtr tmp_iface = virJSONValueArrayGet(ret_array, i);
        virJSONValuePtr ip_addr_arr = NULL;
        const char *hwaddr, *ifname_s, *name = NULL;
        virDomainInterfacePtr iface = NULL;

        /* Shouldn't happen but doesn't hurt to check neither */
        if (!tmp_iface) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("qemu agent reply missing interface entry in array"));
            goto error;
        }

        /* interface name is required to be presented */
        name = virJSONValueObjectGetString(tmp_iface, "name");
        if (!name) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("qemu agent didn't provide 'name' field"));
            goto error;
        }

        /* Handle interface alias (<ifname>:<alias>) */
        ifname = virStringSplit(name, ":", 2);
        ifname_s = ifname[0];

        iface = virHashLookup(ifaces_store, ifname_s);

        /* If the hash table doesn't contain this iface, add it */
        if (!iface) {
            if (VIR_EXPAND_N(ifaces_ret, ifaces_count, 1) < 0)
                goto error;

            if (VIR_ALLOC(ifaces_ret[ifaces_count - 1]) < 0)
                goto error;

            if (virHashAddEntry(ifaces_store, ifname_s,
                                ifaces_ret[ifaces_count - 1]) < 0)
                goto error;

            iface = ifaces_ret[ifaces_count - 1];
            iface->naddrs = 0;

            if (VIR_STRDUP(iface->name, ifname_s) < 0)
                goto error;

            hwaddr = virJSONValueObjectGetString(tmp_iface, "hardware-address");
            if (VIR_STRDUP(iface->hwaddr, hwaddr) < 0)
                goto error;
        }

        /* Has to be freed for each interface. */
2113
        virStringListFree(ifname);
2114 2115 2116 2117 2118 2119 2120

        /* as well as IP address which - moreover -
         * can be presented multiple times */
        ip_addr_arr = virJSONValueObjectGet(tmp_iface, "ip-addresses");
        if (!ip_addr_arr)
            continue;

2121 2122 2123
        if (!virJSONValueIsArray(ip_addr_arr)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Malformed ip-addresses array"));
2124
            goto error;
2125
        }
2126 2127 2128 2129

        /* If current iface already exists, continue with the count */
        addrs_count = iface->naddrs;

2130
        for (j = 0; j < virJSONValueArraySize(ip_addr_arr); j++) {
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
            const char *type, *addr;
            virJSONValuePtr ip_addr_obj = virJSONValueArrayGet(ip_addr_arr, j);
            virDomainIPAddressPtr ip_addr;

            if (VIR_EXPAND_N(iface->addrs, addrs_count, 1)  < 0)
                goto error;

            ip_addr = &iface->addrs[addrs_count - 1];

            /* Shouldn't happen but doesn't hurt to check neither */
            if (!ip_addr_obj) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("qemu agent reply missing IP addr in array"));
                goto error;
            }

            type = virJSONValueObjectGetString(ip_addr_obj, "ip-address-type");
            if (!type) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("qemu agent didn't provide 'ip-address-type'"
                                 " field for interface '%s'"), name);
                goto error;
            } else if (STREQ(type, "ipv4")) {
                ip_addr->type = VIR_IP_ADDR_TYPE_IPV4;
            } else if (STREQ(type, "ipv6")) {
                ip_addr->type = VIR_IP_ADDR_TYPE_IPV6;
            } else {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown ip address type '%s'"),
                               type);
                goto error;
            }

            addr = virJSONValueObjectGetString(ip_addr_obj, "ip-address");
            if (!addr) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("qemu agent didn't provide 'ip-address'"
                                 " field for interface '%s'"), name);
                goto error;
            }
            if (VIR_STRDUP(ip_addr->addr, addr) < 0)
                goto error;

            if (virJSONValueObjectGetNumberUint(ip_addr_obj, "prefix",
                                                &ip_addr->prefix) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("malformed 'prefix' field"));
                goto error;
            }
        }

        iface->naddrs = addrs_count;
    }

2185
    VIR_STEAL_PTR(*ifaces, ifaces_ret);
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
    ret = ifaces_count;

 cleanup:
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    virHashFree(ifaces_store);
    return ret;

 error:
    if (ifaces_ret) {
        for (i = 0; i < ifaces_count; i++)
            virDomainInterfaceFree(ifaces_ret[i]);
    }
    VIR_FREE(ifaces_ret);
2200
    virStringListFree(ifname);
2201 2202 2203

    goto cleanup;
}
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216


int
qemuAgentSetUserPassword(qemuAgentPtr mon,
                         const char *user,
                         const char *password,
                         bool crypted)
{
    int ret = -1;
    virJSONValuePtr cmd = NULL;
    virJSONValuePtr reply = NULL;
    char *password64 = NULL;

2217
    if (!(password64 = virStringEncodeBase64((unsigned char *)password,
2218
                                             strlen(password))))
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
        goto cleanup;

    if (!(cmd = qemuAgentMakeCommand("guest-set-user-password",
                                     "b:crypted", crypted,
                                     "s:username", user,
                                     "s:password", password64,
                                     NULL)))
        goto cleanup;

    if (qemuAgentCommand(mon, cmd, &reply, true,
                         VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    VIR_FREE(password64);
    return ret;
}