qemu_agent.c 70.3 KB
Newer Older
D
Daniel P. Berrange 已提交
1
/*
2
 * qemu_agent.c: interaction with QEMU guest agent
D
Daniel P. Berrange 已提交
3
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
D
Daniel P. Berrange 已提交
20 21 22 23 24 25 26 27
 */

#include <config.h>

#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
28
#include <gio/gio.h>
D
Daniel P. Berrange 已提交
29 30

#include "qemu_agent.h"
31
#include "qemu_domain.h"
32
#include "viralloc.h"
33
#include "virlog.h"
34
#include "virerror.h"
35
#include "virjson.h"
D
Daniel P. Berrange 已提交
36
#include "virfile.h"
37
#include "virprocess.h"
38
#include "virtime.h"
39
#include "virobject.h"
40
#include "virstring.h"
41
#include "virenum.h"
42
#include "virsocket.h"
J
Ján Tomko 已提交
43
#include "virutil.h"
D
Daniel P. Berrange 已提交
44 45 46

#define VIR_FROM_THIS VIR_FROM_QEMU

47 48
VIR_LOG_INIT("qemu.qemu_agent");

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

#define DEBUG_IO 0
#define DEBUG_RAW_IO 0

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

D
Daniel P. Berrange 已提交
63 64 65 66 67 68
/* When you are the first to uncomment this,
 * don't forget to uncomment the corresponding
 * part in qemuAgentIOProcessEvent as well.
 *
static struct {
    const char *type;
69
    void (*handler)(qemuAgentPtr agent, virJSONValuePtr data);
D
Daniel P. Berrange 已提交
70 71 72 73 74 75 76 77 78 79 80 81
} eventHandlers[] = {
};
*/

typedef struct _qemuAgentMessage qemuAgentMessage;
typedef qemuAgentMessage *qemuAgentMessagePtr;

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

82
    /* Used by the JSON agent to hold reply / error */
D
Daniel P. Berrange 已提交
83 84 85 86 87
    char *rxBuffer;
    int rxLength;
    void *rxObject;

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


struct _qemuAgent {
100
    virObjectLockable parent;
101

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

    int fd;
105 106 107 108

    GMainContext *context;
    GSocket *socket;
    GSource *watch;
D
Daniel P. Berrange 已提交
109

110
    bool running;
111 112
    bool singleSync;
    bool inSync;
D
Daniel P. Berrange 已提交
113 114 115 116 117 118 119 120 121

    virDomainObjPtr vm;

    qemuAgentCallbacksPtr cb;

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

122
    /* Buffer incoming data ready for agent
D
Daniel P. Berrange 已提交
123 124 125 126 127 128
     * code to process & find message boundaries */
    size_t bufferOffset;
    size_t bufferLength;
    char *buffer;

    /* If anything went wrong, this will be fed back
129
     * the next agent msg */
D
Daniel P. Berrange 已提交
130
    virError lastError;
131 132

    /* Some guest agent commands don't return anything
133
     * but fire up an event on qemu agent instead.
134 135
     * Take that as indication of successful completion */
    qemuAgentEvent await_event;
136
    int timeout;
D
Daniel P. Berrange 已提交
137 138
};

139 140 141 142 143
static virClassPtr qemuAgentClass;
static void qemuAgentDispose(void *obj);

static int qemuAgentOnceInit(void)
{
144
    if (!VIR_CLASS_NEW(qemuAgent, virClassForObjectLockable()))
145 146 147 148 149
        return -1;

    return 0;
}

150
VIR_ONCE_GLOBAL_INIT(qemuAgent);
151 152


D
Daniel P. Berrange 已提交
153 154 155 156
#if DEBUG_RAW_IO
static char *
qemuAgentEscapeNonPrintable(const char *text)
{
157
    size_t i;
D
Daniel P. Berrange 已提交
158
    virBuffer buf = VIR_BUFFER_INITIALIZER;
159
    for (i = 0; text[i] != '\0'; i++) {
D
Daniel P. Berrange 已提交
160 161
        if (text[i] == '\\')
            virBufferAddLit(&buf, "\\\\");
162
        else if (g_ascii_isprint(text[i]) || text[i] == '\n' ||
D
Daniel P. Berrange 已提交
163 164 165 166 167 168 169 170 171 172
                 (text[i] == '\r' && text[i+1] == '\n'))
            virBufferAddChar(&buf, text[i]);
        else
            virBufferAsprintf(&buf, "\\x%02x", text[i]);
    }
    return virBufferContentAndReset(&buf);
}
#endif


173
static void qemuAgentDispose(void *obj)
D
Daniel P. Berrange 已提交
174
{
175 176 177 178 179 180
    qemuAgentPtr agent = obj;
    VIR_DEBUG("agent=%p", agent);
    if (agent->cb && agent->cb->destroy)
        (agent->cb->destroy)(agent, agent->vm);
    virCondDestroy(&agent->notify);
    VIR_FREE(agent->buffer);
181
    g_main_context_unref(agent->context);
182
    virResetError(&agent->lastError);
D
Daniel P. Berrange 已提交
183 184 185
}

