virsh-domain-monitor.c 71.0 KB
Newer Older
1 2 3
/*
 * virsh-domain-monitor.c: Commands to monitor domain status
 *
4
 * Copyright (C) 2005, 2007-2016 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
18 19 20 21 22 23 24 25
 * <http://www.gnu.org/licenses/>.
 *
 *  Daniel Veillard <veillard@redhat.com>
 *  Karel Zak <kzak@redhat.com>
 *  Daniel P. Berrange <berrange@redhat.com>
 *
 */

26 27
#include <config.h>
#include "virsh-domain-monitor.h"
28
#include "virsh-util.h"
29 30 31 32 33 34 35

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xmlsave.h>

#include "internal.h"
36
#include "conf/virdomainobjlist.h"
37
#include "intprops.h"
38
#include "viralloc.h"
39
#include "virmacaddr.h"
40
#include "virxml.h"
41
#include "virstring.h"
42
#include "vsh-table.h"
43

44 45
VIR_ENUM_DECL(virshDomainIOError)
VIR_ENUM_IMPL(virshDomainIOError,
46 47 48 49 50
              VIR_DOMAIN_DISK_ERROR_LAST,
              N_("no error"),
              N_("unspecified error"),
              N_("no space"))

51
static const char *
52
virshDomainIOErrorToString(int error)
53
{
54
    const char *str = virshDomainIOErrorTypeToString(error);
55
    return str ? _(str) : _("unknown error");
56 57 58
}

/* extract description or title from domain xml */
E
Eric Blake 已提交
59
char *
60 61
virshGetDomainDescription(vshControl *ctl, virDomainPtr dom, bool title,
                          unsigned int flags)
62 63 64 65 66 67 68 69 70 71 72 73 74 75
{
    char *desc = NULL;
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int type;

    if (title)
        type = VIR_DOMAIN_METADATA_TITLE;
    else
        type = VIR_DOMAIN_METADATA_DESCRIPTION;

    if ((desc = virDomainGetMetadata(dom, type, NULL, flags))) {
        return desc;
    } else {
76
        int errCode = virGetLastErrorCode();
77

78
        if (errCode == VIR_ERR_NO_DOMAIN_METADATA) {
79
            desc = vshStrdup(ctl, "");
80
            vshResetLibvirtError();
81 82 83
            return desc;
        }

84
        if (errCode != VIR_ERR_NO_SUPPORT)
85 86 87 88
            return desc;
    }

    /* fall back to xml */
89
    if (virshDomainGetXMLFromDom(ctl, dom, flags, &doc, &ctxt) < 0)
90
        goto cleanup;
91

92 93 94 95 96 97 98 99
    if (title)
        desc = virXPathString("string(./title[1])", ctxt);
    else
        desc = virXPathString("string(./description[1])", ctxt);

    if (!desc)
        desc = vshStrdup(ctl, "");

100
 cleanup:
101 102 103 104 105 106
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(doc);

    return desc;
}

107 108
VIR_ENUM_DECL(virshDomainControlState)
VIR_ENUM_IMPL(virshDomainControlState,
109 110 111 112 113 114
              VIR_DOMAIN_CONTROL_LAST,
              N_("ok"),
              N_("background job"),
              N_("occupied"),
              N_("error"))

115
static const char *
116
virshDomainControlStateToString(int state)
117
{
118
    const char *str = virshDomainControlStateTypeToString(state);
119
    return str ? _(str) : _("unknown");
120 121
}

122 123
VIR_ENUM_DECL(virshDomainControlErrorReason)
VIR_ENUM_IMPL(virshDomainControlErrorReason,
124 125 126 127 128 129 130
              VIR_DOMAIN_CONTROL_ERROR_REASON_LAST,
              "",
              N_("unknown"),
              N_("monitor failure"),
              N_("internal (locking) error"))

static const char *
131
virshDomainControlErrorReasonToString(int reason)
132
{
133
    const char *ret = virshDomainControlErrorReasonTypeToString(reason);
134 135 136
    return ret ? _(ret) : _("unknown");
}

137 138
VIR_ENUM_DECL(virshDomainState)
VIR_ENUM_IMPL(virshDomainState,
139 140 141 142 143 144 145 146 147 148
              VIR_DOMAIN_LAST,
              N_("no state"),
              N_("running"),
              N_("idle"),
              N_("paused"),
              N_("in shutdown"),
              N_("shut off"),
              N_("crashed"),
              N_("pmsuspended"))

149
static const char *
150
virshDomainStateToString(int state)
151
{
152
    const char *str = virshDomainStateTypeToString(state);
153
    return str ? _(str) : _("no state");
154 155
}

156 157
VIR_ENUM_DECL(virshDomainNostateReason)
VIR_ENUM_IMPL(virshDomainNostateReason,
158 159 160
              VIR_DOMAIN_NOSTATE_LAST,
              N_("unknown"))

161 162
VIR_ENUM_DECL(virshDomainRunningReason)
VIR_ENUM_IMPL(virshDomainRunningReason,
163
              VIR_DOMAIN_RUNNING_LAST,
Y
Yuri Chornoivan 已提交
164
              N_("unknown"),
165 166 167 168 169 170 171 172
              N_("booted"),
              N_("migrated"),
              N_("restored"),
              N_("from snapshot"),
              N_("unpaused"),
              N_("migration canceled"),
              N_("save canceled"),
              N_("event wakeup"),
173 174
              N_("crashed"),
              N_("post-copy"))
175

176 177
VIR_ENUM_DECL(virshDomainBlockedReason)
VIR_ENUM_IMPL(virshDomainBlockedReason,
178 179 180
              VIR_DOMAIN_BLOCKED_LAST,
              N_("unknown"))

181 182
VIR_ENUM_DECL(virshDomainPausedReason)
VIR_ENUM_IMPL(virshDomainPausedReason,
183 184 185 186 187 188 189 190 191 192 193
              VIR_DOMAIN_PAUSED_LAST,
              N_("unknown"),
              N_("user"),
              N_("migrating"),
              N_("saving"),
              N_("dumping"),
              N_("I/O error"),
              N_("watchdog"),
              N_("from snapshot"),
              N_("shutting down"),
              N_("creating snapshot"),
194
              N_("crashed"),
195 196 197
              N_("starting up"),
              N_("post-copy"),
              N_("post-copy failed"))
198

199 200
VIR_ENUM_DECL(virshDomainShutdownReason)
VIR_ENUM_IMPL(virshDomainShutdownReason,
201 202 203 204
              VIR_DOMAIN_SHUTDOWN_LAST,
              N_("unknown"),
              N_("user"))

205 206
VIR_ENUM_DECL(virshDomainShutoffReason)
VIR_ENUM_IMPL(virshDomainShutoffReason,
207 208 209 210 211 212 213 214 215 216
              VIR_DOMAIN_SHUTOFF_LAST,
              N_("unknown"),
              N_("shutdown"),
              N_("destroyed"),
              N_("crashed"),
              N_("migrated"),
              N_("saved"),
              N_("failed"),
              N_("from snapshot"))

217 218
VIR_ENUM_DECL(virshDomainCrashedReason)
VIR_ENUM_IMPL(virshDomainCrashedReason,
219 220 221 222
              VIR_DOMAIN_CRASHED_LAST,
              N_("unknown"),
              N_("panicked"))

223 224
VIR_ENUM_DECL(virshDomainPMSuspendedReason)
VIR_ENUM_IMPL(virshDomainPMSuspendedReason,
225 226 227
              VIR_DOMAIN_PMSUSPENDED_LAST,
              N_("unknown"))

228
static const char *
229
virshDomainStateReasonToString(int state, int reason)
230
{
231
    const char *str = NULL;
232 233
    switch ((virDomainState) state) {
    case VIR_DOMAIN_NOSTATE:
234
        str = virshDomainNostateReasonTypeToString(reason);
235 236
        break;
    case VIR_DOMAIN_RUNNING:
237
        str = virshDomainRunningReasonTypeToString(reason);
238 239
        break;
    case VIR_DOMAIN_BLOCKED:
240
        str = virshDomainBlockedReasonTypeToString(reason);
241 242
        break;
    case VIR_DOMAIN_PAUSED:
243
        str = virshDomainPausedReasonTypeToString(reason);
244 245
        break;
    case VIR_DOMAIN_SHUTDOWN:
246
        str = virshDomainShutdownReasonTypeToString(reason);
247 248
        break;
    case VIR_DOMAIN_SHUTOFF:
249
        str = virshDomainShutoffReasonTypeToString(reason);
250 251
        break;
    case VIR_DOMAIN_CRASHED:
252
        str = virshDomainCrashedReasonTypeToString(reason);
253 254
        break;
    case VIR_DOMAIN_PMSUSPENDED:
255
        str = virshDomainPMSuspendedReasonTypeToString(reason);
256 257 258 259 260
        break;
    case VIR_DOMAIN_LAST:
        ;
    }

261
    return str ? _(str) : _("unknown");
262 263 264 265 266 267
}

/*
 * "dommemstat" command
 */
static const vshCmdInfo info_dommemstat[] = {
268 269 270 271 272 273 274
    {.name = "help",
     .data = N_("get memory statistics for a domain")
    },
    {.name = "desc",
     .data = N_("Get memory statistics for a running domain.")
    },
    {.name = NULL}
275 276 277
};

static const vshCmdOptDef opts_dommemstat[] = {
278
    VIRSH_COMMON_OPT_DOMAIN_FULL(VIR_CONNECT_LIST_DOMAINS_ACTIVE),
279
    {.name = "period",
280
     .type = VSH_OT_INT,
281 282 283
     .flags = VSH_OFLAG_REQ_OPT,
     .help = N_("period in seconds to set collection")
    },
284
    VIRSH_COMMON_OPT_CONFIG(N_("affect next boot")),
285
    VIRSH_COMMON_OPT_LIVE(N_("affect running domain")),
286
    VIRSH_COMMON_OPT_CURRENT(N_("affect current domain")),
287
    {.name = NULL}
288 289 290 291 292 293 294
};

