qemu_monitor.c 68.3 KB
Newer Older
1 2 3
/*
 * qemu_monitor.c: interaction with QEMU monitor console
 *
4
 * Copyright (C) 2006-2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 * 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
 * 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 <poll.h>
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>

#include "qemu_monitor.h"
32
#include "qemu_monitor_text.h"
D
Daniel P. Berrange 已提交
33
#include "qemu_monitor_json.h"
34 35
#include "qemu_conf.h"
#include "virterror_internal.h"
36 37
#include "memory.h"
#include "logging.h"
E
Eric Blake 已提交
38
#include "virfile.h"
39 40 41

#define VIR_FROM_THIS VIR_FROM_QEMU

42 43
#define DEBUG_IO 0
#define DEBUG_RAW_IO 0
44

45
struct _qemuMonitor {
S
Stefan Berger 已提交
46
    virMutex lock; /* also used to protect fd */
47 48
    virCond notify;

49
    int refs;
50

51 52 53 54 55 56
    int fd;
    int watch;
    int hasSendFD;

    virDomainObjPtr vm;

57
    qemuMonitorCallbacksPtr cb;
58 59 60 61 62 63 64 65 66 67 68 69 70

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

    /* Buffer incoming data ready for Text/QMP 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 */
71 72 73
    virError lastError;

    int nextSerial;
74

D
Daniel P. Berrange 已提交
75
    unsigned json: 1;
76
    unsigned json_hmp: 1;
77 78
};

79

80 81 82 83
VIR_ENUM_IMPL(qemuMonitorMigrationStatus,
              QEMU_MONITOR_MIGRATION_STATUS_LAST,
              "inactive", "active", "completed", "failed", "cancelled")

84 85 86 87 88 89
VIR_ENUM_IMPL(qemuMonitorVMStatus,
              QEMU_MONITOR_VM_STATUS_LAST,
              "debug", "inmigrate", "internal-error", "io-error", "paused",
              "postmigrate", "prelaunch", "finish-migrate", "restore-vm",
              "running", "save-vm", "shutdown", "watchdog")

90
char *qemuMonitorEscapeArg(const char *in)
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
{
    int len = 0;
    int i, j;
    char *out;

    /* To pass through the QEMU monitor, we need to use escape
       sequences: \r, \n, \", \\
    */

    for (i = 0; in[i] != '\0'; i++) {
        switch(in[i]) {
        case '\r':
        case '\n':
        case '"':
        case '\\':
            len += 2;
            break;
        default:
            len += 1;
            break;
        }
    }

    if (VIR_ALLOC_N(out, len + 1) < 0)
        return NULL;

    for (i = j = 0; in[i] != '\0'; i++) {
        switch(in[i]) {
        case '\r':
            out[j++] = '\\';
            out[j++] = 'r';
            break;
        case '\n':
            out[j++] = '\\';
            out[j++] = 'n';
            break;
        case '"':
        case '\\':
            out[j++] = '\\';
            out[j++] = in[i];
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

J
Jiri Denemark 已提交
142
#if DEBUG_RAW_IO
143
# include <c-ctype.h>
144 145 146 147 148 149 150 151
static char * qemuMonitorEscapeNonPrintable(const char *text)
{
    int i;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    for (i = 0 ; text[i] != '\0' ; i++) {
        if (c_isprint(text[i]) ||
            text[i] == '\n' ||
            (text[i] == '\r' && text[i+1] == '\n'))
152
            virBufferAsprintf(&buf,"%c", text[i]);
153
        else
154
            virBufferAsprintf(&buf, "0x%02x", text[i]);
155 156 157 158 159
    }
    return virBufferContentAndReset(&buf);
}
#endif

160 161 162 163 164 165 166 167 168 169
void qemuMonitorLock(qemuMonitorPtr mon)
{
    virMutexLock(&mon->lock);
}

void qemuMonitorUnlock(qemuMonitorPtr mon)
{
    virMutexUnlock(&mon->lock);
}

170

171
static void qemuMonitorFree(qemuMonitorPtr mon)
172
{
173
    VIR_DEBUG("mon=%p", mon);
174
    if (mon->cb && mon->cb->destroy)
175
        (mon->cb->destroy)(mon, mon->vm);
176 177 178
    if (virCondDestroy(&mon->notify) < 0)
    {}
    virMutexDestroy(&mon->lock);
E
Eric Blake 已提交
179
    VIR_FREE(mon->buffer);
180
    VIR_FREE(mon);
181 182
}

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
int qemuMonitorRef(qemuMonitorPtr mon)
{
    mon->refs++;
    return mon->refs;
}

int qemuMonitorUnref(qemuMonitorPtr mon)
{
    mon->refs--;

    if (mon->refs == 0) {
        qemuMonitorUnlock(mon);
        qemuMonitorFree(mon);
        return 0;
    }

    return mon->refs;
}

202 203 204 205 206 207
static void
qemuMonitorUnwatch(void *monitor)
{
    qemuMonitorPtr mon = monitor;

    qemuMonitorLock(mon);
208 209
    if (qemuMonitorUnref(mon) > 0)
        qemuMonitorUnlock(mon);
210
}
211 212

static int
213
qemuMonitorOpenUnix(const char *monitor, pid_t cpid)
214 215 216 217 218 219 220
{
    struct sockaddr_un addr;
    int monfd;
    int timeout = 3; /* In seconds */
    int ret, i = 0;

    if ((monfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
221
        virReportSystemError(errno,
222 223 224 225 226 227 228
                             "%s", _("failed to create socket"));
        return -1;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    if (virStrcpyStatic(addr.sun_path, monitor) == NULL) {
229 230
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Monitor path %s too big for destination"), monitor);
231 232 233 234 235 236 237 238 239
        goto error;
    }

    do {
        ret = connect(monfd, (struct sockaddr *) &addr, sizeof(addr));

        if (ret == 0)
            break;

240 241
        if ((errno == ENOENT || errno == ECONNREFUSED) &&
            virKillProcess(cpid, 0) == 0) {
242 243 244 245 246
            /* ENOENT       : Socket may not have shown up yet
             * ECONNREFUSED : Leftover socket hasn't been removed yet */
            continue;
        }

247
        virReportSystemError(errno, "%s",
248 249 250 251 252 253
                             _("failed to connect to monitor socket"));
        goto error;

    } while ((++i <= timeout*5) && (usleep(.2 * 1000000) <= 0));

    if (ret != 0) {
254
        virReportSystemError(errno, "%s",
255 256 257 258
                             _("monitor socket did not show up."));
        goto error;
    }

259
    return monfd;
260 261

error:
262
    VIR_FORCE_CLOSE(monfd);
263 264 265 266
    return -1;
}

static int
267
qemuMonitorOpenPty(const char *monitor)
268 269 270 271
{
    int monfd;

    if ((monfd = open(monitor, O_RDWR)) < 0) {
272 273
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Unable to open monitor path %s"), monitor);
274 275 276
        return -1;
    }

277
    return monfd;
278
}
279

280

281 282 283 284
/* This method processes data that has been received
 * from the monitor. Looking for async events and
 * replies/errors.
 */
285 286 287 288 289 290 291 292 293 294 295
static int
qemuMonitorIOProcess(qemuMonitorPtr mon)
{
    int len;
    qemuMonitorMessagePtr msg = NULL;

    /* See if there's a message & whether its ready for its reply
     * ie whether its completed writing all its data */
    if (mon->msg && mon->msg->txOffset == mon->msg->txLength)
        msg = mon->msg;

296
#if DEBUG_IO
297
# if DEBUG_RAW_IO
298 299
    char *str1 = qemuMonitorEscapeNonPrintable(msg ? msg->txBuffer : "");
    char *str2 = qemuMonitorEscapeNonPrintable(mon->buffer);
300
    VIR_ERROR(_("Process %d %p %p [[[[%s]]][[[%s]]]"), (int)mon->bufferOffset, mon->msg, msg, str1, str2);
301 302
    VIR_FREE(str1);
    VIR_FREE(str2);
303
# else
304
    VIR_DEBUG("Process %d", (int)mon->bufferOffset);
305
# endif
306 307
#endif

D
Daniel P. Berrange 已提交
308 309 310 311 312 313 314 315
    if (mon->json)
        len = qemuMonitorJSONIOProcess(mon,
                                       mon->buffer, mon->bufferOffset,
                                       msg);
    else
        len = qemuMonitorTextIOProcess(mon,
                                       mon->buffer, mon->bufferOffset,
                                       msg);
316

317
    if (len < 0)
318 319 320 321 322 323 324 325 326
        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;
    }
327
#if DEBUG_IO
328
    VIR_DEBUG("Process done %d used %d", (int)mon->bufferOffset, len);
329
#endif
330 331 332 333 334 335
    if (msg && msg->finished)
        virCondBroadcast(&mon->notify);
    return len;
}


S
Stefan Berger 已提交
336
/* Call this function while holding the monitor lock. */
337 338 339 340 341 342 343 344 345 346 347 348 349
static int
qemuMonitorIOWriteWithFD(qemuMonitorPtr mon,
                         const char *data,
                         size_t len,
                         int fd)
{
    struct msghdr msg;
    struct iovec iov[1];
    int ret;
    char control[CMSG_SPACE(sizeof(int))];
    struct cmsghdr *cmsg;

    memset(&msg, 0, sizeof(msg));
350
    memset(control, 0, sizeof(control));
351 352 353 354 355 356 357 358 359 360 361

    iov[0].iov_base = (void *)data;
    iov[0].iov_len = len;

    msg.msg_iov = iov;
    msg.msg_iovlen = 1;

    msg.msg_control = control;
    msg.msg_controllen = sizeof(control);

    cmsg = CMSG_FIRSTHDR(&msg);
362 363 364
    /* Some static analyzers, like clang 2.6-0.6.pre2, fail to see
       that our use of CMSG_FIRSTHDR will not return NULL.  */
    sa_assert(cmsg);
365 366 367 368 369 370 371 372 373 374 375 376
    cmsg->cmsg_len = CMSG_LEN(sizeof(int));
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));

    do {
        ret = sendmsg(mon->fd, &msg, 0);
    } while (ret < 0 && errno == EINTR);

    return ret;
}

S
Stefan Berger 已提交
377 378 379 380
/*
 * Called when the monitor is able to write data
 * Call this function while holding the monitor lock.
 */
381 382 383 384 385 386 387 388 389
static int
qemuMonitorIOWrite(qemuMonitorPtr mon)
{
    int done;

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

390 391 392 393 394 395
    if (mon->msg->txFD != -1 && !mon->hasSendFD) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("Monitor does not support sending of file descriptors"));
        return -1;
    }

396 397 398 399 400 401 402 403 404 405 406 407 408 409
    if (mon->msg->txFD == -1)
        done = write(mon->fd,
                     mon->msg->txBuffer + mon->msg->txOffset,
                     mon->msg->txLength - mon->msg->txOffset);
    else
        done = qemuMonitorIOWriteWithFD(mon,
                                        mon->msg->txBuffer + mon->msg->txOffset,
                                        mon->msg->txLength - mon->msg->txOffset,
                                        mon->msg->txFD);

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

410 411
        virReportSystemError(errno, "%s",
                             _("Unable to write to monitor"));
412 413 414 415 416 417 418 419
        return -1;
    }
    mon->msg->txOffset += done;
    return done;
}