static int
186
qemuAgentOpenUnix(const char *socketpath)
D
Daniel P. Berrange 已提交
187 188
{
    struct sockaddr_un addr;
189
    int agentfd;
190
    int ret = -1;
D
Daniel P. Berrange 已提交
191

192
    if ((agentfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
D
Daniel P. Berrange 已提交
193 194 195 196 197
        virReportSystemError(errno,
                             "%s", _("failed to create socket"));
        return -1;
    }

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

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

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

220
    return agentfd;
D
Daniel P. Berrange 已提交
221

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


static int
229
qemuAgentIOProcessEvent(qemuAgentPtr agent,
D
Daniel P. Berrange 已提交
230 231 232
                        virJSONValuePtr obj)
{
    const char *type;
233
    VIR_DEBUG("agent=%p obj=%p", agent, obj);
D
Daniel P. Berrange 已提交
234 235 236 237 238 239 240 241 242

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

/*
243
    for (i = 0; i < G_N_ELEMENTS(eventHandlers); i++) {
D
Daniel P. Berrange 已提交
244 245 246 247
        if (STREQ(eventHandlers[i].type, type)) {
            virJSONValuePtr data = virJSONValueObjectGet(obj, "data");
            VIR_DEBUG("handle %s handler=%p data=%p", type,
                      eventHandlers[i].handler, data);
248
            (eventHandlers[i].handler)(agent, data);
D
Daniel P. Berrange 已提交
249 250 251 252 253 254 255 256
            break;
        }
    }
*/
    return 0;
}

static int
257
qemuAgentIOProcessLine(qemuAgentPtr agent,
D
Daniel P. Berrange 已提交
258 259 260 261 262 263 264 265
                       const char *line,
                       qemuAgentMessagePtr msg)
{
    virJSONValuePtr obj = NULL;
    int ret = -1;

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

266
    if (!(obj = virJSONValueFromString(line))) {
267 268
        /* receiving garbage on first sync is regular situation */
        if (msg && msg->sync && msg->first) {
269 270 271 272 273
            VIR_DEBUG("Received garbage on sync");
            msg->finished = 1;
            return 0;
        }

D
Daniel P. Berrange 已提交
274
        goto cleanup;
275
    }
D
Daniel P. Berrange 已提交
276

277
    if (virJSONValueGetType(obj) != VIR_JSON_TYPE_OBJECT) {
278 279
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Parsed JSON reply '%s' isn't an object"), line);
D
Daniel P. Berrange 已提交
280 281 282 283 284 285
        goto cleanup;
    }

    if (virJSONValueObjectHasKey(obj, "QMP") == 1) {
        ret = 0;
    } else if (virJSONValueObjectHasKey(obj, "event") == 1) {
286
        ret = qemuAgentIOProcessEvent(agent, obj);
D
Daniel P. Berrange 已提交
287 288 289
    } else if (virJSONValueObjectHasKey(obj, "error") == 1 ||
               virJSONValueObjectHasKey(obj, "return") == 1) {
        if (msg) {
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
            if (msg->sync) {
                unsigned long long id;

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

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

                if (msg->id != id) {
                    VIR_DEBUG("Guest agent returned ID: %llu instead of %llu",
                              id, msg->id);
                    ret = 0;
                    goto cleanup;
                }
            }
D
Daniel P. Berrange 已提交
308 309 310 311
            msg->rxObject = obj;
            msg->finished = 1;
            obj = NULL;
        } else {
312 313
            /* we are out of sync */
            VIR_DEBUG("Ignoring delayed reply");
D
Daniel P. Berrange 已提交
314
        }
315
        ret = 0;
D
Daniel P. Berrange 已提交
316
    } else {
317 318
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown JSON reply '%s'"), line);
D
Daniel P. Berrange 已提交
319 320
    }

321
 cleanup:
D
Daniel P. Berrange 已提交
322 323 324 325
    virJSONValueFree(obj);
    return ret;
}

326
static int qemuAgentIOProcessData(qemuAgentPtr agent,
D
Daniel P. Berrange 已提交
327 328 329 330 331
                                  char *data,
                                  size_t len,
                                  qemuAgentMessagePtr msg)
{
    int used = 0;
332
    size_t i = 0;
D
Daniel P. Berrange 已提交
333 334 335
#if DEBUG_IO
# if DEBUG_RAW_IO
    char *str1 = qemuAgentEscapeNonPrintable(data);
336
    VIR_ERROR(_("[%s]"), str1);
D
Daniel P. Berrange 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349
    VIR_FREE(str1);
# else
    VIR_DEBUG("Data %zu bytes [%s]", len, data);
# endif
#endif

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

        if (nl) {
            int got = nl - (data + used);
            for (i = 0; i < strlen(LINE_ENDING); i++)
                data[used + got + i] = '\0';
350
            if (qemuAgentIOProcessLine(agent, data + used, msg) < 0)
D
Daniel P. Berrange 已提交
351 352 353 354 355 356 357 358 359 360 361 362
                return -1;
            used += got + strlen(LINE_ENDING);
        } else {
            break;
        }
    }

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

/* This method processes data that has been received
363
 * from the agent. Looking for async events and
D
Daniel P. Berrange 已提交
364 365 366
 * replies/errors.
 */
static int
367
qemuAgentIOProcess(qemuAgentPtr agent)
D
Daniel P. Berrange 已提交
368 369 370 371 372 373 374
{
    int len;
    qemuAgentMessagePtr msg = NULL;

    /* See if there's a message ready for reply; that is,
     * one that has completed writing all its data.
     */
375 376
    if (agent->msg && agent->msg->txOffset == agent->msg->txLength)
        msg = agent->msg;
D
Daniel P. Berrange 已提交
377 378 379 380

#if DEBUG_IO
# if DEBUG_RAW_IO
    char *str1 = qemuAgentEscapeNonPrintable(msg ? msg->txBuffer : "");
381
    char *str2 = qemuAgentEscapeNonPrintable(agent->buffer);
D
Daniel P. Berrange 已提交
382
    VIR_ERROR(_("Process %zu %p %p [[[%s]]][[[%s]]]"),
383
              agent->bufferOffset, agent->msg, msg, str1, str2);
D
Daniel P. Berrange 已提交
384 385 386
    VIR_FREE(str1);
    VIR_FREE(str2);
# else
387
    VIR_DEBUG("Process %zu", agent->bufferOffset);
D
Daniel P. Berrange 已提交
388 389 390
# endif
#endif

391 392
    len = qemuAgentIOProcessData(agent,
                                 agent->buffer, agent->bufferOffset,
D
Daniel P. Berrange 已提交
393 394 395 396 397
                                 msg);

    if (len < 0)
        return -1;

398 399 400
    if (len < agent->bufferOffset) {
        memmove(agent->buffer, agent->buffer + len, agent->bufferOffset - len);
        agent->bufferOffset -= len;
D
Daniel P. Berrange 已提交
401
    } else {
402 403
        VIR_FREE(agent->buffer);
        agent->bufferOffset = agent->bufferLength = 0;
D
Daniel P. Berrange 已提交
404 405
    }
#if DEBUG_IO
406
    VIR_DEBUG("Process done %zu used %d", agent->bufferOffset, len);
D
Daniel P. Berrange 已提交
407 408
#endif
    if (msg && msg->finished)
409
        virCondBroadcast(&agent->notify);
D
Daniel P. Berrange 已提交
410 411 412 413 414
    return len;
}


/*
415 416
 * Called when the agent is able to write data
 * Call this function while holding the agent lock.
D
Daniel P. Berrange 已提交
417 418
 */
static int
419
qemuAgentIOWrite(qemuAgentPtr agent)
D
Daniel P. Berrange 已提交
420 421 422 423
{
    int done;

    /* If no active message, or fully transmitted, then no-op */
424
    if (!agent->msg || agent->msg->txOffset == agent->msg->txLength)
D
Daniel P. Berrange 已提交
425 426
        return 0;

427 428 429
    done = safewrite(agent->fd,
                     agent->msg->txBuffer + agent->msg->txOffset,
                     agent->msg->txLength - agent->msg->txOffset);
D
Daniel P. Berrange 已提交
430 431 432 433 434 435

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

        virReportSystemError(errno, "%s",
436
                             _("Unable to write to agent"));
D
Daniel P. Berrange 已提交
437 438
        return -1;
    }
439
    agent->msg->txOffset += done;
D
Daniel P. Berrange 已提交
440 441 442 443
    return done;
}

/*
444 445
 * Called when the agent has incoming data to read
 * Call this function while holding the agent lock.
D
Daniel P. Berrange 已提交
446 447 448 449
 *
 * Returns -1 on error, or number of bytes read
 */
static int
450
qemuAgentIORead(qemuAgentPtr agent)
D
Daniel P. Berrange 已提交
451
{
452
    size_t avail = agent->bufferLength - agent->bufferOffset;
D
Daniel P. Berrange 已提交
453 454 455
    int ret = 0;

    if (avail < 1024) {
456
        if (agent->bufferLength >= QEMU_AGENT_MAX_RESPONSE) {
457 458 459 460 461
            virReportSystemError(ERANGE,
                                 _("No complete agent response found in %d bytes"),
                                 QEMU_AGENT_MAX_RESPONSE);
            return -1;
        }
462 463
        if (VIR_REALLOC_N(agent->buffer,
                          agent->bufferLength + 1024) < 0)
D
Daniel P. Berrange 已提交
464
            return -1;
465
        agent->bufferLength += 1024;
D
Daniel P. Berrange 已提交
466 467 468 469 470 471 472
        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;
473 474
        got = read(agent->fd,
                   agent->buffer + agent->bufferOffset,
D
Daniel P. Berrange 已提交
475 476 477 478 479
                   avail - 1);
        if (got < 0) {
            if (errno == EAGAIN)
                break;
            virReportSystemError(errno, "%s",
480
                                 _("Unable to read from agent"));
D
Daniel P. Berrange 已提交
481 482 483 484 485 486 487 488
            ret = -1;
            break;
        }
        if (got == 0)
            break;

        ret += got;
        avail -= got;
489 490
        agent->bufferOffset += got;
        agent->buffer[agent->bufferOffset] = '\0';
D
Daniel P. Berrange 已提交
491 492 493
    }

#if DEBUG_IO
494
    VIR_DEBUG("Now read %zu bytes of data", agent->bufferOffset);
D
Daniel P. Berrange 已提交
495 496 497 498 499 500
#endif

    return ret;
}


501 502 503 504
static gboolean
qemuAgentIO(GSocket *socket,
            GIOCondition cond,
            gpointer opaque);
D
Daniel P. Berrange 已提交
505

506 507 508 509 510

static void
qemuAgentRegister(qemuAgentPtr agent)
{
    GIOCondition cond = 0;
511

512
    if (agent->lastError.code == VIR_ERR_OK) {
513
        cond |= G_IO_IN;
D
Daniel P. Berrange 已提交
514

515
        if (agent->msg && agent->msg->txOffset < agent->msg->txLength)
516
            cond |= G_IO_OUT;
D
Daniel P. Berrange 已提交
517 518
    }

519 520 521 522 523 524 525 526 527 528 529 530
    agent->watch = g_socket_create_source(agent->socket,
                                        cond,
                                        NULL);

    virObjectRef(agent);
    g_source_set_callback(agent->watch,
                          (GSourceFunc)qemuAgentIO,
                          agent,
                          (GDestroyNotify)virObjectUnref);

    g_source_attach(agent->watch,
                    agent->context);
D
Daniel P. Berrange 已提交
531 532 533 534
}


static void
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
qemuAgentUnregister(qemuAgentPtr agent)
{
    if (agent->watch) {
        g_source_destroy(agent->watch);
        g_source_unref(agent->watch);
        agent->watch = NULL;
    }
}


static void qemuAgentUpdateWatch(qemuAgentPtr agent)
{
    qemuAgentUnregister(agent);
    if (agent->socket)
        qemuAgentRegister(agent);
}


static gboolean
qemuAgentIO(GSocket *socket G_GNUC_UNUSED,
            GIOCondition cond,
            gpointer opaque)
557
{
558
    qemuAgentPtr agent = opaque;
D
Daniel P. Berrange 已提交
559 560 561
    bool error = false;
    bool eof = false;

562 563 564
    virObjectRef(agent);
    /* lock access to the agent and protect fd */
    virObjectLock(agent);
D
Daniel P. Berrange 已提交
565
#if DEBUG_IO
566
    VIR_DEBUG("Agent %p I/O on watch %d socket %p cond %d", agent, agent->socket, cond);
D
Daniel P. Berrange 已提交
567 568
#endif

569
    if (agent->fd == -1 || !agent->watch) {
570 571
        virObjectUnlock(agent);
        virObjectUnref(agent);
572
        return G_SOURCE_REMOVE;
573 574
    }

575 576
    if (agent->lastError.code != VIR_ERR_OK) {
        if (cond & (G_IO_HUP | G_IO_ERR))
D
Daniel P. Berrange 已提交
577 578 579
            eof = true;
        error = true;
    } else {
580
        if (cond & G_IO_OUT) {
581
            if (qemuAgentIOWrite(agent) < 0)
582
                error = true;
D
Daniel P. Berrange 已提交
583 584 585
        }

        if (!error &&
586
            cond & G_IO_IN) {
587
            int got = qemuAgentIORead(agent);
D
Daniel P. Berrange 已提交
588 589 590 591 592
            if (got < 0) {
                error = true;
            } else if (got == 0) {
                eof = true;
            } else {
593
                /* Ignore hangup/error cond if we read some data, to
D
Daniel P. Berrange 已提交
594
                 * give time for that data to be consumed */
595
                cond = 0;
D
Daniel P. Berrange 已提交
596

597
                if (qemuAgentIOProcess(agent) < 0)
D
Daniel P. Berrange 已提交
598 599 600 601 602
                    error = true;
            }
        }

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

        if (!error && !eof &&
610
            cond & G_IO_ERR) {
611
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
612
                           _("Invalid file descriptor while waiting for agent"));
613
            eof = true;
D
Daniel P. Berrange 已提交
614 615 616 617
        }
    }

    if (error || eof) {
618
        if (agent->lastError.code != VIR_ERR_OK) {
D
Daniel P. Berrange 已提交
619 620 621
            /* Already have an error, so clear any new error */
            virResetLastError();
        } else {
622
            if (virGetLastErrorCode() == VIR_ERR_OK)
623
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
624 625
                               _("Error while processing agent IO"));
            virCopyLastError(&agent->lastError);
D
Daniel P. Berrange 已提交
626 627 628
            virResetLastError();
        }

629
        VIR_DEBUG("Error on agent %s", NULLSTR(agent->lastError.message));
D
Daniel P. Berrange 已提交
630 631
        /* If IO process resulted in an error & we have a message,
         * then wakeup that waiter */
632 633 634
        if (agent->msg && !agent->msg->finished) {
            agent->msg->finished = 1;
            virCondSignal(&agent->notify);
D
Daniel P. Berrange 已提交
635 636 637
        }
    }

