virsh-interface.c 36.0 KB
Newer Older
1 2 3
/*
 * virsh-interface.c: Commands to manage host interface
 *
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
 * <http://www.gnu.org/licenses/>.
 */

21
#define VIRSH_COMMON_OPT_INTERFACE(cflags) \
22 23 24
    {.name = "interface", \
     .type = VSH_OT_DATA, \
     .flags = VSH_OFLAG_REQ, \
25 26 27
     .help = N_("interface name or MAC address"), \
     .completer = virshInterfaceNameCompleter, \
     .completer_flags = cflags, \
28
    }
29

E
Eric Blake 已提交
30 31
#include <config.h>
#include "virsh-interface.h"
32

E
Eric Blake 已提交
33 34 35 36 37 38
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xmlsave.h>

#include "internal.h"
39
#include "virbuffer.h"
40
#include "viralloc.h"
41
#include "virfile.h"
42
#include "virmacaddr.h"
43
#include "virxml.h"
44
#include "virstring.h"
45
#include "vsh-table.h"
E
Eric Blake 已提交
46 47

virInterfacePtr
48 49 50
virshCommandOptInterfaceBy(vshControl *ctl, const vshCmd *cmd,
                           const char *optname,
                           const char **name, unsigned int flags)
51 52 53
{
    virInterfacePtr iface = NULL;
    const char *n = NULL;
54 55
    bool is_mac = false;
    virMacAddr dummy;
56 57
    virCheckFlags(VIRSH_BYNAME | VIRSH_BYMAC, NULL);
    virshControlPtr priv = ctl->privData;
58 59 60 61

    if (!optname)
       optname = "interface";

62
    if (vshCommandOptStringReq(ctl, cmd, optname, &n) < 0)
63 64 65 66 67 68 69 70
        return NULL;

    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
             cmd->def->name, optname, n);

    if (name)
        *name = n;

71 72 73
    if (virMacAddrParse(n, &dummy) == 0)
        is_mac = true;

74
    /* try it by NAME */
75
    if (!is_mac && (flags & VIRSH_BYNAME)) {
76 77
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface NAME\n",
                 cmd->def->name, optname);
78
        iface = virInterfaceLookupByName(priv->conn, n);
79

80
    /* try it by MAC */
81
    } else if (is_mac && (flags & VIRSH_BYMAC)) {
82 83
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface MAC\n",
                 cmd->def->name, optname);
84
        iface = virInterfaceLookupByMACString(priv->conn, n);
85 86 87 88 89 90 91 92 93 94 95 96
    }

    if (!iface)
        vshError(ctl, _("failed to get interface '%s'"), n);

    return iface;
}

/*
 * "iface-edit" command
 */
static const vshCmdInfo info_interface_edit[] = {
97 98 99 100 101 102 103
    {.name = "help",
     .data = N_("edit XML configuration for a physical host interface")
    },
    {.name = "desc",
     .data = N_("Edit the XML configuration for a physical host interface.")
    },
    {.name = NULL}
104 105 106
};

static const vshCmdOptDef opts_interface_edit[] = {
107
    VIRSH_COMMON_OPT_INTERFACE(0),
108
    {.name = NULL}
109 110 111 112 113 114 115 116 117
};

static bool
cmdInterfaceEdit(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virInterfacePtr iface = NULL;
    virInterfacePtr iface_edited = NULL;
    unsigned int flags = VIR_INTERFACE_XML_INACTIVE;
118
    virshControlPtr priv = ctl->privData;
119

120
    iface = virshCommandOptInterface(ctl, cmd, NULL);
121 122 123 124
    if (iface == NULL)
        goto cleanup;

#define EDIT_GET_XML virInterfaceGetXMLDesc(iface, flags)
125 126
#define EDIT_NOT_CHANGED \
    do { \
127
        vshPrintExtra(ctl, _("Interface %s XML configuration not changed.\n"), \
128 129 130
                 virInterfaceGetName(iface)); \
        ret = true; \
        goto edit_cleanup; \
131
    } while (0)
132
#define EDIT_DEFINE \
133
    (iface_edited = virInterfaceDefineXML(priv->conn, doc_edited, 0))
134 135
#include "virsh-edit.c"

136 137
    vshPrintExtra(ctl, _("Interface %s XML configuration edited.\n"),
                  virInterfaceGetName(iface_edited));
138 139 140

    ret = true;

141
 cleanup:
142 143 144 145 146 147 148 149
    if (iface)
        virInterfaceFree(iface);
    if (iface_edited)
        virInterfaceFree(iface_edited);

    return ret;
}

150
static int
151
virshInterfaceSorter(const void *a, const void *b)
152 153 154 155 156 157 158 159 160 161 162 163 164 165
{
    virInterfacePtr *ia = (virInterfacePtr *) a;
    virInterfacePtr *ib = (virInterfacePtr *) b;

    if (*ia && !*ib)
        return -1;

    if (!*ia)
        return *ib != NULL;

    return vshStrcasecmp(virInterfaceGetName(*ia),
                      virInterfaceGetName(*ib));
}

166
struct virshInterfaceList {
167 168 169
    virInterfacePtr *ifaces;
    size_t nifaces;
};
170
typedef struct virshInterfaceList *virshInterfaceListPtr;
171 172