static bool
cmdDomMemStat(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *name;
295
    virDomainMemoryStatStruct stats[VIR_DOMAIN_MEMORY_STAT_NR];
296 297
    unsigned int nr_stats;
    size_t i;
E
Eric Blake 已提交
298
    bool ret = false;
299 300 301 302 303 304 305 306 307 308 309 310 311
    int rv = 0;
    int period = -1;
    bool config = vshCommandOptBool(cmd, "config");
    bool live = vshCommandOptBool(cmd, "live");
    bool current = vshCommandOptBool(cmd, "current");
    unsigned int flags = VIR_DOMAIN_AFFECT_CURRENT;

    VSH_EXCLUSIVE_OPTIONS_VAR(current, live);
    VSH_EXCLUSIVE_OPTIONS_VAR(current, config);
    if (config)
        flags |= VIR_DOMAIN_AFFECT_CONFIG;
    if (live)
        flags |= VIR_DOMAIN_AFFECT_LIVE;
312

313
    if (!(dom = virshCommandOptDomain(ctl, cmd, &name)))
314 315
        return false;

316 317 318 319 320 321 322 323
    /* If none of the options were specified and we're active
     * then be sure to allow active modification */
    if (!current && !live && !config && virDomainIsActive(dom) == 1)
        flags |= VIR_DOMAIN_AFFECT_LIVE;

    /* Providing a period will adjust the balloon driver collection period.
     * This is not really an unsigned long, but it
     */
324
    if ((rv = vshCommandOptInt(ctl, cmd, "period", &period)) < 0)
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
        goto cleanup;
    if (rv > 0) {
        if (period < 0) {
            vshError(ctl, _("Invalid collection period value '%d'"), period);
            goto cleanup;
        }

        if (virDomainSetMemoryStatsPeriod(dom, period, flags) < 0) {
            vshError(ctl, "%s",
                     _("Unable to change balloon collection period."));
        } else {
            ret = true;
        }
        goto cleanup;
    }

341 342 343
    nr_stats = virDomainMemoryStats(dom, stats, VIR_DOMAIN_MEMORY_STAT_NR, 0);
    if (nr_stats == -1) {
        vshError(ctl, _("Failed to get memory statistics for domain %s"), name);
344
        goto cleanup;
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    }

    for (i = 0; i < nr_stats; i++) {
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_IN)
            vshPrint(ctl, "swap_in %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_OUT)
            vshPrint(ctl, "swap_out %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT)
            vshPrint(ctl, "major_fault %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT)
            vshPrint(ctl, "minor_fault %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_UNUSED)
            vshPrint(ctl, "unused %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_AVAILABLE)
            vshPrint(ctl, "available %llu\n", stats[i].val);
360 361
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_USABLE)
            vshPrint(ctl, "usable %llu\n", stats[i].val);
362 363 364 365
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON)
            vshPrint(ctl, "actual %llu\n", stats[i].val);
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_RSS)
            vshPrint(ctl, "rss %llu\n", stats[i].val);
366 367
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_LAST_UPDATE)
            vshPrint(ctl, "last_update %llu\n", stats[i].val);
368 369
        if (stats[i].tag == VIR_DOMAIN_MEMORY_STAT_DISK_CACHES)
            vshPrint(ctl, "disk_caches %llu\n", stats[i].val);
370 371
    }

372
    ret = true;
373
 cleanup:
374
    virshDomainFree(dom);
375
    return ret;
376 377 378 379 380 381
}

/*
 * "domblkinfo" command
 */
static const vshCmdInfo info_domblkinfo[] = {
382 383 384 385 386 387 388
    {.name = "help",
     .data = N_("domain block device size information")
    },
    {.name = "desc",
     .data = N_("Get block device size info for a domain.")
    },
    {.name = NULL}
389 390 391
};

static const vshCmdOptDef opts_domblkinfo[] = {
392
    VIRSH_COMMON_OPT_DOMAIN_FULL(0),
393
    {.name = "device",
394
     .type = VSH_OT_STRING,
395
     .completer = virshDomainDiskTargetCompleter,
396 397
     .help = N_("block device")
    },
398 399 400 401
    {.name = "human",
     .type = VSH_OT_BOOL,
     .help = N_("Human readable output")
    },
402 403 404 405
    {.name = "all",
     .type = VSH_OT_BOOL,
     .help = N_("display all block devices info")
    },
406
    {.name = NULL}
407 408
};

409 410
static bool
cmdDomblkinfoGet(vshControl *ctl,
411
                   const virDomainBlockInfo *info,
412 413 414 415
                   char **cap,
                   char **alloc,
                   char **phy,
                   bool human)
416
{
417
    if (info->capacity == 0 && info->allocation == 0 && info->physical == 0) {
418 419 420
        *cap = vshStrdup(ctl, "-");
        *alloc = vshStrdup(ctl, "-");
        *phy = vshStrdup(ctl, "-");
421
    } else if (!human) {
422 423 424 425
        if (virAsprintf(cap, "%llu", info->capacity) < 0 ||
            virAsprintf(alloc, "%llu", info->allocation) < 0 ||
            virAsprintf(phy, "%llu", info->physical) < 0)
            return false;
426 427 428 429 430 431 432 433
    } else {
        double val_cap, val_alloc, val_phy;
        const char *unit_cap, *unit_alloc, *unit_phy;

        val_cap = vshPrettyCapacity(info->capacity, &unit_cap);
        val_alloc = vshPrettyCapacity(info->allocation, &unit_alloc);
        val_phy = vshPrettyCapacity(info->physical, &unit_phy);

434 435 436 437
        if (virAsprintf(cap, "%.3lf %s", val_cap, unit_cap) < 0 ||
            virAsprintf(alloc, "%.3lf %s", val_alloc, unit_alloc) < 0 ||
            virAsprintf(phy, "%.3lf %s", val_phy, unit_phy) < 0)
            return false;
438 439
    }

440
    return true;
441 442 443
}


444 445 446 447 448
static bool
cmdDomblkinfo(vshControl *ctl, const vshCmd *cmd)
{
    virDomainBlockInfo info;
    virDomainPtr dom;
449
    bool ret = false;
450
    bool human = false;
451
    bool all = false;
452
    const char *device = NULL;
453 454 455 456 457 458 459
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int ndisks;
    size_t i;
    xmlNodePtr *disks = NULL;
    char *target = NULL;
    char *protocol = NULL;
460 461 462
    char *cap = NULL;
    char *alloc = NULL;
    char *phy = NULL;
463
    vshTablePtr table = NULL;
464

465
    if (!(dom = virshCommandOptDomain(ctl, cmd, NULL)))
466 467
        return false;

468 469 470
    all = vshCommandOptBool(cmd, "all");
    if (!all && vshCommandOptStringQuiet(ctl, cmd, "device", &device) <= 0) {
        vshError(ctl, "command 'domblkinfo' requires <device> option");
471
        goto cleanup;
472
    }
473

474 475
    human = vshCommandOptBool(cmd, "human");

476 477 478 479 480 481 482 483 484 485 486
    if (all) {
        bool active = virDomainIsActive(dom) == 1;
        int rc;

        if (virshDomainGetXML(ctl, cmd, 0, &xmldoc, &ctxt) < 0)
            goto cleanup;

        ndisks = virXPathNodeSet("./devices/disk", ctxt, &disks);
        if (ndisks < 0)
            goto cleanup;

487 488 489 490
        /* title */
        table = vshTableNew(_("Target"), _("Capacity"), _("Allocation"), _("Physical"), NULL);
        if (!table)
            goto cleanup;
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

        for (i = 0; i < ndisks; i++) {
            ctxt->node = disks[i];
            protocol = virXPathString("string(./source/@protocol)", ctxt);
            target = virXPathString("string(./target/@dev)", ctxt);

            rc = virDomainGetBlockInfo(dom, target, &info, 0);

            if (rc < 0) {
                /* If protocol is present that's an indication of a networked
                 * storage device which cannot provide statistics, so generate
                 * 0 based data and get the next disk. */
                if (protocol && !active &&
                    virGetLastErrorCode() == VIR_ERR_INTERNAL_ERROR &&
                    virGetLastErrorDomain() == VIR_FROM_STORAGE) {
                    memset(&info, 0, sizeof(info));
                    vshResetLibvirtError();
                } else {
                    goto cleanup;
                }
            }

513 514
            if (!cmdDomblkinfoGet(ctl, &info, &cap, &alloc, &phy, human))
                goto cleanup;
515 516
            if (vshTableRowAppend(table, target, cap, alloc, phy, NULL) < 0)
                goto cleanup;
517 518 519 520

            VIR_FREE(target);
            VIR_FREE(protocol);
        }
521 522 523

        vshTablePrintToStdout(table, ctl);

524 525 526 527
    } else {
        if (virDomainGetBlockInfo(dom, device, &info, 0) < 0)
            goto cleanup;

528 529 530 531 532
        if (!cmdDomblkinfoGet(ctl, &info, &cap, &alloc, &phy, human))
            goto cleanup;
        vshPrint(ctl, "%-15s %s\n", _("Capacity:"), cap);
        vshPrint(ctl, "%-15s %s\n", _("Allocation:"), alloc);
        vshPrint(ctl, "%-15s %s\n", _("Physical:"), phy);
533
    }
534

535 536
    ret = true;

537
 cleanup:
538
    vshTableFree(table);
539 540 541
    VIR_FREE(cap);
    VIR_FREE(alloc);
    VIR_FREE(phy);
542
    virshDomainFree(dom);
543 544 545 546 547
    VIR_FREE(target);
    VIR_FREE(protocol);
    VIR_FREE(disks);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xmldoc);
548 549 550 551 552 553 554
    return ret;
}

/*
 * "domblklist" command
 */
static const vshCmdInfo info_domblklist[] = {
555 556 557 558 559 560 561
    {.name = "help",
     .data = N_("list all domain blocks")
    },
    {.name = "desc",
     .data = N_("Get the summary of block devices for a domain.")
    },
    {.name = NULL}
562 563 564
};

static const vshCmdOptDef opts_domblklist[] = {
565
    VIRSH_COMMON_OPT_DOMAIN_FULL(0),
566 567 568 569 570 571 572 573 574
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("get inactive rather than running configuration")
    },
    {.name = "details",
     .type = VSH_OT_BOOL,
     .help = N_("additionally display the type and device value")
    },
    {.name = NULL}
575 576 577 578 579 580 581 582 583 584 585
};

