qemu_monitor_json.c 52.7 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3
/*
 * qemu_monitor_json.c: interaction with QEMU monitor console
 *
4
 * Copyright (C) 2006-2010 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 * 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 <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <poll.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>

#include "qemu_monitor_json.h"
#include "qemu_conf.h"
#include "memory.h"
#include "logging.h"
#include "driver.h"
#include "datatypes.h"
#include "virterror_internal.h"
#include "json.h"

#define VIR_FROM_THIS VIR_FROM_QEMU


#define LINE_ENDING "\r\n"

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
static void qemuMonitorJSONHandleShutdown(qemuMonitorPtr mon, virJSONValuePtr data);
static void qemuMonitorJSONHandleReset(qemuMonitorPtr mon, virJSONValuePtr data);
static void qemuMonitorJSONHandlePowerdown(qemuMonitorPtr mon, virJSONValuePtr data);
static void qemuMonitorJSONHandleStop(qemuMonitorPtr mon, virJSONValuePtr data);

struct {
    const char *type;
    void (*handler)(qemuMonitorPtr mon, virJSONValuePtr data);
} eventHandlers[] = {
    { "SHUTDOWN", qemuMonitorJSONHandleShutdown, },
    { "RESET", qemuMonitorJSONHandleReset, },
    { "POWERDOWN", qemuMonitorJSONHandlePowerdown, },
    { "STOP", qemuMonitorJSONHandleStop, },
};


static int
qemuMonitorJSONIOProcessEvent(qemuMonitorPtr mon,
                              virJSONValuePtr obj)
{
68
    const char *type;
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    int i;
    VIR_DEBUG("mon=%p obj=%p", mon, obj);

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

    for (i = 0 ; i < ARRAY_CARDINALITY(eventHandlers) ; i++) {
        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;
}

D
Daniel P. Berrange 已提交
91
static int
92
qemuMonitorJSONIOProcessLine(qemuMonitorPtr mon,
D
Daniel P. Berrange 已提交
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
                             const char *line,
                             qemuMonitorMessagePtr msg)
{
    virJSONValuePtr obj = NULL;
    int ret = -1;

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

    if (!(obj = virJSONValueFromString(line))) {
        VIR_DEBUG0("Parsing JSON string failed");
        errno = EINVAL;
        goto cleanup;
    }

    if (obj->type != VIR_JSON_TYPE_OBJECT) {
        VIR_DEBUG0("Parsed JSON string isn't an object");
        errno = EINVAL;
    }

    if (virJSONValueObjectHasKey(obj, "QMP") == 1) {
        VIR_DEBUG0("Got QMP capabilities data");
        ret = 0;
        goto cleanup;
    }

    if (virJSONValueObjectHasKey(obj, "event") == 1) {
119
        ret = qemuMonitorJSONIOProcessEvent(mon, obj);
D
Daniel P. Berrange 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        goto cleanup;
    }

    if (msg) {
        if (!(msg->rxBuffer = strdup(line))) {
            errno = ENOMEM;
            goto cleanup;
        }
        msg->rxLength = strlen(line);
        msg->finished = 1;
    } else {
        VIR_DEBUG("Ignoring unexpected JSON message [%s]", line);
    }

    ret = 0;

cleanup:
    virJSONValueFree(obj);
    return ret;
}

int qemuMonitorJSONIOProcess(qemuMonitorPtr mon,
                             const char *data,
                             size_t len,
                             qemuMonitorMessagePtr msg)
{
    int used = 0;
    /*VIR_DEBUG("Data %d bytes [%s]", len, data);*/

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

        if (nl) {
            int got = nl - (data + used);
            char *line = strndup(data + used, got);
            if (!line) {
                errno = ENOMEM;
                return -1;
            }
            used += got + strlen(LINE_ENDING);
            line[got] = '\0'; /* kill \n */
            if (qemuMonitorJSONIOProcessLine(mon, line, msg) < 0) {
                VIR_FREE(line);
                return -1;
            }

            VIR_FREE(line);
        } else {
            break;
        }
    }

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

static int
qemuMonitorJSONCommandWithFd(qemuMonitorPtr mon,
                             virJSONValuePtr cmd,
                             int scm_fd,
                             virJSONValuePtr *reply)
{
    int ret = -1;
    qemuMonitorMessage msg;
    char *cmdstr = NULL;

    *reply = NULL;

    memset(&msg, 0, sizeof msg);

    if (!(cmdstr = virJSONValueToString(cmd))) {
191
        virReportOOMError();
D
Daniel P. Berrange 已提交
192 193 194
        goto cleanup;
    }
    if (virAsprintf(&msg.txBuffer, "%s\r\n", cmdstr) < 0) {
195
        virReportOOMError();
D
Daniel P. Berrange 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        goto cleanup;
    }
    msg.txLength = strlen(msg.txBuffer);
    msg.txFD = scm_fd;

    VIR_DEBUG("Send command '%s' for write with FD %d", cmdstr, scm_fd);

    ret = qemuMonitorSend(mon, &msg);

    VIR_DEBUG("Receive command reply ret=%d errno=%d %d bytes '%s'",
              ret, msg.lastErrno, msg.rxLength, msg.rxBuffer);


    /* If we got ret==0, but not reply data something rather bad
     * went wrong, so lets fake an EIO error */
    if (!msg.rxBuffer && ret == 0) {
        msg.lastErrno = EIO;
        ret = -1;
    }

    if (ret == 0) {
        if (!((*reply) = virJSONValueFromString(msg.rxBuffer))) {
218 219
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot parse JSON doc '%s'"), msg.rxBuffer);
D
Daniel P. Berrange 已提交
220 221 222 223 224
            goto cleanup;
        }
    }

    if (ret < 0)
225
        virReportSystemError(msg.lastErrno,
D
Daniel P. Berrange 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                             _("cannot send monitor command '%s'"), cmdstr);

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

    return ret;
}