static void
173
virshInterfaceListFree(virshInterfaceListPtr list)
174
{
175
    size_t i;
176

177
    if (list && list->ifaces) {
178 179 180 181 182 183 184 185 186
        for (i = 0; i < list->nifaces; i++) {
            if (list->ifaces[i])
                virInterfaceFree(list->ifaces[i]);
        }
        VIR_FREE(list->ifaces);
    }
    VIR_FREE(list);
}

187 188 189
static virshInterfaceListPtr
virshInterfaceListCollect(vshControl *ctl,
                          unsigned int flags)
190
{
191
    virshInterfaceListPtr list = vshMalloc(ctl, sizeof(*list));
192
    size_t i;
193 194 195 196 197 198 199 200 201
    int ret;
    char **activeNames = NULL;
    char **inactiveNames = NULL;
    virInterfacePtr iface;
    bool success = false;
    size_t deleted = 0;
    int nActiveIfaces = 0;
    int nInactiveIfaces = 0;
    int nAllIfaces = 0;
202
    virshControlPtr priv = ctl->privData;
203 204

    /* try the list with flags support (0.10.2 and later) */
205
    if ((ret = virConnectListAllInterfaces(priv->conn,
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
                                           &list->ifaces,
                                           flags)) >= 0) {
        list->nifaces = 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 first or second call */
    vshError(ctl, "%s", _("Failed to list interfaces"));
    goto cleanup;


221
 fallback:
222 223 224 225
    /* fall back to old method (0.10.1 and older) */
    vshResetLibvirtError();

    if (flags & VIR_CONNECT_LIST_INTERFACES_ACTIVE) {
226
        nActiveIfaces = virConnectNumOfInterfaces(priv->conn);
227 228 229 230 231 232 233
        if (nActiveIfaces < 0) {
            vshError(ctl, "%s", _("Failed to list active interfaces"));
            goto cleanup;
        }
        if (nActiveIfaces) {
            activeNames = vshMalloc(ctl, sizeof(char *) * nActiveIfaces);

234
            if ((nActiveIfaces = virConnectListInterfaces(priv->conn, activeNames,
235 236 237 238 239 240 241 242
                                                          nActiveIfaces)) < 0) {
                vshError(ctl, "%s", _("Failed to list active interfaces"));
                goto cleanup;
            }
        }
    }

    if (flags & VIR_CONNECT_LIST_INTERFACES_INACTIVE) {
243
        nInactiveIfaces = virConnectNumOfDefinedInterfaces(priv->conn);
244 245 246 247 248 249 250 251
        if (nInactiveIfaces < 0) {
            vshError(ctl, "%s", _("Failed to list inactive interfaces"));
            goto cleanup;
        }
        if (nInactiveIfaces) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * nInactiveIfaces);

            if ((nInactiveIfaces =
252
                     virConnectListDefinedInterfaces(priv->conn, inactiveNames,
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
                                                     nInactiveIfaces)) < 0) {
                vshError(ctl, "%s", _("Failed to list inactive interfaces"));
                goto cleanup;
            }
        }
    }

    nAllIfaces = nActiveIfaces + nInactiveIfaces;
    if (nAllIfaces == 0) {
        VIR_FREE(activeNames);
        VIR_FREE(inactiveNames);
        return list;
    }

    list->ifaces = vshMalloc(ctl, sizeof(virInterfacePtr) * (nAllIfaces));
    list->nifaces = 0;

    /* get active interfaces */
    for (i = 0; i < nActiveIfaces; i++) {
272
        if (!(iface = virInterfaceLookupByName(priv->conn, activeNames[i]))) {
273 274 275 276 277 278 279 280
            vshResetLibvirtError();
            continue;
        }
        list->ifaces[list->nifaces++] = iface;
    }

    /* get inactive interfaces */
    for (i = 0; i < nInactiveIfaces; i++) {
281
        if (!(iface = virInterfaceLookupByName(priv->conn, inactiveNames[i]))) {
282 283 284 285 286 287 288 289 290
            vshResetLibvirtError();
            continue;
        }
        list->ifaces[list->nifaces++] = iface;
    }

    /* truncate interfaces that weren't found */
    deleted = nAllIfaces - list->nifaces;

291
 finished:
292 293 294
    /* sort the list */
    if (list->ifaces && list->nifaces)
        qsort(list->ifaces, list->nifaces,
295
              sizeof(*list->ifaces), virshInterfaceSorter);
296 297 298 299 300 301 302

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

    success = true;

303
 cleanup:
304
    for (i = 0; nActiveIfaces != -1 && i < nActiveIfaces; i++)
305 306
        VIR_FREE(activeNames[i]);

307
    for (i = 0; nInactiveIfaces != -1 && i < nInactiveIfaces; i++)
308 309 310 311 312 313
        VIR_FREE(inactiveNames[i]);

    VIR_FREE(activeNames);
    VIR_FREE(inactiveNames);

    if (!success) {
314
        virshInterfaceListFree(list);
315 316 317 318 319 320
        list = NULL;
    }

    return list;
}

321 322 323 324
/*
 * "iface-list" command
 */
static const vshCmdInfo info_interface_list[] = {
325 326 327 328 329 330 331
    {.name = "help",
     .data = N_("list physical host interfaces")
    },
    {.name = "desc",
     .data = N_("Returns list of physical host interfaces.")
    },
    {.name = NULL}
332 333 334
};