/*
 * Called when the monitor has incoming data to read
S
Stefan Berger 已提交
420
 * Call this function while holding the monitor lock.
421 422 423 424 425 426 427 428 429 430 431 432
 *
 * Returns -1 on error, or number of bytes read
 */
static int
qemuMonitorIORead(qemuMonitorPtr mon)
{
    size_t avail = mon->bufferLength - mon->bufferOffset;
    int ret = 0;

    if (avail < 1024) {
        if (VIR_REALLOC_N(mon->buffer,
                          mon->bufferLength + 1024) < 0) {
433
            virReportOOMError();
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
            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;
450 451
            virReportSystemError(errno, "%s",
                                 _("Unable to read from monitor"));
452 453 454 455 456 457 458 459 460 461 462 463
            ret = -1;
            break;
        }
        if (got == 0)
            break;

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

464
#if DEBUG_IO
465
    VIR_DEBUG("Now read %d bytes of data", (int)mon->bufferOffset);
466
#endif
467 468 469 470 471 472 473 474 475 476 477

    return ret;
}


static void qemuMonitorUpdateWatch(qemuMonitorPtr mon)
{
    int events =
        VIR_EVENT_HANDLE_HANGUP |
        VIR_EVENT_HANDLE_ERROR;

478
    if (mon->lastError.code == VIR_ERR_OK) {
479 480 481 482 483 484 485
        events |= VIR_EVENT_HANDLE_READABLE;

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

    virEventUpdateHandle(mon->watch, events);
486 487
}

488 489 490 491

static void
qemuMonitorIO(int watch, int fd, int events, void *opaque) {
    qemuMonitorPtr mon = opaque;
492 493
    bool error = false;
    bool eof = false;
494

S
Stefan Berger 已提交
495
    /* lock access to the monitor and protect fd */
496
    qemuMonitorLock(mon);
497
    qemuMonitorRef(mon);
498
#if DEBUG_IO
499
    VIR_DEBUG("Monitor %p I/O on watch %d fd %d events %d", mon, watch, fd, events);
500
#endif
501

502
    if (mon->fd != fd || mon->watch != watch) {
503
        if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR))
504 505 506 507 508 509
            eof = true;
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("event from unexpected fd %d!=%d / watch %d!=%d"),
                        mon->fd, fd, mon->watch, watch);
        error = true;
    } else if (mon->lastError.code != VIR_ERR_OK) {
510
        if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR))
511
            eof = true;
512
        error = true;
513
    } else {
514 515 516
        if (events & VIR_EVENT_HANDLE_WRITABLE) {
            if (qemuMonitorIOWrite(mon) < 0)
                error = true;
517 518
            events &= ~VIR_EVENT_HANDLE_WRITABLE;
        }
519 520

        if (!error &&
521 522
            events & VIR_EVENT_HANDLE_READABLE) {
            int got = qemuMonitorIORead(mon);
523 524
            events &= ~VIR_EVENT_HANDLE_READABLE;
            if (got < 0) {
525
                error = true;
526 527 528 529 530
            } 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 */
531 532 533
                events = 0;

                if (qemuMonitorIOProcess(mon) < 0)
534
                    error = true;
535
            }
536 537
        }

538 539 540 541 542 543
        if (!error &&
            events & VIR_EVENT_HANDLE_HANGUP) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("End of file from monitor"));
            eof = 1;
            events &= ~VIR_EVENT_HANDLE_HANGUP;
544 545
        }

546 547 548
        if (!error && !eof &&
            events & VIR_EVENT_HANDLE_ERROR) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
549 550 551
                            _("Invalid file descriptor while waiting for monitor"));
            eof = 1;
            events &= ~VIR_EVENT_HANDLE_ERROR;
552 553 554 555 556
        }
        if (!error && events) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unhandled event %d for monitor fd %d"),
                            events, mon->fd);
557
            error = 1;
558 559 560
        }
    }

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    if (error || eof) {
        if (mon->lastError.code != VIR_ERR_OK) {
            /* Already have an error, so clear any new error */
            virResetLastError();
        } else {
            virErrorPtr err = virGetLastError();
            if (!err)
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Error while processing monitor IO"));
            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);
        }
    }
582 583 584

    qemuMonitorUpdateWatch(mon);

585 586 587
    /* 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 */
588 589
    if (eof) {
        void (*eofNotify)(qemuMonitorPtr, virDomainObjPtr)
590
            = mon->cb->eofNotify;
591
        virDomainObjPtr vm = mon->vm;
592

593 594 595 596 597 598 599 600 601 602
        /* Make sure anyone waiting wakes up now */
        virCondSignal(&mon->notify);
        if (qemuMonitorUnref(mon) > 0)
            qemuMonitorUnlock(mon);
        VIR_DEBUG("Triggering EOF callback");
        (eofNotify)(mon, vm);
    } else if (error) {
        void (*errorNotify)(qemuMonitorPtr, virDomainObjPtr)
            = mon->cb->errorNotify;
        virDomainObjPtr vm = mon->vm;
603

604 605
        /* Make sure anyone waiting wakes up now */
        virCondSignal(&mon->notify);
606
        if (qemuMonitorUnref(mon) > 0)
607
            qemuMonitorUnlock(mon);
608 609
        VIR_DEBUG("Triggering error callback");
        (errorNotify)(mon, vm);
610
    } else {
611 612
        if (qemuMonitorUnref(mon) > 0)
            qemuMonitorUnlock(mon);
613
    }
614 615 616 617
}


qemuMonitorPtr
618
qemuMonitorOpen(virDomainObjPtr vm,
619
                virDomainChrSourceDefPtr config,
D
Daniel P. Berrange 已提交
620
                int json,
621
                qemuMonitorCallbacksPtr cb)
622
{
623 624
    qemuMonitorPtr mon;

625
    if (!cb || !cb->eofNotify) {
626 627
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("EOF notify callback must be supplied"));
628 629 630
        return NULL;
    }

631
    if (VIR_ALLOC(mon) < 0) {
632
        virReportOOMError();
633 634 635
        return NULL;
    }

636
    if (virMutexInit(&mon->lock) < 0) {
637 638
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cannot initialize monitor mutex"));
639 640 641
        VIR_FREE(mon);
        return NULL;
    }
642
    if (virCondInit(&mon->notify) < 0) {
643 644
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cannot initialize monitor condition"));
645 646 647 648
        virMutexDestroy(&mon->lock);
        VIR_FREE(mon);
        return NULL;
    }
649
    mon->fd = -1;
650
    mon->refs = 1;
651
    mon->vm = vm;
D
Daniel P. Berrange 已提交
652
    mon->json = json;
653
    mon->cb = cb;
654
    qemuMonitorLock(mon);
655

656
    switch (config->type) {
657
    case VIR_DOMAIN_CHR_TYPE_UNIX:
658
        mon->hasSendFD = 1;
659
        mon->fd = qemuMonitorOpenUnix(config->data.nix.path, vm->pid);
660 661
        break;

662
    case VIR_DOMAIN_CHR_TYPE_PTY:
663
        mon->fd = qemuMonitorOpenPty(config->data.file.path);
664 665
        break;

666
    default:
667 668
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unable to handle monitor type: %s"),
669
                        virDomainChrTypeToString(config->type));
670 671 672
        goto cleanup;
    }

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

675
    if (virSetCloseExec(mon->fd) < 0) {
676 677
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Unable to set monitor close-on-exec flag"));
678 679 680
        goto cleanup;
    }
    if (virSetNonBlock(mon->fd) < 0) {
681 682
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Unable to put monitor into non-blocking mode"));
683 684 685 686
        goto cleanup;
    }


687
    if ((mon->watch = virEventAddHandle(mon->fd,
688 689 690
                                        VIR_EVENT_HANDLE_HANGUP |
                                        VIR_EVENT_HANDLE_ERROR |
                                        VIR_EVENT_HANDLE_READABLE,
691
                                        qemuMonitorIO,
692
                                        mon, qemuMonitorUnwatch)) < 0) {
693 694
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("unable to register monitor events"));
695 696
        goto cleanup;
    }
697
    qemuMonitorRef(mon);
698

699 700
    VIR_DEBUG("New mon %p fd =%d watch=%d", mon, mon->fd, mon->watch);
    qemuMonitorUnlock(mon);
701

