virsh-nodedev.c 27.4 KB
Newer Older
1 2 3
/*
 * virsh-nodedev.c: Commands in node device group
 *
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>
 *
 */

E
Eric Blake 已提交
26 27 28 29
#include <config.h>
#include "virsh-nodedev.h"

#include "internal.h"
30
#include "virbuffer.h"
31
#include "viralloc.h"
32
#include "virfile.h"
33
#include "virstring.h"
34
#include "virtime.h"
35
#include "conf/node_device_conf.h"
E
Eric Blake 已提交
36

37 38 39 40
/*
 * "nodedev-create" command
 */
static const vshCmdInfo info_node_device_create[] = {
41 42 43 44 45 46 47 48 49 50
    {.name = "help",
     .data = N_("create a device defined "
                "by an XML file on the node")
    },
    {.name = "desc",
     .data = N_("Create a device on the node.  Note that this "
                "command creates devices on the physical host "
                "that can then be assigned to a virtual machine.")
    },
    {.name = NULL}
51 52 53
};

static const vshCmdOptDef opts_node_device_create[] = {
54 55
    VIRSH_COMMON_OPT_FILE(N_("file containing an XML description "
                             "of the device")),
56
    {.name = NULL}
57 58 59 60 61 62 63 64 65
};

static bool
cmdNodeDeviceCreate(vshControl *ctl, const vshCmd *cmd)
{
    virNodeDevicePtr dev = NULL;
    const char *from = NULL;
    bool ret = true;
    char *buffer;
66
    virshControlPtr priv = ctl->privData;
67

68
    if (vshCommandOptStringReq(ctl, cmd, "file", &from) < 0)
69 70
        return false;

E
Eric Blake 已提交
71
    if (virFileReadAll(from, VSH_MAX_XML_FILE, &buffer) < 0)
72 73
        return false;

74
    dev = virNodeDeviceCreateXML(priv->conn, buffer, 0);
75 76 77
    VIR_FREE(buffer);

    if (dev != NULL) {
P
Pino Toscano 已提交
78 79
        vshPrintExtra(ctl, _("Node device %s created from %s\n"),
                      virNodeDeviceGetName(dev), from);
80 81 82 83 84 85 86 87 88 89 90 91 92 93
        virNodeDeviceFree(dev);
    } else {
        vshError(ctl, _("Failed to create node device from %s"), from);
        ret = false;
    }

    return ret;
}


/*
 * "nodedev-destroy" command
 */
static const vshCmdInfo info_node_device_destroy[] = {
94 95 96 97 98 99 100 101
    {.name = "help",
     .data = N_("destroy (stop) a device on the node")
    },
    {.name = "desc",
     .data = N_("Destroy a device on the node.  Note that this "
                "command destroys devices on the physical host")
    },
    {.name = NULL}
102 103 104
};

static const vshCmdOptDef opts_node_device_destroy[] = {
105
    {.name = "name",
106 107 108 109
     .type = VSH_OT_ALIAS,
     .help = "device"
    },
    {.name = "device",
110 111
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
112
     .help = N_("device name or wwn pair in 'wwnn,wwpn' format")
113 114
    },
    {.name = NULL}
115 116 117 118 119 120
};

static bool
cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd)
{
    virNodeDevicePtr dev = NULL;
121 122 123 124
    bool ret = false;
    const char *device_value = NULL;
    char **arr = NULL;
    int narr;
125
    virshControlPtr priv = ctl->privData;
126

127
    if (vshCommandOptStringReq(ctl, cmd, "device", &device_value) < 0)
128 129
        return false;

130 131 132 133 134 135 136 137 138 139
    if (strchr(device_value, ',')) {
        narr = vshStringToArray(device_value, &arr);
        if (narr != 2) {
            vshError(ctl, _("Malformed device value '%s'"), device_value);
            goto cleanup;
        }

        if (!virValidateWWN(arr[0]) || !virValidateWWN(arr[1]))
            goto cleanup;

140
        dev = virNodeDeviceLookupSCSIHostByWWN(priv->conn, arr[0], arr[1], 0);
141
    } else {
142
        dev = virNodeDeviceLookupByName(priv->conn, device_value);
143 144 145 146 147 148
    }

    if (!dev) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), device_value);
        goto cleanup;
    }
