virt-admin.c 24.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/*
 * virt-admin.c: a shell to exercise the libvirt admin API
 *
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 * Authors:
 *     Erik Skultety <eskultet@redhat.com>
 */

#include <config.h>
#include "virt-admin.h"

#include <errno.h>
#include <getopt.h>

#if WITH_READLINE
# include <readline/readline.h>
# include <readline/history.h>
#endif

#include "internal.h"
#include "viralloc.h"
#include "virerror.h"
#include "virfile.h"
#include "virstring.h"
#include "virthread.h"
40
#include "virgettext.h"
41 42 43 44 45 46 47 48 49 50 51 52 53

/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

#define VIRT_ADMIN_PROMPT "virt-admin # "

static char *progname;

static const vshCmdGrp cmdGroups[];
static const vshClientHooks hooks;

54 55 56 57
/*
 * vshAdmCatchDisconnect:
 *
 * We get here when the connection was closed. Unlike virsh, we do not save
58
 * the fact that the event was raised, sice there is virAdmConnectIsAlive to
59 60 61
 * check if the communication channel has not been closed by remote party.
 */
static void
62
vshAdmCatchDisconnect(virAdmConnectPtr conn ATTRIBUTE_UNUSED,
63 64 65 66 67 68 69 70 71 72 73 74
                      int reason,
                      void *opaque)
{
    vshControl *ctl = opaque;
    const char *str = "unknown reason";
    virErrorPtr error;
    char *uri = NULL;

    if (reason == VIR_CONNECT_CLOSE_REASON_CLIENT)
        return;

    error = virSaveLastError();
75
    uri = virAdmConnectGetURI(conn);
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

    switch ((virConnectCloseReason) reason) {
    case VIR_CONNECT_CLOSE_REASON_ERROR:
        str = N_("Disconnected from %s due to I/O error");
        break;
    case VIR_CONNECT_CLOSE_REASON_EOF:
        str = N_("Disconnected from %s due to end of file");
        break;
    case VIR_CONNECT_CLOSE_REASON_KEEPALIVE:
        str = N_("Disconnected from %s due to keepalive timeout");
        break;
        /* coverity[dead_error_condition] */
    case VIR_CONNECT_CLOSE_REASON_CLIENT:
    case VIR_CONNECT_CLOSE_REASON_LAST:
        break;
    }

    vshError(ctl, _(str), NULLSTR(uri));
94
    VIR_FREE(uri);
95 96 97 98 99 100 101

    if (error) {
        virSetError(error);
        virFreeError(error);
    }
}

102
static int
103
vshAdmConnect(vshControl *ctl, unsigned int flags)
104 105 106
{
    vshAdmControlPtr priv = ctl->privData;

107
    priv->conn = virAdmConnectOpen(ctl->connname, flags);
108

109
    if (!priv->conn) {
110 111 112 113 114 115
        if (priv->wantReconnect)
            vshError(ctl, "%s", _("Failed to reconnect to the admin server"));
        else
            vshError(ctl, "%s", _("Failed to connect to the admin server"));
        return -1;
    } else {
116 117
        if (virAdmConnectRegisterCloseCallback(priv->conn, vshAdmCatchDisconnect,
                                               NULL, NULL) < 0)
118 119
            vshError(ctl, "%s", _("Unable to register disconnect callback"));

120 121 122 123 124 125 126 127 128 129 130 131 132
        if (priv->wantReconnect)
            vshPrint(ctl, "%s\n", _("Reconnected to the admin server"));
    }

    return 0;
}

static int
vshAdmDisconnect(vshControl *ctl)
{
    int ret = 0;
    vshAdmControlPtr priv = ctl->privData;

133
    if (!priv->conn)
134 135
        return ret;

136 137
    virAdmConnectUnregisterCloseCallback(priv->conn, vshAdmCatchDisconnect);
    ret = virAdmConnectClose(priv->conn);
138 139 140 141 142
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to disconnect from the admin server"));
    else if (ret > 0)
        vshError(ctl, "%s", _("One or more references were leaked after "
                              "disconnect from the hypervisor"));
143
    priv->conn = NULL;
144 145 146 147 148 149 150 151 152 153 154 155 156
    return ret;
}