638
    qemuAgentUpdateWatch(agent);
D
Daniel P. Berrange 已提交
639 640 641 642 643 644

    /* We have to unlock to avoid deadlock against command thread,
     * but is this safe ?  I think it is, because the callback
     * will try to acquire the virDomainObjPtr mutex next */
    if (eof) {
        void (*eofNotify)(qemuAgentPtr, virDomainObjPtr)
645 646
            = agent->cb->eofNotify;
        virDomainObjPtr vm = agent->vm;
D
Daniel P. Berrange 已提交
647 648

        /* Make sure anyone waiting wakes up now */
649 650 651
        virCondSignal(&agent->notify);
        virObjectUnlock(agent);
        virObjectUnref(agent);
D
Daniel P. Berrange 已提交
652
        VIR_DEBUG("Triggering EOF callback");
653
        (eofNotify)(agent, vm);
D
Daniel P. Berrange 已提交
654 655
    } else if (error) {
        void (*errorNotify)(qemuAgentPtr, virDomainObjPtr)
656 657
            = agent->cb->errorNotify;
        virDomainObjPtr vm = agent->vm;
D
Daniel P. Berrange 已提交
658 659

        /* Make sure anyone waiting wakes up now */
660 661 662
        virCondSignal(&agent->notify);
        virObjectUnlock(agent);
        virObjectUnref(agent);
D
Daniel P. Berrange 已提交
663
        VIR_DEBUG("Triggering error callback");
664
        (errorNotify)(agent, vm);
D
Daniel P. Berrange 已提交
665
    } else {
666 667
        virObjectUnlock(agent);
        virObjectUnref(agent);
D
Daniel P. Berrange 已提交
668
    }
669 670

    return G_SOURCE_REMOVE;
D
Daniel P. Berrange 已提交
671 672 673 674 675
}


qemuAgentPtr
qemuAgentOpen(virDomainObjPtr vm,
676
              const virDomainChrSourceDef *config,
677
              GMainContext *context,
678 679
              qemuAgentCallbacksPtr cb,
              bool singleSync)
D
Daniel P. Berrange 已提交
680
{
681
    qemuAgentPtr agent;
682
    g_autoptr(GError) gerr = NULL;
D
Daniel P. Berrange 已提交
683 684

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

690 691 692
    if (qemuAgentInitialize() < 0)
        return NULL;

693
    if (!(agent = virObjectLockableNew(qemuAgentClass)))
D
Daniel P. Berrange 已提交
694 695
        return NULL;

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

708
    if (config->type != VIR_DOMAIN_CHR_TYPE_UNIX) {
709
        virReportError(VIR_ERR_INTERNAL_ERROR,
710
                       _("unable to handle agent type: %s"),
711
                       virDomainChrTypeToString(config->type));
D
Daniel P. Berrange 已提交
712 713 714
        goto cleanup;
    }

715 716
    agent->fd = qemuAgentOpenUnix(config->data.nix.path);
    if (agent->fd == -1)
D
Daniel P. Berrange 已提交
717 718
        goto cleanup;

719 720 721 722 723 724 725
    agent->context = g_main_context_ref(context);

    agent->socket = g_socket_new_from_fd(agent->fd, &gerr);
    if (!agent->socket) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to create socket object: %s"),
                       gerr->message);
D
Daniel P. Berrange 已提交
726 727 728
        goto cleanup;
    }

729 730
    qemuAgentRegister(agent);

731
    agent->running = true;
732
    VIR_DEBUG("New agent %p fd=%d", agent, agent->fd);
D
Daniel P. Berrange 已提交
733

734
    return agent;
D
Daniel P. Berrange 已提交
735

736
 cleanup:
D
Daniel P. Berrange 已提交
737 738 739 740 741
    /* 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.
     */
742 743
    agent->cb = NULL;
    qemuAgentClose(agent);
D
Daniel P. Berrange 已提交
744 745 746 747
    return NULL;
}


748
static void
749
qemuAgentNotifyCloseLocked(qemuAgentPtr agent)
750
{
751 752
    if (agent) {
        agent->running = false;
753 754 755

        /* If there is somebody waiting for a message
         * wake him up. No message will arrive anyway. */
756 757 758
        if (agent->msg && !agent->msg->finished) {
            agent->msg->finished = 1;
            virCondSignal(&agent->notify);
759 760 761 762 763 764
        }
    }
}


void
765
qemuAgentNotifyClose(qemuAgentPtr agent)
766
{
767
    if (!agent)
768 769
        return;

770
    VIR_DEBUG("agent=%p", agent);
771

772 773 774
    virObjectLock(agent);
    qemuAgentNotifyCloseLocked(agent);
    virObjectUnlock(agent);
775 776 777
}


778
void qemuAgentClose(qemuAgentPtr agent)
D
Daniel P. Berrange 已提交
779
{
780
    if (!agent)
D
Daniel P. Berrange 已提交
781 782
        return;

783
    VIR_DEBUG("agent=%p", agent);
D
Daniel P. Berrange 已提交
784

785
    virObjectLock(agent);
D
Daniel P. Berrange 已提交
786

787 788 789 790 791
    if (agent->socket) {
        qemuAgentUnregister(agent);
        g_object_unref(agent->socket);
        agent->socket = NULL;
        agent->fd = -1;
D
Daniel P. Berrange 已提交
792 793
    }

794 795
    qemuAgentNotifyCloseLocked(agent);
    virObjectUnlock(agent);
796

797
    virObjectUnref(agent);
D
Daniel P. Berrange 已提交
798 799
}

800
#define QEMU_AGENT_WAIT_TIME 5
D
Daniel P. Berrange 已提交
801

802 803
/**
 * qemuAgentSend:
804
 * @agent: agent object
805
 * @msg: Message
806 807
 * @seconds: number of seconds to wait for the result, it can be either
 *           -2, -1, 0 or positive.
808
 *
809
 * Send @msg to agent @agent. If @seconds is equal to
810 811 812
 * VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK(-2), this function will block forever
 * waiting for the result. The value of
 * VIR_DOMAIN_QEMU_AGENT_COMMAND_DEFAULT(-1) means use default timeout value
Y
Yuri Chornoivan 已提交
813
 * and VIR_DOMAIN_QEMU_AGENT_COMMAND_NOWAIT(0) makes this function return
814 815
 * immediately without waiting. Any positive value means the number of seconds
 * to wait for the result.
816 817 818 819 820
 *
 * Returns: 0 on success,
 *          -2 on timeout,
 *          -1 otherwise
 */
821
static int qemuAgentSend(qemuAgentPtr agent,
822
                         qemuAgentMessagePtr msg,
823
                         int seconds)