static int
qemuMonitorJSONCommand(qemuMonitorPtr mon,
                       virJSONValuePtr cmd,
                       virJSONValuePtr *reply) {
    return qemuMonitorJSONCommandWithFd(mon, cmd, -1, reply);
}

/* 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
 */
249 250
static const char *
qemuMonitorJSONStringifyError(virJSONValuePtr error)
D
Daniel P. Berrange 已提交
251
{
252
    const char *klass = virJSONValueObjectGetString(error, "class");
253
    const char *detail = NULL;
D
Daniel P. Berrange 已提交
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    /* The QMP 'desc' field is usually sufficient for our generic
     * error reporting needs.
     */
    if (klass)
        detail = virJSONValueObjectGetString(error, "desc");


    if (!detail)
        detail = "unknown QEMU command error";

    return detail;
}

static const char *
qemuMonitorJSONCommandName(virJSONValuePtr cmd)
{
    const char *name = virJSONValueObjectGetString(cmd, "execute");
    if (name)
        return name;
    else
        return "<unknown>";
D
Daniel P. Berrange 已提交
276 277 278 279 280 281 282 283 284 285 286
}

static int
qemuMonitorJSONCheckError(virJSONValuePtr cmd,
                          virJSONValuePtr reply)
{
    if (virJSONValueObjectHasKey(reply, "error")) {
        virJSONValuePtr error = virJSONValueObjectGet(reply, "error");
        char *cmdstr = virJSONValueToString(cmd);
        char *replystr = virJSONValueToString(reply);

287 288 289 290 291 292
        /* Log the full JSON formatted command & error */
        VIR_DEBUG("unable to execute QEMU command %s: %s",
                  cmdstr, replystr);

        /* Only send the user the command name + friendly error */
        if (!error)
293
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
294 295 296
                            _("unable to execute QEMU command '%s'"),
                            qemuMonitorJSONCommandName(cmd));
        else
297
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
298 299 300 301
                            _("unable to execute QEMU command '%s': %s"),
                            qemuMonitorJSONCommandName(cmd),
                            qemuMonitorJSONStringifyError(error));

D
Daniel P. Berrange 已提交
302 303 304 305 306 307 308 309 310
        VIR_FREE(cmdstr);
        VIR_FREE(replystr);
        return -1;
    } else if (!virJSONValueObjectHasKey(reply, "return")) {
        char *cmdstr = virJSONValueToString(cmd);
        char *replystr = virJSONValueToString(reply);

        VIR_DEBUG("Neither 'return' nor 'error' is set in the JSON reply %s: %s",
                  cmdstr, replystr);
311
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
312 313
                        _("unable to execute QEMU command '%s'"),
                        qemuMonitorJSONCommandName(cmd));
D
Daniel P. Berrange 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326
        VIR_FREE(cmdstr);
        VIR_FREE(replystr);
        return -1;
    }
    return 0;
}


static int
qemuMonitorJSONHasError(virJSONValuePtr reply,
                        const char *klass)
{
    virJSONValuePtr error;
327
    const char *thisklass;
D
Daniel P. Berrange 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

    if (!virJSONValueObjectHasKey(reply, "error"))
        return 0;

    error = virJSONValueObjectGet(reply, "error");
    if (!error)
        return 0;

    if (!virJSONValueObjectHasKey(error, "class"))
        return 0;

    thisklass = virJSONValueObjectGetString(error, "class");

    if (!thisklass)
        return 0;

    return STREQ(klass, thisklass);
}

static int
qemuMonitorJSONCommandAddTimestamp(virJSONValuePtr obj)
{
    struct timeval tv;
    virJSONValuePtr timestamp = NULL;

    if (gettimeofday(&tv, NULL) < 0) {
354
        virReportSystemError(errno, "%s",
D
Daniel P. Berrange 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                             _("cannot query time of day"));
        return -1;
    }

    if (!(timestamp = virJSONValueNewObject()))
        goto no_memory;

    if (virJSONValueObjectAppendNumberLong(timestamp, "seconds", tv.tv_sec) < 0)
        goto no_memory;
    if (virJSONValueObjectAppendNumberLong(timestamp, "microseconds", tv.tv_usec) < 0)
        goto no_memory;

    if (virJSONValueObjectAppend(obj, "timestamp", timestamp) < 0)
        goto no_memory;

    return 0;

no_memory:
373
    virReportOOMError();
D
Daniel P. Berrange 已提交
374 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
    virJSONValueFree(timestamp);
    return -1;
}