149 150

    if (virNodeDeviceDestroy(dev) == 0) {
P
Pino Toscano 已提交
151
        vshPrintExtra(ctl, _("Destroyed node device '%s'\n"), device_value);
152
    } else {
153 154
        vshError(ctl, _("Failed to destroy node device '%s'"), device_value);
        goto cleanup;
155 156
    }

157
    ret = true;
158
 cleanup:
159
    virStringListFree(arr);
160 161
    if (dev)
        virNodeDeviceFree(dev);
162 163 164
    return ret;
}

165
struct virshNodeList {
166 167 168 169 170
    char **names;
    char **parents;
};

static const char *
171
virshNodeListLookup(int devid, bool parent, void *opaque)
172
{
173
    struct virshNodeList *arrays = opaque;
174 175 176 177 178
    if (parent)
        return arrays->parents[devid];
    return arrays->names[devid];
}

179
static int
180
virshNodeDeviceSorter(const void *a, const void *b)
181 182 183 184 185 186 187 188 189 190 191 192 193 194
{
    virNodeDevicePtr *na = (virNodeDevicePtr *) a;
    virNodeDevicePtr *nb = (virNodeDevicePtr *) b;

    if (*na && !*nb)
        return -1;

    if (!*na)
        return *nb != NULL;

    return vshStrcasecmp(virNodeDeviceGetName(*na),
                         virNodeDeviceGetName(*nb));
}

195
struct virshNodeDeviceList {
196 197 198
    virNodeDevicePtr *devices;
    size_t ndevices;
};
199
typedef struct virshNodeDeviceList *virshNodeDeviceListPtr;
200 201

static void
202
virshNodeDeviceListFree(virshNodeDeviceListPtr list)
203
{
204
    size_t i;
205

206
    if (list && list->devices) {
207 208 209 210 211 212 213 214 215
        for (i = 0; i < list->ndevices; i++) {
            if (list->devices[i])
                virNodeDeviceFree(list->devices[i]);
        }
        VIR_FREE(list->devices);
    }
    VIR_FREE(list);
}