static bool
cmdDomblklist(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    unsigned int flags = 0;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int ndisks;
    xmlNodePtr *disks = NULL;
586
    size_t i;
587
    bool details = false;
588 589 590 591
    char *type = NULL;
    char *device = NULL;
    char *target = NULL;
    char *source = NULL;
592 593 594 595 596 597

    if (vshCommandOptBool(cmd, "inactive"))
        flags |= VIR_DOMAIN_XML_INACTIVE;

    details = vshCommandOptBool(cmd, "details");

598
    if (virshDomainGetXML(ctl, cmd, flags, &xmldoc, &ctxt) < 0)
599 600 601 602 603 604 605
        goto cleanup;

    ndisks = virXPathNodeSet("./devices/disk", ctxt, &disks);
    if (ndisks < 0)
        goto cleanup;

    if (details)
606 607
        vshPrintExtra(ctl, "%-10s %-10s %-10s %s\n", _("Type"),
                      _("Device"), _("Target"), _("Source"));
608
    else
609
        vshPrintExtra(ctl, "%-10s %s\n", _("Target"), _("Source"));
610

611
    vshPrintExtra(ctl, "------------------------------------------------\n");
612 613 614 615 616 617 618

    for (i = 0; i < ndisks; i++) {
        ctxt->node = disks[i];

        if (details) {
            type = virXPathString("string(./@type)", ctxt);
            device = virXPathString("string(./@device)", ctxt);
619 620 621 622
            if (!type || !device) {
                vshPrint(ctl, "unable to query block list details");
                goto cleanup;
            }
623 624 625 626 627 628 629 630 631 632
        }

        target = virXPathString("string(./target/@dev)", ctxt);
        if (!target) {
            vshError(ctl, "unable to query block list");
            goto cleanup;
        }
        source = virXPathString("string(./source/@file"
                                "|./source/@dev"
                                "|./source/@dir"
633 634
                                "|./source/@name"
                                "|./source/@volume)", ctxt);
635 636 637 638 639 640 641 642
        if (details) {
            vshPrint(ctl, "%-10s %-10s %-10s %s\n", type, device,
                     target, source ? source : "-");
        } else {
            vshPrint(ctl, "%-10s %s\n", target, source ? source : "-");
        }

        VIR_FREE(source);
643 644 645
        VIR_FREE(target);
        VIR_FREE(device);
        VIR_FREE(type);
646 647 648 649
    }

    ret = true;

650
 cleanup:
651 652 653 654
    VIR_FREE(source);
    VIR_FREE(target);
    VIR_FREE(device);
    VIR_FREE(type);
655 656
    VIR_FREE(disks);
    xmlXPathFreeContext(ctxt);
657
    xmlFreeDoc(xmldoc);
658 659 660 661 662 663 664 665 666 667 668 669 670
    return ret;
}

/*
 * "domiflist" command
 */
static const vshCmdInfo info_domiflist[] = {
    {"help", N_("list all domain virtual interfaces")},
    {"desc", N_("Get the summary of virtual interfaces for a domain.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_domiflist[] = {
671
    VIRSH_COMMON_OPT_DOMAIN_FULL(0),
672 673 674 675 676
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("get inactive rather than running configuration")
    },
    {.name = NULL}
677 678 679 680 681 682 683 684 685 686 687
};

static bool
cmdDomiflist(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    unsigned int flags = 0;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int ninterfaces;
    xmlNodePtr *interfaces = NULL;
688
    size_t i;
689 690 691 692

    if (vshCommandOptBool(cmd, "inactive"))
        flags |= VIR_DOMAIN_XML_INACTIVE;

693
    if (virshDomainGetXML(ctl, cmd, flags, &xmldoc, &ctxt) < 0)
694 695 696 697 698 699
        goto cleanup;

    ninterfaces = virXPathNodeSet("./devices/interface", ctxt, &interfaces);
    if (ninterfaces < 0)
        goto cleanup;

700 701 702
    vshPrintExtra(ctl, "%-10s %-10s %-10s %-11s %s\n", _("Interface"),
                  _("Type"), _("Source"), _("Model"), _("MAC"));
    vshPrintExtra(ctl, "-------------------------------------------------------\n");
703 704 705 706 707 708 709 710 711 712 713 714 715 716

    for (i = 0; i < ninterfaces; i++) {
        char *type = NULL;
        char *source = NULL;
        char *target = NULL;
        char *model = NULL;
        char *mac = NULL;

        ctxt->node = interfaces[i];
        type = virXPathString("string(./@type)", ctxt);

        source = virXPathString("string(./source/@bridge"
                                "|./source/@dev"
                                "|./source/@network"
717 718
                                "|./source/@name"
                                "|./source/@path)", ctxt);
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739

        target = virXPathString("string(./target/@dev)", ctxt);
        model = virXPathString("string(./model/@type)", ctxt);
        mac = virXPathString("string(./mac/@address)", ctxt);

        vshPrint(ctl, "%-10s %-10s %-10s %-11s %-10s\n",
                 target ? target : "-",
                 type,
                 source ? source : "-",
                 model ? model : "-",
                 mac ? mac : "-");

        VIR_FREE(type);
        VIR_FREE(source);
        VIR_FREE(target);
        VIR_FREE(model);
        VIR_FREE(mac);
    }

    ret = true;

740
 cleanup:
741 742 743 744 745 746 747 748 749 750
    VIR_FREE(interfaces);
    xmlFreeDoc(xmldoc);
    xmlXPathFreeContext(ctxt);
    return ret;
}

/*
 * "domif-getlink" command
 */
static const vshCmdInfo info_domif_getlink[] = {
751 752 753 754 755 756 757
    {.name = "help",
     .data = N_("get link state of a virtual interface")
    },
    {.name = "desc",
     .data = N_("Get link state of a domain's virtual interface.")
    },
    {.name = NULL}
758 759 760
};

static const vshCmdOptDef opts_domif_getlink[] = {
761
    VIRSH_COMMON_OPT_DOMAIN_FULL(0),
762 763 764
    {.name = "interface",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
765
     .completer = virshDomainInterfaceCompleter,
766 767 768 769 770 771
     .help = N_("interface device (MAC Address)")
    },
    {.name = "persistent",
     .type = VSH_OT_ALIAS,
     .help = "config"
    },
772
    VIRSH_COMMON_OPT_CONFIG(N_("Get persistent interface state")),
773
    {.name = NULL}
774 775 776 777 778 779 780
};

static bool
cmdDomIfGetLink(vshControl *ctl, const vshCmd *cmd)
{
    const char *iface = NULL;
    char *state = NULL;
781
    char *xpath = NULL;
782
    virMacAddr macaddr;
783
    char macstr[VIR_MAC_STRING_BUFLEN] = "";
784 785
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
786 787 788 789
    xmlNodePtr *interfaces = NULL;
    int ninterfaces;
    unsigned int flags = 0;
    bool ret = false;
790

791
    if (vshCommandOptStringReq(ctl, cmd, "interface", &iface) < 0)
792 793 794 795 796
        return false;

    if (vshCommandOptBool(cmd, "config"))
        flags = VIR_DOMAIN_XML_INACTIVE;

797
    if (virshDomainGetXML(ctl, cmd, flags, &xml, &ctxt) < 0)
798 799
        goto cleanup;

800 801 802 803 804 805
    /* normalize the mac addr */
    if (virMacAddrParse(iface, &macaddr) == 0)
        virMacAddrFormat(&macaddr, macstr);

    if (virAsprintf(&xpath, "/domain/devices/interface[(mac/@address = '%s') or "
                            "                          (target/@dev = '%s')]",
806
                           macstr, iface) < 0)
807 808
        goto cleanup;

809 810 811
    if ((ninterfaces = virXPathNodeSet(xpath, ctxt, &interfaces)) < 0) {
        vshError(ctl, _("Failed to extract interface information"));
        goto cleanup;
812 813
    }

814
    if (ninterfaces < 1) {
815 816 817 818
        if (macstr[0])
            vshError(ctl, _("Interface (mac: %s) not found."), macstr);
        else
            vshError(ctl, _("Interface (dev: %s) not found."), iface);
819

820
        goto cleanup;
821 822 823
    } else if (ninterfaces > 1) {
        vshError(ctl, _("multiple matching interfaces found"));
        goto cleanup;
824 825
    }

826
    ctxt->node = interfaces[0];
827

828 829 830
    if ((state = virXPathString("string(./link/@state)", ctxt)))
        vshPrint(ctl, "%s %s", iface, state);
    else
831
        vshPrint(ctl, "%s up", iface);
832 833

    ret = true;
834

835
 cleanup:
836 837 838
    VIR_FREE(state);
    VIR_FREE(interfaces);
    VIR_FREE(xpath);
839 840 841 842 843 844 845 846 847 848
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);

    return ret;
}

/*
 * "domcontrol" command
 */
static const vshCmdInfo info_domcontrol[] = {
849 850 851 852 853 854 855
    {.name = "help",
     .data = N_("domain control interface state")
    },
    {.name = "desc",
     .data = N_("Returns state of a control interface to the domain.")
    },
    {.name = NULL}
856 857 858
};

static const vshCmdOptDef opts_domcontrol[] = {
859
    VIRSH_COMMON_OPT_DOMAIN_FULL(VIR_CONNECT_LIST_DOMAINS_ACTIVE),
860
    {.name = NULL}
861 862 863 864 865 866 867 868 869
};

static bool
cmdDomControl(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    bool ret = true;
    virDomainControlInfo info;

870
    if (!(dom = virshCommandOptDomain(ctl, cmd, NULL)))
871 872 873 874 875 876 877 878 879 880
        return false;

    if (virDomainGetControlInfo(dom, &info, 0) < 0) {
        ret = false;
        goto cleanup;
    }

    if (info.state != VIR_DOMAIN_CONTROL_OK &&
        info.state != VIR_DOMAIN_CONTROL_ERROR) {
        vshPrint(ctl, "%s (%0.3fs)\n",
881
                 virshDomainControlStateToString(info.state),
882
                 info.stateTime / 1000.0);
883 884
    } else if (info.state == VIR_DOMAIN_CONTROL_ERROR && info.details > 0) {
        vshPrint(ctl, "%s: %s\n",
885 886
                 virshDomainControlStateToString(info.state),
                 virshDomainControlErrorReasonToString(info.details));
887 888
    } else {
        vshPrint(ctl, "%s\n",
889
                 virshDomainControlStateToString(info.state));
890 891
    }

892
 cleanup:
893
    virshDomainFree(dom);
894 895 896 897 898 899 900
    return ret;
}

/*
 * "domblkstat" command
 */
static const vshCmdInfo info_domblkstat[] = {
901 902 903 904 905 906 907 908
    {.name = "help",
     .data = N_("get device block stats for a domain")
    },
    {.name = "desc",
     .data = N_("Get device block stats for a running domain. See man page or "
                "use --human for explanation of fields")
    },
    {.name = NULL}
909 910 911
};

static const vshCmdOptDef opts_domblkstat[] = {
912
    VIRSH_COMMON_OPT_DOMAIN_FULL(VIR_CONNECT_LIST_DOMAINS_ACTIVE),
913
    {.name = "device",
914
     .type = VSH_OT_STRING,
915
     .flags = VSH_OFLAG_EMPTY_OK,
916
     .completer = virshDomainDiskTargetCompleter,
917 918 919 920 921 922 923
     .help = N_("block device")
    },
    {.name = "human",
     .type = VSH_OT_BOOL,
     .help = N_("print a more human readable output")
    },
    {.name = NULL}
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
};

struct _domblkstat_sequence {
    const char *field;  /* field name */
    const char *legacy; /* legacy name from previous releases */
    const char *human;  /* human-friendly explanation */
};