static const vshCmdOptDef opts_interface_list[] = {
335 336 337 338 339 340 341 342 343
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("list inactive interfaces")
    },
    {.name = "all",
     .type = VSH_OT_BOOL,
     .help = N_("list inactive & active interfaces")
    },
    {.name = NULL}
344
};
345

346
static bool
J
Ján Tomko 已提交
347
cmdInterfaceList(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
348 349 350
{
    bool inactive = vshCommandOptBool(cmd, "inactive");
    bool all = vshCommandOptBool(cmd, "all");
351
    unsigned int flags = VIR_CONNECT_LIST_INTERFACES_ACTIVE;
352
    virshInterfaceListPtr list = NULL;
353
    size_t i;
354 355
    bool ret = false;
    vshTablePtr table = NULL;
356

357 358 359 360 361
    if (inactive)
        flags = VIR_CONNECT_LIST_INTERFACES_INACTIVE;
    if (all)
        flags = VIR_CONNECT_LIST_INTERFACES_INACTIVE |
                VIR_CONNECT_LIST_INTERFACES_ACTIVE;
362

363
    if (!(list = virshInterfaceListCollect(ctl, flags)))
364
        return false;
365

366 367 368
    table = vshTableNew(_("Name"), _("State"), _("MAC Address"), NULL);
    if (!table)
        goto cleanup;
369

370 371
    for (i = 0; i < list->nifaces; i++) {
        virInterfacePtr iface = list->ifaces[i];
372

373 374 375 376 377 378 379
        if (vshTableRowAppend(table,
                              virInterfaceGetName(iface),
                              virInterfaceIsActive(iface) ? _("active")
                              : _("inactive"),
                              virInterfaceGetMACString(iface),
                              NULL) < 0)
            goto cleanup;
380 381
    }

382 383 384 385 386
    vshTablePrintToStdout(table, ctl);

    ret = true;
 cleanup:
    vshTableFree(table);
387
    virshInterfaceListFree(list);
388
    return ret;
389 390 391 392 393 394
}

/*
 * "iface-name" command
 */
static const vshCmdInfo info_interface_name[] = {
395 396 397 398 399 400 401
    {.name = "help",
     .data = N_("convert an interface MAC address to interface name")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
402 403 404
};

static const vshCmdOptDef opts_interface_name[] = {
405 406 407 408 409 410
    {.name = "interface",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("interface mac")
    },
    {.name = NULL}
411 412 413 414 415 416 417
};

static bool
cmdInterfaceName(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;

418 419
    if (!(iface = virshCommandOptInterfaceBy(ctl, cmd, NULL, NULL,
                                             VIRSH_BYMAC)))
420 421 422 423 424 425 426 427 428 429 430
        return false;

    vshPrint(ctl, "%s\n", virInterfaceGetName(iface));
    virInterfaceFree(iface);
    return true;
}

/*
 * "iface-mac" command
 */
static const vshCmdInfo info_interface_mac[] = {
431 432 433 434 435 436 437
    {.name = "help",
     .data = N_("convert an interface name to interface MAC address")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
438 439 440
};

static const vshCmdOptDef opts_interface_mac[] = {
441 442 443 444 445 446
    {.name = "interface",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("interface name")
    },
    {.name = NULL}
447 448 449 450 451 452 453
};

static bool
cmdInterfaceMAC(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;

454 455
    if (!(iface = virshCommandOptInterfaceBy(ctl, cmd, NULL, NULL,
                                             VIRSH_BYNAME)))
456 457 458 459 460 461 462 463 464 465 466
        return false;

    vshPrint(ctl, "%s\n", virInterfaceGetMACString(iface));
    virInterfaceFree(iface);
    return true;
}

/*
 * "iface-dumpxml" command
 */
static const vshCmdInfo info_interface_dumpxml[] = {
467 468 469 470 471 472 473
    {.name = "help",
     .data = N_("interface information in XML")
    },
    {.name = "desc",
     .data = N_("Output the physical host interface information as an XML dump to stdout.")
    },
    {.name = NULL}
474 475 476
};

static const vshCmdOptDef opts_interface_dumpxml[] = {
477
    VIRSH_COMMON_OPT_INTERFACE(0),
478 479 480 481 482
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("show inactive defined XML")
    },
    {.name = NULL}
483 484 485 486 487 488 489 490 491 492 493 494 495 496
};

static bool
cmdInterfaceDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
    bool ret = true;
    char *dump;
    unsigned int flags = 0;
    bool inactive = vshCommandOptBool(cmd, "inactive");

    if (inactive)
        flags |= VIR_INTERFACE_XML_INACTIVE;

497
    if (!(iface = virshCommandOptInterface(ctl, cmd, NULL)))
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
        return false;

    dump = virInterfaceGetXMLDesc(iface, flags);
    if (dump != NULL) {
        vshPrint(ctl, "%s", dump);
        VIR_FREE(dump);
    } else {
        ret = false;
    }

    virInterfaceFree(iface);
    return ret;
}

/*
 * "iface-define" command
 */
static const vshCmdInfo info_interface_define[] = {
516
    {.name = "help",
517 518
     .data = N_("define an inactive persistent physical host interface or "
                "modify an existing persistent one from an XML file")
519 520
    },
    {.name = "desc",
521
     .data = N_("Define or modify a persistent physical host interface.")
522 523
    },
    {.name = NULL}
524 525 526
};

static const vshCmdOptDef opts_interface_define[] = {
527
    VIRSH_COMMON_OPT_FILE(N_("file containing an XML interface description")),
528
    {.name = NULL}
529 530 531 532 533 534 535 536 537
};

static bool
cmdInterfaceDefine(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
    const char *from = NULL;
    bool ret = true;
    char *buffer;
538
    virshControlPtr priv = ctl->privData;
539

540
    if (vshCommandOptStringReq(ctl, cmd, "file", &from) < 0)
541 542
        return false;

E
Eric Blake 已提交
543
    if (virFileReadAll(from, VSH_MAX_XML_FILE, &buffer) < 0)
544 545
        return false;

546
    iface = virInterfaceDefineXML(priv->conn, buffer, 0);
547 548 549
    VIR_FREE(buffer);

    if (iface != NULL) {
P
Pino Toscano 已提交
550 551
        vshPrintExtra(ctl, _("Interface %s defined from %s\n"),
                      virInterfaceGetName(iface), from);
552 553 554 555 556 557 558 559 560 561 562 563
        virInterfaceFree(iface);
    } else {
        vshError(ctl, _("Failed to define interface from %s"), from);
        ret = false;
    }
    return ret;
}

/*
 * "iface-undefine" command
 */
static const vshCmdInfo info_interface_undefine[] = {
564 565 566 567 568 569 570
    {.name = "help",
     .data = N_("undefine a physical host interface (remove it from configuration)")
    },
    {.name = "desc",
     .data = N_("undefine an interface.")
    },
    {.name = NULL}
571 572 573
};

static const vshCmdOptDef opts_interface_undefine[] = {
574
    VIRSH_COMMON_OPT_INTERFACE(0),
575
    {.name = NULL}
576 577 578 579 580 581 582 583 584
};

static bool
cmdInterfaceUndefine(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
    bool ret = true;
    const char *name;

585
    if (!(iface = virshCommandOptInterface(ctl, cmd, &name)))
586 587 588
        return false;

    if (virInterfaceUndefine(iface) == 0) {
P
Pino Toscano 已提交
589
        vshPrintExtra(ctl, _("Interface %s undefined\n"), name);
590 591 592 593 594 595 596 597 598 599 600 601 602
    } else {
        vshError(ctl, _("Failed to undefine interface %s"), name);
        ret = false;
    }

    virInterfaceFree(iface);
    return ret;
}

/*
 * "iface-start" command
 */
static const vshCmdInfo info_interface_start[] = {
603 604 605 606 607 608 609
    {.name = "help",
     .data = N_("start a physical host interface (enable it / \"if-up\")")
    },
    {.name = "desc",
     .data = N_("start a physical host interface.")
    },
    {.name = NULL}
610 611 612
};

static const vshCmdOptDef opts_interface_start[] = {
613
    VIRSH_COMMON_OPT_INTERFACE(VIR_CONNECT_LIST_INTERFACES_INACTIVE),
614
    {.name = NULL}
615 616 617 618 619 620 621 622 623
};

static bool
cmdInterfaceStart(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
    bool ret = true;
    const char *name;

624
    if (!(iface = virshCommandOptInterface(ctl, cmd, &name)))
625 626 627
        return false;

    if (virInterfaceCreate(iface, 0) == 0) {
P
Pino Toscano 已提交
628
        vshPrintExtra(ctl, _("Interface %s started\n"), name);
629 630 631 632 633 634 635 636 637 638 639 640 641
    } else {
        vshError(ctl, _("Failed to start interface %s"), name);
        ret = false;
    }

    virInterfaceFree(iface);
    return ret;
}

/*
 * "iface-destroy" command
 */
static const vshCmdInfo info_interface_destroy[] = {
642 643 644 645 646 647 648
    {.name = "help",
     .data = N_("destroy a physical host interface (disable it / \"if-down\")")
    },
    {.name = "desc",
     .data = N_("forcefully stop a physical host interface.")
    },
    {.name = NULL}
649 650 651
};

static const vshCmdOptDef opts_interface_destroy[] = {
652
    VIRSH_COMMON_OPT_INTERFACE(VIR_CONNECT_LIST_INTERFACES_ACTIVE),
653
    {.name = NULL}
654 655 656 657 658 659 660 661 662
};

static bool
cmdInterfaceDestroy(vshControl *ctl, const vshCmd *cmd)
{
    virInterfacePtr iface;
    bool ret = true;
    const char *name;

663
    if (!(iface = virshCommandOptInterface(ctl, cmd, &name)))
664 665 666
        return false;

    if (virInterfaceDestroy(iface, 0) == 0) {
P
Pino Toscano 已提交
667
        vshPrintExtra(ctl, _("Interface %s destroyed\n"), name);
668 669 670 671 672 673 674 675 676 677 678 679 680
    } else {
        vshError(ctl, _("Failed to destroy interface %s"), name);
        ret = false;
    }

    virInterfaceFree(iface);
    return ret;
}

/*
 * "iface-begin" command
 */
static const vshCmdInfo info_interface_begin[] = {
681 682
    {.name = "help",
     .data = N_("create a snapshot of current interfaces settings, "
683
                "which can be later committed (iface-commit) or "
684 685 686 687 688 689
                "restored (iface-rollback)")
    },
    {.name = "desc",
     .data = N_("Create a restore point for interfaces settings")
    },
    {.name = NULL}
690 691 692
};

static const vshCmdOptDef opts_interface_begin[] = {
693
    {.name = NULL}
694 695 696
};

static bool
J
Ján Tomko 已提交
697
cmdInterfaceBegin(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
698
{
699 700 701
    virshControlPtr priv = ctl->privData;

    if (virInterfaceChangeBegin(priv->conn, 0) < 0) {
702 703 704 705
        vshError(ctl, "%s", _("Failed to begin network config change transaction"));
        return false;
    }

P
Pino Toscano 已提交
706
    vshPrintExtra(ctl, "%s", _("Network config change transaction started\n"));
707 708 709 710 711 712 713
    return true;
}

/*
 * "iface-commit" command
 */
static const vshCmdInfo info_interface_commit[] = {
714 715 716 717 718 719 720
    {.name = "help",
     .data = N_("commit changes made since iface-begin and free restore point")
    },
    {.name = "desc",
     .data = N_("commit changes and free restore point")
    },
    {.name = NULL}
721 722 723
};

static const vshCmdOptDef opts_interface_commit[] = {
724
    {.name = NULL}
725 726 727
};

static bool
J
Ján Tomko 已提交
728
cmdInterfaceCommit(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
729
{
730 731 732
    virshControlPtr priv = ctl->privData;

    if (virInterfaceChangeCommit(priv->conn, 0) < 0) {
733 734 735 736
        vshError(ctl, "%s", _("Failed to commit network config change transaction"));
        return false;
    }

P
Pino Toscano 已提交
737
    vshPrintExtra(ctl, "%s", _("Network config change transaction committed\n"));
738 739 740 741 742 743 744
    return true;
}

/*
 * "iface-rollback" command
 */
static const vshCmdInfo info_interface_rollback[] = {
745 746 747 748 749 750 751
    {.name = "help",
     .data = N_("rollback to previous saved configuration created via iface-begin")
    },
    {.name = "desc",
     .data = N_("rollback to previous restore point")
    },
    {.name = NULL}
752 753 754
};

static const vshCmdOptDef opts_interface_rollback[] = {
755
    {.name = NULL}
756 757 758
};

static bool
J
Ján Tomko 已提交
759
cmdInterfaceRollback(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
760
{
761 762 763
    virshControlPtr priv = ctl->privData;

    if (virInterfaceChangeRollback(priv->conn, 0) < 0) {
764 765 766 767
        vshError(ctl, "%s", _("Failed to rollback network config change transaction"));
        return false;
    }

P
Pino Toscano 已提交
768
    vshPrintExtra(ctl, "%s", _("Network config change transaction rolled back\n"));
769 770 771 772 773 774 775
    return true;
}

/*
 * "iface-bridge" command
 */
static const vshCmdInfo info_interface_bridge[] = {
776 777 778 779 780 781 782
    {.name = "help",
     .data = N_("create a bridge device and attach an existing network device to it")
    },
    {.name = "desc",
     .data = N_("bridge an existing network device")
    },
    {.name = NULL}
783 784 785
};

static const vshCmdOptDef opts_interface_bridge[] = {
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    {.name = "interface",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("existing interface name")
    },
    {.name = "bridge",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("new bridge device name")
    },
    {.name = "no-stp",
     .type = VSH_OT_BOOL,
     .help = N_("do not enable STP for this bridge")
    },
    {.name = "delay",
     .type = VSH_OT_INT,
     .help = N_("number of seconds to squelch traffic on newly connected ports")
    },
    {.name = "no-start",
     .type = VSH_OT_BOOL,
     .help = N_("don't start the bridge immediately")
    },
    {.name = NULL}
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
};

static bool
cmdInterfaceBridge(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virInterfacePtr if_handle = NULL, br_handle = NULL;
    const char *if_name, *br_name;
    char *if_type = NULL, *if2_name = NULL, *delay_str = NULL;
    bool stp = false, nostart = false;
    unsigned int delay = 0;
    char *if_xml = NULL;
    xmlChar *br_xml = NULL;
    int br_xml_size;
    xmlDocPtr xml_doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr top_node, br_node, if_node, cur;
826
    virshControlPtr priv = ctl->privData;
827 828

    /* Get a handle to the original device */
829 830
    if (!(if_handle = virshCommandOptInterfaceBy(ctl, cmd, "interface",
                                                 &if_name, VIRSH_BYNAME))) {
831 832 833 834
        goto cleanup;
    }

    /* Name for new bridge device */
835
    if (vshCommandOptStringReq(ctl, cmd, "bridge", &br_name) < 0)
836 837 838
        goto cleanup;

    /* make sure "new" device doesn't already exist */
839
    if ((br_handle = virInterfaceLookupByName(priv->conn, br_name))) {
840 841 842 843 844 845 846
        vshError(ctl, _("Network device %s already exists"), br_name);
        goto cleanup;
    }

    /* use "no-stp" because we want "stp" to default true */
    stp = !vshCommandOptBool(cmd, "no-stp");

847
    if (vshCommandOptUInt(ctl, cmd, "delay", &delay) < 0)
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
        goto cleanup;

    nostart = vshCommandOptBool(cmd, "no-start");

    /* Get the original interface into an xmlDoc */
    if (!(if_xml = virInterfaceGetXMLDesc(if_handle, VIR_INTERFACE_XML_INACTIVE)))
        goto cleanup;
    if (!(xml_doc = virXMLParseStringCtxt(if_xml,
                                          _("(interface definition)"), &ctxt))) {
        vshError(ctl, _("Failed to parse configuration of %s"), if_name);
        goto cleanup;
    }
    top_node = ctxt->node;

    /* Verify that the original device isn't already a bridge. */
    if (!(if_type = virXMLPropString(top_node, "type"))) {
        vshError(ctl, _("Existing device %s has no type"), if_name);
        goto cleanup;
    }

    if (STREQ(if_type, "bridge")) {
        vshError(ctl, _("Existing device %s is already a bridge"), if_name);
        goto cleanup;
    }

    /* verify the name in the XML matches the device name */
    if (!(if2_name = virXMLPropString(top_node, "name")) ||
        STRNEQ(if2_name, if_name)) {
        vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"),
                 if2_name, if_name);
        goto cleanup;
    }

    /* Create a <bridge> node under <interface>. */
    if (!(br_node = xmlNewChild(top_node, NULL, BAD_CAST "bridge", NULL))) {
        vshError(ctl, "%s", _("Failed to create bridge node in xml document"));
        goto cleanup;
    }

    /* Set stp and delay attributes in <bridge> according to the
     * commandline options.
     */
890
    if (!xmlSetProp(br_node, BAD_CAST "stp", BAD_CAST(stp ? "on" : "off"))) {
891 892 893 894
        vshError(ctl, "%s", _("Failed to set stp attribute in xml document"));
        goto cleanup;
    }

895 896 897 898 899 900
    if (stp) {
        delay_str = g_strdup_printf("%d", delay);
        if (!xmlSetProp(br_node, BAD_CAST "delay", BAD_CAST delay_str)) {
            vshError(ctl, _("Failed to set bridge delay %d in xml document"), delay);
            goto cleanup;
        }
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    }

    /* Change the type of the outer/master interface to "bridge" and the
     * name to the provided bridge name.
     */
    if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST "bridge")) {
        vshError(ctl, "%s", _("Failed to set bridge interface type to 'bridge' in xml document"));
        goto cleanup;
    }

    if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST br_name)) {
        vshError(ctl, _("Failed to set master bridge interface name to '%s' in xml document"),
            br_name);
        goto cleanup;
    }

    /* Create an <interface> node under <bridge> that uses the
     * original interface's type and name.
     */
    if (!(if_node = xmlNewChild(br_node, NULL, BAD_CAST "interface", NULL))) {
        vshError(ctl, "%s", _("Failed to create interface node under bridge node in xml document"));
        goto cleanup;
    }