702 703 704
    return mon;

cleanup:
705 706 707 708 709 710
    /* 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;
711
    qemuMonitorUnlock(mon);
712 713 714 715 716
    qemuMonitorClose(mon);
    return NULL;
}


717
void qemuMonitorClose(qemuMonitorPtr mon)
718 719
{
    if (!mon)
720
        return;
721 722

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

724
    qemuMonitorLock(mon);
S
Stefan Berger 已提交
725 726

    if (mon->fd >= 0) {
727 728
        if (mon->watch)
            virEventRemoveHandle(mon->watch);
S
Stefan Berger 已提交
729
        VIR_FORCE_CLOSE(mon->fd);
730
    }
731

E
Eric Blake 已提交
732
    if (qemuMonitorUnref(mon) > 0)
733
        qemuMonitorUnlock(mon);
734 735 736
}


737 738 739 740 741 742 743 744 745 746 747 748
char *qemuMonitorNextCommandID(qemuMonitorPtr mon)
{
    char *id;

    if (virAsprintf(&id, "libvirt-%d", ++mon->nextSerial) < 0) {
        virReportOOMError();
        return NULL;
    }
    return id;
}


749 750
int qemuMonitorSend(qemuMonitorPtr mon,
                    qemuMonitorMessagePtr msg)
751
{
752
    int ret = -1;
753

754
    /* Check whether qemu quited unexpectedly */
755 756 757 758
    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);
759 760 761
        return -1;
    }

762 763
    mon->msg = msg;
    qemuMonitorUpdateWatch(mon);
764

765
    while (!mon->msg->finished) {
766 767 768
        if (virCondWait(&mon->notify, &mon->lock) < 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("Unable to wait on monitor condition"));
769
            goto cleanup;
770 771 772 773 774 775 776 777
        }
    }

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

780
    ret = 0;
781

782 783 784
cleanup:
    mon->msg = NULL;
    qemuMonitorUpdateWatch(mon);
785

786
    return ret;
787
}
788 789


790 791 792 793
int qemuMonitorHMPCommandWithFd(qemuMonitorPtr mon,
                                const char *cmd,
                                int scm_fd,
                                char **reply)
794 795 796 797 798 799 800
{
    if (mon->json)
        return qemuMonitorJSONHumanCommandWithFd(mon, cmd, scm_fd, reply);
    else
        return qemuMonitorTextCommandWithFd(mon, cmd, scm_fd, reply);
}

E
Eric Blake 已提交
801 802 803 804 805 806 807 808
/* Ensure proper locking around callbacks.  */
#define QEMU_MONITOR_CALLBACK(mon, ret, callback, ...)          \
    do {                                                        \
        qemuMonitorRef(mon);                                    \
        qemuMonitorUnlock(mon);                                 \
        if ((mon)->cb && (mon)->cb->callback)                   \
            (ret) = ((mon)->cb->callback)(mon, __VA_ARGS__);    \
        qemuMonitorLock(mon);                                   \
809
        ignore_value(qemuMonitorUnref(mon));                    \
E
Eric Blake 已提交
810
    } while (0)
811

812 813 814 815 816 817
int qemuMonitorGetDiskSecret(qemuMonitorPtr mon,
                             virConnectPtr conn,
                             const char *path,
                             char **secret,
                             size_t *secretLen)
{
818
    int ret = -1;
819 820 821
    *secret = NULL;
    *secretLen = 0;

E
Eric Blake 已提交
822 823
    QEMU_MONITOR_CALLBACK(mon, ret, diskSecretLookup, conn, mon->vm,
                          path, secret, secretLen);
824
    return ret;
825
}
826 827


828 829 830 831 832
int qemuMonitorEmitShutdown(qemuMonitorPtr mon)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
833
    QEMU_MONITOR_CALLBACK(mon, ret, domainShutdown, mon->vm);
834 835 836 837 838 839 840 841 842
    return ret;
}


int qemuMonitorEmitReset(qemuMonitorPtr mon)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
843
    QEMU_MONITOR_CALLBACK(mon, ret, domainReset, mon->vm);
844 845 846 847 848 849 850 851 852
    return ret;
}


int qemuMonitorEmitPowerdown(qemuMonitorPtr mon)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
853
    QEMU_MONITOR_CALLBACK(mon, ret, domainPowerdown, mon->vm);
854 855 856 857 858 859 860 861 862
    return ret;
}


int qemuMonitorEmitStop(qemuMonitorPtr mon)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
863
    QEMU_MONITOR_CALLBACK(mon, ret, domainStop, mon->vm);
864 865 866 867
    return ret;
}


868 869 870 871 872
int qemuMonitorEmitRTCChange(qemuMonitorPtr mon, long long offset)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
873
    QEMU_MONITOR_CALLBACK(mon, ret, domainRTCChange, mon->vm, offset);
874 875 876 877
    return ret;
}


878 879 880 881 882
int qemuMonitorEmitWatchdog(qemuMonitorPtr mon, int action)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
883
    QEMU_MONITOR_CALLBACK(mon, ret, domainWatchdog, mon->vm, action);
884 885 886 887
    return ret;
}


888 889
int qemuMonitorEmitIOError(qemuMonitorPtr mon,
                           const char *diskAlias,
890 891
                           int action,
                           const char *reason)
892 893 894 895
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
896 897
    QEMU_MONITOR_CALLBACK(mon, ret, domainIOError, mon->vm,
                          diskAlias, action, reason);
898 899 900 901
    return ret;
}


902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
int qemuMonitorEmitGraphics(qemuMonitorPtr mon,
                            int phase,
                            int localFamily,
                            const char *localNode,
                            const char *localService,
                            int remoteFamily,
                            const char *remoteNode,
                            const char *remoteService,
                            const char *authScheme,
                            const char *x509dname,
                            const char *saslUsername)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

E
Eric Blake 已提交
917 918 919 920
    QEMU_MONITOR_CALLBACK(mon, ret, domainGraphics, mon->vm, phase,
                          localFamily, localNode, localService,
                          remoteFamily, remoteNode, remoteService,
                          authScheme, x509dname, saslUsername);
921 922 923
    return ret;
}

924 925 926 927 928 929 930 931 932 933 934 935 936
int qemuMonitorEmitBlockJob(qemuMonitorPtr mon,
                            const char *diskAlias,
                            int type,
                            int status)
{
    int ret = -1;
    VIR_DEBUG("mon=%p", mon);

    QEMU_MONITOR_CALLBACK(mon, ret, domainBlockJob, mon->vm,
                          diskAlias, type, status);
    return ret;
}

937 938


939 940 941
int qemuMonitorSetCapabilities(qemuMonitorPtr mon)
{
    int ret;
942
    VIR_DEBUG("mon=%p", mon);
943 944 945 946 947 948

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
949

950
    if (mon->json) {
951
        ret = qemuMonitorJSONSetCapabilities(mon);
952 953 954 955 956 957 958 959 960 961
        if (ret == 0) {
            int hmp = qemuMonitorJSONCheckHMP(mon);
            if (hmp < 0) {
                /* qemu may quited unexpectedly when we call
                 * qemuMonitorJSONCheckHMP() */
                ret = -1;
            } else {
                mon->json_hmp = hmp > 0;
            }
        }
962
    } else {
963
        ret = 0;
964
    }
965 966 967 968
    return ret;
}


969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
int
qemuMonitorCheckHMP(qemuMonitorPtr mon, const char *cmd)
{
    if (!mon->json || mon->json_hmp)
        return 1;

    if (cmd) {
        VIR_DEBUG("HMP passthrough not supported by qemu process;"
                  " not trying HMP for command %s", cmd);
    }

    return 0;
}


984 985 986 987
int
qemuMonitorStartCPUs(qemuMonitorPtr mon,
                     virConnectPtr conn)
{
D
Daniel P. Berrange 已提交
988
    int ret;
989
    VIR_DEBUG("mon=%p", mon);
990 991 992 993 994 995

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
996

D
Daniel P. Berrange 已提交
997 998 999 1000 1001
    if (mon->json)
        ret = qemuMonitorJSONStartCPUs(mon, conn);
    else
        ret = qemuMonitorTextStartCPUs(mon, conn);
    return ret;
1002 1003 1004 1005 1006 1007
}


int
qemuMonitorStopCPUs(qemuMonitorPtr mon)
{
D
Daniel P. Berrange 已提交
1008
    int ret;
1009
    VIR_DEBUG("mon=%p", mon);
1010 1011 1012 1013 1014 1015

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1016

D
Daniel P. Berrange 已提交
1017 1018 1019 1020 1021
    if (mon->json)
        ret = qemuMonitorJSONStopCPUs(mon);
    else
        ret = qemuMonitorTextStopCPUs(mon);
    return ret;
1022 1023 1024
}


1025
int
1026 1027 1028
qemuMonitorGetStatus(qemuMonitorPtr mon,
                     bool *running,
                     virDomainPausedReason *reason)
1029 1030
{
    int ret;
1031
    VIR_DEBUG("mon=%p, running=%p, reason=%p", mon, running, reason);
1032 1033 1034 1035 1036 1037 1038 1039

    if (!mon || !running) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("both monitor and running must not be NULL"));
        return -1;
    }

    if (mon->json)
1040
        ret = qemuMonitorJSONGetStatus(mon, running, reason);
1041
    else
1042
        ret = qemuMonitorTextGetStatus(mon, running, reason);
1043 1044 1045 1046
    return ret;
}


1047 1048
int qemuMonitorSystemPowerdown(qemuMonitorPtr mon)
{
D
Daniel P. Berrange 已提交
1049
    int ret;
1050
    VIR_DEBUG("mon=%p", mon);
1051 1052 1053 1054 1055 1056

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1057

D
Daniel P. Berrange 已提交
1058 1059 1060 1061 1062
    if (mon->json)
        ret = qemuMonitorJSONSystemPowerdown(mon);
    else
        ret = qemuMonitorTextSystemPowerdown(mon);
    return ret;
1063 1064 1065
}