/* sequence of values for output to honor legacy format from previous
 * versions */
static const struct _domblkstat_sequence domblkstat_output[] = {
    { VIR_DOMAIN_BLOCK_STATS_READ_REQ,          "rd_req",
      N_("number of read operations:") }, /* 0 */
    { VIR_DOMAIN_BLOCK_STATS_READ_BYTES,        "rd_bytes",
      N_("number of bytes read:") }, /* 1 */
    { VIR_DOMAIN_BLOCK_STATS_WRITE_REQ,         "wr_req",
      N_("number of write operations:") }, /* 2 */
    { VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES,       "wr_bytes",
      N_("number of bytes written:") }, /* 3 */
    { VIR_DOMAIN_BLOCK_STATS_ERRS,              "errs",
      N_("error count:") }, /* 4 */
    { VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ,         NULL,
      N_("number of flush operations:") }, /* 5 */
    { VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES,  NULL,
      N_("total duration of reads (ns):") }, /* 6 */
    { VIR_DOMAIN_BLOCK_STATS_WRITE_TOTAL_TIMES, NULL,
      N_("total duration of writes (ns):") }, /* 7 */
    { VIR_DOMAIN_BLOCK_STATS_FLUSH_TOTAL_TIMES, NULL,
      N_("total duration of flushes (ns):") }, /* 8 */
    { NULL, NULL, NULL }
};

956 957 958 959
#define DOMBLKSTAT_LEGACY_PRINT(ID, VALUE) \
    if (VALUE >= 0) \
        vshPrint(ctl, "%s %-*s %lld\n", device, \
                 human ? 31 : 0, \
960
                 human ? _(domblkstat_output[ID].human) \
961
                 : domblkstat_output[ID].legacy, \
962 963 964 965 966 967 968
                 VALUE);

static bool
cmdDomblkstat(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *name = NULL, *device = NULL;
969
    virDomainBlockStatsStruct stats;
970 971 972 973 974
    virTypedParameterPtr params = NULL;
    virTypedParameterPtr par = NULL;
    char *value = NULL;
    const char *field = NULL;
    int rc, nparams = 0;
975
    size_t i;
976 977 978
    bool ret = false;
    bool human = vshCommandOptBool(cmd, "human"); /* human readable output */

979
    if (!(dom = virshCommandOptDomain(ctl, cmd, &name)))
980 981
        return false;

982 983 984 985
    /* device argument is optional now. if it's missing, supply empty
       string to denote 'all devices'. A NULL device arg would violate
       API contract.
     */
986
    if (vshCommandOptStringReq(ctl, cmd, "device", &device) < 0)
987 988
        goto cleanup;

989 990 991
    if (!device)
        device = "";

992 993 994 995 996 997 998 999 1000 1001 1002
    rc = virDomainBlockStatsFlags(dom, device, NULL, &nparams, 0);

    /* It might fail when virDomainBlockStatsFlags is not
     * supported on older libvirt, fallback to use virDomainBlockStats
     * then.
     */
    if (rc < 0) {
        /* try older API if newer is not supported */
        if (last_error->code != VIR_ERR_NO_SUPPORT)
            goto cleanup;

1003
        vshResetLibvirtError();
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

        if (virDomainBlockStats(dom, device, &stats,
                                sizeof(stats)) == -1) {
            vshError(ctl, _("Failed to get block stats %s %s"),
                     name, device);
            goto cleanup;
        }

        /* human friendly output */
        if (human) {
            vshPrint(ctl, N_("Device: %s\n"), device);
            device = "";
        }

        DOMBLKSTAT_LEGACY_PRINT(0, stats.rd_req);
        DOMBLKSTAT_LEGACY_PRINT(1, stats.rd_bytes);
        DOMBLKSTAT_LEGACY_PRINT(2, stats.wr_req);
        DOMBLKSTAT_LEGACY_PRINT(3, stats.wr_bytes);
        DOMBLKSTAT_LEGACY_PRINT(4, stats.errs);
    } else {
        params = vshCalloc(ctl, nparams, sizeof(*params));

        if (virDomainBlockStatsFlags(dom, device, params, &nparams, 0) < 0) {
1027
            vshError(ctl, _("Failed to get block stats for domain '%s' device '%s'"), name, device);
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
            goto cleanup;
        }

        /* set for prettier output */
        if (human) {
            vshPrint(ctl, N_("Device: %s\n"), device);
            device = "";
        }

        /* at first print all known values in desired order */
        for (i = 0; domblkstat_output[i].field != NULL; i++) {
1039 1040
            if (!(par = virTypedParamsGet(params, nparams,
                                          domblkstat_output[i].field)))
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
                continue;

            value = vshGetTypedParamValue(ctl, par);

            /* to print other not supported fields, mark the already printed */
            par->field[0] = '\0'; /* set the name to empty string */

            /* translate into human readable or legacy spelling */
            field = NULL;
            if (human)
                field = _(domblkstat_output[i].human);
            else
                field = domblkstat_output[i].legacy;

            /* use the provided spelling if no translation is available */
            if (!field)
                field = domblkstat_output[i].field;

            vshPrint(ctl, "%s %-*s %s\n", device,
                     human ? 31 : 0, field, value);

            VIR_FREE(value);
        }

        /* go through the fields again, for remaining fields */
        for (i = 0; i < nparams; i++) {
            if (!*params[i].field)
                continue;

            value = vshGetTypedParamValue(ctl, params+i);
            vshPrint(ctl, "%s %s %s\n", device, params[i].field, value);
            VIR_FREE(value);
        }
    }

    ret = true;

1078
 cleanup:
1079
    VIR_FREE(params);
1080
    virshDomainFree(dom);
1081 1082 1083 1084 1085 1086 1087 1088
    return ret;
}
#undef DOMBLKSTAT_LEGACY_PRINT

/*
 * "domifstat" command
 */
static const vshCmdInfo info_domifstat[] = {
1089 1090 1091 1092 1093 1094 1095
    {.name = "help",
     .data = N_("get network interface stats for a domain")
    },
    {.name = "desc",
     .data = N_("Get network interface stats for a running domain.")
    },
    {.name = NULL}
1096 1097 1098
};

static const vshCmdOptDef opts_domifstat[] = {
1099
    VIRSH_COMMON_OPT_DOMAIN_FULL(VIR_CONNECT_LIST_DOMAINS_ACTIVE),
1100 1101 1102
    {.name = "interface",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
1103
     .completer = virshDomainInterfaceCompleter,
1104
     .help = N_("interface device specified by name or MAC Address")
1105 1106
    },
    {.name = NULL}
1107 1108 1109 1110 1111 1112 1113
};

static bool
cmdDomIfstat(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    const char *name = NULL, *device = NULL;
1114
    virDomainInterfaceStatsStruct stats;
1115
    bool ret = false;
1116

1117
    if (!(dom = virshCommandOptDomain(ctl, cmd, &name)))
1118 1119
        return false;

1120 1121
    if (vshCommandOptStringReq(ctl, cmd, "interface", &device) < 0)
        goto cleanup;
1122 1123 1124

    if (virDomainInterfaceStats(dom, device, &stats, sizeof(stats)) == -1) {
        vshError(ctl, _("Failed to get interface stats %s %s"), name, device);
1125
        goto cleanup;
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
    }

    if (stats.rx_bytes >= 0)
        vshPrint(ctl, "%s rx_bytes %lld\n", device, stats.rx_bytes);

    if (stats.rx_packets >= 0)
        vshPrint(ctl, "%s rx_packets %lld\n", device, stats.rx_packets);

    if (stats.rx_errs >= 0)
        vshPrint(ctl, "%s rx_errs %lld\n", device, stats.rx_errs);

    if (stats.rx_drop >= 0)
        vshPrint(ctl, "%s rx_drop %lld\n", device, stats.rx_drop);

    if (stats.tx_bytes >= 0)
        vshPrint(ctl, "%s tx_bytes %lld\n", device, stats.tx_bytes);

    if (stats.tx_packets >= 0)
        vshPrint(ctl, "%s tx_packets %lld\n", device, stats.tx_packets);

    if (stats.tx_errs >= 0)
        vshPrint(ctl, "%s tx_errs %lld\n", device, stats.tx_errs);

    if (stats.tx_drop >= 0)
        vshPrint(ctl, "%s tx_drop %lld\n", device, stats.tx_drop);

1152 1153
    ret = true;

1154
 cleanup:
1155
    virshDomainFree(dom);
1156
    return ret;
1157 1158 1159 1160 1161 1162
}

/*
 * "domblkerror" command
 */
static const vshCmdInfo info_domblkerror[] = {
1163 1164 1165 1166 1167 1168 1169
    {.name = "help",
     .data = N_("Show errors on block devices")
    },
    {.name = "desc",
     .data = N_("Show block device errors")
    },
    {.name = NULL}
1170 1171 1172
};

static const vshCmdOptDef opts_domblkerror[] = {
1173
    VIRSH_COMMON_OPT_DOMAIN_FULL(VIR_CONNECT_LIST_DOMAINS_ACTIVE),
1174
    {.name = NULL}
1175 1176 1177 1178 1179 1180 1181 1182
};

static bool
cmdDomBlkError(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    virDomainDiskErrorPtr disks = NULL;
    unsigned int ndisks;
1183
    size_t i;
1184 1185 1186
    int count;
    bool ret = false;

1187
    if (!(dom = virshCommandOptDomain(ctl, cmd, NULL)))
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        return false;

    if ((count = virDomainGetDiskErrors(dom, NULL, 0, 0)) < 0)
        goto cleanup;
    ndisks = count;

    if (ndisks) {
        if (VIR_ALLOC_N(disks, ndisks) < 0)
            goto cleanup;

        if ((count = virDomainGetDiskErrors(dom, disks, ndisks, 0)) == -1)
            goto cleanup;
    }

    if (count == 0) {
        vshPrint(ctl, _("No errors found\n"));
    } else {
        for (i = 0; i < count; i++) {
            vshPrint(ctl, "%s: %s\n",
                     disks[i].disk,
1208
                     virshDomainIOErrorToString(disks[i].error));
1209 1210 1211 1212 1213
        }
    }

    ret = true;

1214
 cleanup:
1215
    VIR_FREE(disks);
1216
    virshDomainFree(dom);
1217 1218 1219 1220 1221 1222 1223
    return ret;
}

/*
 * "dominfo" command
 */
static const vshCmdInfo info_dominfo[] = {
1224 1225 1226 1227 1228 1229 1230
    {.name = "help",
     .data = N_("domain information")
    },
    {.name = "desc",
     .data = N_("Returns basic information about the domain.")
    },
    {.name = NULL}
1231 1232 1233
};