static virJSONValuePtr ATTRIBUTE_SENTINEL
qemuMonitorJSONMakeCommand(const char *cmdname,
                           ...)
{
    virJSONValuePtr obj;
    virJSONValuePtr jargs = NULL;
    va_list args;
    char *key;

    va_start(args, cmdname);

    if (!(obj = virJSONValueNewObject()))
        goto no_memory;

    if (virJSONValueObjectAppendString(obj, "execute", cmdname) < 0)
        goto no_memory;

    if (qemuMonitorJSONCommandAddTimestamp(obj) < 0)
        goto error;

    while ((key = va_arg(args, char *)) != NULL) {
        int ret;
        char type;

        if (strlen(key) < 3) {
403 404 405
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("argument key '%s' is too short, missing type prefix"),
                            key);
D
Daniel P. Berrange 已提交
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
            goto error;
        }

        /* Keys look like   s:name  the first letter is a type code */
        type = key[0];
        key += 2;

        if (!jargs &&
            !(jargs = virJSONValueNewObject()))
            goto no_memory;

        /* This doesn't supports maps/arrays.  This hasn't
         * proved to be a problem..... yet :-)  */
        switch (type) {
        case 's': {
            char *val = va_arg(args, char *);
            ret = virJSONValueObjectAppendString(jargs, key, val);
        }   break;
        case 'i': {
            int val = va_arg(args, int);
            ret = virJSONValueObjectAppendNumberInt(jargs, key, val);
        }   break;
        case 'u': {
            unsigned int val = va_arg(args, unsigned int);
            ret = virJSONValueObjectAppendNumberUint(jargs, key, val);
        }   break;
        case 'I': {
            long long val = va_arg(args, long long);
            ret = virJSONValueObjectAppendNumberLong(jargs, key, val);
        }   break;
        case 'U': {
            unsigned long long val = va_arg(args, unsigned long long);
            ret = virJSONValueObjectAppendNumberUlong(jargs, key, val);
        }   break;
        case 'd': {
            double val = va_arg(args, double);
            ret = virJSONValueObjectAppendNumberDouble(jargs, key, val);
        }   break;
        case 'b': {
            int val = va_arg(args, int);
            ret = virJSONValueObjectAppendBoolean(jargs, key, val);
        }   break;
        case 'n': {
            ret = virJSONValueObjectAppendNull(jargs, key);
        }   break;
        default:
452 453
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unsupported data type '%c' for arg '%s'"), type, key - 2);
D
Daniel P. Berrange 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
            goto error;
        }
        if (ret < 0)
            goto no_memory;
    }

    if (jargs &&
        virJSONValueObjectAppend(obj, "arguments", jargs) < 0)
        goto no_memory;

    va_end(args);

    return obj;

no_memory:
469
    virReportOOMError();
D
Daniel P. Berrange 已提交
470 471 472 473 474 475 476 477
error:
    virJSONValueFree(obj);
    virJSONValueFree(jargs);
    va_end(args);
    return NULL;
}


478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
static void qemuMonitorJSONHandleShutdown(qemuMonitorPtr mon, virJSONValuePtr data ATTRIBUTE_UNUSED)
{
    qemuMonitorEmitShutdown(mon);
}

static void qemuMonitorJSONHandleReset(qemuMonitorPtr mon, virJSONValuePtr data ATTRIBUTE_UNUSED)
{
    qemuMonitorEmitReset(mon);
}

static void qemuMonitorJSONHandlePowerdown(qemuMonitorPtr mon, virJSONValuePtr data ATTRIBUTE_UNUSED)
{
    qemuMonitorEmitPowerdown(mon);
}

static void qemuMonitorJSONHandleStop(qemuMonitorPtr mon, virJSONValuePtr data ATTRIBUTE_UNUSED)
{
    qemuMonitorEmitStop(mon);
}


499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
int
qemuMonitorJSONSetCapabilities(qemuMonitorPtr mon)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("qmp_capabilities", NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


D
Daniel P. Berrange 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
int
qemuMonitorJSONStartCPUs(qemuMonitorPtr mon,
                         virConnectPtr conn ATTRIBUTE_UNUSED)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("cont", NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int
qemuMonitorJSONStopCPUs(qemuMonitorPtr mon)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("stop", NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONSystemPowerdown(qemuMonitorPtr mon)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("system_powerdown", NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
/*
 * [ { "CPU": 0, "current": true, "halted": false, "pc": 3227107138 },
 *   { "CPU": 1, "current": false, "halted": true, "pc": 7108165 } ]
 */
static int
qemuMonitorJSONExtractCPUInfo(virJSONValuePtr reply,
                              int **pids)
{
    virJSONValuePtr data;
    int ret = -1;
    int i;
    int *threads = NULL;
    int ncpus;

    if (!(data = virJSONValueObjectGet(reply, "return"))) {
594 595
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cpu reply was missing return data"));
596 597 598 599
        goto cleanup;
    }

    if (data->type != VIR_JSON_TYPE_ARRAY) {
600 601
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cpu information was not an array"));
602 603 604 605
        goto cleanup;
    }

    if ((ncpus = virJSONValueArraySize(data)) <= 0) {
606 607
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cpu information was empty"));
608 609 610 611
        goto cleanup;
    }

    if (VIR_REALLOC_N(threads, ncpus) < 0) {
612
        virReportOOMError();
613 614 615 616 617 618 619 620
        goto cleanup;
    }

    for (i = 0 ; i < ncpus ; i++) {
        virJSONValuePtr entry = virJSONValueArrayGet(data, i);
        int cpu;
        int thread;
        if (!entry) {
621 622
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("character device information was missing aray element"));
623 624 625 626
            goto cleanup;
        }

        if (virJSONValueObjectGetNumberInt(entry, "CPU", &cpu) < 0) {
627 628
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("cpu information was missing cpu number"));
629 630 631 632
            goto cleanup;
        }

        if (virJSONValueObjectGetNumberInt(entry, "thread_id", &thread) < 0) {
633 634
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("cpu information was missing thread ID"));
635 636 637 638
            goto cleanup;
        }

        if (cpu != i) {
639 640 641
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unexpected cpu index %d expecting %d"),
                            i, cpu);
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
            goto cleanup;
        }

        threads[i] = thread;
    }

    *pids = threads;
    threads = NULL;
    ret = 0;

cleanup:
    VIR_FREE(threads);
    return ret;
}


D
Daniel P. Berrange 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
int qemuMonitorJSONGetCPUInfo(qemuMonitorPtr mon,
                              int **pids)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("query-cpus",
                                                     NULL);
    virJSONValuePtr reply = NULL;

    *pids = NULL;

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