925
    /* set the type of the attached interface to the original
926 927 928
     * if_type, and the name to the original if_name.
     */
    if (!xmlSetProp(if_node, BAD_CAST "type", BAD_CAST if_type)) {
929
        vshError(ctl, _("Failed to set new attached interface type to '%s' in xml document"),
930
                 if_type);
931 932 933 934
        goto cleanup;
    }

    if (!xmlSetProp(if_node, BAD_CAST "name", BAD_CAST if_name)) {
935
        vshError(ctl, _("Failed to set new attached interface name to '%s' in xml document"),
936
                 if_name);
937 938 939 940 941 942 943 944 945 946 947 948 949
        goto cleanup;
    }

    /* Cycle through all the nodes under the original <interface>,
     * moving all <mac>, <bond> and <vlan> nodes down into the new
     * lower level <interface>.
     */
    cur = top_node->children;
    while (cur) {
        xmlNodePtr old = cur;

        cur = cur->next;
        if ((old->type == XML_ELEMENT_NODE) &&
950 951 952
            (virXMLNodeNameEqual(old, "mac") ||  /* ethernet stuff to move down */
             virXMLNodeNameEqual(old, "bond") || /* bond stuff to move down */
             virXMLNodeNameEqual(old, "vlan"))) { /* vlan stuff to move down */
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
            xmlUnlinkNode(old);
            if (!xmlAddChild(if_node, old)) {
                vshError(ctl, _("Failed to move '%s' element in xml document"), old->name);
                xmlFreeNode(old);
                goto cleanup;
            }
        }
    }

    /* The document should now be fully converted; write it out to a string. */
    xmlDocDumpMemory(xml_doc, &br_xml, &br_xml_size);

    if (!br_xml || br_xml_size <= 0) {
        vshError(ctl, _("Failed to format new xml document for bridge %s"), br_name);
        goto cleanup;
    }


    /* br_xml is the new interface to define. It will automatically undefine the
     * independent original interface.
     */