1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
int qemuMonitorSystemReset(qemuMonitorPtr mon)
{
    int ret;
    VIR_DEBUG("mon=%p", mon);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (mon->json)
        ret = qemuMonitorJSONSystemReset(mon);
    else
        ret = qemuMonitorTextSystemReset(mon);
    return ret;
}


1085 1086 1087
int qemuMonitorGetCPUInfo(qemuMonitorPtr mon,
                          int **pids)
{
D
Daniel P. Berrange 已提交
1088
    int ret;
1089
    VIR_DEBUG("mon=%p", mon);
1090 1091 1092 1093 1094 1095

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1096

D
Daniel P. Berrange 已提交
1097 1098 1099 1100 1101
    if (mon->json)
        ret = qemuMonitorJSONGetCPUInfo(mon, pids);
    else
        ret = qemuMonitorTextGetCPUInfo(mon, pids);
    return ret;
1102 1103
}

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
int qemuMonitorSetLink(qemuMonitorPtr mon,
                       const char *name,
                       enum virDomainNetInterfaceLinkState state)
{
    int ret;
    VIR_DEBUG("mon=%p, name=%p:%s, state=%u", mon, name, name, state);

    if (!mon || !name) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("monitor || name must not be NULL"));
        return -1;
    }

    if (mon->json)
        ret = qemuMonitorJSONSetLink(mon, name, state);
    else
        ret = qemuMonitorTextSetLink(mon, name, state);
    return ret;
}
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

int qemuMonitorGetVirtType(qemuMonitorPtr mon,
                           int *virtType)
{
    int ret;
    VIR_DEBUG("mon=%p", mon);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (mon->json)
        ret = qemuMonitorJSONGetVirtType(mon, virtType);
    else
        ret = qemuMonitorTextGetVirtType(mon, virtType);
    return ret;
}


1144 1145 1146
int qemuMonitorGetBalloonInfo(qemuMonitorPtr mon,
                              unsigned long *currmem)
{
D
Daniel P. Berrange 已提交
1147
    int ret;
1148
    VIR_DEBUG("mon=%p", mon);
1149 1150 1151 1152 1153 1154

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1155

D
Daniel P. Berrange 已提交
1156 1157 1158 1159 1160
    if (mon->json)
        ret = qemuMonitorJSONGetBalloonInfo(mon, currmem);
    else
        ret = qemuMonitorTextGetBalloonInfo(mon, currmem);
    return ret;
1161 1162 1163
}


1164 1165 1166 1167 1168
int qemuMonitorGetMemoryStats(qemuMonitorPtr mon,
                              virDomainMemoryStatPtr stats,
                              unsigned int nr_stats)
{
    int ret;
1169
    VIR_DEBUG("mon=%p stats=%p nstats=%u", mon, stats, nr_stats);
1170 1171 1172 1173 1174 1175

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1176 1177 1178 1179 1180 1181 1182 1183

    if (mon->json)
        ret = qemuMonitorJSONGetMemoryStats(mon, stats, nr_stats);
    else
        ret = qemuMonitorTextGetMemoryStats(mon, stats, nr_stats);
    return ret;
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
int qemuMonitorGetBlockInfo(qemuMonitorPtr mon,
                            const char *devname,
                            struct qemuDomainDiskInfo *info)
{
    int ret;

    VIR_DEBUG("mon=%p dev=%p info=%p", mon, devname, info);
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (mon->json)
        ret = qemuMonitorJSONGetBlockInfo(mon, devname, info);
    else
        ret = qemuMonitorTextGetBlockInfo(mon, devname, info);
    return ret;
}
1203

1204
int qemuMonitorGetBlockStatsInfo(qemuMonitorPtr mon,
1205
                                 const char *dev_name,
1206 1207
                                 long long *rd_req,
                                 long long *rd_bytes,
1208
                                 long long *rd_total_times,
1209 1210
                                 long long *wr_req,
                                 long long *wr_bytes,
1211 1212 1213
                                 long long *wr_total_times,
                                 long long *flush_req,
                                 long long *flush_total_times,
1214 1215
                                 long long *errs)
{
D
Daniel P. Berrange 已提交
1216
    int ret;
1217
    VIR_DEBUG("mon=%p dev=%s", mon, dev_name);
1218 1219 1220 1221 1222 1223

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1224

D
Daniel P. Berrange 已提交
1225
    if (mon->json)
1226
        ret = qemuMonitorJSONGetBlockStatsInfo(mon, dev_name,
D
Daniel P. Berrange 已提交
1227
                                               rd_req, rd_bytes,
1228
                                               rd_total_times,
D
Daniel P. Berrange 已提交
1229
                                               wr_req, wr_bytes,
1230 1231 1232
                                               wr_total_times,
                                               flush_req,
                                               flush_total_times,
D
Daniel P. Berrange 已提交
1233 1234
                                               errs);
    else
1235
        ret = qemuMonitorTextGetBlockStatsInfo(mon, dev_name,
D
Daniel P. Berrange 已提交
1236
                                               rd_req, rd_bytes,
1237
                                               rd_total_times,
D
Daniel P. Berrange 已提交
1238
                                               wr_req, wr_bytes,
1239 1240 1241
                                               wr_total_times,
                                               flush_req,
                                               flush_total_times,
D
Daniel P. Berrange 已提交
1242 1243
                                               errs);
    return ret;
1244 1245
}

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
/* Return 0 and update @nparams with the number of block stats
 * QEMU supports if success. Return -1 if failure.
 */
int qemuMonitorGetBlockStatsParamsNumber(qemuMonitorPtr mon,
                                         int *nparams)
{
    int ret;
    VIR_DEBUG("mon=%p nparams=%p", mon, nparams);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (mon->json)
        ret = qemuMonitorJSONGetBlockStatsParamsNumber(mon, nparams);
    else
        ret = qemuMonitorTextGetBlockStatsParamsNumber(mon, nparams);

    return ret;
}

1269
int qemuMonitorGetBlockExtent(qemuMonitorPtr mon,
1270
                              const char *dev_name,
1271 1272 1273
                              unsigned long long *extent)
{
    int ret;
1274 1275
    VIR_DEBUG("mon=%p, fd=%d, dev_name=%p",
          mon, mon->fd, dev_name);
1276 1277

    if (mon->json)
1278
        ret = qemuMonitorJSONGetBlockExtent(mon, dev_name, extent);
1279
    else
1280
        ret = qemuMonitorTextGetBlockExtent(mon, dev_name, extent);
1281 1282 1283 1284

    return ret;
}

1285 1286 1287 1288

int qemuMonitorSetVNCPassword(qemuMonitorPtr mon,
                              const char *password)
{
D
Daniel P. Berrange 已提交
1289
    int ret;
1290
    VIR_DEBUG("mon=%p, password=%p",
1291 1292 1293 1294 1295 1296 1297
          mon, password);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1298

1299 1300 1301
    if (!password)
        password = "";

D
Daniel P. Berrange 已提交
1302 1303 1304 1305 1306
    if (mon->json)
        ret = qemuMonitorJSONSetVNCPassword(mon, password);
    else
        ret = qemuMonitorTextSetVNCPassword(mon, password);
    return ret;
1307 1308
}

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
static const char* qemuMonitorTypeToProtocol(int type)
{
    switch (type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        return "vnc";
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        return "spice";
    default:
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported protocol type %s"),
                        virDomainGraphicsTypeToString(type));
        return NULL;
    }
}

/* Returns -2 if not supported with this monitor connection */
int qemuMonitorSetPassword(qemuMonitorPtr mon,
                           int type,
                           const char *password,
                           const char *action_if_connected)
{
    const char *protocol = qemuMonitorTypeToProtocol(type);
    int ret;

    if (!protocol)
        return -1;

1336
    VIR_DEBUG("mon=%p, protocol=%s, password=%p, action_if_connected=%s",
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
          mon, protocol, password, action_if_connected);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (!password)
        password = "";

    if (!action_if_connected)
        action_if_connected = "keep";

    if (mon->json)
        ret = qemuMonitorJSONSetPassword(mon, protocol, password, action_if_connected);
    else
        ret = qemuMonitorTextSetPassword(mon, protocol, password, action_if_connected);
    return ret;
}

int qemuMonitorExpirePassword(qemuMonitorPtr mon,
                              int type,
                              const char *expire_time)
{
    const char *protocol = qemuMonitorTypeToProtocol(type);
    int ret;

    if (!protocol)
        return -1;

1368
    VIR_DEBUG("mon=%p, protocol=%s, expire_time=%s",
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
          mon, protocol, expire_time);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (!expire_time)
        expire_time = "now";

    if (mon->json)
        ret = qemuMonitorJSONExpirePassword(mon, protocol, expire_time);
    else
        ret = qemuMonitorTextExpirePassword(mon, protocol, expire_time);
    return ret;
}
1386 1387 1388 1389

int qemuMonitorSetBalloon(qemuMonitorPtr mon,
                          unsigned long newmem)
{
D
Daniel P. Berrange 已提交
1390
    int ret;
1391
    VIR_DEBUG("mon=%p newmem=%lu", mon, newmem);
1392 1393 1394 1395 1396 1397

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1398

D
Daniel P. Berrange 已提交
1399 1400 1401 1402 1403
    if (mon->json)
        ret = qemuMonitorJSONSetBalloon(mon, newmem);
    else
        ret = qemuMonitorTextSetBalloon(mon, newmem);
    return ret;
1404 1405
}

1406 1407 1408 1409