676 677
    if (ret == 0)
        ret = qemuMonitorJSONExtractCPUInfo(reply, pids);
D
Daniel P. Berrange 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714

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


/*
 * Returns: 0 if balloon not supported, +1 if balloon query worked
 * or -1 on failure
 */
int qemuMonitorJSONGetBalloonInfo(qemuMonitorPtr mon,
                                  unsigned long *currmem)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("query-balloon",
                                                     NULL);
    virJSONValuePtr reply = NULL;

    *currmem = 0;

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0) {
        /* See if balloon soft-failed */
        if (qemuMonitorJSONHasError(reply, "DeviceNotActive") ||
            qemuMonitorJSONHasError(reply, "KVMMissingCap"))
            goto cleanup;

        /* See if any other fatal error occurred */
        ret = qemuMonitorJSONCheckError(cmd, reply);

        /* Success */
        if (ret == 0) {
715
            virJSONValuePtr data;
D
Daniel P. Berrange 已提交
716 717
            unsigned long long mem;

718
            if (!(data = virJSONValueObjectGet(reply, "return"))) {
719 720
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("info balloon reply was missing return data"));
721 722 723 724 725
                ret = -1;
                goto cleanup;
            }

            if (virJSONValueObjectGetNumberUlong(data, "balloon", &mem) < 0) {
726 727
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("info balloon reply was missing balloon data"));
D
Daniel P. Berrange 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
                ret = -1;
                goto cleanup;
            }

            *currmem = mem;
            ret = 1;
        }
    }

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


int qemuMonitorJSONGetBlockStatsInfo(qemuMonitorPtr mon,
                                     const char *devname,
                                     long long *rd_req,
                                     long long *rd_bytes,
                                     long long *wr_req,
                                     long long *wr_bytes,
                                     long long *errs)
{
    int ret;
    int i;
    int found = 0;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("query-blockstats",
                                                     NULL);
    virJSONValuePtr reply = NULL;
    virJSONValuePtr devices;

    *rd_req = *rd_bytes = *wr_req = *wr_bytes = *errs = 0;

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0) {
        ret = qemuMonitorJSONCheckError(cmd, reply);
        if (ret < 0)
            goto cleanup;
    }
    ret = -1;

    devices = virJSONValueObjectGet(reply, "return");
    if (!devices || devices->type != VIR_JSON_TYPE_ARRAY) {
776 777
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("blockstats reply was missing device list"));
D
Daniel P. Berrange 已提交
778 779 780 781 782 783 784 785
        goto cleanup;
    }

    for (i = 0 ; i < virJSONValueArraySize(devices) ; i++) {
        virJSONValuePtr dev = virJSONValueArrayGet(devices, i);
        virJSONValuePtr stats;
        const char *thisdev;
        if (!dev || dev->type != VIR_JSON_TYPE_OBJECT) {
786 787
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("blockstats device entry was not in expected format"));
D
Daniel P. Berrange 已提交
788 789 790 791
            goto cleanup;
        }

        if ((thisdev = virJSONValueObjectGetString(dev, "device")) == NULL) {
792 793
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("blockstats device entry was not in expected format"));
D
Daniel P. Berrange 已提交
794 795 796
            goto cleanup;
        }

797 798 799 800 801 802 803
        /* New QEMU has separate names for host & guest side of the disk
         * and libvirt gives the host side a 'drive-' prefix. The passed
         * in devname is the guest side though
         */
        if (STRPREFIX(thisdev, QEMU_DRIVE_HOST_PREFIX))
            thisdev += strlen(QEMU_DRIVE_HOST_PREFIX);

D
Daniel P. Berrange 已提交
804 805 806 807 808 809
        if (STRNEQ(thisdev, devname))
            continue;

        found = 1;
        if ((stats = virJSONValueObjectGet(dev, "stats")) == NULL ||
            stats->type != VIR_JSON_TYPE_OBJECT) {
810 811
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("blockstats stats entry was not in expected format"));
D
Daniel P. Berrange 已提交
812 813 814 815
            goto cleanup;
        }

        if (virJSONValueObjectGetNumberLong(stats, "rd_bytes", rd_bytes) < 0) {
816 817 818
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot read %s statistic"),
                            "rd_bytes");
D
Daniel P. Berrange 已提交
819 820 821
            goto cleanup;
        }
        if (virJSONValueObjectGetNumberLong(stats, "rd_operations", rd_req) < 0) {
822 823 824
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot read %s statistic"),
                            "rd_operations");
D
Daniel P. Berrange 已提交
825 826 827
            goto cleanup;
        }
        if (virJSONValueObjectGetNumberLong(stats, "wr_bytes", wr_bytes) < 0) {
828 829 830
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot read %s statistic"),
                            "wr_bytes");
D
Daniel P. Berrange 已提交
831 832 833
            goto cleanup;
        }
        if (virJSONValueObjectGetNumberLong(stats, "wr_operations", wr_req) < 0) {
834 835 836
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot read %s statistic"),
                            "wr_operations");
D
Daniel P. Berrange 已提交
837 838 839 840 841
            goto cleanup;
        }
    }

    if (!found) {
842 843
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find statistics for device '%s'"), devname);
D
Daniel P. Berrange 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 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 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
        goto cleanup;
    }
    ret = 0;

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