216 217
static virshNodeDeviceListPtr
virshNodeDeviceListCollect(vshControl *ctl,
218 219 220 221
                         char **capnames,
                         int ncapnames,
                         unsigned int flags)
{
222
    virshNodeDeviceListPtr list = vshMalloc(ctl, sizeof(*list));
223
    size_t i;
224 225 226 227 228 229
    int ret;
    virNodeDevicePtr device;
    bool success = false;
    size_t deleted = 0;
    int ndevices = 0;
    char **names = NULL;
230
    virshControlPtr priv = ctl->privData;
231 232

    /* try the list with flags support (0.10.2 and later) */
233
    if ((ret = virConnectListAllNodeDevices(priv->conn,
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                                            &list->devices,
                                            flags)) >= 0) {
        list->ndevices = ret;
        goto finished;
    }

    /* check if the command is actually supported */
    if (last_error && last_error->code == VIR_ERR_NO_SUPPORT)
        goto fallback;

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


249
 fallback:
250 251 252
    /* fall back to old method (0.10.1 and older) */
    vshResetLibvirtError();

253
    ndevices = virNodeNumOfDevices(priv->conn, NULL, 0);
254 255 256 257 258 259 260 261 262 263
    if (ndevices < 0) {
        vshError(ctl, "%s", _("Failed to count node devices"));
        goto cleanup;
    }

    if (ndevices == 0)
        return list;

    names = vshMalloc(ctl, sizeof(char *) * ndevices);

264
    ndevices = virNodeListDevices(priv->conn, NULL, names, ndevices, 0);
265 266 267 268 269 270 271 272 273
    if (ndevices < 0) {
        vshError(ctl, "%s", _("Failed to list node devices"));
        goto cleanup;
    }

    list->devices = vshMalloc(ctl, sizeof(virNodeDevicePtr) * (ndevices));
    list->ndevices = 0;

    /* get the node devices */
274
    for (i = 0; i < ndevices; i++) {
275
        if (!(device = virNodeDeviceLookupByName(priv->conn, names[i])))
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
            continue;
        list->devices[list->ndevices++] = device;
    }

    /* truncate domains that weren't found */
    deleted = ndevices - list->ndevices;

    if (!capnames)
        goto finished;

    /* filter the list if the list was acquired by fallback means */
    for (i = 0; i < list->ndevices; i++) {
        char **caps = NULL;
        int ncaps = 0;
        bool match = false;

        device = list->devices[i];

        if ((ncaps = virNodeDeviceNumOfCaps(device)) < 0) {
            vshError(ctl, "%s", _("Failed to get capability numbers "
                                  "of the device"));
            goto cleanup;
        }

        caps = vshMalloc(ctl, sizeof(char *) * ncaps);

        if ((ncaps = virNodeDeviceListCaps(device, caps, ncaps)) < 0) {
            vshError(ctl, "%s", _("Failed to get capability names of the device"));
            VIR_FREE(caps);
            goto cleanup;
        }

308
        /* Check if the device's capability matches with provided
309 310
         * capabilities.
         */
311
        size_t j, k;
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        for (j = 0; j < ncaps; j++) {
            for (k = 0; k < ncapnames; k++) {
                if (STREQ(caps[j], capnames[k])) {
                    match = true;
                    break;
                }
            }
        }

        VIR_FREE(caps);

        if (!match)
            goto remove_entry;

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

329
 remove_entry:
330 331 332 333 334 335
        /* the device has to be removed as it failed one of the filters */
        virNodeDeviceFree(list->devices[i]);
        list->devices[i] = NULL;
        deleted++;
    }

336
 finished:
337 338 339
    /* sort the list */
    if (list->devices && list->ndevices)
        qsort(list->devices, list->ndevices,
340
              sizeof(*list->devices), virshNodeDeviceSorter);
341 342 343 344 345 346 347

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

    success = true;

348
 cleanup:
349
    for (i = 0; ndevices != -1 && i < ndevices; i++)
350 351 352 353
        VIR_FREE(names[i]);
    VIR_FREE(names);

    if (!success) {
354
        virshNodeDeviceListFree(list);
355 356 357 358 359 360
        list = NULL;
    }

    return list;
}

361 362 363 364
/*
 * "nodedev-list" command
 */