static const vshCmdOptDef opts_dominfo[] = {
1234
    VIRSH_COMMON_OPT_DOMAIN_FULL(0),
1235
    {.name = NULL}
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
};

static bool
cmdDominfo(vshControl *ctl, const vshCmd *cmd)
{
    virDomainInfo info;
    virDomainPtr dom;
    virSecurityModel secmodel;
    virSecurityLabelPtr seclabel;
    int persistent = 0;
    bool ret = true;
    int autostart;
    unsigned int id;
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
    int has_managed_save = 0;
1251
    virshControlPtr priv = ctl->privData;
1252

1253
    if (!(dom = virshCommandOptDomain(ctl, cmd, NULL)))
1254 1255 1256 1257 1258 1259 1260 1261 1262
        return false;

    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
        vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
    else
        vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

1263
    if (virDomainGetUUIDString(dom, &uuid[0]) == 0)
1264 1265 1266 1267 1268 1269 1270 1271 1272
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);

    if ((str = virDomainGetOSType(dom))) {
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
        VIR_FREE(str);
    }

    if (virDomainGetInfo(dom, &info) == 0) {
        vshPrint(ctl, "%-15s %s\n", _("State:"),
1273
                 virshDomainStateToString(info.state));
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310

        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);

        if (info.cpuTime != 0) {
            double cpuUsed = info.cpuTime;

            cpuUsed /= 1000000000.0;

            vshPrint(ctl, "%-15s %.1lfs\n", _("CPU time:"), cpuUsed);
        }

        if (info.maxMem != UINT_MAX)
            vshPrint(ctl, "%-15s %lu KiB\n", _("Max memory:"),
                 info.maxMem);
        else
            vshPrint(ctl, "%-15s %s\n", _("Max memory:"),
                 _("no limit"));

        vshPrint(ctl, "%-15s %lu KiB\n", _("Used memory:"),
                 info.memory);

    } else {
        ret = false;
    }

    /* Check and display whether the domain is persistent or not */
    persistent = virDomainIsPersistent(dom);
    vshDebug(ctl, VSH_ERR_DEBUG, "Domain persistent flag value: %d\n",
             persistent);
    if (persistent < 0)
        vshPrint(ctl, "%-15s %s\n", _("Persistent:"), _("unknown"));
    else
        vshPrint(ctl, "%-15s %s\n", _("Persistent:"), persistent ? _("yes") : _("no"));

    /* Check and display whether the domain autostarts or not */
    if (!virDomainGetAutostart(dom, &autostart)) {
        vshPrint(ctl, "%-15s %s\n", _("Autostart:"),
1311
                 autostart ? _("enable") : _("disable"));
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    }

    has_managed_save = virDomainHasManagedSaveImage(dom, 0);
    if (has_managed_save < 0)
        vshPrint(ctl, "%-15s %s\n", _("Managed save:"), _("unknown"));
    else
        vshPrint(ctl, "%-15s %s\n", _("Managed save:"),
                 has_managed_save ? _("yes") : _("no"));

    /* Security model and label information */
    memset(&secmodel, 0, sizeof(secmodel));
1323
    if (virNodeGetSecurityModel(priv->conn, &secmodel) == -1) {
1324
        if (last_error->code != VIR_ERR_NO_SUPPORT) {
1325
            virshDomainFree(dom);
1326 1327
            return false;
        } else {
1328
            vshResetLibvirtError();
1329 1330 1331 1332 1333 1334 1335 1336 1337
        }
    } else {
        /* Only print something if a security model is active */
        if (secmodel.model[0] != '\0') {
            vshPrint(ctl, "%-15s %s\n", _("Security model:"), secmodel.model);
            vshPrint(ctl, "%-15s %s\n", _("Security DOI:"), secmodel.doi);

            /* Security labels are only valid for active domains */
            if (VIR_ALLOC(seclabel) < 0) {
1338
                virshDomainFree(dom);
1339 1340 1341 1342
                return false;
            }

            if (virDomainGetSecurityLabel(dom, seclabel) == -1) {
1343
                virshDomainFree(dom);
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
                VIR_FREE(seclabel);
                return false;
            } else {
                if (seclabel->label[0] != '\0')
                    vshPrint(ctl, "%-15s %s (%s)\n", _("Security label:"),
                             seclabel->label, seclabel->enforcing ? "enforcing" : "permissive");
            }

            VIR_FREE(seclabel);
        }
    }
1355
    virshDomainFree(dom);
1356 1357 1358 1359 1360 1361 1362
    return ret;
}

/*
 * "domstate" command
 */
static const vshCmdInfo info_domstate[] = {
1363 1364 1365 1366 1367 1368 1369
    {.name = "help",
     .data = N_("domain state")
    },
    {.name = "desc",
     .data = N_("Returns state about a domain.")
    },
    {.name = NULL}
1370 1371 1372
};

static const vshCmdOptDef opts_domstate[] = {
1373
    VIRSH_COMMON_OPT_DOMAIN_FULL(0),
1374 1375 1376 1377 1378
    {.name = "reason",
     .type = VSH_OT_BOOL,
     .help = N_("also print reason for the state")
    },
    {.name = NULL}
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
};

static bool
cmdDomstate(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    bool ret = true;
    bool showReason = vshCommandOptBool(cmd, "reason");
    int state, reason;

1389
    if (!(dom = virshCommandOptDomain(ctl, cmd, NULL)))
1390 1391
        return false;

1392
    if ((state = virshDomainState(ctl, dom, &reason)) < 0) {
1393 1394 1395 1396 1397 1398
        ret = false;
        goto cleanup;
    }

    if (showReason) {
        vshPrint(ctl, "%s (%s)\n",
1399 1400
                 virshDomainStateToString(state),
                 virshDomainStateReasonToString(state, reason));
1401 1402
    } else {
        vshPrint(ctl, "%s\n",
1403
                 virshDomainStateToString(state));
1404 1405
    }

1406
 cleanup:
1407
    virshDomainFree(dom);
1408 1409 1410
    return ret;
}

1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
/*
 * "domtime" command
 */
static const vshCmdInfo info_domtime[] = {
    {.name = "help",
     .data = N_("domain time")
    },
    {.name = "desc",
     .data = N_("Gets or sets the domain's system time")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_domtime[] = {
1425
    VIRSH_COMMON_OPT_DOMAIN_FULL(VIR_CONNECT_LIST_DOMAINS_ACTIVE),
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
    {.name = "now",
     .type = VSH_OT_BOOL,
     .help = N_("set to the time of the host running virsh")
    },
    {.name = "pretty",
     .type = VSH_OT_BOOL,
     .help = N_("print domain's time in human readable form")
    },
    {.name = "sync",
     .type = VSH_OT_BOOL,
     .help = N_("instead of setting given time, synchronize from domain's RTC"),
    },
    {.name = "time",
     .type = VSH_OT_INT,
     .help = N_("time to set")
    },
    {.name = NULL}
};

static bool
cmdDomTime(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    bool ret = false;
    bool now = vshCommandOptBool(cmd, "now");
    bool pretty = vshCommandOptBool(cmd, "pretty");
E
Eric Blake 已提交
1452
    bool rtcSync = vshCommandOptBool(cmd, "sync");
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    long long seconds = 0;
    unsigned int nseconds = 0;
    unsigned int flags = 0;
    bool doSet = false;
    int rv;

    VSH_EXCLUSIVE_OPTIONS("time", "now");
    VSH_EXCLUSIVE_OPTIONS("time", "sync");
    VSH_EXCLUSIVE_OPTIONS("now", "sync");

1463
    if (!(dom = virshCommandOptDomain(ctl, cmd, NULL)))
1464 1465
        return false;

1466
    rv = vshCommandOptLongLong(ctl, cmd, "time", &seconds);
1467 1468 1469 1470 1471 1472 1473 1474 1475

    if (rv < 0) {
        /* invalid integer format */
        goto cleanup;
    } else if (rv > 0) {
        /* valid integer to set */
        doSet = true;
    }

E
Eric Blake 已提交
1476
    if (doSet || now || rtcSync) {
1477 1478 1479 1480 1481
        if (now && ((seconds = time(NULL)) == (time_t) -1)) {
            vshError(ctl, _("Unable to get current time"));
            goto cleanup;
        }

E
Eric Blake 已提交
1482
        if (rtcSync)
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
            flags |= VIR_DOMAIN_TIME_SYNC;

        if (virDomainSetTime(dom, seconds, nseconds, flags) < 0)
            goto cleanup;

    } else {
        if (virDomainGetTime(dom, &seconds, &nseconds, flags) < 0)
            goto cleanup;

        if (pretty) {
            char timestr[100];
            time_t cur_time = seconds;
            struct tm time_info;

            if (!gmtime_r(&cur_time, &time_info)) {
                vshError(ctl, _("Unable to format time"));
                goto cleanup;
            }
            strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", &time_info);

            vshPrint(ctl, _("Time: %s"), timestr);
        } else {
            vshPrint(ctl, _("Time: %lld"), seconds);
        }
    }

    ret = true;
 cleanup:
1511
    virshDomainFree(dom);
1512 1513 1514
    return ret;
}

1515 1516 1517 1518
/*
 * "list" command
 */
static const vshCmdInfo info_list[] = {
1519 1520 1521 1522 1523 1524 1525
    {.name = "help",
     .data = N_("list domains")
    },
    {.name = "desc",
     .data = N_("Returns list of domains.")
    },
    {.name = NULL}
1526 1527 1528 1529
};

/* compare domains, pack NULLed ones at the end*/
static int
1530
virshDomainSorter(const void *a, const void *b)
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
{
    virDomainPtr *da = (virDomainPtr *) a;
    virDomainPtr *db = (virDomainPtr *) b;
    unsigned int ida;
    unsigned int idb;
    unsigned int inactive = (unsigned int) -1;

    if (*da && !*db)
        return -1;

    if (!*da)
        return *db != NULL;

    ida = virDomainGetID(*da);
    idb = virDomainGetID(*db);

    if (ida == inactive && idb == inactive)
1548
        return vshStrcasecmp(virDomainGetName(*da), virDomainGetName(*db));
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562

    if (ida != inactive && idb != inactive) {
        if (ida > idb)
            return 1;
        else if (ida < idb)
            return -1;
    }

    if (ida != inactive)
        return -1;
    else
        return 1;
}

1563
struct virshDomainList {
1564 1565 1566
    virDomainPtr *domains;
    size_t ndomains;
};
1567
typedef struct virshDomainList *virshDomainListPtr;
1568 1569

static void
1570
virshDomainListFree(virshDomainListPtr domlist)
1571
{
1572
    size_t i;
1573 1574 1575 1576

    if (domlist && domlist->domains) {
        for (i = 0; i < domlist->ndomains; i++) {
            if (domlist->domains[i])
1577
                virshDomainFree(domlist->domains[i]);
1578 1579 1580 1581 1582 1583
        }
        VIR_FREE(domlist->domains);
    }
    VIR_FREE(domlist);
}

1584 1585
static virshDomainListPtr
virshDomainListCollect(vshControl *ctl, unsigned int flags)
1586
{
1587
    virshDomainListPtr list = vshMalloc(ctl, sizeof(*list));
1588
    size_t i;
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
    int ret;
    int *ids = NULL;
    int nids = 0;
    char **names = NULL;
    int nnames = 0;
    virDomainPtr dom;
    bool success = false;
    size_t deleted = 0;
    int persistent;
    int autostart;
    int state;
    int nsnap;
    int mansave;
1602
    virshControlPtr priv = ctl->privData;
1603 1604

    /* try the list with flags support (0.9.13 and later) */
1605
    if ((ret = virConnectListAllDomains(priv->conn, &list->domains,
1606 1607 1608 1609 1610 1611 1612
                                        flags)) >= 0) {
        list->ndomains = ret;
        goto finished;
    }

    /* check if the command is actually supported */
    if (last_error && last_error->code == VIR_ERR_NO_SUPPORT) {
1613
        vshResetLibvirtError();
1614 1615 1616 1617 1618 1619 1620 1621
        goto fallback;
    }

    if (last_error && last_error->code ==  VIR_ERR_INVALID_ARG) {
        /* try the new API again but mask non-guaranteed flags */
        unsigned int newflags = flags & (VIR_CONNECT_LIST_DOMAINS_ACTIVE |
                                         VIR_CONNECT_LIST_DOMAINS_INACTIVE);

1622
        vshResetLibvirtError();
1623
        if ((ret = virConnectListAllDomains(priv->conn, &list->domains,
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
                                            newflags)) >= 0) {
            list->ndomains = ret;
            goto filter;
        }
    }

    /* there was an error during the first or second call */
    vshError(ctl, "%s", _("Failed to list domains"));
    goto cleanup;


1635
 fallback:
1636
    /* fall back to old method (0.9.12 and older) */
1637
    vshResetLibvirtError();
1638 1639

    /* list active domains, if necessary */
1640 1641
    if (!VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
        VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE)) {
1642
        if ((nids = virConnectNumOfDomains(priv->conn)) < 0) {
1643 1644 1645 1646 1647 1648 1649
            vshError(ctl, "%s", _("Failed to list active domains"));
            goto cleanup;
        }

        if (nids) {
            ids = vshMalloc(ctl, sizeof(int) * nids);

1650
            if ((nids = virConnectListDomains(priv->conn, ids, nids)) < 0) {
1651 1652 1653 1654 1655 1656
                vshError(ctl, "%s", _("Failed to list active domains"));
                goto cleanup;
            }
        }
    }

1657 1658
    if (!VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
        VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE)) {
1659
        if ((nnames = virConnectNumOfDefinedDomains(priv->conn)) < 0) {
1660 1661 1662 1663 1664 1665 1666
            vshError(ctl, "%s", _("Failed to list inactive domains"));
            goto cleanup;
        }

        if (nnames) {
            names = vshMalloc(ctl, sizeof(char *) * nnames);

1667
            if ((nnames = virConnectListDefinedDomains(priv->conn, names,
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
                                                      nnames)) < 0) {
                vshError(ctl, "%s", _("Failed to list inactive domains"));
                goto cleanup;
            }
        }
    }

    list->domains = vshMalloc(ctl, sizeof(virDomainPtr) * (nids + nnames));
    list->ndomains = 0;

    /* get active domains */
    for (i = 0; i < nids; i++) {
1680
        if (!(dom = virDomainLookupByID(priv->conn, ids[i])))
1681 1682 1683 1684 1685 1686
            continue;
        list->domains[list->ndomains++] = dom;
    }

    /* get inactive domains */
    for (i = 0; i < nnames; i++) {
1687
        if (!(dom = virDomainLookupByName(priv->conn, names[i])))
1688 1689 1690 1691 1692 1693 1694
            continue;
        list->domains[list->ndomains++] = dom;
    }

    /* truncate domains that weren't found */
    deleted = (nids + nnames) - list->ndomains;

1695
 filter:
1696 1697 1698 1699 1700
    /* filter list the list if the list was acquired by fallback means */
    for (i = 0; i < list->ndomains; i++) {
        dom = list->domains[i];

        /* persistence filter */
1701
        if (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_PERSISTENT)) {
1702 1703 1704 1705 1706
            if ((persistent = virDomainIsPersistent(dom)) < 0) {
                vshError(ctl, "%s", _("Failed to get domain persistence info"));
                goto cleanup;
            }

1707 1708
            if (!((VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT) && persistent) ||
                  (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) && !persistent)))