int qemuMonitorJSONSetVNCPassword(qemuMonitorPtr mon,
                                  const char *password)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("change",
                                                     "s:device", "vnc",
                                                     "s:target", "password",
                                                     "s:arg", password,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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

/*
 * Returns: 0 if balloon not supported, +1 if balloon adjust worked
 * or -1 on failure
 */
int qemuMonitorJSONSetBalloon(qemuMonitorPtr mon,
                              unsigned long newmem)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("balloon",
                                                     "U:value", (unsigned long long)newmem,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0) {
        /* See if balloon soft-failed */
        if (qemuMonitorJSONHasError(reply, "DeviceNotActive") ||
            qemuMonitorJSONHasError(reply, "KVMMissingCap"))
            goto cleanup;

        /* See if any other fatal error occurred */
        ret = qemuMonitorJSONCheckError(cmd, reply);

        /* Real success */
        if (ret == 0)
            ret = 1;
    }

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


int qemuMonitorJSONEjectMedia(qemuMonitorPtr mon,
                              const char *devname)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("eject",
                                                     "s:device", devname,
                                                     "i:force", 0,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONChangeMedia(qemuMonitorPtr mon,
                               const char *devname,
                               const char *newmedia,
                               const char *format)
{
    int ret;
    virJSONValuePtr cmd;
    if (format)
        cmd = qemuMonitorJSONMakeCommand("change",
                                         "s:device", devname,
                                         "s:target", newmedia,
                                         "s:arg", format,
                                         NULL);
    else
        cmd = qemuMonitorJSONMakeCommand("change",
                                         "s:device", devname,
                                         "s:target", newmedia,
                                         NULL);

    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


static int qemuMonitorJSONSaveMemory(qemuMonitorPtr mon,
                                     const char *cmdtype,
                                     unsigned long long offset,
                                     size_t length,
                                     const char *path)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand(cmdtype,
                                                     "U:val", offset,
                                                     "u:size", length,
                                                     "s:filename", path,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONSaveVirtualMemory(qemuMonitorPtr mon,
                                     unsigned long long offset,
                                     size_t length,
                                     const char *path)
{
    return qemuMonitorJSONSaveMemory(mon, "memsave", offset, length, path);
}

int qemuMonitorJSONSavePhysicalMemory(qemuMonitorPtr mon,
                                      unsigned long long offset,
                                      size_t length,
                                      const char *path)
{
    return qemuMonitorJSONSaveMemory(mon, "pmemsave", offset, length, path);
}


int qemuMonitorJSONSetMigrationSpeed(qemuMonitorPtr mon,
                                     unsigned long bandwidth)
{
    int ret;
    char *bandwidthstr;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    if (virAsprintf(&bandwidthstr, "%lum", bandwidth) < 0) {
1025
        virReportOOMError();
D
Daniel P. Berrange 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        return -1;
    }
    cmd = qemuMonitorJSONMakeCommand("migrate_set_speed",
                                     "s:value", bandwidthstr,
                                     NULL);
    VIR_FREE(bandwidthstr);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


static int
qemuMonitorJSONGetMigrationStatusReply(virJSONValuePtr reply,
                                       int *status,
                                       unsigned long long *transferred,
                                       unsigned long long *remaining,
                                       unsigned long long *total)
{
    virJSONValuePtr ret;
1054
    const char *statusstr;
D
Daniel P. Berrange 已提交
1055 1056

    if (!(ret = virJSONValueObjectGet(reply, "return"))) {
1057 1058
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("info migration reply was missing return data"));
D
Daniel P. Berrange 已提交
1059 1060 1061 1062
        return -1;
    }

    if (!(statusstr = virJSONValueObjectGetString(ret, "status"))) {
1063 1064
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("info migration reply was missing return status"));
D
Daniel P. Berrange 已提交
1065 1066 1067 1068
        return -1;
    }

    if ((*status = qemuMonitorMigrationStatusTypeFromString(statusstr)) < 0) {
1069 1070
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unexpected migration status in %s"), statusstr);
D
Daniel P. Berrange 已提交
1071 1072 1073 1074 1075 1076
        return -1;
    }

    if (*status == QEMU_MONITOR_MIGRATION_STATUS_ACTIVE) {
        virJSONValuePtr ram = virJSONValueObjectGet(ret, "ram");
        if (!ram) {
1077 1078
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("migration was active, but no RAM info was set"));
D
Daniel P. Berrange 已提交
1079 1080 1081 1082
            return -1;
        }

        if (virJSONValueObjectGetNumberUlong(ram, "transferred", transferred) < 0) {
1083 1084
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("migration was active, but RAM 'transferred' data was missing"));
D
Daniel P. Berrange 已提交
1085 1086 1087
            return -1;
        }
        if (virJSONValueObjectGetNumberUlong(ram, "remaining", remaining) < 0) {
1088 1089
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("migration was active, but RAM 'remaining' data was missing"));
D
Daniel P. Berrange 已提交
1090 1091 1092
            return -1;
        }
        if (virJSONValueObjectGetNumberUlong(ram, "total", total) < 0) {
1093 1094
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("migration was active, but RAM 'total' data was missing"));
D
Daniel P. Berrange 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
            return -1;
        }
    }

    return 0;
}


int qemuMonitorJSONGetMigrationStatus(qemuMonitorPtr mon,
                                      int *status,
                                      unsigned long long *transferred,
                                      unsigned long long *remaining,
                                      unsigned long long *total)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("query-migration",
                                                     NULL);
    virJSONValuePtr reply = NULL;

    *status = 0;
    *transferred = *remaining = *total = 0;

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    if (ret == 0 &&
        qemuMonitorJSONGetMigrationStatusReply(reply,
                                               status,
                                               transferred,
                                               remaining,
                                               total) < 0)
        ret = -1;

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