int qemuMonitorSetCPU(qemuMonitorPtr mon, int cpu, int online)
{
    int ret;
1410
    VIR_DEBUG("mon=%p cpu=%d online=%d", mon, cpu, online);
1411 1412 1413 1414 1415 1416

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1417 1418 1419 1420 1421 1422 1423 1424 1425

    if (mon->json)
        ret = qemuMonitorJSONSetCPU(mon, cpu, online);
    else
        ret = qemuMonitorTextSetCPU(mon, cpu, online);
    return ret;
}


1426
int qemuMonitorEjectMedia(qemuMonitorPtr mon,
1427
                          const char *dev_name,
1428
                          bool force)
1429
{
D
Daniel P. Berrange 已提交
1430
    int ret;
1431
    VIR_DEBUG("mon=%p dev_name=%s force=%d", mon, dev_name, force);
1432 1433 1434 1435 1436 1437

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1438

D
Daniel P. Berrange 已提交
1439
    if (mon->json)
1440
        ret = qemuMonitorJSONEjectMedia(mon, dev_name, force);
D
Daniel P. Berrange 已提交
1441
    else
1442
        ret = qemuMonitorTextEjectMedia(mon, dev_name, force);
D
Daniel P. Berrange 已提交
1443
    return ret;
1444 1445 1446 1447
}


int qemuMonitorChangeMedia(qemuMonitorPtr mon,
1448
                           const char *dev_name,
1449 1450
                           const char *newmedia,
                           const char *format)
1451
{
D
Daniel P. Berrange 已提交
1452
    int ret;
1453 1454
    VIR_DEBUG("mon=%p dev_name=%s newmedia=%s format=%s",
          mon, dev_name, newmedia, format);
1455 1456 1457 1458 1459 1460

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1461

D
Daniel P. Berrange 已提交
1462
    if (mon->json)
1463
        ret = qemuMonitorJSONChangeMedia(mon, dev_name, newmedia, format);
D
Daniel P. Berrange 已提交
1464
    else
1465
        ret = qemuMonitorTextChangeMedia(mon, dev_name, newmedia, format);
D
Daniel P. Berrange 已提交
1466
    return ret;
1467 1468 1469 1470 1471 1472 1473 1474
}


int qemuMonitorSaveVirtualMemory(qemuMonitorPtr mon,
                                 unsigned long long offset,
                                 size_t length,
                                 const char *path)
{
D
Daniel P. Berrange 已提交
1475
    int ret;
1476
    VIR_DEBUG("mon=%p offset=%llu length=%zu path=%s",
1477 1478 1479 1480 1481 1482 1483
          mon, offset, length, path);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1484

D
Daniel P. Berrange 已提交
1485 1486 1487 1488 1489
    if (mon->json)
        ret = qemuMonitorJSONSaveVirtualMemory(mon, offset, length, path);
    else
        ret = qemuMonitorTextSaveVirtualMemory(mon, offset, length, path);
    return ret;
1490 1491 1492 1493 1494 1495 1496
}

int qemuMonitorSavePhysicalMemory(qemuMonitorPtr mon,
                                  unsigned long long offset,
                                  size_t length,
                                  const char *path)
{
D
Daniel P. Berrange 已提交
1497
    int ret;
1498
    VIR_DEBUG("mon=%p offset=%llu length=%zu path=%s",
1499 1500 1501 1502 1503 1504 1505
          mon, offset, length, path);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1506

D
Daniel P. Berrange 已提交
1507 1508 1509 1510 1511
    if (mon->json)
        ret = qemuMonitorJSONSavePhysicalMemory(mon, offset, length, path);
    else
        ret = qemuMonitorTextSavePhysicalMemory(mon, offset, length, path);
    return ret;
1512 1513 1514 1515 1516 1517
}


int qemuMonitorSetMigrationSpeed(qemuMonitorPtr mon,
                                 unsigned long bandwidth)
{
D
Daniel P. Berrange 已提交
1518
    int ret;
1519
    VIR_DEBUG("mon=%p bandwidth=%lu", mon, bandwidth);
1520 1521 1522 1523 1524 1525

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1526

D
Daniel P. Berrange 已提交
1527 1528 1529 1530 1531
    if (mon->json)
        ret = qemuMonitorJSONSetMigrationSpeed(mon, bandwidth);
    else
        ret = qemuMonitorTextSetMigrationSpeed(mon, bandwidth);
    return ret;
1532 1533
}

1534 1535 1536 1537 1538

int qemuMonitorSetMigrationDowntime(qemuMonitorPtr mon,
                                    unsigned long long downtime)
{
    int ret;
1539
    VIR_DEBUG("mon=%p downtime=%llu", mon, downtime);
1540 1541 1542 1543 1544 1545

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1546 1547 1548 1549 1550 1551 1552 1553 1554

    if (mon->json)
        ret = qemuMonitorJSONSetMigrationDowntime(mon, downtime);
    else
        ret = qemuMonitorTextSetMigrationDowntime(mon, downtime);
    return ret;
}


1555 1556 1557 1558 1559 1560
int qemuMonitorGetMigrationStatus(qemuMonitorPtr mon,
                                  int *status,
                                  unsigned long long *transferred,
                                  unsigned long long *remaining,
                                  unsigned long long *total)
{
D
Daniel P. Berrange 已提交
1561
    int ret;
1562
    VIR_DEBUG("mon=%p", mon);
1563 1564 1565 1566 1567 1568

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1569

D
Daniel P. Berrange 已提交
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
    if (mon->json)
        ret = qemuMonitorJSONGetMigrationStatus(mon, status,
                                                transferred,
                                                remaining,
                                                total);
    else
        ret = qemuMonitorTextGetMigrationStatus(mon, status,
                                                transferred,
                                                remaining,
                                                total);
    return ret;
1581 1582 1583
}


E
Eric Blake 已提交
1584 1585 1586 1587 1588
int qemuMonitorMigrateToFd(qemuMonitorPtr mon,
                           unsigned int flags,
                           int fd)
{
    int ret;
1589
    VIR_DEBUG("mon=%p fd=%d flags=%x",
E
Eric Blake 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
          mon, fd, flags);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (qemuMonitorSendFileHandle(mon, "migrate", fd) < 0)
        return -1;

    if (mon->json)
        ret = qemuMonitorJSONMigrate(mon, flags, "fd:migrate");
    else
        ret = qemuMonitorTextMigrate(mon, flags, "fd:migrate");

    if (ret < 0) {
        if (qemuMonitorCloseFileHandle(mon, "migrate") < 0)
1608
            VIR_WARN("failed to close migration handle");
E
Eric Blake 已提交
1609 1610 1611 1612 1613 1614
    }

    return ret;
}


1615
int qemuMonitorMigrateToHost(qemuMonitorPtr mon,
1616
                             unsigned int flags,
1617 1618 1619
                             const char *hostname,
                             int port)
{
D
Daniel P. Berrange 已提交
1620
    int ret;
1621
    char *uri = NULL;
1622
    VIR_DEBUG("mon=%p hostname=%s port=%d flags=%x",
1623
          mon, hostname, port, flags);
1624 1625 1626 1627 1628 1629

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1630

1631 1632 1633 1634 1635 1636

    if (virAsprintf(&uri, "tcp:%s:%d", hostname, port) < 0) {
        virReportOOMError();
        return -1;
    }

D
Daniel P. Berrange 已提交
1637
    if (mon->json)
1638
        ret = qemuMonitorJSONMigrate(mon, flags, uri);
D
Daniel P. Berrange 已提交
1639
    else
1640 1641 1642
        ret = qemuMonitorTextMigrate(mon, flags, uri);

    VIR_FREE(uri);
D
Daniel P. Berrange 已提交
1643
    return ret;
1644 1645 1646 1647
}


int qemuMonitorMigrateToCommand(qemuMonitorPtr mon,
1648
                                unsigned int flags,
1649
                                const char * const *argv)
1650
{
1651 1652 1653
    char *argstr;
    char *dest = NULL;
    int ret = -1;
1654
    VIR_DEBUG("mon=%p argv=%p flags=%x",
1655
          mon, argv, flags);
1656 1657 1658 1659 1660 1661

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1662

1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
    argstr = virArgvToString(argv);
    if (!argstr) {
        virReportOOMError();
        goto cleanup;
    }

    if (virAsprintf(&dest, "exec:%s", argstr) < 0) {
        virReportOOMError();
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
1674
    if (mon->json)
1675
        ret = qemuMonitorJSONMigrate(mon, flags, dest);
D
Daniel P. Berrange 已提交
1676
    else
1677 1678 1679 1680 1681
        ret = qemuMonitorTextMigrate(mon, flags, dest);

cleanup:
    VIR_FREE(argstr);
    VIR_FREE(dest);
1682 1683 1684 1685
    return ret;
}

int qemuMonitorMigrateToFile(qemuMonitorPtr mon,
1686
                             unsigned int flags,
1687 1688 1689 1690
                             const char * const *argv,
                             const char *target,
                             unsigned long long offset)
{
1691 1692 1693 1694
    char *argstr;
    char *dest = NULL;
    int ret = -1;
    char *safe_target = NULL;
1695
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1696
    VIR_DEBUG("mon=%p argv=%p target=%s offset=%llu flags=%x",
1697
          mon, argv, target, offset, flags);
1698 1699 1700 1701 1702 1703

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1704 1705 1706 1707 1708 1709 1710 1711

    if (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("file offset must be a multiple of %llu"),
                        QEMU_MONITOR_MIGRATE_TO_FILE_BS);
        return -1;
    }

1712 1713 1714 1715 1716 1717 1718
    argstr = virArgvToString(argv);
    if (!argstr) {
        virReportOOMError();
        goto cleanup;
    }

    /* Migrate to file */
1719 1720
    virBufferEscapeShell(&buf, target);
    if (virBufferError(&buf)) {
1721
        virReportOOMError();
1722
        virBufferFreeAndReset(&buf);
1723 1724
        goto cleanup;
    }
1725
    safe_target = virBufferContentAndReset(&buf);
1726 1727 1728 1729 1730 1731 1732

    /* Two dd processes, sharing the same stdout, are necessary to
     * allow starting at an alignment of 512, but without wasting
     * padding to get to the larger alignment useful for speed.  Use
     * <> redirection to avoid truncating a regular file.  */
    if (virAsprintf(&dest, "exec:" VIR_WRAPPER_SHELL_PREFIX "%s | "
                    "{ dd bs=%llu seek=%llu if=/dev/null && "
1733
                    "dd ibs=%llu obs=%llu; } 1<>%s" VIR_WRAPPER_SHELL_SUFFIX,
1734 1735 1736
                    argstr, QEMU_MONITOR_MIGRATE_TO_FILE_BS,
                    offset / QEMU_MONITOR_MIGRATE_TO_FILE_BS,
                    QEMU_MONITOR_MIGRATE_TO_FILE_TRANSFER_SIZE,
1737
                    QEMU_MONITOR_MIGRATE_TO_FILE_TRANSFER_SIZE,
1738 1739 1740 1741 1742
                    safe_target) < 0) {
        virReportOOMError();
        goto cleanup;
    }

1743
    if (mon->json)
1744
        ret = qemuMonitorJSONMigrate(mon, flags, dest);
1745
    else
1746 1747 1748 1749 1750 1751
        ret = qemuMonitorTextMigrate(mon, flags, dest);

cleanup:
    VIR_FREE(safe_target);
    VIR_FREE(argstr);
    VIR_FREE(dest);
D
Daniel P. Berrange 已提交
1752
    return ret;
1753 1754 1755
}