static const vshCmdInfo info_node_list_devices[] = {
365 366 367 368 369 370 371
    {.name = "help",
     .data = N_("enumerate devices on this host")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
372 373 374
};

static const vshCmdOptDef opts_node_list_devices[] = {
375 376 377 378 379 380 381 382 383
    {.name = "tree",
     .type = VSH_OT_BOOL,
     .help = N_("list devices in a tree")
    },
    {.name = "cap",
     .type = VSH_OT_STRING,
     .help = N_("capability names, separated by comma")
    },
    {.name = NULL}
384 385 386 387 388
};

static bool
cmdNodeListDevices(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
389
    const char *cap_str = NULL;
390
    size_t i;
391 392
    bool tree = vshCommandOptBool(cmd, "tree");
    bool ret = true;
393 394 395
    unsigned int flags = 0;
    char **caps = NULL;
    int ncaps = 0;
396
    virshNodeDeviceListPtr list = NULL;
397
    int cap_type = -1;
398

399
    ignore_value(vshCommandOptStringQuiet(ctl, cmd, "cap", &cap_str));
400

401 402 403 404 405
    if (cap_str) {
        if (tree) {
            vshError(ctl, "%s", _("Options --tree and --cap are incompatible"));
            return false;
        }
406 407
        if ((ncaps = vshStringToArray(cap_str, &caps)) < 0)
            return false;
408 409
    }

410 411 412
    for (i = 0; i < ncaps; i++) {
        if ((cap_type = virNodeDevCapTypeFromString(caps[i])) < 0) {
            vshError(ctl, "%s", _("Invalid capability type"));
413 414
            ret = false;
            goto cleanup;
415 416
        }

417
        switch ((virNodeDevCapType) cap_type) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        case VIR_NODE_DEV_CAP_SYSTEM:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_SYSTEM;
            break;
        case VIR_NODE_DEV_CAP_PCI_DEV:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_PCI_DEV;
            break;
        case VIR_NODE_DEV_CAP_USB_DEV:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_USB_DEV;
            break;
        case VIR_NODE_DEV_CAP_USB_INTERFACE:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_USB_INTERFACE;
            break;
        case VIR_NODE_DEV_CAP_NET:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_NET;
            break;
        case VIR_NODE_DEV_CAP_SCSI_HOST:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI_HOST;
            break;
        case VIR_NODE_DEV_CAP_SCSI_TARGET:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI_TARGET;
            break;
        case VIR_NODE_DEV_CAP_SCSI:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI;
            break;
        case VIR_NODE_DEV_CAP_STORAGE:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_STORAGE;
            break;
445 446 447 448 449 450
        case VIR_NODE_DEV_CAP_FC_HOST:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_FC_HOST;
            break;
        case VIR_NODE_DEV_CAP_VPORTS:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_VPORTS;
            break;
451 452 453
        case VIR_NODE_DEV_CAP_SCSI_GENERIC:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI_GENERIC;
            break;
454 455 456 457
        case VIR_NODE_DEV_CAP_DRM:
            flags |= VIR_CONNECT_LIST_NODE_DEVICES_CAP_DRM;
            break;
        case VIR_NODE_DEV_CAP_LAST:
458 459
            break;
        }
460
    }
461

462
    if (!(list = virshNodeDeviceListCollect(ctl, caps, ncaps, flags))) {
463 464 465 466
        ret = false;
        goto cleanup;
    }

467
    if (tree) {
468 469
        char **parents = vshMalloc(ctl, sizeof(char *) * list->ndevices);
        char **names = vshMalloc(ctl, sizeof(char *) * list->ndevices);
470
        struct virshNodeList arrays = { names, parents };
471 472 473

        for (i = 0; i < list->ndevices; i++)
            names[i] = vshStrdup(ctl, virNodeDeviceGetName(list->devices[i]));
474

475 476 477
        for (i = 0; i < list->ndevices; i++) {
            virNodeDevicePtr dev = list->devices[i];
            if (STRNEQ(names[i], "computer")) {
478 479 480 481 482 483
                const char *parent = virNodeDeviceGetParent(dev);
                parents[i] = parent ? vshStrdup(ctl, parent) : NULL;
            } else {
                parents[i] = NULL;
            }
        }
484

485
        for (i = 0; i < list->ndevices; i++) {
486
            if (parents[i] == NULL &&
487
                vshTreePrint(ctl, virshNodeListLookup, &arrays,
488
                             list->ndevices, i) < 0)
489 490
                ret = false;
        }
491

492
        for (i = 0; i < list->ndevices; i++)
493 494
            VIR_FREE(parents[i]);
        VIR_FREE(parents);
495 496 497
        for (i = 0; i < list->ndevices; i++)
            VIR_FREE(names[i]);
        VIR_FREE(names);
498
    } else {
499 500 501 502
        for (i = 0; i < list->ndevices; i++)
            vshPrint(ctl, "%s\n", virNodeDeviceGetName(list->devices[i]));
    }

503
 cleanup:
504
    virStringListFree(caps);
505
    virshNodeDeviceListFree(list);
506 507 508 509 510 511 512
    return ret;
}

/*
 * "nodedev-dumpxml" command
 */
static const vshCmdInfo info_node_device_dumpxml[] = {
513 514 515 516 517 518 519
    {.name = "help",
     .data = N_("node device details in XML")
    },
    {.name = "desc",
     .data = N_("Output the node device details as an XML dump to stdout.")
    },
    {.name = NULL}
520 521 522 523
};