974
    if (!(br_handle = virInterfaceDefineXML(priv->conn, (char *) br_xml, 0))) {
975 976 977 978 979
        vshError(ctl, _("Failed to define new bridge interface %s"),
                 br_name);
        goto cleanup;
    }

980 981
    vshPrintExtra(ctl, _("Created bridge %s with attached device %s\n"),
                  br_name, if_name);
982 983 984 985 986 987 988

    /* start it up unless requested not to */
    if (!nostart) {
        if (virInterfaceCreate(br_handle, 0) < 0) {
            vshError(ctl, _("Failed to start bridge interface %s"), br_name);
            goto cleanup;
        }
989
        vshPrintExtra(ctl, _("Bridge interface %s started\n"), br_name);
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    }

    ret = true;
 cleanup:
    if (if_handle)
       virInterfaceFree(if_handle);
    if (br_handle)
       virInterfaceFree(br_handle);
    VIR_FREE(if_xml);
    VIR_FREE(br_xml);
    VIR_FREE(if_type);
    VIR_FREE(if2_name);
    VIR_FREE(delay_str);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml_doc);
    return ret;
}

/*
 * "iface-unbridge" command
 */
static const vshCmdInfo info_interface_unbridge[] = {
1012
    {.name = "help",
1013
     .data = N_("undefine a bridge device after detaching its device(s)")
1014 1015 1016 1017 1018
    },
    {.name = "desc",
     .data = N_("unbridge a network device")
    },
    {.name = NULL}
1019 1020 1021
};