D
Daniel P. Berrange 已提交
824 825
{
    int ret = -1;
826
    unsigned long long then = 0;
D
Daniel P. Berrange 已提交
827 828

    /* Check whether qemu quit unexpectedly */
829
    if (agent->lastError.code != VIR_ERR_OK) {
D
Daniel P. Berrange 已提交
830
        VIR_DEBUG("Attempt to send command while error is set %s",
831 832
                  NULLSTR(agent->lastError.message));
        virSetError(&agent->lastError);
D
Daniel P. Berrange 已提交
833 834 835
        return -1;
    }

836 837
    if (seconds > VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK) {
        unsigned long long now;
838 839
        if (virTimeMillisNow(&now) < 0)
            return -1;
840 841 842
        if (seconds == VIR_DOMAIN_QEMU_AGENT_COMMAND_DEFAULT)
            seconds = QEMU_AGENT_WAIT_TIME;
        then = now + seconds * 1000ull;
843 844
    }

845 846
    agent->msg = msg;
    qemuAgentUpdateWatch(agent);
D
Daniel P. Berrange 已提交
847

848 849 850
    while (!agent->msg->finished) {
        if ((then && virCondWaitUntil(&agent->notify, &agent->parent.lock, then) < 0) ||
            (!then && virCondWait(&agent->notify, &agent->parent.lock) < 0)) {
851
            if (errno == ETIMEDOUT) {
852
                virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
853
                               _("Guest agent not available for now"));
854 855
                ret = -2;
            } else {
856
                virReportSystemError(errno, "%s",
857
                                     _("Unable to wait on agent socket "
858
                                       "condition"));
859
            }
860
            agent->inSync = false;
D
Daniel P. Berrange 已提交
861 862 863 864
            goto cleanup;
        }
    }

865
    if (agent->lastError.code != VIR_ERR_OK) {
D
Daniel P. Berrange 已提交
866
        VIR_DEBUG("Send command resulted in error %s",
867 868
                  NULLSTR(agent->lastError.message));
        virSetError(&agent->lastError);
D
Daniel P. Berrange 已提交
869 870 871 872 873
        goto cleanup;
    }

    ret = 0;

874
 cleanup:
875 876
    agent->msg = NULL;
    qemuAgentUpdateWatch(agent);
D
Daniel P. Berrange 已提交
877 878 879 880 881

    return ret;
}


882 883
/**
 * qemuAgentGuestSync:
884
 * @agent: agent object
885 886 887 888 889 890 891 892 893
 *
 * Send guest-sync with unique ID
 * and wait for reply. If we get one, check if
 * received ID is equal to given.
 *
 * Returns: 0 on success,
 *          -1 otherwise
 */
static int
894
qemuAgentGuestSync(qemuAgentPtr agent)
895 896 897
{
    int ret = -1;
    int send_ret;
898
    unsigned long long id;
899
    qemuAgentMessage sync_msg;
900 901
    int timeout = VIR_DOMAIN_QEMU_AGENT_COMMAND_DEFAULT;

902 903 904
    if (agent->singleSync && agent->inSync)
        return 0;

905 906
    /* if user specified a custom agent timeout that is lower than the
     * default timeout, use the shorter timeout instead */
907
    if ((agent->timeout >= 0) && (agent->timeout < QEMU_AGENT_WAIT_TIME))
908
        timeout = agent->timeout;
909 910

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

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

918 919
    sync_msg.txBuffer = g_strdup_printf("{\"execute\":\"guest-sync\", "
                                        "\"arguments\":{\"id\":%llu}}\n", id);
920 921

    sync_msg.txLength = strlen(sync_msg.txBuffer);
922
    sync_msg.sync = true;
923
    sync_msg.id = id;
924 925 926

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

927
    send_ret = qemuAgentSend(agent, &sync_msg, timeout);
928 929 930

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

931
    if (send_ret < 0)
932 933 934
        goto cleanup;

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

950 951 952
    if (agent->singleSync)
        agent->inSync = true;

953 954
    ret = 0;

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

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
static const char *
qemuAgentStringifyErrorClass(const char *klass)
{
    if (STREQ_NULLABLE(klass, "BufferOverrun"))
        return "Buffer overrun";
    else if (STREQ_NULLABLE(klass, "CommandDisabled"))
        return "The command has been disabled for this instance";
    else if (STREQ_NULLABLE(klass, "CommandNotFound"))
        return "The command has not been found";
    else if (STREQ_NULLABLE(klass, "FdNotFound"))
        return "File descriptor not found";
    else if (STREQ_NULLABLE(klass, "InvalidParameter"))
        return "Invalid parameter";
    else if (STREQ_NULLABLE(klass, "InvalidParameterType"))
        return "Invalid parameter type";
    else if (STREQ_NULLABLE(klass, "InvalidParameterValue"))
        return "Invalid parameter value";
    else if (STREQ_NULLABLE(klass, "OpenFileFailed"))
        return "Cannot open file";
    else if (STREQ_NULLABLE(klass, "QgaCommandFailed"))
        return "Guest agent command failed";
    else if (STREQ_NULLABLE(klass, "QMPBadInputObjectMember"))
        return "Bad QMP input object member";
    else if (STREQ_NULLABLE(klass, "QMPExtraInputObjectMember"))
        return "Unexpected extra object member";
    else if (STREQ_NULLABLE(klass, "UndefinedError"))
        return "An undefined error has occurred";
    else if (STREQ_NULLABLE(klass, "Unsupported"))
        return "this feature or command is not currently supported";
    else if (klass)
        return klass;
    else
        return "unknown QEMU command error";
}
D
Daniel P. Berrange 已提交
995

996 997 998 999 1000 1001 1002 1003 1004 1005
/* Checks whether the agent reply msg is an error caused by an unsupported
 * command.
 *
 * Returns true when reply is CommandNotFound or CommandDisabled
 *         false otherwise
 */
static bool
qemuAgentErrorCommandUnsupported(virJSONValuePtr reply)
{
    const char *klass;
1006 1007 1008 1009 1010 1011
    virJSONValuePtr error;

    if (!reply)
        return false;

    error = virJSONValueObjectGet(reply, "error");
1012 1013 1014 1015 1016 1017 1018 1019 1020

    if (!error)
        return false;

    klass = virJSONValueObjectGetString(error, "class");
    return STREQ_NULLABLE(klass, "CommandNotFound") ||
        STREQ_NULLABLE(klass, "CommandDisabled");
}

D
Daniel P. Berrange 已提交
1021 1022 1023 1024 1025 1026 1027 1028 1029
/* Ignoring OOM in this method, since we're already reporting
 * a more important error
 *
 * XXX see qerror.h for different klasses & fill out useful params
 */
static const char *
qemuAgentStringifyError(virJSONValuePtr error)
{
    const char *klass = virJSONValueObjectGetString(error, "class");
1030
    const char *detail = virJSONValueObjectGetString(error, "desc");
D
Daniel P. Berrange 已提交
1031 1032

    /* The QMP 'desc' field is usually sufficient for our generic
1033 1034
     * error reporting needs. However, if not present, translate
     * the class into something readable.
D
Daniel P. Berrange 已提交
1035 1036
     */
    if (!detail)
1037
        detail = qemuAgentStringifyErrorClass(klass);
D
Daniel P. Berrange 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

    return detail;
}

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

static int
qemuAgentCheckError(virJSONValuePtr cmd,
                    virJSONValuePtr reply)
{
    if (virJSONValueObjectHasKey(reply, "error")) {
        virJSONValuePtr error = virJSONValueObjectGet(reply, "error");
1058 1059
        g_autofree char *cmdstr = virJSONValueToString(cmd, false);
        g_autofree char *replystr = virJSONValueToString(reply, false);
D
Daniel P. Berrange 已提交
1060 1061

        /* Log the full JSON formatted command & error */
1062
        VIR_DEBUG("unable to execute QEMU agent command %s: %s",
1063
                  NULLSTR(cmdstr), NULLSTR(replystr));
D
Daniel P. Berrange 已提交
1064 1065 1066

        /* Only send the user the command name + friendly error */
        if (!error)
1067
            virReportError(VIR_ERR_INTERNAL_ERROR,
1068
                           _("unable to execute QEMU agent command '%s'"),
1069
                           qemuAgentCommandName(cmd));
D
Daniel P. Berrange 已提交
1070
        else
1071
            virReportError(VIR_ERR_INTERNAL_ERROR,
1072
                           _("unable to execute QEMU agent command '%s': %s"),
1073 1074
                           qemuAgentCommandName(cmd),
                           qemuAgentStringifyError(error));
D
Daniel P. Berrange 已提交
1075 1076 1077

        return -1;
    } else if (!virJSONValueObjectHasKey(reply, "return")) {
1078 1079
        g_autofree char *cmdstr = virJSONValueToString(cmd, false);
        g_autofree char *replystr = virJSONValueToString(reply, false);
D
Daniel P. Berrange 已提交
1080 1081

        VIR_DEBUG("Neither 'return' nor 'error' is set in the JSON reply %s: %s",
1082
                  NULLSTR(cmdstr), NULLSTR(replystr));
1083
        virReportError(VIR_ERR_INTERNAL_ERROR,
1084
                       _("unable to execute QEMU agent command '%s'"),
1085
                       qemuAgentCommandName(cmd));
D
Daniel P. Berrange 已提交
1086 1087 1088 1089 1090
        return -1;
    }
    return 0;
}

1091
static int
1092
qemuAgentCommand(qemuAgentPtr agent,
1093 1094 1095 1096 1097 1098 1099
                 virJSONValuePtr cmd,
                 virJSONValuePtr *reply,
                 int seconds)
{
    int ret = -1;
    qemuAgentMessage msg;
    char *cmdstr = NULL;
1100
    int await_event = agent->await_event;
1101 1102

    *reply = NULL;
1103
    memset(&msg, 0, sizeof(msg));
1104

1105
    if (!agent->running) {
1106 1107
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                       _("Guest agent disappeared while executing command"));
1108
        goto cleanup;
1109 1110
    }

1111
    if (qemuAgentGuestSync(agent) < 0)
1112
        goto cleanup;
1113 1114 1115

    if (!(cmdstr = virJSONValueToString(cmd, false)))
        goto cleanup;
1116
    msg.txBuffer = g_strdup_printf("%s" LINE_ENDING, cmdstr);
1117 1118 1119 1120
    msg.txLength = strlen(msg.txBuffer);

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

1121
    ret = qemuAgentSend(agent, &msg, seconds);
1122 1123 1124 1125

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

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    if (ret < 0)
        goto cleanup;

    /* If we haven't obtained any reply but we wait for an
     * event, then don't report this as error */
    if (!msg.rxObject) {
        if (!await_event) {
            if (agent->running) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing agent reply object"));
1136
            } else {
1137 1138
                virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                               _("Guest agent disappeared while executing command"));
1139
            }
1140
            ret = -1;
1141
        }