static const vshCmdOptDef opts_node_device_dumpxml[] = {
524 525 526
    {.name = "device",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
527
     .help = N_("device name or wwn pair in 'wwnn,wwpn' format"),
528 529
    },
    {.name = NULL}
530 531 532 533 534
};

static bool
cmdNodeDeviceDumpXML(vshControl *ctl, const vshCmd *cmd)
{
535 536
    virNodeDevicePtr device = NULL;
    char *xml = NULL;
537 538 539
    const char *device_value = NULL;
    char **arr = NULL;
    int narr;
540
    bool ret = false;
541
    virshControlPtr priv = ctl->privData;
542

543 544
    if (vshCommandOptStringReq(ctl, cmd, "device", &device_value) < 0)
         return false;
545

546 547 548 549 550 551 552 553 554 555
    if (strchr(device_value, ',')) {
        narr = vshStringToArray(device_value, &arr);
        if (narr != 2) {
            vshError(ctl, _("Malformed device value '%s'"), device_value);
            goto cleanup;
        }

        if (!virValidateWWN(arr[0]) || !virValidateWWN(arr[1]))
            goto cleanup;

556
        device = virNodeDeviceLookupSCSIHostByWWN(priv->conn, arr[0], arr[1], 0);
557
    } else {
558
        device = virNodeDeviceLookupByName(priv->conn, device_value);
559 560 561 562 563
    }

    if (!device) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), device_value);
        goto cleanup;
564 565
    }

566 567
    if (!(xml = virNodeDeviceGetXMLDesc(device, 0)))
        goto cleanup;
568 569

    vshPrint(ctl, "%s\n", xml);
570

571
    ret = true;
572
 cleanup:
573
    virStringListFree(arr);
574
    VIR_FREE(xml);
575 576
    if (device)
        virNodeDeviceFree(device);
577
    return ret;
578 579 580 581 582 583
}

/*
 * "nodedev-detach" command
 */
static const vshCmdInfo info_node_device_detach[] = {
584 585 586 587 588 589 590
    {.name = "help",
     .data = N_("detach node device from its device driver")
    },
    {.name = "desc",
     .data = N_("Detach node device from its device driver before assigning to a domain.")
    },
    {.name = NULL}
591 592 593 594
};


static const vshCmdOptDef opts_node_device_detach[] = {
595 596 597 598 599
    {.name = "device",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("device key")
    },
600 601
    {.name = "driver",
     .type = VSH_OT_STRING,
602
     .help = N_("pci device assignment backend driver (e.g. 'vfio' or 'kvm')")
603
    },
604
    {.name = NULL}
605 606 607 608 609 610
};

static bool
cmdNodeDeviceDetach(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
611
    const char *driverName = NULL;
612 613
    virNodeDevicePtr device;
    bool ret = true;
614
    virshControlPtr priv = ctl->privData;
615

616
    if (vshCommandOptStringReq(ctl, cmd, "device", &name) < 0)
617
        return false;
618

619
    ignore_value(vshCommandOptStringQuiet(ctl, cmd, "driver", &driverName));
620

621
    if (!(device = virNodeDeviceLookupByName(priv->conn, name))) {
622
        vshError(ctl, _("Could not find matching device '%s'"), name);
623 624 625
        return false;
    }

626 627 628 629
    if (driverName) {
        /* we must use the newer API that accepts a driverName */
        if (virNodeDeviceDetachFlags(device, driverName, 0) < 0)
            ret = false;
630
    } else {
631 632 633 634
        /* Yes, our (old) public API is misspelled.  At least virsh
         * can accept either spelling.  */
        if (virNodeDeviceDettach(device) < 0)
            ret = false;
635
    }
636

637
    if (ret)
P
Pino Toscano 已提交
638
        vshPrintExtra(ctl, _("Device %s detached\n"), name);
639 640 641
    else
        vshError(ctl, _("Failed to detach device %s"), name);

642 643 644 645 646 647 648 649
    virNodeDeviceFree(device);
    return ret;
}