int qemuMonitorMigrateToUnix(qemuMonitorPtr mon,
1756
                             unsigned int flags,
1757 1758
                             const char *unixfile)
{
1759 1760
    char *dest = NULL;
    int ret = -1;
1761
    VIR_DEBUG("mon=%p, unixfile=%s flags=%x",
1762
          mon, unixfile, flags);
1763 1764 1765 1766 1767 1768

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1769

1770 1771 1772 1773 1774
    if (virAsprintf(&dest, "unix:%s", unixfile) < 0) {
        virReportOOMError();
        return -1;
    }

D
Daniel P. Berrange 已提交
1775
    if (mon->json)
1776
        ret = qemuMonitorJSONMigrate(mon, flags, dest);
D
Daniel P. Berrange 已提交
1777
    else
1778 1779 1780
        ret = qemuMonitorTextMigrate(mon, flags, dest);

    VIR_FREE(dest);
D
Daniel P. Berrange 已提交
1781
    return ret;
1782 1783 1784 1785
}

int qemuMonitorMigrateCancel(qemuMonitorPtr mon)
{
D
Daniel P. Berrange 已提交
1786
    int ret;
1787
    VIR_DEBUG("mon=%p", mon);
1788 1789 1790 1791 1792 1793

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1794

D
Daniel P. Berrange 已提交
1795 1796 1797 1798 1799
    if (mon->json)
        ret = qemuMonitorJSONMigrateCancel(mon);
    else
        ret = qemuMonitorTextMigrateCancel(mon);
    return ret;
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 1826 1827 1828 1829 1830 1831 1832

int qemuMonitorGraphicsRelocate(qemuMonitorPtr mon,
                                int type,
                                const char *hostname,
                                int port,
                                int tlsPort,
                                const char *tlsSubject)
{
    int ret;
    VIR_DEBUG("mon=%p type=%d hostname=%s port=%d tlsPort=%d tlsSubject=%s",
              mon, type, hostname, port, tlsPort, NULLSTR(tlsSubject));

    if (mon->json)
        ret = qemuMonitorJSONGraphicsRelocate(mon,
                                              type,
                                              hostname,
                                              port,
                                              tlsPort,
                                              tlsSubject);
    else
        ret = qemuMonitorTextGraphicsRelocate(mon,
                                              type,
                                              hostname,
                                              port,
                                              tlsPort,
                                              tlsSubject);

    return ret;
}


1833 1834 1835
int qemuMonitorAddUSBDisk(qemuMonitorPtr mon,
                          const char *path)
{
D
Daniel P. Berrange 已提交
1836
    int ret;
1837
    VIR_DEBUG("mon=%p path=%s", mon, path);
1838 1839 1840 1841 1842 1843

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1844

D
Daniel P. Berrange 已提交
1845 1846 1847 1848 1849
    if (mon->json)
        ret = qemuMonitorJSONAddUSBDisk(mon, path);
    else
        ret = qemuMonitorTextAddUSBDisk(mon, path);
    return ret;
1850 1851 1852 1853 1854 1855 1856
}


int qemuMonitorAddUSBDeviceExact(qemuMonitorPtr mon,
                                 int bus,
                                 int dev)
{
D
Daniel P. Berrange 已提交
1857
    int ret;
1858
    VIR_DEBUG("mon=%p bus=%d dev=%d", mon, bus, dev);
1859 1860 1861 1862 1863 1864

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1865

D
Daniel P. Berrange 已提交
1866 1867 1868 1869 1870
    if (mon->json)
        ret = qemuMonitorJSONAddUSBDeviceExact(mon, bus, dev);
    else
        ret = qemuMonitorTextAddUSBDeviceExact(mon, bus, dev);
    return ret;
1871 1872 1873 1874 1875 1876
}

int qemuMonitorAddUSBDeviceMatch(qemuMonitorPtr mon,
                                 int vendor,
                                 int product)
{
D
Daniel P. Berrange 已提交
1877
    int ret;
1878
    VIR_DEBUG("mon=%p vendor=%d product=%d",
1879 1880 1881 1882 1883 1884 1885
          mon, vendor, product);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1886

D
Daniel P. Berrange 已提交
1887 1888 1889 1890 1891
    if (mon->json)
        ret = qemuMonitorJSONAddUSBDeviceMatch(mon, vendor, product);
    else
        ret = qemuMonitorTextAddUSBDeviceMatch(mon, vendor, product);
    return ret;
1892 1893 1894 1895
}


int qemuMonitorAddPCIHostDevice(qemuMonitorPtr mon,
1896 1897
                                virDomainDevicePCIAddress *hostAddr,
                                virDomainDevicePCIAddress *guestAddr)
1898
{
D
Daniel P. Berrange 已提交
1899
    int ret;
1900
    VIR_DEBUG("mon=%p domain=%d bus=%d slot=%d function=%d",
1901
          mon,
1902
          hostAddr->domain, hostAddr->bus, hostAddr->slot, hostAddr->function);
1903

1904 1905 1906 1907 1908 1909
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

D
Daniel P. Berrange 已提交
1910
    if (mon->json)
1911
        ret = qemuMonitorJSONAddPCIHostDevice(mon, hostAddr, guestAddr);
D
Daniel P. Berrange 已提交
1912
    else
1913
        ret = qemuMonitorTextAddPCIHostDevice(mon, hostAddr, guestAddr);
D
Daniel P. Berrange 已提交
1914
    return ret;
1915 1916 1917 1918 1919 1920
}


int qemuMonitorAddPCIDisk(qemuMonitorPtr mon,
                          const char *path,
                          const char *bus,
1921
                          virDomainDevicePCIAddress *guestAddr)
1922
{
D
Daniel P. Berrange 已提交
1923
    int ret;
1924
    VIR_DEBUG("mon=%p path=%s bus=%s",
1925 1926 1927 1928 1929 1930 1931
          mon, path, bus);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1932

D
Daniel P. Berrange 已提交
1933
    if (mon->json)
1934
        ret = qemuMonitorJSONAddPCIDisk(mon, path, bus, guestAddr);
D
Daniel P. Berrange 已提交
1935
    else
1936
        ret = qemuMonitorTextAddPCIDisk(mon, path, bus, guestAddr);
D
Daniel P. Berrange 已提交
1937
    return ret;
1938 1939 1940 1941 1942
}


int qemuMonitorAddPCINetwork(qemuMonitorPtr mon,
                             const char *nicstr,
1943
                             virDomainDevicePCIAddress *guestAddr)
1944
{
D
Daniel P. Berrange 已提交
1945
    int ret;
1946
    VIR_DEBUG("mon=%p nicstr=%s", mon, nicstr);
1947 1948 1949 1950 1951 1952

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1953

D
Daniel P. Berrange 已提交
1954
    if (mon->json)
1955
        ret = qemuMonitorJSONAddPCINetwork(mon, nicstr, guestAddr);
D
Daniel P. Berrange 已提交
1956
    else
1957
        ret = qemuMonitorTextAddPCINetwork(mon, nicstr, guestAddr);
D
Daniel P. Berrange 已提交
1958
    return ret;
1959 1960 1961 1962
}


int qemuMonitorRemovePCIDevice(qemuMonitorPtr mon,
1963
                               virDomainDevicePCIAddress *guestAddr)
1964
{
D
Daniel P. Berrange 已提交
1965
    int ret;
1966
    VIR_DEBUG("mon=%p domain=%d bus=%d slot=%d function=%d",
1967
          mon, guestAddr->domain, guestAddr->bus,
1968
          guestAddr->slot, guestAddr->function);
1969

1970 1971 1972 1973 1974 1975
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

D
Daniel P. Berrange 已提交
1976
    if (mon->json)
1977
        ret = qemuMonitorJSONRemovePCIDevice(mon, guestAddr);
D
Daniel P. Berrange 已提交
1978
    else
1979
        ret = qemuMonitorTextRemovePCIDevice(mon, guestAddr);
D
Daniel P. Berrange 已提交
1980
    return ret;
1981 1982 1983 1984 1985 1986 1987
}


int qemuMonitorSendFileHandle(qemuMonitorPtr mon,
                              const char *fdname,
                              int fd)
{
D
Daniel P. Berrange 已提交
1988
    int ret;
1989
    VIR_DEBUG("mon=%p, fdname=%s fd=%d",
1990 1991 1992 1993 1994 1995 1996
          mon, fdname, fd);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
1997

1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
    if (fd < 0) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("fd must be valid"));
        return -1;
    }

    if (!mon->hasSendFD) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("qemu is not using a unix socket monitor, "
                          "cannot send fd %s"), fdname);
        return -1;
    }