static int qemuMonitorJSONMigrate(qemuMonitorPtr mon,
                                  int background,
                                  const char *uri)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("migrate",
                                                     "i:detach", background ? 1 : 0,
                                                     "s:uri", uri,
                                                     NULL);
    virJSONValuePtr reply = NULL;

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONMigrateToHost(qemuMonitorPtr mon,
                                 int background,
                                 const char *hostname,
                                 int port)
{
    char *uri = NULL;
    int ret;

    if (virAsprintf(&uri, "tcp:%s:%d", hostname, port) < 0) {
1173
        virReportOOMError();
D
Daniel P. Berrange 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
        return -1;
    }

    ret = qemuMonitorJSONMigrate(mon, background, uri);

    VIR_FREE(uri);

    return ret;
}


int qemuMonitorJSONMigrateToCommand(qemuMonitorPtr mon,
                                    int background,
                                    const char * const *argv,
                                    const char *target)
{
    char *argstr;
    char *dest = NULL;
    int ret = -1;
    char *safe_target = NULL;

    argstr = virArgvToString(argv);
    if (!argstr) {
1197
        virReportOOMError();
D
Daniel P. Berrange 已提交
1198 1199 1200 1201 1202 1203
        goto cleanup;
    }

    /* Migrate to file */
    safe_target = qemuMonitorEscapeShell(target);
    if (!safe_target) {
1204
        virReportOOMError();
D
Daniel P. Berrange 已提交
1205 1206 1207 1208
        goto cleanup;
    }

    if (virAsprintf(&dest, "exec:%s >>%s 2>/dev/null", argstr, safe_target) < 0) {
1209
        virReportOOMError();
D
Daniel P. Berrange 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
        goto cleanup;
    }

    ret = qemuMonitorJSONMigrate(mon, background, dest);

cleanup:
    VIR_FREE(safe_target);
    VIR_FREE(argstr);
    VIR_FREE(dest);
    return ret;
}

int qemuMonitorJSONMigrateToUnix(qemuMonitorPtr mon,
                                 int background,
                                 const char *unixfile)
{
    char *dest = NULL;
    int ret = -1;

    if (virAsprintf(&dest, "unix:%s", unixfile) < 0) {
1230
        virReportOOMError();
D
Daniel P. Berrange 已提交
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 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 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
        return -1;
    }

    ret = qemuMonitorJSONMigrate(mon, background, dest);

    VIR_FREE(dest);

    return ret;
}


int qemuMonitorJSONMigrateCancel(qemuMonitorPtr mon)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("migrate_cancel", NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


static int qemuMonitorJSONAddUSB(qemuMonitorPtr mon,
                                 const char *dev)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("usb_add",
                                                     "s:devname", dev,
                                                     NULL);
    virJSONValuePtr reply = NULL;

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONAddUSBDisk(qemuMonitorPtr mon,
                              const char *path)
{
    int ret;
    char *disk;

    if (virAsprintf(&disk, "disk:%s", path) < 0) {
1291
        virReportOOMError();
D
Daniel P. Berrange 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        return -1;
    }

    ret = qemuMonitorJSONAddUSB(mon, disk);

    VIR_FREE(disk);

    return ret;
}


int qemuMonitorJSONAddUSBDeviceExact(qemuMonitorPtr mon,
                                     int bus,
                                     int dev)
{
    int ret;
    char *addr;

    if (virAsprintf(&addr, "host:%.3d.%.3d", bus, dev) < 0) {
1311
        virReportOOMError();
D
Daniel P. Berrange 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
        return -1;
    }

    ret = qemuMonitorJSONAddUSB(mon, addr);

    VIR_FREE(addr);
    return ret;
}


int qemuMonitorJSONAddUSBDeviceMatch(qemuMonitorPtr mon,
                                     int vendor,
                                     int product)
{
    int ret;
    char *addr;

    if (virAsprintf(&addr, "host:%.4x:%.4x", vendor, product) < 0) {
1330
        virReportOOMError();
D
Daniel P. Berrange 已提交
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
        return -1;
    }

    ret = qemuMonitorJSONAddUSB(mon, addr);

    VIR_FREE(addr);
    return ret;
}


static int
1342 1343
qemuMonitorJSONGetGuestPCIAddress(virJSONValuePtr reply,
                                  virDomainDevicePCIAddress *guestAddr)
D
Daniel P. Berrange 已提交
1344 1345 1346 1347 1348
{
    virJSONValuePtr addr;

    addr = virJSONValueObjectGet(reply, "return");
    if (!addr || addr->type != VIR_JSON_TYPE_OBJECT) {
1349 1350
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("pci_add reply was missing device address"));
D
Daniel P. Berrange 已提交
1351 1352 1353
        return -1;
    }

1354
    if (virJSONValueObjectGetNumberUint(addr, "domain", &guestAddr->domain) < 0) {
1355 1356
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("pci_add reply was missing device domain number"));
D
Daniel P. Berrange 已提交
1357 1358 1359
        return -1;
    }

1360
    if (virJSONValueObjectGetNumberUint(addr, "bus", &guestAddr->bus) < 0) {
1361 1362
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("pci_add reply was missing device bus number"));
D
Daniel P. Berrange 已提交
1363 1364 1365
        return -1;
    }

1366
    if (virJSONValueObjectGetNumberUint(addr, "slot", &guestAddr->slot) < 0) {
1367 1368
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("pci_add reply was missing device slot number"));
D
Daniel P. Berrange 已提交
1369 1370 1371
        return -1;
    }

1372
    if (virJSONValueObjectGetNumberUint(addr, "function", &guestAddr->function) < 0) {
1373 1374
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("pci_add reply was missing device function number"));
1375 1376 1377
        return -1;
    }

D
Daniel P. Berrange 已提交
1378 1379 1380 1381 1382
    return 0;
}


int qemuMonitorJSONAddPCIHostDevice(qemuMonitorPtr mon,
1383 1384
                                    virDomainDevicePCIAddress *hostAddr,
                                    virDomainDevicePCIAddress *guestAddr)