static const vshCmdOptDef opts_interface_unbridge[] = {
1022 1023 1024 1025 1026 1027 1028
    {.name = "bridge",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("current bridge device name")
    },
    {.name = "no-start",
     .type = VSH_OT_BOOL,
1029
     .help = N_("don't start the detached interface immediately (not recommended)")
1030 1031
    },
    {.name = NULL}
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
};

static bool
cmdInterfaceUnbridge(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virInterfacePtr if_handle = NULL, br_handle = NULL;
    const char *br_name;
    char *if_type = NULL, *if_name = NULL;
    bool nostart = false;
    char *br_xml = NULL;
    xmlChar *if_xml = NULL;
    int if_xml_size;
    xmlDocPtr xml_doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
1047
    xmlNodePtr top_node, if_node, cur;
1048
    virshControlPtr priv = ctl->privData;
1049 1050

    /* Get a handle to the original device */
1051 1052
    if (!(br_handle = virshCommandOptInterfaceBy(ctl, cmd, "bridge",
                                                 &br_name, VIRSH_BYNAME))) {
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 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
        goto cleanup;
    }

    nostart = vshCommandOptBool(cmd, "no-start");

    /* Get the bridge xml into an xmlDoc */
    if (!(br_xml = virInterfaceGetXMLDesc(br_handle, VIR_INTERFACE_XML_INACTIVE)))
        goto cleanup;
    if (!(xml_doc = virXMLParseStringCtxt(br_xml,
                                          _("(bridge interface definition)"),
                                          &ctxt))) {
        vshError(ctl, _("Failed to parse configuration of %s"), br_name);
        goto cleanup;
    }
    top_node = ctxt->node;

    /* Verify that the device really is a bridge. */
    if (!(if_type = virXMLPropString(top_node, "type"))) {
        vshError(ctl, _("Existing device %s has no type"), br_name);
        goto cleanup;
    }

    if (STRNEQ(if_type, "bridge")) {
        vshError(ctl, _("Device %s is not a bridge"), br_name);
        goto cleanup;
    }
    VIR_FREE(if_type);

    /* verify the name in the XML matches the device name */
    if (!(if_name = virXMLPropString(top_node, "name")) ||
        STRNEQ(if_name, br_name)) {
        vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"),
                 if_name, br_name);
        goto cleanup;
    }
    VIR_FREE(if_name);

    /* Find the <bridge> node under <interface>. */