/*
 * "nodedev-reattach" command
 */
static const vshCmdInfo info_node_device_reattach[] = {
650 651 652 653 654 655 656
    {.name = "help",
     .data = N_("reattach node device to its device driver")
    },
    {.name = "desc",
     .data = N_("Reattach node device to its device driver once released by the domain.")
    },
    {.name = NULL}
657 658 659 660
};


static const vshCmdOptDef opts_node_device_reattach[] = {
661 662 663 664 665 666
    {.name = "device",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("device key")
    },
    {.name = NULL}
667 668 669 670 671 672 673 674
};

static bool
cmdNodeDeviceReAttach(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
675
    virshControlPtr priv = ctl->privData;
676

677
    if (vshCommandOptStringReq(ctl, cmd, "device", &name) < 0)
678
        return false;
679

680
    if (!(device = virNodeDeviceLookupByName(priv->conn, name))) {
681
        vshError(ctl, _("Could not find matching device '%s'"), name);
682 683 684 685
        return false;
    }

    if (virNodeDeviceReAttach(device) == 0) {
P
Pino Toscano 已提交
686
        vshPrintExtra(ctl, _("Device %s re-attached\n"), name);
687 688 689 690
    } else {
        vshError(ctl, _("Failed to re-attach device %s"), name);
        ret = false;
    }
691

692 693 694 695 696 697 698 699
    virNodeDeviceFree(device);
    return ret;
}

/*
 * "nodedev-reset" command
 */
static const vshCmdInfo info_node_device_reset[] = {
700 701 702 703 704 705 706
    {.name = "help",
     .data = N_("reset node device")
    },
    {.name = "desc",
     .data = N_("Reset node device before or after assigning to a domain.")
    },
    {.name = NULL}
707 708 709 710
};


static const vshCmdOptDef opts_node_device_reset[] = {
711 712 713 714 715 716
    {.name = "device",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("device key")
    },
    {.name = NULL}
717 718 719 720 721 722 723 724
};

static bool
cmdNodeDeviceReset(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
725
    virshControlPtr priv = ctl->privData;
726

727
    if (vshCommandOptStringReq(ctl, cmd, "device", &name) < 0)
728
        return false;
729

730
    if (!(device = virNodeDeviceLookupByName(priv->conn, name))) {
731
        vshError(ctl, _("Could not find matching device '%s'"), name);
732 733 734 735
        return false;
    }

    if (virNodeDeviceReset(device) == 0) {
P
Pino Toscano 已提交
736
        vshPrintExtra(ctl, _("Device %s reset\n"), name);
737 738 739 740
    } else {
        vshError(ctl, _("Failed to reset device %s"), name);
        ret = false;
    }
741

742 743 744
    virNodeDeviceFree(device);
    return ret;
}
745

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
/*
 * "nodedev-event" command
 */
VIR_ENUM_DECL(virshNodeDeviceEvent)
VIR_ENUM_IMPL(virshNodeDeviceEvent,
              VIR_NODE_DEVICE_EVENT_LAST,
              N_("Created"),
              N_("Deleted"))

static const char *
virshNodeDeviceEventToString(int event)
{
    const char *str = virshNodeDeviceEventTypeToString(event);
    return str ? _(str) : _("unknown");
}

762 763 764 765 766 767
struct vshEventCallback {
    const char *name;
    virConnectNodeDeviceEventGenericCallback cb;
};
typedef struct vshEventCallback vshEventCallback;

768 769 770 771 772
struct virshNodeDeviceEventData {
    vshControl *ctl;
    bool loop;
    bool timestamp;
    int count;
773
    vshEventCallback *cb;
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
};
typedef struct virshNodeDeviceEventData virshNodeDeviceEventData;