/*
 * vshAdmReconnect:
 *
 * Reconnect to a daemon's admin server
 *
 */
static void
vshAdmReconnect(vshControl *ctl)
{
    vshAdmControlPtr priv = ctl->privData;
157
    if (priv->conn)
158 159 160
        priv->wantReconnect = true;

    vshAdmDisconnect(ctl);
161
    vshAdmConnect(ctl, 0);
162 163 164 165

    priv->wantReconnect = false;
}

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
/*
 * 'uri' command
 */

static const vshCmdInfo info_uri[] = {
    {.name = "help",
     .data = N_("print the admin server URI")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
};

static bool
cmdURI(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *uri;
    vshAdmControlPtr priv = ctl->privData;

186
    uri = virAdmConnectGetURI(priv->conn);
187 188 189 190 191 192 193 194 195 196 197
    if (!uri) {
        vshError(ctl, "%s", _("failed to get URI"));
        return false;
    }

    vshPrint(ctl, "%s\n", uri);
    VIR_FREE(uri);

    return true;
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
/*
 * "version" command
 */

static const vshCmdInfo info_version[] = {
    {.name = "help",
     .data = N_("show version")
    },
    {.name = "desc",
     .data = N_("Display the system and also the daemon version information.")
    },
    {.name = NULL}
};

static bool
cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    unsigned long libVersion;
    unsigned long long includeVersion;
    unsigned long long daemonVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
    vshAdmControlPtr priv = ctl->privData;

    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
    vshPrint(ctl, _("Compiled against library: libvirt %d.%d.%d\n"),
             major, minor, rel);

    ret = virGetVersion(&libVersion, NULL, NULL);
    if (ret < 0) {
        vshError(ctl, "%s", _("failed to get the library version"));
        return false;
    }
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
    vshPrint(ctl, _("Using library: libvirt %d.%d.%d\n"),
             major, minor, rel);

244
    ret = virAdmConnectGetLibVersion(priv->conn, &daemonVersion);
245 246 247 248 249 250 251 252 253 254 255 256 257 258
    if (ret < 0) {
        vshError(ctl, "%s", _("failed to get the daemon version"));
    } else {
        major = daemonVersion / 1000000;
        daemonVersion %= 1000000;
        minor = daemonVersion / 1000;
        rel = daemonVersion % 1000;
        vshPrint(ctl, _("Running against daemon: %d.%d.%d\n"),
                 major, minor, rel);
    }

    return true;
}

259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
/* ---------------
 * Command Connect
 * ---------------
 */

static const vshCmdOptDef opts_connect[] = {
    {.name = "name",
     .type = VSH_OT_STRING,
     .flags = VSH_OFLAG_EMPTY_OK,
     .help = N_("daemon's admin server connection URI")
    },
    {.name = NULL}
};

static const vshCmdInfo info_connect[] = {
    {.name = "help",
     .data = N_("connect to daemon's admin server")
    },
    {.name = "desc",
     .data = N_("Connect to a daemon's administrating server.")
    },
    {.name = NULL}
};

static bool
cmdConnect(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
    vshAdmControlPtr priv = ctl->privData;
289
    bool connected = priv->conn;
290 291 292 293

    if (vshCommandOptStringReq(ctl, cmd, "name", &name) < 0)
        return false;

294 295
    VIR_FREE(ctl->connname);
    ctl->connname = vshStrdup(ctl, name);
296 297

    vshAdmReconnect(ctl);
298 299
    if (!connected)
        vshPrint(ctl, "%s\n", _("Connected to the admin server"));
300

301
    return !!priv->conn;
302 303
}

E
Erik Skultety 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

/* ---------------
 * Command srv-list
 * ---------------
 */

static const vshCmdInfo info_srv_list[] = {
    {.name = "help",
     .data = N_("list available servers on a daemon")
    },
    {.name = "desc",
     .data = N_("List all manageable servers on a daemon.")
    },
    {.name = NULL}
};

static bool
cmdSrvList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    int nsrvs = 0;
    size_t i;
    bool ret = false;
326
    char *uri = NULL;
E
Erik Skultety 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    virAdmServerPtr *srvs = NULL;
    vshAdmControlPtr priv = ctl->privData;

    /* Obtain a list of available servers on the daemon */
    if ((nsrvs = virAdmConnectListServers(priv->conn, &srvs, 0)) < 0) {
        uri = virAdmConnectGetURI(priv->conn);
        vshError(ctl, _("failed to obtain list of available servers from %s"),
                 NULLSTR(uri));
        goto cleanup;
    }

    printf(" %-5s %-15s\n", "Id", "Name");
    printf("---------------\n");
    for (i = 0; i < nsrvs; i++)
        vshPrint(ctl, " %-5zu %-15s\n", i, virAdmServerGetName(srvs[i]));

    ret = true;
 cleanup:
    if (srvs) {
        for (i = 0; i < nsrvs; i++)
            virAdmServerFree(srvs[i]);
        VIR_FREE(srvs);
    }
350
    VIR_FREE(uri);
E
Erik Skultety 已提交
351 352 353 354

    return ret;
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522

/* ---------------------------
 * Command srv-threadpool-info
 * ---------------------------
 */

static const vshCmdInfo info_srv_threadpool_info[] = {
    {.name = "help",
     .data = N_("get server workerpool parameters")
    },
    {.name = "desc",
     .data = N_("Retrieve threadpool attributes from a server. ")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_srv_threadpool_info[] = {
    {.name = "server",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("Server to retrieve threadpool attributes from."),
    },
    {.name = NULL}
};

static bool
cmdSrvThreadpoolInfo(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virTypedParameterPtr params = NULL;
    int nparams = 0;
    size_t i;
    const char *srvname = NULL;
    virAdmServerPtr srv = NULL;
    vshAdmControlPtr priv = ctl->privData;

    if (vshCommandOptStringReq(ctl, cmd, "server", &srvname) < 0)
        return false;

    if (!(srv = virAdmConnectLookupServer(priv->conn, srvname, 0)))
        goto cleanup;

    if (virAdmServerGetThreadPoolParameters(srv, &params,
                                            &nparams, 0) < 0) {
        vshError(ctl, "%s",
                 _("Unable to get server workerpool parameters"));
        goto cleanup;
    }

    for (i = 0; i < nparams; i++)
        vshPrint(ctl, "%-15s: %d\n", params[i].field, params[i].value.ui);

    ret = true;

 cleanup:
    virTypedParamsFree(params, nparams);
    if (srv)
        virAdmServerFree(srv);
    return ret;
}

/* --------------------------
 * Command srv-threadpool-set
 * --------------------------
 */

static const vshCmdInfo info_srv_threadpool_set[] = {
    {.name = "help",
     .data = N_("set server workerpool parameters")
    },
    {.name = "desc",
     .data = N_("Tune threadpool attributes on a server. See OPTIONS for "
                "currently supported attributes.")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_srv_threadpool_set[] = {
    {.name = "server",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("Server to alter threadpool attributes on."),
    },
    {.name = "min-workers",
     .type = VSH_OT_INT,
     .help = N_("Change bottom limit to number of workers."),
    },
    {.name = "max-workers",
     .type = VSH_OT_INT,
     .help = N_("Change upper limit to number of workers."),
    },
    {.name = "priority-workers",
     .type = VSH_OT_INT,
     .help = N_("Change the current number of priority workers"),
    },
    {.name = NULL}
};

static bool
cmdSrvThreadpoolSet(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    int rv = 0;
    unsigned int val, min, max;
    int maxparams = 0;
    int nparams = 0;
    const char *srvname = NULL;
    virTypedParameterPtr params = NULL;
    virAdmServerPtr srv = NULL;
    vshAdmControlPtr priv = ctl->privData;

    if (vshCommandOptStringReq(ctl, cmd, "server", &srvname) < 0)
        return false;

#define PARSE_CMD_TYPED_PARAM(NAME, FIELD)                                   \
    if ((rv = vshCommandOptUInt(ctl, cmd, NAME, &val)) < 0) {                \
        vshError(ctl, _("Unable to parse integer parameter '%s'"), NAME);    \
        goto cleanup;                                                        \
    } else if (rv > 0) {                                                     \
        if (virTypedParamsAddUInt(&params, &nparams, &maxparams,             \
                                  FIELD, val) < 0)                           \
        goto save_error;                                                     \
    }

    PARSE_CMD_TYPED_PARAM("max-workers", VIR_THREADPOOL_WORKERS_MAX);
    PARSE_CMD_TYPED_PARAM("min-workers", VIR_THREADPOOL_WORKERS_MIN);
    PARSE_CMD_TYPED_PARAM("priority-workers", VIR_THREADPOOL_WORKERS_PRIORITY);

#undef PARSE_CMD_TYPED_PARAM

    if (!nparams) {
        vshError(ctl, "%s",
                 _("At least one of options --min-workers, --max-workers, "
                   "--priority-workers is mandatory "));
            goto cleanup;
    }

    if (virTypedParamsGetUInt(params, nparams,
                              VIR_THREADPOOL_WORKERS_MAX, &max) &&
        virTypedParamsGetUInt(params, nparams,
                              VIR_THREADPOOL_WORKERS_MIN, &min) && min > max) {
        vshError(ctl, "%s", _("--min-workers must be less than --max-workers"));
        goto cleanup;
    }

    if (!(srv = virAdmConnectLookupServer(priv->conn, srvname, 0)))
        goto cleanup;

    if (virAdmServerSetThreadPoolParameters(srv, params,
                                            nparams, 0) < 0)
        goto error;

    ret = true;

 cleanup:
    virTypedParamsFree(params, nparams);
    if (srv)
        virAdmServerFree(srv);
    return ret;

 save_error:
    vshSaveLibvirtError();

 error:
    vshError(ctl, "%s", _("Unable to change server workerpool parameters"));
    goto cleanup;
}

523
static void *
524
vshAdmConnectionHandler(vshControl *ctl)
525 526 527
{
    vshAdmControlPtr priv = ctl->privData;

528
    if (!virAdmConnectIsAlive(priv->conn))
529 530
        vshAdmReconnect(ctl);

531
    if (!virAdmConnectIsAlive(priv->conn)) {
532 533 534 535
        vshError(ctl, "%s", _("no valid connection"));
        return NULL;
    }

536
    return priv->conn;
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
}

/*
 * Initialize connection.
 */
static bool
vshAdmInit(vshControl *ctl)
{
    vshAdmControlPtr priv = ctl->privData;

    /* Since we have the commandline arguments parsed, we need to
     * reload our initial settings to make debugging and readline
     * work properly */
    vshInitReload(ctl);

552
    if (priv->conn)
553 554 555 556 557 558 559 560 561 562 563 564
        return false;

    /* set up the library error handler */
    virSetErrorFunc(NULL, vshErrorHandler);

    if (virEventRegisterDefaultImpl() < 0)
        return false;

    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

565
    if (ctl->connname) {
566 567 568 569 570 571 572
        vshAdmReconnect(ctl);
        /* Connecting to a named connection must succeed, but we delay
         * connecting to the default connection until we need it
         * (since the first command might be 'connect' which allows a
         * non-default connection, or might be 'help' which needs no
         * connection).
         */
573
        if (!priv->conn) {
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
            vshReportError(ctl);
            return false;
        }
    }

    return true;
}

static void
vshAdmDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

/*
 * Deinitialize virt-admin
 */
static void
vshAdmDeinit(vshControl *ctl)
{
    vshAdmControlPtr priv = ctl->privData;

    vshDeinit(ctl);
597
    VIR_FREE(ctl->connname);
598

599
    if (priv->conn)
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        vshAdmDisconnect(ctl);

    virResetLastError();

    if (ctl->eventLoopStarted) {
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
        /* HACK: Add a dummy timeout to break event loop */
        timer = virEventAddTimeout(0, vshAdmDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

    virMutexDestroy(&ctl->lock);
}

/*
 * Print usage
 */
static void
vshAdmUsage(void)
{
    const vshCmdGrp *grp;
    const vshCmdDef *cmd;

    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
                      "  options:\n"
                      "    -c | --connect=URI      daemon admin connection URI\n"
                      "    -d | --debug=NUM        debug level [0-4]\n"
                      "    -h | --help             this help\n"
                      "    -l | --log=FILE         output logging to file\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
                      "  commands (non interactive mode):\n\n"), progname,
            progname);

    for (grp = cmdGroups; grp->name; grp++) {
        fprintf(stdout, _(" %s (help keyword '%s')\n"),
                grp->name, grp->keyword);
        for (cmd = grp->commands; cmd->name; cmd++) {
            if (cmd->flags & VSH_CMD_FLAG_ALIAS)
                continue;
            fprintf(stdout,
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
}

/*
 * Show version and options compiled in
 */
static void
vshAdmShowVersion(vshControl *ctl ATTRIBUTE_UNUSED)
{
    /* FIXME - list a copyright blurb, as in GNU programs?  */
    vshPrint(ctl, _("Virt-admin command line tool of libvirt %s\n"), VERSION);
    vshPrint(ctl, _("See web site at %s\n\n"), "http://libvirt.org/");

    vshPrint(ctl, "%s", _("Compiled with support for:"));
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
#ifdef ENABLE_DEBUG
    vshPrint(ctl, " Debug");
#endif
#if WITH_READLINE
    vshPrint(ctl, " Readline");
#endif
    vshPrint(ctl, "\n");
}

static bool
vshAdmParseArgv(vshControl *ctl, int argc, char **argv)
{
    int arg, debug;
    size_t i;
    int longindex = -1;
    struct option opt[] = {
        {"connect", required_argument, NULL, 'c'},
        {"debug", required_argument, NULL, 'd'},
        {"help", no_argument, NULL, 'h'},
        {"log", required_argument, NULL, 'l'},
        {"quiet", no_argument, NULL, 'q'},
        {"version", optional_argument, NULL, 'v'},
        {NULL, 0, NULL, 0}
    };

    /* Standard (non-command) options. The leading + ensures that no
     * argument reordering takes place, so that command options are
     * not confused with top-level virt-admin options. */
    while ((arg = getopt_long(argc, argv, "+:c:d:hl:qvV", opt, &longindex)) != -1) {
        switch (arg) {
        case 'c':
712 713
            VIR_FREE(ctl->connname);
            ctl->connname = vshStrdup(ctl, optarg);
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
            break;
        case 'd':
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
                vshError(ctl, _("option %s takes a numeric argument"),
                         longindex == -1 ? "-d" : "--debug");
                exit(EXIT_FAILURE);
            }
            if (debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR)
                vshError(ctl, _("ignoring debug level %d out of range [%d-%d]"),
                         debug, VSH_ERR_DEBUG, VSH_ERR_ERROR);
            else
                ctl->debug = debug;
            break;
        case 'h':
            vshAdmUsage();
            exit(EXIT_SUCCESS);
            break;
        case 'l':
            vshCloseLogFile(ctl);
            ctl->logfile = vshStrdup(ctl, optarg);
            vshOpenLogFile(ctl);
            break;
        case 'q':
            ctl->quiet = true;
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
            vshAdmShowVersion(ctl);
            exit(EXIT_SUCCESS);
        case ':':
            for (i = 0; opt[i].name != NULL; i++) {
                if (opt[i].val == optopt)
                    break;
            }
            if (opt[i].name)
                vshError(ctl, _("option '-%c'/'--%s' requires an argument"),
                         optopt, opt[i].name);
            else
                vshError(ctl, _("option '-%c' requires an argument"), optopt);
            exit(EXIT_FAILURE);
        case '?':
            if (optopt)
                vshError(ctl, _("unsupported option '-%c'. See --help."), optopt);
            else
                vshError(ctl, _("unsupported option '%s'. See --help."), argv[optind - 1]);
            exit(EXIT_FAILURE);
        default:
            vshError(ctl, _("unknown option"));
            exit(EXIT_FAILURE);
        }
        longindex = -1;
    }

    if (argc == optind) {
        ctl->imode = true;
    } else {
        /* parse command */
        ctl->imode = false;
        if (argc - optind == 1) {
            vshDebug(ctl, VSH_ERR_INFO, "commands: \"%s\"\n", argv[optind]);
            return vshCommandStringParse(ctl, argv[optind]);
        } else {
            return vshCommandArgvParse(ctl, argc - optind, argv + optind);
        }
    }
    return true;
}

static const vshCmdDef vshAdmCmds[] = {
    VSH_CMD_CD,
    VSH_CMD_ECHO,
    VSH_CMD_EXIT,
    VSH_CMD_HELP,
    VSH_CMD_PWD,
    VSH_CMD_QUIT,
794 795 796 797 798 799
    {.name = "uri",
     .handler = cmdURI,
     .opts = NULL,
     .info = info_uri,
     .flags = 0
    },
800 801 802 803 804 805
    {.name = "version",
     .handler = cmdVersion,
     .opts = NULL,
     .info = info_version,
     .flags = 0
    },
806 807 808 809 810 811 812 813 814
    {.name = "connect",
     .handler = cmdConnect,
     .opts = opts_connect,
     .info = info_connect,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = NULL}
};

E
Erik Skultety 已提交
815 816 817 818 819 820 821
static const vshCmdDef monitoringCmds[] = {
    {.name = "srv-list",
     .handler = cmdSrvList,
     .opts = NULL,
     .info = info_srv_list,
     .flags = 0
    },
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
    {.name = "srv-threadpool-info",
     .handler = cmdSrvThreadpoolInfo,
     .opts = opts_srv_threadpool_info,
     .info = info_srv_threadpool_info,
     .flags = 0
    },
    {.name = NULL}
};

static const vshCmdDef managementCmds[] = {
    {.name = "srv-threadpool-set",
     .handler = cmdSrvThreadpoolSet,
     .opts = opts_srv_threadpool_set,
     .info = info_srv_threadpool_set,
     .flags = 0
    },
E
Erik Skultety 已提交
838 839 840
    {.name = NULL}
};

841 842
static const vshCmdGrp cmdGroups[] = {
    {"Virt-admin itself", "virt-admin", vshAdmCmds},
E
Erik Skultety 已提交
843
    {"Monitoring commands", "monitor", monitoringCmds},
844
    {"Management commands", "management", managementCmds},
845 846 847 848
    {NULL, NULL, NULL}
};

static const vshClientHooks hooks = {
849
    .connHandler = vshAdmConnectionHandler
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
};

int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
    vshAdmControl virtAdminCtl;
    bool ret = true;

    memset(ctl, 0, sizeof(vshControl));
    memset(&virtAdminCtl, 0, sizeof(vshAdmControl));
    ctl->name = "virt-admin";        /* hardcoded name of the binary */
    ctl->log_fd = -1;                /* Initialize log file descriptor */
    ctl->debug = VSH_DEBUG_DEFAULT;
    ctl->hooks = &hooks;

    ctl->eventPipe[0] = -1;
    ctl->eventPipe[1] = -1;
    ctl->privData = &virtAdminCtl;

    if (!(progname = strrchr(argv[0], '/')))
        progname = argv[0];
    else
        progname++;
    ctl->progname = progname;

876
    if (virGettextInitialize() < 0)
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
        return EXIT_FAILURE;

    if (isatty(STDIN_FILENO)) {
        ctl->istty = true;

#ifndef WIN32
        if (tcgetattr(STDIN_FILENO, &ctl->termattr) < 0)
            ctl->istty = false;
#endif
    }

    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

    virFileActivateDirOverride(argv[0]);

    if (!vshInit(ctl, cmdGroups, NULL))
        exit(EXIT_FAILURE);

    if (!vshAdmParseArgv(ctl, argc, argv) ||
        !vshAdmInit(ctl)) {
        vshAdmDeinit(ctl);
        exit(EXIT_FAILURE);
    }

    if (!ctl->imode) {
        ret = vshCommandRun(ctl, ctl->cmd);
    } else {
        /* interactive mode */
        if (!ctl->quiet) {
            vshPrint(ctl,
                     _("Welcome to %s, the administrating virtualization "
                       "interactive terminal.\n\n"),
                     progname);
            vshPrint(ctl, "%s",
                     _("Type:  'help' for help with commands\n"
                       "       'quit' to quit\n\n"));
        }

        do {
            ctl->cmdstr = vshReadline(ctl, VIRT_ADMIN_PROMPT);
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
            if (*ctl->cmdstr) {
#if WITH_READLINE
                add_history(ctl->cmdstr);
#endif
                if (vshCommandStringParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            VIR_FREE(ctl->cmdstr);
        } while (ctl->imode);

        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
    }

    vshAdmDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
}