1091
    if (virXPathNode("./bridge", ctxt) == NULL) {
1092 1093 1094 1095
        vshError(ctl, "%s", _("No bridge node in xml document"));
        goto cleanup;
    }

1096
    if (virXPathNode("./bridge/interface[2]", ctxt) != NULL) {
1097 1098 1099 1100 1101 1102 1103 1104 1105
        vshError(ctl, "%s", _("Multiple interfaces attached to bridge"));
        goto cleanup;
    }

    if (!(if_node = virXPathNode("./bridge/interface", ctxt))) {
        vshError(ctl, "%s", _("No interface attached to bridge"));
        goto cleanup;
    }

1106 1107
    /* Change the type and name of the bridge interface to
     * the type/name of the attached interface.
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
     */
    if (!(if_name = virXMLPropString(if_node, "name"))) {
        vshError(ctl, _("Device attached to bridge %s has no name"), br_name);
        goto cleanup;
    }

    if (!(if_type = virXMLPropString(if_node, "type"))) {
        vshError(ctl, _("Attached device %s has no type"), if_name);
        goto cleanup;
    }

    if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST if_type)) {
        vshError(ctl, _("Failed to set interface type to '%s' in xml document"),
                 if_type);
        goto cleanup;
    }

    if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST if_name)) {
        vshError(ctl, _("Failed to set interface name to '%s' in xml document"),
                 if_name);
        goto cleanup;
    }

    /* Cycle through all the nodes under the attached <interface>,
     * moving all <mac>, <bond> and <vlan> nodes up into the toplevel
     * <interface>.
     */
    cur = if_node->children;
    while (cur) {
        xmlNodePtr old = cur;

        cur = cur->next;
        if ((old->type == XML_ELEMENT_NODE) &&
1141 1142 1143
            (virXMLNodeNameEqual(old, "mac") ||  /* ethernet stuff to move down */
             virXMLNodeNameEqual(old, "bond") || /* bond stuff to move down */
             virXMLNodeNameEqual(old, "vlan"))) { /* vlan stuff to move down */
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
            xmlUnlinkNode(old);
            if (!xmlAddChild(top_node, old)) {
                vshError(ctl, _("Failed to move '%s' element in xml document"), old->name);
                xmlFreeNode(old);
                goto cleanup;
            }
        }
    }

    /* The document should now be fully converted; write it out to a string. */
    xmlDocDumpMemory(xml_doc, &if_xml, &if_xml_size);

    if (!if_xml || if_xml_size <= 0) {
1157
        vshError(ctl, _("Failed to format new xml document for detached interface %s"),
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
                 if_name);
        goto cleanup;
    }

    /* Destroy and Undefine the bridge device, since we otherwise
     * can't safely define the unattached device.
     */
    if (virInterfaceDestroy(br_handle, 0) < 0) {
        vshError(ctl, _("Failed to destroy bridge interface %s"), br_name);
        goto cleanup;
    }
    if (virInterfaceUndefine(br_handle) < 0) {
        vshError(ctl, _("Failed to undefine bridge interface %s"), br_name);
        goto cleanup;
    }

    /* if_xml is the new interface to define.
     */