1142
        goto cleanup;
1143 1144
    }

1145 1146 1147
    *reply = msg.rxObject;
    ret = qemuAgentCheckError(cmd, *reply);

1148 1149 1150
 cleanup:
    VIR_FREE(cmdstr);
    VIR_FREE(msg.txBuffer);
1151
    agent->await_event = QEMU_AGENT_EVENT_NONE;
1152 1153 1154 1155

    return ret;
}

1156
static virJSONValuePtr G_GNUC_NULL_TERMINATED
D
Daniel P. Berrange 已提交
1157 1158 1159
qemuAgentMakeCommand(const char *cmdname,
                     ...)
{
1160
    virJSONValuePtr obj = virJSONValueNewObject();
D
Daniel P. Berrange 已提交
1161 1162 1163 1164 1165 1166
    virJSONValuePtr jargs = NULL;
    va_list args;

    va_start(args, cmdname);

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

1169 1170
    if (virJSONValueObjectCreateVArgs(&jargs, args) < 0)
        goto error;
D
Daniel P. Berrange 已提交
1171 1172 1173

    if (jargs &&
        virJSONValueObjectAppend(obj, "arguments", jargs) < 0)
1174
        goto error;
D
Daniel P. Berrange 已提交
1175 1176 1177 1178 1179

    va_end(args);

    return obj;

1180
 error:
D
Daniel P. Berrange 已提交
1181 1182 1183 1184 1185 1186
    virJSONValueFree(obj);
    virJSONValueFree(jargs);
    va_end(args);
    return NULL;
}

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
static virJSONValuePtr
qemuAgentMakeStringsArray(const char **strings, unsigned int len)
{
    size_t i;
    virJSONValuePtr ret = virJSONValueNewArray(), str;

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

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

 error:
    virJSONValueFree(ret);
    return NULL;
}

1210
void qemuAgentNotifyEvent(qemuAgentPtr agent,
1211 1212
                          qemuAgentEvent event)
{
1213
    virObjectLock(agent);
1214

1215 1216 1217
    VIR_DEBUG("agent=%p event=%d await_event=%d", agent, event, agent->await_event);
    if (agent->await_event == event) {
        agent->await_event = QEMU_AGENT_EVENT_NONE;
1218
        /* somebody waiting for this event, wake him up. */
1219 1220 1221
        if (agent->msg && !agent->msg->finished) {
            agent->msg->finished = 1;
            virCondSignal(&agent->notify);
1222 1223
        }
    }
1224

1225
    virObjectUnlock(agent);
1226 1227
}

D
Daniel P. Berrange 已提交
1228 1229 1230 1231
VIR_ENUM_DECL(qemuAgentShutdownMode);

VIR_ENUM_IMPL(qemuAgentShutdownMode,
              QEMU_AGENT_SHUTDOWN_LAST,
1232 1233
              "powerdown", "reboot", "halt",
);
D
Daniel P. Berrange 已提交
1234

1235
int qemuAgentShutdown(qemuAgentPtr agent,
D
Daniel P. Berrange 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
                      qemuAgentShutdownMode mode)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

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

1248
    if (mode == QEMU_AGENT_SHUTDOWN_REBOOT)
1249
        agent->await_event = QEMU_AGENT_EVENT_RESET;
1250
    else
1251
        agent->await_event = QEMU_AGENT_EVENT_SHUTDOWN;
1252
    ret = qemuAgentCommand(agent, cmd, &reply,
1253
                           VIR_DOMAIN_QEMU_AGENT_COMMAND_SHUTDOWN);
D
Daniel P. Berrange 已提交
1254 1255 1256 1257 1258

    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1259 1260 1261

/*
 * qemuAgentFSFreeze:
1262
 * @agent: agent object
1263 1264
 * @mountpoints: Array of mountpoint paths to be frozen, or NULL for all
 * @nmountpoints: Number of mountpoints to be frozen, or 0 for all
1265 1266
 *
 * Issue guest-fsfreeze-freeze command to guest agent,
1267 1268
 * which freezes file systems mounted on specified mountpoints
 * (or all file systems when @mountpoints is NULL), and returns
1269 1270 1271 1272 1273
 * number of frozen file systems on success.
 *
 * Returns: number of file system frozen on success,
 *          -1 on error.
 */
1274
int qemuAgentFSFreeze(qemuAgentPtr agent, const char **mountpoints,
1275
                      unsigned int nmountpoints)
1276 1277
{
    int ret = -1;
1278
    virJSONValuePtr cmd, arg = NULL;
1279 1280
    virJSONValuePtr reply = NULL;

1281 1282 1283 1284 1285
    if (mountpoints && nmountpoints) {
        arg = qemuAgentMakeStringsArray(mountpoints, nmountpoints);
        if (!arg)
            return -1;

1286
        cmd = qemuAgentMakeCommand("guest-fsfreeze-freeze-list",
1287
                                   "a:mountpoints", &arg, NULL);
1288 1289 1290
    } else {
        cmd = qemuAgentMakeCommand("guest-fsfreeze-freeze", NULL);
    }
1291 1292

    if (!cmd)
1293
        goto cleanup;
1294

1295
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
1296 1297 1298
        goto cleanup;

    if (virJSONValueObjectGetNumberInt(reply, "return", &ret) < 0) {
1299 1300
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed return value"));
1301 1302
    }

1303
 cleanup:
1304
    virJSONValueFree(arg);
1305 1306 1307 1308 1309 1310 1311
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}

/*
 * qemuAgentFSThaw:
1312
 * @agent: agent object
1313 1314 1315 1316 1317 1318 1319 1320
 *
 * Issue guest-fsfreeze-thaw command to guest agent,
 * which unfreezes all mounted file systems and returns
 * number of thawed file systems on success.
 *
 * Returns: number of file system thawed on success,
 *          -1 on error.
 */
1321
int qemuAgentFSThaw(qemuAgentPtr agent)
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

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

    if (!cmd)
        return -1;

1332
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
1333 1334 1335
        goto cleanup;

    if (virJSONValueObjectGetNumberInt(reply, "return", &ret) < 0) {
1336 1337
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed return value"));
1338 1339
    }

1340
 cleanup:
1341 1342 1343 1344
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1345 1346 1347 1348 1349 1350 1351

VIR_ENUM_DECL(qemuAgentSuspendMode);

VIR_ENUM_IMPL(qemuAgentSuspendMode,
              VIR_NODE_SUSPEND_TARGET_LAST,
              "guest-suspend-ram",
              "guest-suspend-disk",
1352 1353
              "guest-suspend-hybrid",
);
1354 1355

int
1356
qemuAgentSuspend(qemuAgentPtr agent,
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
                 unsigned int target)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

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

1368
    agent->await_event = QEMU_AGENT_EVENT_SUSPEND;
1369
    ret = qemuAgentCommand(agent, cmd, &reply, agent->timeout);
1370 1371 1372 1373 1374

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

int
1377
qemuAgentArbitraryCommand(qemuAgentPtr agent,
1378 1379 1380 1381 1382
                          const char *cmd_str,
                          char **result,
                          int timeout)
{
    int ret = -1;
1383
    virJSONValuePtr cmd = NULL;
1384 1385 1386
    virJSONValuePtr reply = NULL;

    *result = NULL;
1387 1388 1389 1390 1391 1392 1393
    if (timeout < VIR_DOMAIN_QEMU_AGENT_COMMAND_MIN) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("guest agent timeout '%d' is "
                         "less than the minimum '%d'"),
                       timeout, VIR_DOMAIN_QEMU_AGENT_COMMAND_MIN);
        goto cleanup;
    }