static void
vshEventLifecyclePrint(virConnectPtr conn ATTRIBUTE_UNUSED,
                       virNodeDevicePtr dev,
                       int event,
                       int detail ATTRIBUTE_UNUSED,
                       void *opaque)
{
    virshNodeDeviceEventData *data = opaque;

    if (!data->loop && data->count)
        return;

    if (data->timestamp) {
        char timestamp[VIR_TIME_STRING_BUFLEN];

        if (virTimeStringNowRaw(timestamp) < 0)
            timestamp[0] = '\0';

        vshPrint(data->ctl, _("%s: event 'lifecycle' for node device %s: %s\n"),
                 timestamp,
                 virNodeDeviceGetName(dev), virshNodeDeviceEventToString(event));
    } else {
        vshPrint(data->ctl, _("event 'lifecycle' for node device %s: %s\n"),
                 virNodeDeviceGetName(dev), virshNodeDeviceEventToString(event));
    }

    data->count++;
    if (!data->loop)
        vshEventDone(data->ctl);
}

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
static void
vshEventGenericPrint(virConnectPtr conn ATTRIBUTE_UNUSED,
                     virNodeDevicePtr dev,
                     void *opaque)
{
    virshNodeDeviceEventData *data = opaque;

    if (!data->loop && data->count)
        return;

    if (data->timestamp) {
        char timestamp[VIR_TIME_STRING_BUFLEN];

        if (virTimeStringNowRaw(timestamp) < 0)
            timestamp[0] = '\0';

Y
Yuri Chornoivan 已提交
824
        vshPrint(data->ctl, _("%s: event '%s' for node device %s\n"),
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
                 timestamp,
                 data->cb->name,
                 virNodeDeviceGetName(dev));
    } else {
        vshPrint(data->ctl, _("event '%s' for node device %s\n"),
                 data->cb->name,
                 virNodeDeviceGetName(dev));
    }

    data->count++;
    if (!data->loop)
        vshEventDone(data->ctl);
}

static vshEventCallback vshEventCallbacks[] = {
    { "lifecycle",
      VIR_NODE_DEVICE_EVENT_CALLBACK(vshEventLifecyclePrint), },
    { "update", vshEventGenericPrint, }
};
verify(VIR_NODE_DEVICE_EVENT_ID_LAST == ARRAY_CARDINALITY(vshEventCallbacks));