1709 1710 1711 1712
                goto remove_entry;
        }

        /* domain state filter */
1713
        if (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE)) {
1714 1715 1716 1717 1718
            if (virDomainGetState(dom, &state, NULL, 0) < 0) {
                vshError(ctl, "%s", _("Failed to get domain state"));
                goto cleanup;
            }

1719
            if (!((VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
1720
                   state == VIR_DOMAIN_RUNNING) ||
1721
                  (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
1722
                   state == VIR_DOMAIN_PAUSED) ||
1723
                  (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
1724
                   state == VIR_DOMAIN_SHUTOFF) ||
1725
                  (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
1726 1727 1728 1729 1730 1731 1732
                   (state != VIR_DOMAIN_RUNNING &&
                    state != VIR_DOMAIN_PAUSED &&
                    state != VIR_DOMAIN_SHUTOFF))))
                goto remove_entry;
        }

        /* autostart filter */
1733
        if (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
1734 1735 1736 1737 1738
            if (virDomainGetAutostart(dom, &autostart) < 0) {
                vshError(ctl, "%s", _("Failed to get domain autostart state"));
                goto cleanup;
            }

1739 1740
            if (!((VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) && autostart) ||
                  (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART) && !autostart)))
1741 1742 1743 1744
                goto remove_entry;
        }

        /* managed save filter */
1745
        if (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_MANAGEDSAVE)) {
1746 1747 1748 1749 1750 1751
            if ((mansave = virDomainHasManagedSaveImage(dom, 0)) < 0) {
                vshError(ctl, "%s",
                         _("Failed to check for managed save image"));
                goto cleanup;
            }

1752 1753
            if (!((VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) && mansave) ||
                  (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE) && !mansave)))
1754 1755 1756 1757
                goto remove_entry;
        }

        /* snapshot filter */
1758
        if (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
1759 1760 1761 1762
            if ((nsnap = virDomainSnapshotNum(dom, 0)) < 0) {
                vshError(ctl, "%s", _("Failed to get snapshot count"));
                goto cleanup;
            }
1763 1764
            if (!((VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) && nsnap > 0) ||
                  (VSH_MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) && nsnap == 0)))
1765 1766 1767 1768 1769 1770
                goto remove_entry;
        }

        /* the domain matched all filters, it may stay */
        continue;

1771
 remove_entry:
1772
        /* the domain has to be removed as it failed one of the filters */
1773
        virshDomainFree(list->domains[i]);
1774 1775 1776 1777
        list->domains[i] = NULL;
        deleted++;
    }

1778
 finished:
1779 1780 1781
    /* sort the list */
    if (list->domains && list->ndomains)
        qsort(list->domains, list->ndomains, sizeof(*list->domains),
1782
              virshDomainSorter);
1783 1784 1785 1786 1787 1788 1789

    /* truncate the list if filter simulation deleted entries */
    if (deleted)
        VIR_SHRINK_N(list->domains, list->ndomains, deleted);

    success = true;

1790
 cleanup:
1791
    for (i = 0; nnames != -1 && i < nnames; i++)
1792 1793 1794
        VIR_FREE(names[i]);

    if (!success) {
1795
        virshDomainListFree(list);
1796 1797 1798 1799 1800 1801 1802 1803 1804
        list = NULL;
    }

    VIR_FREE(names);
    VIR_FREE(ids);
    return list;
}

static const vshCmdOptDef opts_list[] = {
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 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
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("list inactive domains")
    },
    {.name = "all",
     .type = VSH_OT_BOOL,
     .help = N_("list inactive & active domains")
    },
    {.name = "transient",
     .type = VSH_OT_BOOL,
     .help = N_("list transient domains")
    },
    {.name = "persistent",
     .type = VSH_OT_BOOL,
     .help = N_("list persistent domains")
    },
    {.name = "with-snapshot",
     .type = VSH_OT_BOOL,
     .help = N_("list domains with existing snapshot")
    },
    {.name = "without-snapshot",
     .type = VSH_OT_BOOL,
     .help = N_("list domains without a snapshot")
    },
    {.name = "state-running",
     .type = VSH_OT_BOOL,
     .help = N_("list domains in running state")
    },
    {.name = "state-paused",
     .type = VSH_OT_BOOL,
     .help = N_("list domains in paused state")
    },
    {.name = "state-shutoff",
     .type = VSH_OT_BOOL,
     .help = N_("list domains in shutoff state")
    },
    {.name = "state-other",
     .type = VSH_OT_BOOL,
     .help = N_("list domains in other states")
    },
    {.name = "autostart",
     .type = VSH_OT_BOOL,
     .help = N_("list domains with autostart enabled")
    },
    {.name = "no-autostart",
     .type = VSH_OT_BOOL,
     .help = N_("list domains with autostart disabled")
    },
    {.name = "with-managed-save",
     .type = VSH_OT_BOOL,
     .help = N_("list domains with managed save state")
    },
    {.name = "without-managed-save",
     .type = VSH_OT_BOOL,
     .help = N_("list domains without managed save")
    },
    {.name = "uuid",
     .type = VSH_OT_BOOL,
     .help = N_("list uuid's only")
    },
    {.name = "name",
     .type = VSH_OT_BOOL,
     .help = N_("list domain names only")
    },
    {.name = "table",
     .type = VSH_OT_BOOL,
     .help = N_("list table (default)")
    },
    {.name = "managed-save",
     .type = VSH_OT_BOOL,
     .help = N_("mark inactive domains with managed save state")
    },
    {.name = "title",
     .type = VSH_OT_BOOL,
1879
     .help = N_("show domain title")
1880 1881
    },
    {.name = NULL}
1882 1883
};

1884 1885
#define FILTER(NAME, FLAG) \
    if (vshCommandOptBool(cmd, NAME)) \
1886 1887
        flags |= (FLAG)