1394

1395 1396 1397
    if (!(cmd = virJSONValueFromString(cmd_str)))
        goto cleanup;

1398
    if ((ret = qemuAgentCommand(agent, cmd, &reply, timeout)) < 0)
1399
        goto cleanup;
1400

1401 1402
    if (!(*result = virJSONValueToString(reply, false)))
        ret = -1;
1403

1404

1405
 cleanup:
1406 1407 1408 1409
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
M
Michal Privoznik 已提交
1410 1411

int
1412
qemuAgentFSTrim(qemuAgentPtr agent,
M
Michal Privoznik 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                unsigned long long minimum)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

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

1425
    ret = qemuAgentCommand(agent, cmd, &reply, agent->timeout);
M
Michal Privoznik 已提交
1426 1427 1428 1429 1430

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

int
1433
qemuAgentGetVCPUs(qemuAgentPtr agent,
1434 1435 1436
                  qemuAgentCPUInfoPtr *info)
{
    int ret = -1;
1437
    size_t i;
1438 1439 1440
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr data = NULL;
1441
    size_t ndata;
1442 1443 1444 1445

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

1446
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
1447 1448
        goto cleanup;

1449
    if (!(data = virJSONValueObjectGetArray(reply, "return"))) {
1450 1451 1452 1453 1454
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest-get-vcpus reply was missing return data"));
        goto cleanup;
    }

1455 1456 1457 1458 1459 1460
    if (!virJSONValueIsArray(data)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed guest-get-vcpus data array"));
        goto cleanup;
    }

1461 1462
    ndata = virJSONValueArraySize(data);

1463
    if (VIR_ALLOC_N(*info, ndata) < 0)
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
        goto cleanup;

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

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

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

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

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

    ret = ndata;

1499
 cleanup:
1500 1501 1502 1503 1504
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}

1505 1506 1507

/* returns the value provided by the guest agent or -1 on internal error */
static int
1508
qemuAgentSetVCPUsCommand(qemuAgentPtr agent,
1509 1510 1511
                         qemuAgentCPUInfoPtr info,
                         size_t ninfo,
                         int *nmodified)
1512 1513 1514 1515 1516 1517 1518 1519
{
    int ret = -1;
    virJSONValuePtr cmd = NULL;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr cpus = NULL;
    virJSONValuePtr cpu = NULL;
    size_t i;

1520 1521
    *nmodified = 0;

1522
    /* create the key data array */
1523
    cpus = virJSONValueNewArray();
1524 1525 1526 1527

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

1528 1529 1530 1531 1532 1533
        /* don't set state for cpus that were not touched */
        if (!in->modified)
            continue;

        (*nmodified)++;

1534
        /* create single cpu object */
1535
        cpu = virJSONValueNewObject();
1536 1537

        if (virJSONValueObjectAppendNumberInt(cpu, "logical-id", in->id) < 0)
1538
            goto cleanup;
1539 1540

        if (virJSONValueObjectAppendBoolean(cpu, "online", in->online) < 0)
1541
            goto cleanup;
1542 1543

        if (virJSONValueArrayAppend(cpus, cpu) < 0)
1544
            goto cleanup;
1545 1546 1547 1548

        cpu = NULL;
    }

1549 1550 1551 1552 1553
    if (*nmodified == 0) {
        ret = 0;
        goto cleanup;
    }

1554
    if (!(cmd = qemuAgentMakeCommand("guest-set-vcpus",
1555
                                     "a:vcpus", &cpus,
1556 1557 1558
                                     NULL)))
        goto cleanup;

1559
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
1560 1561
        goto cleanup;

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

1572
 cleanup:
1573 1574 1575 1576 1577 1578
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    virJSONValueFree(cpu);
    virJSONValueFree(cpus);
    return ret;
}
1579 1580


1581 1582 1583 1584 1585 1586 1587 1588 1589
/**
 * Set the VCPU state using guest agent.
 *
 * Attempts to set the guest agent state for all cpus or until a proper error is
 * reported by the guest agent. This may require multiple calls.
 *
 * Returns -1 on error, 0 on success.
 */
int
1590
qemuAgentSetVCPUs(qemuAgentPtr agent,
1591 1592 1593 1594 1595 1596 1597 1598
                  qemuAgentCPUInfoPtr info,
                  size_t ninfo)
{
    int rv;
    int nmodified;
    size_t i;

    do {
1599
        if ((rv = qemuAgentSetVCPUsCommand(agent, info, ninfo, &nmodified)) < 0)
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
            return -1;

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

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

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

    return 0;
}


1620 1621 1622 1623 1624 1625 1626 1627 1628
/* modify the cpu info structure to set the correct amount of cpus */
int
qemuAgentUpdateCPUInfo(unsigned int nvcpus,
                       qemuAgentCPUInfoPtr cpuinfo,
                       int ncpuinfo)
{
    size_t i;
    int nonline = 0;
    int nofflinable = 0;
1629
    ssize_t cpu0 = -1;
1630 1631 1632

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

1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
        if (cpuinfo[i].online)
            nonline++;

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

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

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

1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
    /* the guest agent reported less cpus than requested */
    if (nvcpus > ncpuinfo) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest agent reports less cpu than requested"));
        return -1;
    }

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

    for (i = 0; i < ncpuinfo; i++) {
        if (nvcpus < nonline) {
            /* unplug */
            if (cpuinfo[i].offlinable && cpuinfo[i].online) {
                cpuinfo[i].online = false;
1678
                cpuinfo[i].modified = true;
1679 1680 1681 1682 1683 1684
                nonline--;
            }
        } else if (nvcpus > nonline) {
            /* plug */
            if (!cpuinfo[i].online) {
                cpuinfo[i].online = true;
1685
                cpuinfo[i].modified = true;
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
                nonline++;
            }
        } else {
            /* done */
            break;
        }
    }

    return 0;
}
1696 1697


1698
int
1699
qemuAgentGetHostname(qemuAgentPtr agent,
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
                     char **hostname)
{
    int ret = -1;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr data = NULL;
    const char *result = NULL;

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

    if (!cmd)
        return ret;

1714
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0) {
1715 1716
        if (qemuAgentErrorCommandUnsupported(reply))
            ret = -2;
1717
        goto cleanup;
1718
    }
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

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

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

1732
    *hostname = g_strdup(result);
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742

    ret = 0;

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


1743
int
1744
qemuAgentGetTime(qemuAgentPtr agent,
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
                 long long *seconds,
                 unsigned int *nseconds)
{
    int ret = -1;
    unsigned long long json_time;
    virJSONValuePtr cmd;
    virJSONValuePtr reply = NULL;

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

1758
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
        goto cleanup;

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

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

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


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

P
Pavel Hrdina 已提交
1795
    if (rtcSync) {
1796 1797 1798 1799 1800 1801 1802
        cmd = qemuAgentMakeCommand("guest-set-time", NULL);
    } else {
        /* guest agent expect time with nanosecond granularity.
         * Impressing. */
        long long json_time;

        /* Check if we overflow. For some reason qemu doesn't handle unsigned
1803
         * long long on the agent well as it silently truncates numbers to
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
         * signed long long. Therefore we must check overflow against LLONG_MAX
         * not ULLONG_MAX. */
        if (seconds > LLONG_MAX / 1000000000LL) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Time '%lld' is too big for guest agent"),
                           seconds);
            return ret;
        }

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

    if (!cmd)
        return ret;

1823
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
1824 1825 1826 1827 1828 1829 1830 1831
        goto cleanup;

    ret = 0;
 cleanup:
    virJSONValueFree(cmd);
    virJSONValueFree(reply);
    return ret;
}
1832

1833 1834 1835 1836 1837 1838
static void
qemuAgentDiskInfoFree(qemuAgentDiskInfoPtr info)
{
    if (!info)
        return;

1839 1840 1841 1842
    g_free(info->serial);
    g_free(info->bus_type);
    g_free(info->devnode);
    g_free(info);
1843 1844
}

1845
void
1846 1847 1848 1849 1850 1851 1852
qemuAgentFSInfoFree(qemuAgentFSInfoPtr info)
{
    size_t i;

    if (!info)
        return;

1853 1854 1855
    g_free(info->mountpoint);
    g_free(info->name);
    g_free(info->fstype);
1856 1857 1858

    for (i = 0; i < info->ndisks; i++)
        qemuAgentDiskInfoFree(info->disks[i]);
1859
    g_free(info->disks);
1860

1861
    g_free(info);
1862 1863 1864
}