D
Daniel P. Berrange 已提交
1385 1386 1387 1388 1389 1390
{
    int ret;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    char *dev;

1391
    memset(guestAddr, 0, sizeof(*guestAddr));
D
Daniel P. Berrange 已提交
1392 1393 1394

    /* XXX hostDomain */
    if (virAsprintf(&dev, "host=%.2x:%.2x.%.1x",
1395
                    hostAddr->bus, hostAddr->slot, hostAddr->function) < 0) {
1396
        virReportOOMError();
D
Daniel P. Berrange 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
        return -1;
    }

    cmd = qemuMonitorJSONMakeCommand("pci_add",
                                     "s:pci_addr", "auto"
                                     "s:type", "host",
                                     "s:opts", dev,
                                     NULL);
    VIR_FREE(dev);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    if (ret == 0 &&
1415
        qemuMonitorJSONGetGuestPCIAddress(reply, guestAddr) < 0)
D
Daniel P. Berrange 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
        ret = -1;

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


int qemuMonitorJSONAddPCIDisk(qemuMonitorPtr mon,
                              const char *path,
                              const char *bus,
1427 1428
                              virDomainDevicePCIAddress *guestAddr)
{
D
Daniel P. Berrange 已提交
1429 1430 1431 1432 1433
    int ret;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    char *dev;

1434
    memset(guestAddr, 0, sizeof(*guestAddr));
D
Daniel P. Berrange 已提交
1435 1436

    if (virAsprintf(&dev, "file=%s,if=%s", path, bus) < 0) {
1437
        virReportOOMError();
D
Daniel P. Berrange 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
        return -1;
    }

    cmd = qemuMonitorJSONMakeCommand("pci_add",
                                     "s:pci_addr", "auto",
                                     "s:type", "storage",
                                     "s:opts", dev,
                                     NULL);
    VIR_FREE(dev);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    if (ret == 0 &&
1456
        qemuMonitorJSONGetGuestPCIAddress(reply, guestAddr) < 0)
D
Daniel P. Berrange 已提交
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
        ret = -1;

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


int qemuMonitorJSONAddPCINetwork(qemuMonitorPtr mon,
                                 const char *nicstr,
1467
                                 virDomainDevicePCIAddress *guestAddr)
D
Daniel P. Berrange 已提交
1468 1469 1470 1471 1472 1473 1474 1475 1476
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("pci_add",
                                                     "s:pci_addr", "auto",
                                                     "s:type", "nic",
                                                     "s:opts", nicstr,
                                                     NULL);
    virJSONValuePtr reply = NULL;

1477
    memset(guestAddr, 0, sizeof(*guestAddr));
D
Daniel P. Berrange 已提交
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    if (ret == 0 &&
1488
        qemuMonitorJSONGetGuestPCIAddress(reply, guestAddr) < 0)
D
Daniel P. Berrange 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497
        ret = -1;

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


int qemuMonitorJSONRemovePCIDevice(qemuMonitorPtr mon,
1498
                                   virDomainDevicePCIAddress *guestAddr)
D
Daniel P. Berrange 已提交
1499 1500 1501 1502 1503 1504
{
    int ret;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    char *addr;

1505
    /* XXX what about function ? */
D
Daniel P. Berrange 已提交
1506
    if (virAsprintf(&addr, "%.4x:%.2x:%.2x",
1507
                    guestAddr->domain, guestAddr->bus, guestAddr->slot) < 0) {
1508
        virReportOOMError();
D
Daniel P. Berrange 已提交
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 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 1613 1614 1615 1616 1617 1618
        return -1;
    }

    cmd = qemuMonitorJSONMakeCommand("pci_del",
                                     "s:pci_addr", addr,
                                     NULL);
    VIR_FREE(addr);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONSendFileHandle(qemuMonitorPtr mon,
                                  const char *fdname,
                                  int fd)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("getfd",
                                                     "s:fdname", fdname,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommandWithFd(mon, cmd, fd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONCloseFileHandle(qemuMonitorPtr mon,
                                   const char *fdname)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("closefd",
                                                     "s:fdname", fdname,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONAddHostNetwork(qemuMonitorPtr mon,
                                  const char *netstr)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("host_net_add",
                                                     "s:device", netstr,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONRemoveHostNetwork(qemuMonitorPtr mon,
                                     int vlan,
                                     const char *netname)
{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("host_net_remove",
                                                     "i:vlan", vlan,
                                                     "s:device", netname,
                                                     NULL);
    virJSONValuePtr reply = NULL;
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1619 1620


1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
/*
 * Example return data
 *
 * {"return": [
 *      {"filename": "stdio", "label": "monitor"},
 *      {"filename": "pty:/dev/pts/6", "label": "serial0"},
 *      {"filename": "pty:/dev/pts/7", "label": "parallel0"}
 * ]}
 *
 */
static int qemuMonitorJSONExtractPtyPaths(virJSONValuePtr reply,
                                          virHashTablePtr paths)
{
    virJSONValuePtr data;
    int ret = -1;
    int i;

    if (!(data = virJSONValueObjectGet(reply, "return"))) {
1639 1640
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("character device reply was missing return data"));
1641 1642 1643 1644
        goto cleanup;
    }

    if (data->type != VIR_JSON_TYPE_ARRAY) {
1645 1646
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("character device information was not an array"));
1647 1648 1649 1650 1651 1652 1653 1654
        goto cleanup;
    }

    for (i = 0 ; i < virJSONValueArraySize(data) ; i++) {
        virJSONValuePtr entry = virJSONValueArrayGet(data, i);
        const char *type;
        const char *id;
        if (!entry) {
1655 1656
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("character device information was missing aray element"));
1657 1658 1659 1660
            goto cleanup;
        }

        if (!(type = virJSONValueObjectGetString(entry, "filename"))) {
1661 1662
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("character device information was missing filename"));
1663 1664 1665 1666
            goto cleanup;
        }

        if (!(id = virJSONValueObjectGetString(entry, "label"))) {
1667 1668
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("character device information was missing filename"));
1669 1670 1671 1672 1673 1674
            goto cleanup;
        }

        if (STRPREFIX(type, "pty:")) {
            char *path = strdup(type + strlen("pty:"));
            if (!path) {
1675
                virReportOOMError();
1676 1677 1678 1679
                goto cleanup;
            }

            if (virHashAddEntry(paths, id, path) < 0) {
1680 1681
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                _("failed to save chardev path '%s'"), path);
1682 1683 1684 1685 1686 1687 1688 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
                VIR_FREE(path);
                goto cleanup;
            }
        }
    }

    ret = 0;

cleanup:
    return ret;
}

int qemuMonitorJSONGetPtyPaths(qemuMonitorPtr mon,
                               virHashTablePtr paths)

{
    int ret;
    virJSONValuePtr cmd = qemuMonitorJSONMakeCommand("query-chardev",
                                                     NULL);
    virJSONValuePtr reply = NULL;

    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    if (ret == 0)
        ret = qemuMonitorJSONExtractPtyPaths(reply, paths);

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


1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
int qemuMonitorJSONAttachPCIDiskController(qemuMonitorPtr mon,
                                           const char *bus,
                                           virDomainDevicePCIAddress *guestAddr)
{
    int ret;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    char *dev;

    memset(guestAddr, 0, sizeof(*guestAddr));

    if (virAsprintf(&dev, "if=%s", bus) < 0) {
1732
        virReportOOMError();
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
        return -1;
    }

    cmd = qemuMonitorJSONMakeCommand("pci_add",
                                     "s:pci_addr", "auto",
                                     "s:type", "storage",
                                     "s:opts", dev,
                                     NULL);
    VIR_FREE(dev);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    if (ret == 0 &&
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
        qemuMonitorJSONGetGuestPCIAddress(reply, guestAddr) < 0)
        ret = -1;

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


static int
qemuMonitorJSONGetGuestDriveAddress(virJSONValuePtr reply,
                                    virDomainDeviceDriveAddress *driveAddr)
{
    virJSONValuePtr addr;

    addr = virJSONValueObjectGet(reply, "return");
    if (!addr || addr->type != VIR_JSON_TYPE_OBJECT) {
1768 1769
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("drive_add reply was missing device address"));
1770 1771 1772 1773
        return -1;
    }

    if (virJSONValueObjectGetNumberUint(addr, "bus", &driveAddr->bus) < 0) {
1774 1775
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("drive_add reply was missing device bus number"));
1776 1777 1778 1779
        return -1;
    }

    if (virJSONValueObjectGetNumberUint(addr, "unit", &driveAddr->unit) < 0) {
1780 1781
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("drive_add reply was missing device unit number"));
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
        return -1;
    }

    return 0;
}


int qemuMonitorJSONAttachDrive(qemuMonitorPtr mon,
                               const char *drivestr,
                               virDomainDevicePCIAddress* controllerAddr,
                               virDomainDeviceDriveAddress* driveAddr)
{
    int ret;
    virJSONValuePtr cmd = NULL;
    virJSONValuePtr reply = NULL;
    char *dev;

    if (virAsprintf(&dev, "%.2x:%.2x.%.1x",
                    controllerAddr->bus, controllerAddr->slot, controllerAddr->function) < 0) {
1801
        virReportOOMError();
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
        return -1;
    }

    cmd = qemuMonitorJSONMakeCommand("drive_add",
                                     "s:pci_addr", dev,
                                     "s:opts", drivestr,
                                     NULL);
    VIR_FREE(dev);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    if (ret == 0 &&
        qemuMonitorJSONGetGuestDriveAddress(reply, driveAddr) < 0)
1820 1821 1822 1823 1824 1825
        ret = -1;

    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1826 1827 1828 1829 1830


int qemuMonitorJSONGetAllPCIAddresses(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                                      qemuMonitorPCIAddress **addrs ATTRIBUTE_UNUSED)
{
1831 1832
    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("query-pci not suppported in JSON mode"));
1833 1834
    return -1;
}
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883


int qemuMonitorJSONAddDevice(qemuMonitorPtr mon,
                             const char *devicestr)
{
    int ret;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

    cmd = qemuMonitorJSONMakeCommand("device_add",
                                     "s:config", devicestr,
                                     NULL);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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


int qemuMonitorJSONAddDrive(qemuMonitorPtr mon,
                            const char *drivestr)
{
    int ret;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

    cmd = qemuMonitorJSONMakeCommand("drive_add",
                                     "s:pci_addr", "dummy",
                                     "s:opts", drivestr,
                                     NULL);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916


int qemuMonitorJSONSetDrivePassphrase(qemuMonitorPtr mon,
                                      const char *alias,
                                      const char *passphrase)
{
    int ret;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    char *drive;

    if (virAsprintf(&drive, "%s%s", QEMU_DRIVE_HOST_PREFIX, alias) < 0) {
        virReportOOMError();
        return -1;
    }

    cmd = qemuMonitorJSONMakeCommand("block_passwd",
                                     "s:device", drive,
                                     "s:password", passphrase,
                                     NULL);
    VIR_FREE(drive);
    if (!cmd)
        return -1;

    ret = qemuMonitorJSONCommand(mon, cmd, &reply);

    if (ret == 0)
        ret = qemuMonitorJSONCheckError(cmd, reply);

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