D
Daniel P. Berrange 已提交
2011 2012 2013 2014 2015
    if (mon->json)
        ret = qemuMonitorJSONSendFileHandle(mon, fdname, fd);
    else
        ret = qemuMonitorTextSendFileHandle(mon, fdname, fd);
    return ret;
2016 2017 2018 2019 2020 2021
}


int qemuMonitorCloseFileHandle(qemuMonitorPtr mon,
                               const char *fdname)
{
2022 2023 2024
    int ret = -1;
    virErrorPtr error;

2025
    VIR_DEBUG("mon=%p fdname=%s",
2026 2027
          mon, fdname);

2028 2029
    error = virSaveLastError();

2030 2031 2032
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
2033
        goto cleanup;
2034
    }
2035

D
Daniel P. Berrange 已提交
2036 2037 2038 2039
    if (mon->json)
        ret = qemuMonitorJSONCloseFileHandle(mon, fdname);
    else
        ret = qemuMonitorTextCloseFileHandle(mon, fdname);
2040 2041 2042 2043 2044 2045

cleanup:
    if (error) {
        virSetError(error);
        virFreeError(error);
    }
D
Daniel P. Berrange 已提交
2046
    return ret;
2047 2048 2049 2050
}


int qemuMonitorAddHostNetwork(qemuMonitorPtr mon,
2051 2052 2053
                              const char *netstr,
                              int tapfd, const char *tapfd_name,
                              int vhostfd, const char *vhostfd_name)
2054
{
2055 2056 2057 2058 2059
    int ret = -1;
    VIR_DEBUG("mon=%p netstr=%s tapfd=%d tapfd_name=%s "
              "vhostfd=%d vhostfd_name=%s",
              mon, netstr, tapfd, NULLSTR(tapfd_name),
              vhostfd, NULLSTR(vhostfd_name));
2060 2061 2062 2063 2064 2065

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
2066

2067 2068 2069 2070 2071 2072 2073 2074
    if (tapfd >= 0 && qemuMonitorSendFileHandle(mon, tapfd_name, tapfd) < 0)
        return -1;
    if (vhostfd >= 0 &&
        qemuMonitorSendFileHandle(mon, vhostfd_name, vhostfd) < 0) {
        vhostfd = -1;
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
2075 2076 2077 2078
    if (mon->json)
        ret = qemuMonitorJSONAddHostNetwork(mon, netstr);
    else
        ret = qemuMonitorTextAddHostNetwork(mon, netstr);
2079 2080 2081 2082 2083 2084 2085 2086 2087

cleanup:
    if (ret < 0) {
        if (tapfd >= 0 && qemuMonitorCloseFileHandle(mon, tapfd_name) < 0)
            VIR_WARN("failed to close device handle '%s'", tapfd_name);
        if (vhostfd >= 0 && qemuMonitorCloseFileHandle(mon, vhostfd_name) < 0)
            VIR_WARN("failed to close device handle '%s'", vhostfd_name);
    }

D
Daniel P. Berrange 已提交
2088
    return ret;
2089 2090 2091 2092 2093 2094 2095
}


int qemuMonitorRemoveHostNetwork(qemuMonitorPtr mon,
                                 int vlan,
                                 const char *netname)
{
D
Daniel P. Berrange 已提交
2096
    int ret;
2097
    VIR_DEBUG("mon=%p netname=%s",
2098 2099 2100 2101 2102 2103 2104
          mon, netname);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
2105

D
Daniel P. Berrange 已提交
2106 2107 2108 2109 2110
    if (mon->json)
        ret = qemuMonitorJSONRemoveHostNetwork(mon, vlan, netname);
    else
        ret = qemuMonitorTextRemoveHostNetwork(mon, vlan, netname);
    return ret;
2111
}
2112

2113 2114

int qemuMonitorAddNetdev(qemuMonitorPtr mon,
2115 2116 2117
                         const char *netdevstr,
                         int tapfd, const char *tapfd_name,
                         int vhostfd, const char *vhostfd_name)
2118
{
2119 2120 2121 2122 2123
    int ret = -1;
    VIR_DEBUG("mon=%p netdevstr=%s tapfd=%d tapfd_name=%s "
              "vhostfd=%d vhostfd_name=%s",
              mon, netdevstr, tapfd, NULLSTR(tapfd_name),
              vhostfd, NULLSTR(vhostfd_name));
2124 2125 2126 2127 2128 2129

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
2130

2131 2132 2133 2134 2135 2136 2137 2138
    if (tapfd >= 0 && qemuMonitorSendFileHandle(mon, tapfd_name, tapfd) < 0)
        return -1;
    if (vhostfd >= 0 &&
        qemuMonitorSendFileHandle(mon, vhostfd_name, vhostfd) < 0) {
        vhostfd = -1;
        goto cleanup;
    }

2139 2140 2141 2142
    if (mon->json)
        ret = qemuMonitorJSONAddNetdev(mon, netdevstr);
    else
        ret = qemuMonitorTextAddNetdev(mon, netdevstr);
2143 2144 2145 2146 2147 2148 2149 2150 2151

cleanup:
    if (ret < 0) {
        if (tapfd >= 0 && qemuMonitorCloseFileHandle(mon, tapfd_name) < 0)
            VIR_WARN("failed to close device handle '%s'", tapfd_name);
        if (vhostfd >= 0 && qemuMonitorCloseFileHandle(mon, vhostfd_name) < 0)
            VIR_WARN("failed to close device handle '%s'", vhostfd_name);
    }

2152 2153 2154 2155 2156 2157 2158
    return ret;
}

int qemuMonitorRemoveNetdev(qemuMonitorPtr mon,
                            const char *alias)
{
    int ret;
2159
    VIR_DEBUG("mon=%p alias=%s",
2160 2161 2162 2163 2164 2165 2166
          mon, alias);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
2167 2168 2169 2170 2171 2172 2173 2174 2175

    if (mon->json)
        ret = qemuMonitorJSONRemoveNetdev(mon, alias);
    else
        ret = qemuMonitorTextRemoveNetdev(mon, alias);
    return ret;
}


2176 2177 2178
int qemuMonitorGetPtyPaths(qemuMonitorPtr mon,
                           virHashTablePtr paths)
{
2179
    int ret;
2180
    VIR_DEBUG("mon=%p",
2181 2182 2183 2184 2185 2186 2187
          mon);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }
2188

2189 2190 2191 2192 2193
    if (mon->json)
        ret = qemuMonitorJSONGetPtyPaths(mon, paths);
    else
        ret = qemuMonitorTextGetPtyPaths(mon, paths);
    return ret;
2194
}
2195 2196 2197 2198 2199 2200


int qemuMonitorAttachPCIDiskController(qemuMonitorPtr mon,
                                       const char *bus,
                                       virDomainDevicePCIAddress *guestAddr)
{
2201
    VIR_DEBUG("mon=%p type=%s", mon, bus);
2202 2203
    int ret;

2204 2205 2206 2207 2208 2209
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

2210 2211 2212 2213 2214 2215 2216
    if (mon->json)
        ret = qemuMonitorJSONAttachPCIDiskController(mon, bus, guestAddr);
    else
        ret = qemuMonitorTextAttachPCIDiskController(mon, bus, guestAddr);

    return ret;
}
2217 2218 2219 2220 2221 2222 2223


int qemuMonitorAttachDrive(qemuMonitorPtr mon,
                           const char *drivestr,
                           virDomainDevicePCIAddress *controllerAddr,
                           virDomainDeviceDriveAddress *driveAddr)
{
2224
    VIR_DEBUG("mon=%p drivestr=%s domain=%d bus=%d slot=%d function=%d",
2225
          mon, drivestr,
2226 2227 2228 2229
          controllerAddr->domain, controllerAddr->bus,
          controllerAddr->slot, controllerAddr->function);
    int ret;

2230 2231 2232 2233 2234 2235
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

2236 2237 2238 2239 2240 2241 2242
    if (mon->json)
        ret = qemuMonitorJSONAttachDrive(mon, drivestr, controllerAddr, driveAddr);
    else
        ret = qemuMonitorTextAttachDrive(mon, drivestr, controllerAddr, driveAddr);

    return ret;
}
2243 2244 2245 2246

int qemuMonitorGetAllPCIAddresses(qemuMonitorPtr mon,
                                  qemuMonitorPCIAddress **addrs)
{
2247
    VIR_DEBUG("mon=%p addrs=%p", mon, addrs);
2248 2249
    int ret;

2250 2251 2252 2253 2254 2255
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

2256 2257 2258 2259 2260 2261
    if (mon->json)
        ret = qemuMonitorJSONGetAllPCIAddresses(mon, addrs);
    else
        ret = qemuMonitorTextGetAllPCIAddresses(mon, addrs);
    return ret;
}
2262

2263 2264
int qemuMonitorDriveDel(qemuMonitorPtr mon,
                        const char *drivestr)
2265
{
2266
    VIR_DEBUG("mon=%p drivestr=%s", mon, drivestr);
2267 2268 2269 2270 2271 2272 2273 2274 2275
    int ret;

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (mon->json)
2276
        ret = qemuMonitorJSONDriveDel(mon, drivestr);
2277
    else
2278
        ret = qemuMonitorTextDriveDel(mon, drivestr);
2279 2280 2281
    return ret;
}

2282
int qemuMonitorDelDevice(qemuMonitorPtr mon,
2283
                         const char *devalias)