static int
1865
qemuAgentGetFSInfoFillDisks(virJSONValuePtr jsondisks,
1866
                            qemuAgentFSInfoPtr fsinfo)
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
{
    size_t ndisks;
    size_t i;

    if (!virJSONValueIsArray(jsondisks)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed guest-get-fsinfo 'disk' data array"));
        return -1;
    }

    ndisks = virJSONValueArraySize(jsondisks);

1879 1880
    if (ndisks)
        fsinfo->disks = g_new0(qemuAgentDiskInfoPtr, ndisks);
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
    fsinfo->ndisks = ndisks;

    for (i = 0; i < fsinfo->ndisks; i++) {
        virJSONValuePtr jsondisk = virJSONValueArrayGet(jsondisks, i);
        virJSONValuePtr pci;
        qemuAgentDiskInfoPtr disk;
        const char *val;

        if (!jsondisk) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("array element '%zd' of '%zd' missing in "
                             "guest-get-fsinfo 'disk' data"),
                           i, fsinfo->ndisks);
            return -1;
        }

1897
        fsinfo->disks[i] = g_new0(qemuAgentDiskInfo, 1);
1898 1899
        disk = fsinfo->disks[i];

1900 1901 1902
        if ((val = virJSONValueObjectGetString(jsondisk, "bus-type")))
            disk->bus_type = g_strdup(val);

1903 1904
        if ((val = virJSONValueObjectGetString(jsondisk, "serial")))
            disk->serial = g_strdup(val);
1905

1906 1907
        if ((val = virJSONValueObjectGetString(jsondisk, "dev")))
            disk->devnode = g_strdup(val);
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918

#define GET_DISK_ADDR(jsonObject, var, name) \
        do { \
            if (virJSONValueObjectGetNumberUint(jsonObject, name, var) < 0) { \
                virReportError(VIR_ERR_INTERNAL_ERROR, \
                               _("'%s' missing in guest-get-fsinfo " \
                                 "'disk' data"), name); \
                return -1; \
            } \
        } while (0)

1919 1920 1921
        GET_DISK_ADDR(jsondisk, &disk->bus, "bus");
        GET_DISK_ADDR(jsondisk, &disk->target, "target");
        GET_DISK_ADDR(jsondisk, &disk->unit, "unit");
1922 1923 1924 1925 1926 1927 1928 1929

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

1930 1931 1932 1933
        GET_DISK_ADDR(pci, &disk->pci_controller.domain, "domain");
        GET_DISK_ADDR(pci, &disk->pci_controller.bus, "bus");
        GET_DISK_ADDR(pci, &disk->pci_controller.slot, "slot");
        GET_DISK_ADDR(pci, &disk->pci_controller.function, "function");
1934 1935 1936 1937 1938 1939
#undef GET_DISK_ADDR
    }

    return 0;
}

1940
/* Returns: number of entries in '@info' on success
1941 1942 1943
 *          -2 when agent command is not supported by the agent
 *          -1 otherwise
 */
1944
int
1945
qemuAgentGetFSInfo(qemuAgentPtr agent,
1946
                   qemuAgentFSInfoPtr **info)
1947
{
1948
    size_t i;
1949
    int ret = -1;
J
Ján Tomko 已提交
1950 1951
    g_autoptr(virJSONValue) cmd = NULL;
    g_autoptr(virJSONValue) reply = NULL;
1952
    virJSONValuePtr data;
1953 1954
    size_t ndata = 0;
    qemuAgentFSInfoPtr *info_ret = NULL;
1955 1956 1957 1958 1959

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

1960
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0) {
1961 1962
        if (qemuAgentErrorCommandUnsupported(reply))
            ret = -2;
1963
        goto cleanup;
1964
    }
1965 1966 1967 1968 1969 1970 1971

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

1972
    if (!virJSONValueIsArray(data)) {
1973
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1974
                       _("Malformed guest-get-fsinfo data array"));
1975 1976 1977 1978
        goto cleanup;
    }

    ndata = virJSONValueArraySize(data);
1979
    if (ndata == 0) {
1980
        ret = 0;
1981
        *info = NULL;
1982 1983
        goto cleanup;
    }
1984
    info_ret = g_new0(qemuAgentFSInfoPtr, ndata);
1985 1986 1987 1988

    for (i = 0; i < ndata; i++) {
        /* Reverse the order to arrange in mount order */
        virJSONValuePtr entry = virJSONValueArrayGet(data, ndata - 1 - i);
1989 1990 1991
        virJSONValuePtr disk;
        unsigned long long bytes_val;
        const char *result = NULL;
1992 1993 1994

        if (!entry) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
1995
                           _("array element '%zd' of '%zd' missing in "
1996 1997 1998 1999 2000
                             "guest-get-fsinfo return data"),
                           i, ndata);
            goto cleanup;
        }

2001
        info_ret[i] = g_new0(qemuAgentFSInfo, 1);
2002

2003
        if (!(result = virJSONValueObjectGetString(entry, "mountpoint"))) {
2004 2005 2006 2007 2008 2009
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'mountpoint' missing in reply of "
                             "guest-get-fsinfo"));
            goto cleanup;
        }

2010
        info_ret[i]->mountpoint = g_strdup(result);
2011 2012

        if (!(result = virJSONValueObjectGetString(entry, "name"))) {
2013 2014 2015 2016 2017
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'name' missing in reply of guest-get-fsinfo"));
            goto cleanup;
        }

2018
        info_ret[i]->name = g_strdup(result);
2019 2020

        if (!(result = virJSONValueObjectGetString(entry, "type"))) {
2021 2022 2023 2024 2025
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'type' missing in reply of guest-get-fsinfo"));
            goto cleanup;
        }

2026
        info_ret[i]->fstype = g_strdup(result);
2027

2028

2029 2030 2031 2032 2033 2034
        /* 'used-bytes' and 'total-bytes' were added in qemu-ga 3.0 */
        if (virJSONValueObjectHasKey(entry, "used-bytes")) {
            if (virJSONValueObjectGetNumberUlong(entry, "used-bytes",
                                                 &bytes_val) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Error getting 'used-bytes' in reply of guest-get-fsinfo"));
2035 2036
                goto cleanup;
            }
2037 2038 2039 2040
            info_ret[i]->used_bytes = bytes_val;
        } else {
            info_ret[i]->used_bytes = -1;
        }
2041

2042 2043 2044
        if (virJSONValueObjectHasKey(entry, "total-bytes")) {
            if (virJSONValueObjectGetNumberUlong(entry, "total-bytes",
                                                 &bytes_val) < 0) {
2045
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2046
                               _("Error getting 'total-bytes' in reply of guest-get-fsinfo"));
2047 2048
                goto cleanup;
            }
2049 2050 2051 2052
            info_ret[i]->total_bytes = bytes_val;
        } else {
            info_ret[i]->total_bytes = -1;
        }
2053

2054 2055 2056 2057
        if (!(disk = virJSONValueObjectGet(entry, "disk"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'disk' missing in reply of guest-get-fsinfo"));
            goto cleanup;
2058
        }
2059

2060
        if (qemuAgentGetFSInfoFillDisks(disk, info_ret[i]) < 0)
2061
            goto cleanup;
2062 2063
    }

2064
    *info = g_steal_pointer(&info_ret);
2065 2066 2067 2068 2069
    ret = ndata;

 cleanup:
    if (info_ret) {
        for (i = 0; i < ndata; i++)
2070
            qemuAgentFSInfoFree(info_ret[i]);
2071
        g_free(info_ret);
2072
    }
2073 2074 2075
    return ret;
}

2076 2077
/*
 * qemuAgentGetInterfaces:
2078
 * @agent: agent object
2079 2080 2081 2082 2083 2084 2085 2086 2087
 * @ifaces: pointer to an array of pointers pointing to interface objects
 *
 * Issue guest-network-get-interfaces to guest agent, which returns a
 * list of interfaces of a running domain along with their IP and MAC
 * addresses.
 *
 * Returns: number of interfaces on success, -1 on error.
 */
int
2088
qemuAgentGetInterfaces(qemuAgentPtr agent,
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
                       virDomainInterfacePtr **ifaces)
{
    int ret = -1;
    size_t i, j;
    virJSONValuePtr cmd = NULL;
    virJSONValuePtr reply = NULL;
    virJSONValuePtr ret_array = NULL;
    size_t ifaces_count = 0;
    size_t addrs_count = 0;
    virDomainInterfacePtr *ifaces_ret = NULL;
    virHashTablePtr ifaces_store = NULL;
    char **ifname = NULL;

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

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

2111
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
2112 2113 2114 2115 2116 2117 2118 2119
        goto cleanup;

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

2120
    if (!virJSONValueIsArray(ret_array)) {
2121 2122 2123 2124 2125
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("qemu agent didn't return an array of interfaces"));
        goto cleanup;
    }

2126
    for (i = 0; i < virJSONValueArraySize(ret_array); i++) {
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
        virJSONValuePtr tmp_iface = virJSONValueArrayGet(ret_array, i);
        virJSONValuePtr ip_addr_arr = NULL;
        const char *hwaddr, *ifname_s, *name = NULL;
        virDomainInterfacePtr iface = NULL;

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

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

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

        iface = virHashLookup(ifaces_store, ifname_s);

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

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

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

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

2168
            iface->name = g_strdup(ifname_s);
2169 2170

            hwaddr = virJSONValueObjectGetString(tmp_iface, "hardware-address");
2171
            iface->hwaddr = g_strdup(hwaddr);
2172 2173 2174
        }

        /* Has to be freed for each interface. */