static bool
1888
cmdList(vshControl *ctl, const vshCmd *cmd)
1889 1890 1891 1892 1893 1894
{
    bool managed = vshCommandOptBool(cmd, "managed-save");
    bool optTitle = vshCommandOptBool(cmd, "title");
    bool optTable = vshCommandOptBool(cmd, "table");
    bool optUUID = vshCommandOptBool(cmd, "uuid");
    bool optName = vshCommandOptBool(cmd, "name");
1895
    size_t i;
1896 1897 1898 1899
    char *title;
    char uuid[VIR_UUID_STRING_BUFLEN];
    int state;
    bool ret = false;
1900
    virshDomainListPtr list = NULL;
1901 1902 1903 1904
    virDomainPtr dom;
    char id_buf[INT_BUFSIZE_BOUND(unsigned int)];
    unsigned int id;
    unsigned int flags = VIR_CONNECT_LIST_DOMAINS_ACTIVE;
1905
    vshTablePtr table = NULL;
1906 1907

    /* construct filter flags */
1908 1909
    if (vshCommandOptBool(cmd, "inactive") ||
        vshCommandOptBool(cmd, "state-shutoff"))
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
        flags = VIR_CONNECT_LIST_DOMAINS_INACTIVE;

    if (vshCommandOptBool(cmd, "all"))
        flags = VIR_CONNECT_LIST_DOMAINS_INACTIVE |
                VIR_CONNECT_LIST_DOMAINS_ACTIVE;

    FILTER("persistent", VIR_CONNECT_LIST_DOMAINS_PERSISTENT);
    FILTER("transient",  VIR_CONNECT_LIST_DOMAINS_TRANSIENT);

    FILTER("with-managed-save",    VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE);
    FILTER("without-managed-save", VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE);

    FILTER("autostart",    VIR_CONNECT_LIST_DOMAINS_AUTOSTART);
    FILTER("no-autostart", VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART);

    FILTER("with-snapshot",    VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT);
    FILTER("without-snapshot", VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT);

    FILTER("state-running", VIR_CONNECT_LIST_DOMAINS_RUNNING);
    FILTER("state-paused",  VIR_CONNECT_LIST_DOMAINS_PAUSED);
    FILTER("state-shutoff", VIR_CONNECT_LIST_DOMAINS_SHUTOFF);
    FILTER("state-other",   VIR_CONNECT_LIST_DOMAINS_OTHER);

1933 1934
    VSH_EXCLUSIVE_OPTIONS("table", "name");
    VSH_EXCLUSIVE_OPTIONS("table", "uuid");
1935 1936 1937 1938

    if (!optUUID && !optName)
        optTable = true;

1939
    if (!(list = virshDomainListCollect(ctl, flags)))
1940 1941 1942 1943 1944
        goto cleanup;

    /* print table header in legacy mode */
    if (optTable) {
        if (optTitle)
1945
            table = vshTableNew(_("Id"), _("Name"), _("State"), _("Title"), NULL);
1946
        else
1947
            table = vshTableNew(_("Id"), _("Name"), _("State"), NULL);
1948 1949 1950

        if (!table)
            goto cleanup;
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
    }

    for (i = 0; i < list->ndomains; i++) {
        dom = list->domains[i];
        id = virDomainGetID(dom);
        if (id != (unsigned int) -1)
            snprintf(id_buf, sizeof(id_buf), "%d", id);
        else
            ignore_value(virStrcpyStatic(id_buf, "-"));

1961 1962
        if (optTable) {
            state = virshDomainState(ctl, dom, NULL);
1963

1964 1965 1966
            /* Domain could've been removed in the meantime */
            if (state < 0)
                continue;
1967

1968 1969 1970
            if (managed && state == VIR_DOMAIN_SHUTOFF &&
                virDomainHasManagedSaveImage(dom, 0) > 0)
                state = -2;
1971 1972

            if (optTitle) {
1973
                if (!(title = virshGetDomainDescription(ctl, dom, true, 0)))
1974
                    goto cleanup;
1975 1976 1977 1978 1979 1980
                if (vshTableRowAppend(table, id_buf,
                                      virDomainGetName(dom),
                                      state == -2 ? _("saved")
                                      : virshDomainStateToString(state),
                                      title, NULL) < 0)
                    goto cleanup;
1981 1982
                VIR_FREE(title);
            } else {
1983 1984 1985 1986 1987 1988
                if (vshTableRowAppend(table, id_buf,
                                      virDomainGetName(dom),
                                      state == -2 ? _("saved")
                                      : virshDomainStateToString(state),
                                      NULL) < 0)
                    goto cleanup;
1989
            }
1990

1991 1992 1993 1994 1995 1996
        } else if (optUUID && optName) {
            if (virDomainGetUUIDString(dom, uuid) < 0) {
                vshError(ctl, "%s", _("Failed to get domain's UUID"));
                goto cleanup;
            }
            vshPrint(ctl, "%-36s %-30s\n", uuid, virDomainGetName(dom));
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
        } else if (optUUID) {
            if (virDomainGetUUIDString(dom, uuid) < 0) {
                vshError(ctl, "%s", _("Failed to get domain's UUID"));
                goto cleanup;
            }
            vshPrint(ctl, "%s\n", uuid);
        } else if (optName) {
            vshPrint(ctl, "%s\n", virDomainGetName(dom));
        }
    }

2008 2009 2010
    if (optTable)
        vshTablePrintToStdout(table, ctl);

2011
    ret = true;
2012
 cleanup:
2013
    vshTableFree(table);
2014
    virshDomainListFree(list);
2015 2016 2017
    return ret;
}
#undef FILTER
2018

2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
/*
 * "domstats" command
 */