2284
{
2285
    VIR_DEBUG("mon=%p devalias=%s", mon, devalias);
2286 2287
    int ret;

2288 2289 2290 2291 2292 2293
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

2294
    if (mon->json)
2295
        ret = qemuMonitorJSONDelDevice(mon, devalias);
2296
    else
2297
        ret = qemuMonitorTextDelDevice(mon, devalias);
2298 2299 2300
    return ret;
}

2301

2302 2303 2304 2305
int qemuMonitorAddDeviceWithFd(qemuMonitorPtr mon,
                               const char *devicestr,
                               int fd,
                               const char *fdname)
2306
{
2307 2308
    VIR_DEBUG("mon=%p device=%s fd=%d fdname=%s", mon, devicestr, fd,
              NULLSTR(fdname));
2309 2310
    int ret;

2311 2312 2313 2314 2315 2316
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

2317 2318 2319
    if (fd >= 0 && qemuMonitorSendFileHandle(mon, fdname, fd) < 0)
        return -1;

2320 2321 2322 2323
    if (mon->json)
        ret = qemuMonitorJSONAddDevice(mon, devicestr);
    else
        ret = qemuMonitorTextAddDevice(mon, devicestr);
2324 2325 2326 2327 2328 2329

    if (ret < 0 && fd >= 0) {
        if (qemuMonitorCloseFileHandle(mon, fdname) < 0)
            VIR_WARN("failed to close device handle '%s'", fdname);
    }

2330 2331 2332
    return ret;
}

2333 2334 2335 2336 2337 2338
int qemuMonitorAddDevice(qemuMonitorPtr mon,
                         const char *devicestr)
{
    return qemuMonitorAddDeviceWithFd(mon, devicestr, -1, NULL);
}

2339 2340 2341
int qemuMonitorAddDrive(qemuMonitorPtr mon,
                        const char *drivestr)
{
2342
    VIR_DEBUG("mon=%p drive=%s", mon, drivestr);
2343 2344
    int ret;

2345 2346 2347 2348 2349 2350
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

2351 2352 2353 2354 2355 2356
    if (mon->json)
        ret = qemuMonitorJSONAddDrive(mon, drivestr);
    else
        ret = qemuMonitorTextAddDrive(mon, drivestr);
    return ret;
}
2357 2358 2359 2360 2361 2362


int qemuMonitorSetDrivePassphrase(qemuMonitorPtr mon,
                                  const char *alias,
                                  const char *passphrase)
{
2363
    VIR_DEBUG("mon=%p alias=%s passphrase=%p(value hidden)", mon, alias, passphrase);
2364 2365
    int ret;

2366 2367 2368 2369 2370 2371
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

2372 2373 2374 2375 2376 2377
    if (mon->json)
        ret = qemuMonitorJSONSetDrivePassphrase(mon, alias, passphrase);
    else
        ret = qemuMonitorTextSetDrivePassphrase(mon, alias, passphrase);
    return ret;
}
C
Chris Lalancette 已提交
2378 2379 2380 2381 2382

int qemuMonitorCreateSnapshot(qemuMonitorPtr mon, const char *name)
{
    int ret;

2383
    VIR_DEBUG("mon=%p, name=%s",mon,name);
C
Chris Lalancette 已提交
2384

2385 2386 2387 2388 2389 2390
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

C
Chris Lalancette 已提交
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
    if (mon->json)
        ret = qemuMonitorJSONCreateSnapshot(mon, name);
    else
        ret = qemuMonitorTextCreateSnapshot(mon, name);
    return ret;
}

int qemuMonitorLoadSnapshot(qemuMonitorPtr mon, const char *name)
{
    int ret;

2402
    VIR_DEBUG("mon=%p, name=%s",mon,name);
C
Chris Lalancette 已提交
2403

2404 2405 2406 2407 2408 2409
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

C
Chris Lalancette 已提交
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
    if (mon->json)
        ret = qemuMonitorJSONLoadSnapshot(mon, name);
    else
        ret = qemuMonitorTextLoadSnapshot(mon, name);
    return ret;
}

int qemuMonitorDeleteSnapshot(qemuMonitorPtr mon, const char *name)
{
    int ret;

2421
    VIR_DEBUG("mon=%p, name=%s",mon,name);
C
Chris Lalancette 已提交
2422

2423 2424 2425 2426 2427 2428
    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

C
Chris Lalancette 已提交
2429 2430 2431 2432 2433 2434
    if (mon->json)
        ret = qemuMonitorJSONDeleteSnapshot(mon, name);
    else
        ret = qemuMonitorTextDeleteSnapshot(mon, name);
    return ret;
}
2435

2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
/* Use the snapshot_blkdev command to convert the existing file for
 * device into a read-only backing file of a new qcow2 image located
 * at file.  */
int
qemuMonitorDiskSnapshot(qemuMonitorPtr mon, const char *device,
                        const char *file)
{
    int ret;

    VIR_DEBUG("mon=%p, device=%s, file=%s", mon, device, file);

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (mon->json)
        ret = qemuMonitorJSONDiskSnapshot(mon, device, file);
    else
        ret = qemuMonitorTextDiskSnapshot(mon, device, file);
    return ret;
}

2460 2461 2462 2463
int qemuMonitorArbitraryCommand(qemuMonitorPtr mon,
                                const char *cmd,
                                char **reply,
                                bool hmp)
2464 2465 2466
{
    int ret;

2467
    VIR_DEBUG("mon=%p, cmd=%s, reply=%p, hmp=%d", mon, cmd, reply, hmp);
2468 2469

    if (mon->json)
2470
        ret = qemuMonitorJSONArbitraryCommand(mon, cmd, reply, hmp);
2471 2472 2473 2474
    else
        ret = qemuMonitorTextArbitraryCommand(mon, cmd, reply);
    return ret;
}
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488


int qemuMonitorInjectNMI(qemuMonitorPtr mon)
{
    int ret;

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

    if (mon->json)
        ret = qemuMonitorJSONInjectNMI(mon);
    else
        ret = qemuMonitorTextInjectNMI(mon);
    return ret;
}
2489

2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
int qemuMonitorSendKey(qemuMonitorPtr mon,
                       unsigned int holdtime,
                       unsigned int *keycodes,
                       unsigned int nkeycodes)
{
    int ret;

    VIR_DEBUG("mon=%p, holdtime=%u, nkeycodes=%u",
              mon, holdtime, nkeycodes);

    if (mon->json)
        ret = qemuMonitorJSONSendKey(mon, holdtime, keycodes, nkeycodes);
    else
        ret = qemuMonitorTextSendKey(mon, holdtime, keycodes, nkeycodes);
    return ret;
}

2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
int qemuMonitorScreendump(qemuMonitorPtr mon,
                          const char *file)
{
    int ret;

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

    if (!mon) {
        qemuReportError(VIR_ERR_INVALID_ARG,"%s",
                        _("monitor must not be NULL"));
        return -1;
    }

    if (mon->json)
        ret = qemuMonitorJSONScreendump(mon, file);
    else
        ret = qemuMonitorTextScreendump(mon, file);
    return ret;
}
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543

int qemuMonitorBlockJob(qemuMonitorPtr mon,
                        const char *device,
                        unsigned long bandwidth,
                        virDomainBlockJobInfoPtr info,
                        int mode)
{
    int ret;

    VIR_DEBUG("mon=%p, device=%p, bandwidth=%lu, info=%p, mode=%o",
              mon, device, bandwidth, info, mode);

    if (mon->json)
        ret = qemuMonitorJSONBlockJob(mon, device, bandwidth, info, mode);
    else
        ret = qemuMonitorTextBlockJob(mon, device, bandwidth, info, mode);
    return ret;
}
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593

int qemuMonitorVMStatusToPausedReason(const char *status)
{
    int st;

    if (!status)
        return VIR_DOMAIN_PAUSED_UNKNOWN;

    if ((st = qemuMonitorVMStatusTypeFromString(status)) < 0) {
        VIR_WARN("Qemu reported unknown VM status: '%s'", status);
        return VIR_DOMAIN_PAUSED_UNKNOWN;
    }

    switch ((qemuMonitorVMStatus) st) {
    case QEMU_MONITOR_VM_STATUS_DEBUG:
    case QEMU_MONITOR_VM_STATUS_INTERNAL_ERROR:
    case QEMU_MONITOR_VM_STATUS_RESTORE_VM:
        return VIR_DOMAIN_PAUSED_UNKNOWN;

    case QEMU_MONITOR_VM_STATUS_INMIGRATE:
    case QEMU_MONITOR_VM_STATUS_POSTMIGRATE:
    case QEMU_MONITOR_VM_STATUS_FINISH_MIGRATE:
        return VIR_DOMAIN_PAUSED_MIGRATION;

    case QEMU_MONITOR_VM_STATUS_IO_ERROR:
        return VIR_DOMAIN_PAUSED_IOERROR;

    case QEMU_MONITOR_VM_STATUS_PAUSED:
    case QEMU_MONITOR_VM_STATUS_PRELAUNCH:
        return VIR_DOMAIN_PAUSED_USER;

    case QEMU_MONITOR_VM_STATUS_RUNNING:
        VIR_WARN("Qemu reports the guest is paused but status is 'running'");
        return VIR_DOMAIN_PAUSED_UNKNOWN;

    case QEMU_MONITOR_VM_STATUS_SAVE_VM:
        return VIR_DOMAIN_PAUSED_SAVE;

    case QEMU_MONITOR_VM_STATUS_SHUTDOWN:
        return VIR_DOMAIN_PAUSED_SHUTTING_DOWN;

    case QEMU_MONITOR_VM_STATUS_WATCHDOG:
        return VIR_DOMAIN_PAUSED_WATCHDOG;

    /* unreachable from this point on */
    case QEMU_MONITOR_VM_STATUS_LAST:
        ;
    }
    return VIR_DOMAIN_PAUSED_UNKNOWN;
}