2175
        virStringListFree(ifname);
2176 2177 2178 2179 2180 2181 2182

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

2183 2184 2185
        if (!virJSONValueIsArray(ip_addr_arr)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Malformed ip-addresses array"));
2186
            goto error;
2187
        }
2188 2189 2190 2191

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

2192
        for (j = 0; j < virJSONValueArraySize(ip_addr_arr); j++) {
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
            const char *type, *addr;
            virJSONValuePtr ip_addr_obj = virJSONValueArrayGet(ip_addr_arr, j);
            virDomainIPAddressPtr ip_addr;

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

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

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

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

            addr = virJSONValueObjectGetString(ip_addr_obj, "ip-address");
            if (!addr) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("qemu agent didn't provide 'ip-address'"
                                 " field for interface '%s'"), name);
                goto error;
            }
2233
            ip_addr->addr = g_strdup(addr);
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245

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

        iface->naddrs = addrs_count;
    }

2246
    *ifaces = g_steal_pointer(&ifaces_ret);
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
    ret = ifaces_count;

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

 error:
    if (ifaces_ret) {
        for (i = 0; i < ifaces_count; i++)
            virDomainInterfaceFree(ifaces_ret[i]);
    }
    VIR_FREE(ifaces_ret);
2261
    virStringListFree(ifname);
2262 2263 2264

    goto cleanup;
}
2265 2266 2267


int
2268
qemuAgentSetUserPassword(qemuAgentPtr agent,
2269 2270 2271 2272
                         const char *user,
                         const char *password,
                         bool crypted)
{
2273 2274 2275
    g_autoptr(virJSONValue) cmd = NULL;
    g_autoptr(virJSONValue) reply = NULL;
    g_autofree char *password64 = NULL;
2276

2277 2278
    password64 = g_base64_encode((unsigned char *)password,
                                 strlen(password));
2279 2280 2281 2282 2283 2284

    if (!(cmd = qemuAgentMakeCommand("guest-set-user-password",
                                     "b:crypted", crypted,
                                     "s:username", user,
                                     "s:password", password64,
                                     NULL)))
2285
        return -1;
2286

2287
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0)
2288
        return -1;
2289

2290
    return 0;
2291
}
2292

2293 2294 2295 2296
/* Returns: 0 on success
 *          -2 when agent command is not supported by the agent
 *          -1 otherwise
 */
2297
int
2298
qemuAgentGetUsers(qemuAgentPtr agent,
2299 2300 2301 2302
                  virTypedParameterPtr *params,
                  int *nparams,
                  int *maxparams)
{
J
Ján Tomko 已提交
2303 2304
    g_autoptr(virJSONValue) cmd = NULL;
    g_autoptr(virJSONValue) reply = NULL;
2305 2306 2307 2308 2309 2310 2311
    virJSONValuePtr data = NULL;
    size_t ndata;
    size_t i;

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

2312
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0) {
2313 2314
        if (qemuAgentErrorCommandUnsupported(reply))
            return -2;
2315
        return -1;
2316
    }
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354

    if (!(data = virJSONValueObjectGetArray(reply, "return"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest-get-users reply was missing return data"));
        return -1;
    }

    if (!virJSONValueIsArray(data)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed guest-get-users data array"));
        return -1;
    }

    ndata = virJSONValueArraySize(data);

    if (virTypedParamsAddUInt(params, nparams, maxparams,
                              "user.count", ndata) < 0)
        return -1;

    for (i = 0; i < ndata; i++) {
        virJSONValuePtr entry = virJSONValueArrayGet(data, i);
        char param_name[VIR_TYPED_PARAM_FIELD_LENGTH];
        const char *strvalue;
        double logintime;

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

        if (!(strvalue = virJSONValueObjectGetString(entry, "user"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'user' missing in reply of guest-get-users"));
            return -1;
        }

2355
        g_snprintf(param_name, VIR_TYPED_PARAM_FIELD_LENGTH, "user.%zu.name", i);
2356 2357 2358 2359 2360 2361
        if (virTypedParamsAddString(params, nparams, maxparams,
                                    param_name, strvalue) < 0)
            return -1;

        /* 'domain' is only present for windows guests */
        if ((strvalue = virJSONValueObjectGetString(entry, "domain"))) {
2362 2363
            g_snprintf(param_name, VIR_TYPED_PARAM_FIELD_LENGTH,
                       "user.%zu.domain", i);
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
            if (virTypedParamsAddString(params, nparams, maxparams,
                                        param_name, strvalue) < 0)
                return -1;
        }

        if (virJSONValueObjectGetNumberDouble(entry, "login-time", &logintime) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("'login-time' missing in reply of guest-get-users"));
            return -1;
        }
2374 2375
        g_snprintf(param_name, VIR_TYPED_PARAM_FIELD_LENGTH,
                   "user.%zu.login-time", i);
2376 2377 2378 2379 2380 2381 2382
        if (virTypedParamsAddULLong(params, nparams, maxparams,
                                    param_name, logintime * 1000) < 0)
            return -1;
    }

    return ndata;
}
2383

2384 2385 2386 2387
/* Returns: 0 on success
 *          -2 when agent command is not supported by the agent
 *          -1 otherwise
 */
2388
int
2389
qemuAgentGetOSInfo(qemuAgentPtr agent,
2390 2391 2392 2393
                   virTypedParameterPtr *params,
                   int *nparams,
                   int *maxparams)
{
J
Ján Tomko 已提交
2394 2395
    g_autoptr(virJSONValue) cmd = NULL;
    g_autoptr(virJSONValue) reply = NULL;
2396 2397 2398 2399 2400
    virJSONValuePtr data = NULL;

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

2401
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0) {
2402 2403
        if (qemuAgentErrorCommandUnsupported(reply))
            return -2;
2404
        return -1;
2405
    }
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435

    if (!(data = virJSONValueObjectGetObject(reply, "return"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest-get-osinfo reply was missing return data"));
        return -1;
    }

#define OSINFO_ADD_PARAM(agent_string_, param_string_) \
    do { \
        const char *result; \
        if ((result = virJSONValueObjectGetString(data, agent_string_))) { \
            if (virTypedParamsAddString(params, nparams, maxparams, \
                                        param_string_, result) < 0) { \
                return -1; \
            } \
        } \
    } while (0)
    OSINFO_ADD_PARAM("id", "os.id");
    OSINFO_ADD_PARAM("name", "os.name");
    OSINFO_ADD_PARAM("pretty-name", "os.pretty-name");
    OSINFO_ADD_PARAM("version", "os.version");
    OSINFO_ADD_PARAM("version-id", "os.version-id");
    OSINFO_ADD_PARAM("machine", "os.machine");
    OSINFO_ADD_PARAM("variant", "os.variant");
    OSINFO_ADD_PARAM("variant-id", "os.variant-id");
    OSINFO_ADD_PARAM("kernel-release", "os.kernel-release");
    OSINFO_ADD_PARAM("kernel-version", "os.kernel-version");

    return 0;
}
2436

2437 2438 2439 2440
/* Returns: 0 on success
 *          -2 when agent command is not supported by the agent
 *          -1 otherwise
 */
2441
int
2442
qemuAgentGetTimezone(qemuAgentPtr agent,
2443 2444 2445 2446
                     virTypedParameterPtr *params,
                     int *nparams,
                     int *maxparams)
{
J
Ján Tomko 已提交
2447 2448
    g_autoptr(virJSONValue) cmd = NULL;
    g_autoptr(virJSONValue) reply = NULL;
2449 2450 2451 2452 2453 2454 2455
    virJSONValuePtr data = NULL;
    const char *name;
    int offset;

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

2456
    if (qemuAgentCommand(agent, cmd, &reply, agent->timeout) < 0) {
2457 2458
        if (qemuAgentErrorCommandUnsupported(reply))
            return -2;
2459
        return -1;
2460
    }
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484

    if (!(data = virJSONValueObjectGetObject(reply, "return"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest-get-timezone reply was missing return data"));
        return -1;
    }

    if ((name = virJSONValueObjectGetString(data, "zone")) &&
        virTypedParamsAddString(params, nparams, maxparams,
                                "timezone.name", name) < 0)
        return -1;

    if ((virJSONValueObjectGetNumberInt(data, "offset", &offset)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("'offset' missing in reply of guest-get-timezone"));
        return -1;
    }

    if (virTypedParamsAddInt(params, nparams, maxparams,
                             "timezone.offset", offset) < 0)
        return -1;

    return 0;
}
2485 2486

/* qemuAgentSetResponseTimeout:
2487 2488
 * @agent: agent object
 * @timeout: number of seconds to wait for agent response
2489 2490 2491 2492
 *
 * The agent object must be locked prior to calling this function.
 */
void
2493
qemuAgentSetResponseTimeout(qemuAgentPtr agent,
2494 2495
                            int timeout)
{
2496
    agent->timeout = timeout;
2497
}