847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
static const vshCmdInfo info_node_device_event[] = {
    {.name = "help",
     .data = N_("Node Device Events")
    },
    {.name = "desc",
     .data = N_("List event types, or wait for node device events to occur")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_node_device_event[] = {
    {.name = "device",
     .type = VSH_OT_STRING,
     .help = N_("filter by node device name")
    },
    {.name = "event",
     .type = VSH_OT_STRING,
     .help = N_("which event type to wait for")
    },
    {.name = "loop",
     .type = VSH_OT_BOOL,
     .help = N_("loop until timeout or interrupt, rather than one-shot")
    },
    {.name = "timeout",
     .type = VSH_OT_INT,
     .help = N_("timeout seconds")
    },
    {.name = "list",
     .type = VSH_OT_BOOL,
     .help = N_("list valid event types")
    },
    {.name = "timestamp",
     .type = VSH_OT_BOOL,
     .help = N_("show timestamp for each printed event")
    },
    {.name = NULL}
};

static bool
cmdNodeDeviceEvent(vshControl *ctl, const vshCmd *cmd)
{
    virNodeDevicePtr dev = NULL;
    bool ret = false;
    int eventId = -1;
    int timeout = 0;
    virshNodeDeviceEventData data;
    const char *eventName = NULL;
    const char *device_value = NULL;
    int event;
    virshControlPtr priv = ctl->privData;

    if (vshCommandOptBool(cmd, "list")) {
        size_t i;

        for (i = 0; i < VIR_NODE_DEVICE_EVENT_ID_LAST; i++)
902
            vshPrint(ctl, "%s\n", vshEventCallbacks[i].name);
903 904 905 906 907 908
        return true;
    }

    if (vshCommandOptStringReq(ctl, cmd, "event", &eventName) < 0)
        return false;
    if (!eventName) {
909
        vshError(ctl, "%s", _("either --list or --event <type> is required"));
910 911
        return false;
    }
912 913 914 915 916

    for (event = 0; event < VIR_NODE_DEVICE_EVENT_ID_LAST; event++)
        if (STREQ(eventName, vshEventCallbacks[event].name))
            break;
    if (event == VIR_NODE_DEVICE_EVENT_ID_LAST) {
917 918 919 920 921 922 923 924
        vshError(ctl, _("unknown event type %s"), eventName);
        return false;
    }

    data.ctl = ctl;
    data.loop = vshCommandOptBool(cmd, "loop");
    data.timestamp = vshCommandOptBool(cmd, "timestamp");
    data.count = 0;
925
    data.cb = &vshEventCallbacks[event];
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    if (vshCommandOptTimeoutToMs(ctl, cmd, &timeout) < 0)
        return false;
    if (vshCommandOptStringReq(ctl, cmd, "device", &device_value) < 0)
        return false;

    if (device_value) {
        if (!(dev = virNodeDeviceLookupByName(priv->conn, device_value))) {
            vshError(ctl, "%s '%s'",
                     _("Could not find matching device"), device_value);
            goto cleanup;
        }
    }
    if (vshEventStart(ctl, timeout) < 0)
        goto cleanup;

    if ((eventId = virConnectNodeDeviceEventRegisterAny(priv->conn, dev, event,
942
                                                     data.cb->cb,
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
                                                     &data, NULL)) < 0)
        goto cleanup;
    switch (vshEventWait(ctl)) {
    case VSH_EVENT_INTERRUPT:
        vshPrint(ctl, "%s", _("event loop interrupted\n"));
        break;
    case VSH_EVENT_TIMEOUT:
        vshPrint(ctl, "%s", _("event loop timed out\n"));
        break;
    case VSH_EVENT_DONE:
        break;
    default:
        goto cleanup;
    }
    vshPrint(ctl, _("events received: %d\n"), data.count);
    if (data.count)
        ret = true;

 cleanup:
    vshEventCleanup(ctl);
    if (eventId >= 0 &&
        virConnectNodeDeviceEventDeregisterAny(priv->conn, eventId) < 0)
        ret = false;
    if (dev)
        virNodeDeviceFree(dev);
    return ret;
}


E
Eric Blake 已提交
972
const vshCmdDef nodedevCmds[] = {
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
    {.name = "nodedev-create",
     .handler = cmdNodeDeviceCreate,
     .opts = opts_node_device_create,
     .info = info_node_device_create,
     .flags = 0
    },
    {.name = "nodedev-destroy",
     .handler = cmdNodeDeviceDestroy,
     .opts = opts_node_device_destroy,
     .info = info_node_device_destroy,
     .flags = 0
    },
    {.name = "nodedev-detach",
     .handler = cmdNodeDeviceDetach,
     .opts = opts_node_device_detach,
     .info = info_node_device_detach,
     .flags = 0
    },
    {.name = "nodedev-dettach",
992 993
     .flags = VSH_CMD_FLAG_ALIAS,
     .alias = "nodedev-detach"
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    },
    {.name = "nodedev-dumpxml",
     .handler = cmdNodeDeviceDumpXML,
     .opts = opts_node_device_dumpxml,
     .info = info_node_device_dumpxml,
     .flags = 0
    },
    {.name = "nodedev-list",
     .handler = cmdNodeListDevices,
     .opts = opts_node_list_devices,
     .info = info_node_list_devices,
     .flags = 0
    },
    {.name = "nodedev-reattach",
     .handler = cmdNodeDeviceReAttach,
     .opts = opts_node_device_reattach,
     .info = info_node_device_reattach,
     .flags = 0
    },
    {.name = "nodedev-reset",
     .handler = cmdNodeDeviceReset,
     .opts = opts_node_device_reset,
     .info = info_node_device_reset,
     .flags = 0
    },
1019 1020 1021 1022 1023 1024
    {.name = "nodedev-event",
     .handler = cmdNodeDeviceEvent,
     .opts = opts_node_device_event,
     .info = info_node_device_event,
     .flags = 0
    },
1025
    {.name = NULL}
1026
};