1176
    if (!(if_handle = virInterfaceDefineXML(priv->conn, (char *) if_xml, 0))) {
1177 1178 1179 1180
        vshError(ctl, _("Failed to define new interface %s"), if_name);
        goto cleanup;
    }

1181 1182
    vshPrintExtra(ctl, _("Device %s un-attached from bridge %s\n"),
                  if_name, br_name);
1183 1184 1185 1186 1187 1188 1189

    /* unless requested otherwise, undefine the bridge device */
    if (!nostart) {
        if (virInterfaceCreate(if_handle, 0) < 0) {
            vshError(ctl, _("Failed to start interface %s"), if_name);
            goto cleanup;
        }
1190
        vshPrintExtra(ctl, _("Interface %s started\n"), if_name);
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    }

    ret = true;
 cleanup:
    if (if_handle)
       virInterfaceFree(if_handle);
    if (br_handle)
       virInterfaceFree(br_handle);
    VIR_FREE(if_xml);
    VIR_FREE(br_xml);
    VIR_FREE(if_type);
    VIR_FREE(if_name);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml_doc);
    return ret;
}
1207

E
Eric Blake 已提交
1208
const vshCmdDef ifaceCmds[] = {
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    {.name = "iface-begin",
     .handler = cmdInterfaceBegin,
     .opts = opts_interface_begin,
     .info = info_interface_begin,
     .flags = 0
    },
    {.name = "iface-bridge",
     .handler = cmdInterfaceBridge,
     .opts = opts_interface_bridge,
     .info = info_interface_bridge,
     .flags = 0
    },
    {.name = "iface-commit",
     .handler = cmdInterfaceCommit,
     .opts = opts_interface_commit,
     .info = info_interface_commit,
     .flags = 0
    },
    {.name = "iface-define",
     .handler = cmdInterfaceDefine,
     .opts = opts_interface_define,
     .info = info_interface_define,
     .flags = 0
    },
    {.name = "iface-destroy",
     .handler = cmdInterfaceDestroy,
     .opts = opts_interface_destroy,
     .info = info_interface_destroy,
     .flags = 0
    },
    {.name = "iface-dumpxml",
     .handler = cmdInterfaceDumpXML,
     .opts = opts_interface_dumpxml,
     .info = info_interface_dumpxml,
     .flags = 0
    },
    {.name = "iface-edit",
     .handler = cmdInterfaceEdit,
     .opts = opts_interface_edit,
     .info = info_interface_edit,
     .flags = 0
    },
    {.name = "iface-list",
     .handler = cmdInterfaceList,
     .opts = opts_interface_list,
     .info = info_interface_list,
     .flags = 0
    },
    {.name = "iface-mac",
     .handler = cmdInterfaceMAC,
     .opts = opts_interface_mac,
     .info = info_interface_mac,
     .flags = 0
    },
    {.name = "iface-name",
     .handler = cmdInterfaceName,
     .opts = opts_interface_name,
     .info = info_interface_name,
     .flags = 0
    },
    {.name = "iface-rollback",
     .handler = cmdInterfaceRollback,
     .opts = opts_interface_rollback,
     .info = info_interface_rollback,
     .flags = 0
    },
    {.name = "iface-start",
     .handler = cmdInterfaceStart,
     .opts = opts_interface_start,
     .info = info_interface_start,
     .flags = 0
    },
    {.name = "iface-unbridge",
     .handler = cmdInterfaceUnbridge,
     .opts = opts_interface_unbridge,
     .info = info_interface_unbridge,
     .flags = 0
    },
    {.name = "iface-undefine",
     .handler = cmdInterfaceUndefine,
     .opts = opts_interface_undefine,
     .info = info_interface_undefine,
     .flags = 0
    },
    {.name = NULL}
1294
};