static const vshCmdInfo info_domstats[] = {
    {.name = "help",
     .data = N_("get statistics about one or multiple domains")
    },
    {.name = "desc",
     .data = N_("Gets statistics about one or more (or all) domains")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_domstats[] = {
    {.name = "state",
     .type = VSH_OT_BOOL,
     .help = N_("report domain state"),
    },
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
    {.name = "cpu-total",
     .type = VSH_OT_BOOL,
     .help = N_("report domain physical cpu usage"),
    },
    {.name = "balloon",
     .type = VSH_OT_BOOL,
     .help = N_("report domain balloon statistics"),
    },
    {.name = "vcpu",
     .type = VSH_OT_BOOL,
     .help = N_("report domain virtual cpu information"),
    },
    {.name = "interface",
     .type = VSH_OT_BOOL,
     .help = N_("report domain network interface information"),
    },
    {.name = "block",
     .type = VSH_OT_BOOL,
     .help = N_("report domain block device statistics"),
    },
Q
Qiaowei Ren 已提交
2057 2058 2059 2060
    {.name = "perf",
     .type = VSH_OT_BOOL,
     .help = N_("report domain perf event statistics"),
    },
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
    {.name = "list-active",
     .type = VSH_OT_BOOL,
     .help = N_("list only active domains"),
    },
    {.name = "list-inactive",
     .type = VSH_OT_BOOL,
     .help = N_("list only inactive domains"),
    },
    {.name = "list-persistent",
     .type = VSH_OT_BOOL,
     .help = N_("list only persistent domains"),
    },
    {.name = "list-transient",
     .type = VSH_OT_BOOL,
     .help = N_("list only transient domains"),
    },
    {.name = "list-running",
     .type = VSH_OT_BOOL,
     .help = N_("list only running domains"),
    },
    {.name = "list-paused",
     .type = VSH_OT_BOOL,
     .help = N_("list only paused domains"),
    },
    {.name = "list-shutoff",
     .type = VSH_OT_BOOL,
     .help = N_("list only shutoff domains"),
    },
    {.name = "list-other",
     .type = VSH_OT_BOOL,
     .help = N_("list only domains in other states"),
    },
    {.name = "raw",
     .type = VSH_OT_BOOL,
     .help = N_("do not pretty-print the fields"),
    },
    {.name = "enforce",
     .type = VSH_OT_BOOL,
     .help = N_("enforce requested stats parameters"),
    },
2101 2102 2103 2104
    {.name = "backing",
     .type = VSH_OT_BOOL,
     .help = N_("add backing chain information to block stats"),
    },
2105 2106 2107 2108
    {.name = "nowait",
     .type = VSH_OT_BOOL,
     .help = N_("report only stats that are accessible instantly"),
    },
2109
    VIRSH_COMMON_OPT_DOMAIN_OT_ARGV(N_("list of domains to get stats for"), 0),
2110 2111 2112 2113 2114
    {.name = NULL}
};


static bool
2115 2116 2117
virshDomainStatsPrintRecord(vshControl *ctl ATTRIBUTE_UNUSED,
                            virDomainStatsRecordPtr record,
                            bool raw ATTRIBUTE_UNUSED)
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
{
    char *param;
    size_t i;

    vshPrint(ctl, "Domain: '%s'\n", virDomainGetName(record->dom));

    /* XXX: Implement pretty-printing */

    for (i = 0; i < record->nparams; i++) {
        if (!(param = vshGetTypedParamValue(ctl, record->params + i)))
            return false;

        vshPrint(ctl, "  %s=%s\n", record->params[i].field, param);

        VIR_FREE(param);
    }

    return true;
}

static bool
cmdDomstats(vshControl *ctl, const vshCmd *cmd)
{
    unsigned int stats = 0;
    virDomainPtr *domlist = NULL;
    virDomainPtr dom;
    size_t ndoms = 0;
    virDomainStatsRecordPtr *records = NULL;
    virDomainStatsRecordPtr *next;
    bool raw = vshCommandOptBool(cmd, "raw");
    int flags = 0;
    const vshCmdOpt *opt = NULL;
    bool ret = false;
2151
    virshControlPtr priv = ctl->privData;
2152 2153 2154 2155

    if (vshCommandOptBool(cmd, "state"))
        stats |= VIR_DOMAIN_STATS_STATE;

2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
    if (vshCommandOptBool(cmd, "cpu-total"))
        stats |= VIR_DOMAIN_STATS_CPU_TOTAL;

    if (vshCommandOptBool(cmd, "balloon"))
        stats |= VIR_DOMAIN_STATS_BALLOON;

    if (vshCommandOptBool(cmd, "vcpu"))
        stats |= VIR_DOMAIN_STATS_VCPU;

    if (vshCommandOptBool(cmd, "interface"))
        stats |= VIR_DOMAIN_STATS_INTERFACE;

    if (vshCommandOptBool(cmd, "block"))
        stats |= VIR_DOMAIN_STATS_BLOCK;

Q
Qiaowei Ren 已提交
2171 2172 2173
    if (vshCommandOptBool(cmd, "perf"))
        stats |= VIR_DOMAIN_STATS_PERF;

2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
    if (vshCommandOptBool(cmd, "list-active"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_ACTIVE;

    if (vshCommandOptBool(cmd, "list-inactive"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_INACTIVE;

    if (vshCommandOptBool(cmd, "list-persistent"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_PERSISTENT;

    if (vshCommandOptBool(cmd, "list-transient"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_TRANSIENT;

    if (vshCommandOptBool(cmd, "list-running"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING;

    if (vshCommandOptBool(cmd, "list-paused"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_PAUSED;

    if (vshCommandOptBool(cmd, "list-shutoff"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_SHUTOFF;

    if (vshCommandOptBool(cmd, "list-other"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_OTHER;

    if (vshCommandOptBool(cmd, "enforce"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS;

2201 2202 2203
    if (vshCommandOptBool(cmd, "backing"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_BACKING;

2204 2205 2206
    if (vshCommandOptBool(cmd, "nowait"))
        flags |= VIR_CONNECT_GET_ALL_DOMAINS_STATS_NOWAIT;

2207 2208 2209 2210 2211
    if (vshCommandOptBool(cmd, "domain")) {
        if (VIR_ALLOC_N(domlist, 1) < 0)
            goto cleanup;
        ndoms = 1;

2212
        while ((opt = vshCommandOptArgv(ctl, cmd, opt))) {
2213 2214 2215
            if (!(dom = virshLookupDomainBy(ctl, opt->data,
                                            VIRSH_BYID |
                                            VIRSH_BYUUID | VIRSH_BYNAME)))
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
                goto cleanup;

            if (VIR_INSERT_ELEMENT(domlist, ndoms - 1, ndoms, dom) < 0)
                goto cleanup;
        }

        if (virDomainListGetStats(domlist,
                                  stats,
                                  &records,
                                  flags) < 0)
            goto cleanup;
    } else {
2228
       if ((virConnectGetAllDomainStats(priv->conn,
2229 2230 2231 2232 2233 2234
                                        stats,
                                        &records,
                                        flags)) < 0)
           goto cleanup;
    }

2235 2236
    next = records;
    while (*next) {
2237
        if (!virshDomainStatsPrintRecord(ctl, *next, raw))
2238
            goto cleanup;
2239 2240 2241

        if (*(++next))
            vshPrint(ctl, "\n");
2242 2243 2244 2245 2246
    }

    ret = true;
 cleanup:
    virDomainStatsRecordListFree(records);
2247
    virObjectListFree(domlist);
2248 2249 2250 2251

    return ret;
}

N
Nehal J Wani 已提交
2252 2253 2254 2255 2256 2257 2258 2259 2260
/* "domifaddr" command
 */
static const vshCmdInfo info_domifaddr[] = {
    {"help", N_("Get network interfaces' addresses for a running domain")},
    {"desc", N_("Get network interfaces' addresses for a running domain")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_domifaddr[] = {
2261
    VIRSH_COMMON_OPT_DOMAIN_FULL(VIR_CONNECT_LIST_DOMAINS_ACTIVE),
N
Nehal J Wani 已提交
2262 2263 2264
    {.name = "interface",
     .type = VSH_OT_STRING,
     .flags = VSH_OFLAG_NONE,
2265
     .completer = virshDomainInterfaceCompleter,
N
Nehal J Wani 已提交
2266 2267 2268 2269
     .help = N_("network interface name")},
    {.name = "full",
     .type = VSH_OT_BOOL,
     .flags = VSH_OFLAG_NONE,
2270
     .help = N_("always display names and MACs of interfaces")},
N
Nehal J Wani 已提交
2271 2272 2273
    {.name = "source",
     .type = VSH_OT_STRING,
     .flags = VSH_OFLAG_NONE,
2274
     .help = N_("address source: 'lease', 'agent', or 'arp'")},
N
Nehal J Wani 已提交
2275 2276 2277 2278 2279 2280 2281
    {.name = NULL}
};

static bool
cmdDomIfAddr(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
2282
    const char *ifacestr = NULL;
N
Nehal J Wani 已提交
2283 2284 2285 2286 2287 2288 2289 2290
    virDomainInterfacePtr *ifaces = NULL;
    size_t i, j;
    int ifaces_count = 0;
    bool ret = false;
    bool full = vshCommandOptBool(cmd, "full");
    const char *sourcestr = NULL;
    int source = VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE;

2291
    if (!(dom = virshCommandOptDomain(ctl, cmd, NULL)))
N
Nehal J Wani 已提交
2292 2293
        return false;

2294
    if (vshCommandOptStringReq(ctl, cmd, "interface", &ifacestr) < 0)
N
Nehal J Wani 已提交
2295
        goto cleanup;
2296
    if (vshCommandOptStringReq(ctl, cmd, "source", &sourcestr) < 0)
N
Nehal J Wani 已提交
2297 2298 2299 2300 2301 2302 2303
        goto cleanup;

    if (sourcestr) {
        if (STREQ(sourcestr, "lease")) {
            source = VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE;
        } else if (STREQ(sourcestr, "agent")) {
            source = VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT;
2304 2305
        } else if (STREQ(sourcestr, "arp")) {
            source = VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_ARP;
N
Nehal J Wani 已提交
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
        } else {
            vshError(ctl, _("Unknown data source '%s'"), sourcestr);
            goto cleanup;
        }
    }

    if ((ifaces_count = virDomainInterfaceAddresses(dom, &ifaces, source, 0)) < 0) {
        vshError(ctl, _("Failed to query for interfaces addresses"));
        goto cleanup;
    }

    vshPrintExtra(ctl, " %-10s %-20s %-8s     %s\n%s%s\n", _("Name"),
                  _("MAC address"), _("Protocol"), _("Address"),
                  _("-------------------------------------------------"),
                  _("------------------------------"));

    for (i = 0; i < ifaces_count; i++) {
        virDomainInterfacePtr iface = ifaces[i];
2324
        char *ip_addr_str = NULL;
N
Nehal J Wani 已提交
2325 2326
        const char *type = NULL;

2327
        if (ifacestr && STRNEQ(ifacestr, iface->name))
N
Nehal J Wani 已提交
2328 2329 2330 2331
            continue;

        /* When the interface has no IP address */
        if (!iface->naddrs) {
2332 2333 2334
            vshPrint(ctl, " %-10s %-17s    %-12s %s\n",
                     iface->name,
                     iface->hwaddr ? iface->hwaddr : "N/A", "N/A", "N/A");
N
Nehal J Wani 已提交
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
            continue;
        }

        for (j = 0; j < iface->naddrs; j++) {
            virBuffer buf = VIR_BUFFER_INITIALIZER;

            switch (iface->addrs[j].type) {
            case VIR_IP_ADDR_TYPE_IPV4:
                type = "ipv4";
                break;
            case VIR_IP_ADDR_TYPE_IPV6:
                type = "ipv6";
                break;
            }

            virBufferAsprintf(&buf, "%-12s %s/%d",
                              type, iface->addrs[j].addr,
                              iface->addrs[j].prefix);

            if (virBufferError(&buf)) {
                virBufferFreeAndReset(&buf);
                virReportOOMError();
                goto cleanup;
            }

            ip_addr_str = virBufferContentAndReset(&buf);

            if (!ip_addr_str)
2363
                ip_addr_str = vshStrdup(ctl, "");
N
Nehal J Wani 已提交
2364 2365 2366

            /* Don't repeat interface name */
            if (full || !j)
2367 2368 2369
                vshPrint(ctl, " %-10s %-17s    %s\n",
                         iface->name,
                         iface->hwaddr ? iface->hwaddr : "", ip_addr_str);
N
Nehal J Wani 已提交
2370
            else
2371 2372
                vshPrint(ctl, " %-10s %-17s    %s\n",
                         "-", "-", ip_addr_str);
N
Nehal J Wani 已提交
2373 2374

            virBufferFreeAndReset(&buf);
2375
            VIR_FREE(ip_addr_str);
N
Nehal J Wani 已提交
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
        }
    }

    ret = true;

 cleanup:
    if (ifaces && ifaces_count > 0) {
        for (i = 0; i < ifaces_count; i++)
            virDomainInterfaceFree(ifaces[i]);
    }
    VIR_FREE(ifaces);

2388
    virshDomainFree(dom);
N
Nehal J Wani 已提交
2389 2390 2391
    return ret;
}

2392
const vshCmdDef domMonitoringCmds[] = {
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
    {.name = "domblkerror",
     .handler = cmdDomBlkError,
     .opts = opts_domblkerror,
     .info = info_domblkerror,
     .flags = 0
    },
    {.name = "domblkinfo",
     .handler = cmdDomblkinfo,
     .opts = opts_domblkinfo,
     .info = info_domblkinfo,
     .flags = 0
    },
    {.name = "domblklist",
     .handler = cmdDomblklist,
     .opts = opts_domblklist,
     .info = info_domblklist,
     .flags = 0
    },
    {.name = "domblkstat",
     .handler = cmdDomblkstat,
     .opts = opts_domblkstat,
     .info = info_domblkstat,
     .flags = 0
    },
    {.name = "domcontrol",
     .handler = cmdDomControl,
     .opts = opts_domcontrol,
     .info = info_domcontrol,
     .flags = 0
    },
    {.name = "domif-getlink",
     .handler = cmdDomIfGetLink,
     .opts = opts_domif_getlink,
     .info = info_domif_getlink,
     .flags = 0
    },
N
Nehal J Wani 已提交
2429 2430 2431 2432 2433 2434
    {.name = "domifaddr",
     .handler = cmdDomIfAddr,
     .opts = opts_domifaddr,
     .info = info_domifaddr,
     .flags = 0
    },
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
    {.name = "domiflist",
     .handler = cmdDomiflist,
     .opts = opts_domiflist,
     .info = info_domiflist,
     .flags = 0
    },
    {.name = "domifstat",
     .handler = cmdDomIfstat,
     .opts = opts_domifstat,
     .info = info_domifstat,
     .flags = 0
    },
    {.name = "dominfo",
     .handler = cmdDominfo,
     .opts = opts_dominfo,
     .info = info_dominfo,
     .flags = 0
    },
    {.name = "dommemstat",
     .handler = cmdDomMemStat,
     .opts = opts_dommemstat,
     .info = info_dommemstat,
     .flags = 0
    },
    {.name = "domstate",
     .handler = cmdDomstate,
     .opts = opts_domstate,
     .info = info_domstate,
     .flags = 0
    },
2465 2466 2467 2468 2469 2470
    {.name = "domstats",
     .handler = cmdDomstats,
     .opts = opts_domstats,
     .info = info_domstats,
     .flags = 0
    },
2471 2472 2473 2474 2475 2476
    {.name = "domtime",
     .handler = cmdDomTime,
     .opts = opts_domtime,
     .info = info_domtime,
     .flags = 0
    },
2477 2478 2479 2480 2481 2482 2483
    {.name = "list",
     .handler = cmdList,
     .opts = opts_list,
     .info = info_list,
     .flags = 0
    },
    {.name = NULL}
2484
};