virt-admin.c 42.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
/*
 * 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/>.
 */

#include <config.h>
#include "virt-admin.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"
37
#include "virgettext.h"
38
#include "virtime.h"
39
#include "virt-admin-completer.h"
40
#include "vsh-table.h"
41
#include "virenum.h"
42 43 44 45 46 47 48 49

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

#define VIRT_ADMIN_PROMPT "virt-admin # "

50 51 52
/* we don't need precision to milliseconds in this module */
#define VIRT_ADMIN_TIME_BUFLEN VIR_TIME_STRING_BUFLEN - 3

53 54 55 56 57
static char *progname;

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

58
VIR_ENUM_DECL(virClientTransport);
59 60 61 62
VIR_ENUM_IMPL(virClientTransport,
              VIR_CLIENT_TRANS_LAST,
              N_("unix"),
              N_("tcp"),
63
              N_("tls"));
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

static const char *
vshAdmClientTransportToString(int transport)
{
    const char *str = virClientTransportTypeToString(transport);
    return str ? _(str) : _("unknown");
}

/*
 * vshAdmGetTimeStr:
 *
 * Produces string representation (local time) of @then
 * (seconds since epoch UTC) using format 'YYYY-MM-DD HH:MM:SS+ZZZZ'.
 *
 * Returns 0 if conversion finished successfully, -1 in case of an error.
 * Caller is responsible for freeing the string returned.
 */
static int
vshAdmGetTimeStr(vshControl *ctl, time_t then, char **result)
{
    char *tmp = NULL;
    struct tm timeinfo;

    if (!localtime_r(&then, &timeinfo))
        goto error;

    if (VIR_ALLOC_N(tmp, VIRT_ADMIN_TIME_BUFLEN) < 0)
        goto error;

    if (strftime(tmp, VIRT_ADMIN_TIME_BUFLEN, "%Y-%m-%d %H:%M:%S%z",
                 &timeinfo) == 0) {
        VIR_FREE(tmp);
        goto error;
    }

    *result = tmp;
    return 0;

 error:
    vshError(ctl, "%s", _("Timestamp string conversion failed"));
    return -1;
}

107 108 109 110
/*
 * vshAdmCatchDisconnect:
 *
 * We get here when the connection was closed. Unlike virsh, we do not save
N
Nitesh Konkar 已提交
111
 * the fact that the event was raised, since there is virAdmConnectIsAlive to
112 113 114
 * check if the communication channel has not been closed by remote party.
 */
static void
J
Ján Tomko 已提交
115
vshAdmCatchDisconnect(virAdmConnectPtr conn G_GNUC_UNUSED,
116 117 118 119 120 121 122 123 124 125 126
                      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;

127
    virErrorPreserveLast(&error);
128
    uri = virAdmConnectGetURI(conn);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

    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));
147
    VIR_FREE(uri);
148

149
    virErrorRestore(&error);
150 151
}

152
static int
153
vshAdmConnect(vshControl *ctl, unsigned int flags)
154 155 156
{
    vshAdmControlPtr priv = ctl->privData;

157
    priv->conn = virAdmConnectOpen(ctl->connname, flags);
158

159
    if (!priv->conn) {
160 161 162 163 164 165
        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 {
166 167
        if (virAdmConnectRegisterCloseCallback(priv->conn, vshAdmCatchDisconnect,
                                               NULL, NULL) < 0)
168 169
            vshError(ctl, "%s", _("Unable to register disconnect callback"));

170 171 172 173 174 175 176 177 178 179 180 181 182
        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;

183
    if (!priv->conn)
184 185
        return ret;

186 187
    virAdmConnectUnregisterCloseCallback(priv->conn, vshAdmCatchDisconnect);
    ret = virAdmConnectClose(priv->conn);
188 189 190 191 192
    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"));
193
    priv->conn = NULL;
194 195 196 197 198 199 200 201 202 203 204 205 206
    return ret;
}

/*
 * vshAdmReconnect:
 *
 * Reconnect to a daemon's admin server
 *
 */
static void
vshAdmReconnect(vshControl *ctl)
{
    vshAdmControlPtr priv = ctl->privData;
207
    if (priv->conn)
208 209 210
        priv->wantReconnect = true;

    vshAdmDisconnect(ctl);
211
    vshAdmConnect(ctl, 0);
212 213 214 215

    priv->wantReconnect = false;
}

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
/*
 * 'uri' command
 */

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

static bool
J
Ján Tomko 已提交
231
cmdURI(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
232 233 234 235
{
    char *uri;
    vshAdmControlPtr priv = ctl->privData;

236
    uri = virAdmConnectGetURI(priv->conn);
237 238 239 240 241 242 243 244 245 246 247
    if (!uri) {
        vshError(ctl, "%s", _("failed to get URI"));
        return false;
    }

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

    return true;
}

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
/*
 * "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
J
Ján Tomko 已提交
263
cmdVersion(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
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 289 290 291 292 293
{
    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);

294
    ret = virAdmConnectGetLibVersion(priv->conn, &daemonVersion);
295 296 297 298 299 300 301 302 303 304 305 306 307 308
    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;
}

309

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
/* ---------------
 * 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;
339
    bool connected = priv->conn;
340 341 342 343

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

M
Martin Kletzander 已提交
344 345
    if (name) {
        VIR_FREE(ctl->connname);
J
Ján Tomko 已提交
346
        ctl->connname = g_strdup(name);
M
Martin Kletzander 已提交
347
    }
348 349

    vshAdmReconnect(ctl);
350
    if (!connected && priv->conn)
351
        vshPrint(ctl, "%s\n", _("Connected to the admin server"));
352

353
    return !!priv->conn;
354 355
}

E
Erik Skultety 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

/* ---------------
 * 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
J
Ján Tomko 已提交
373
cmdSrvList(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
E
Erik Skultety 已提交
374 375 376 377
{
    int nsrvs = 0;
    size_t i;
    bool ret = false;
378
    char *uri = NULL;
E
Erik Skultety 已提交
379 380
    virAdmServerPtr *srvs = NULL;
    vshAdmControlPtr priv = ctl->privData;
381
    vshTablePtr table = NULL;
E
Erik Skultety 已提交
382 383 384 385 386 387 388 389 390

    /* 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;
    }

391 392 393 394 395
    table = vshTableNew(_("Id"), _("Name"), NULL);
    if (!table)
        goto cleanup;

    for (i = 0; i < nsrvs; i++) {
396
        g_autofree char *idStr = NULL;
M
Michal Privoznik 已提交
397
        if (virAsprintf(&idStr, "%zu", i) < 0)
398 399 400 401 402 403 404 405 406 407
            goto cleanup;

        if (vshTableRowAppend(table,
                              idStr,
                              virAdmServerGetName(srvs[i]),
                              NULL) < 0)
            goto cleanup;
    }

    vshTablePrintToStdout(table, ctl);
E
Erik Skultety 已提交
408 409 410

    ret = true;
 cleanup:
411
    vshTableFree(table);
E
Erik Skultety 已提交
412 413 414 415 416
    if (srvs) {
        for (i = 0; i < nsrvs; i++)
            virAdmServerFree(srvs[i]);
        VIR_FREE(srvs);
    }
417
    VIR_FREE(uri);
E
Erik Skultety 已提交
418 419 420 421

    return ret;
}

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

/* ---------------------------
 * 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,
442
     .completer = vshAdmServerCompleter,
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
     .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++)
473
        vshPrint(ctl, "%-15s: %u\n", params[i].field, params[i].value.ui);
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

    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,
504
     .completer = vshAdmServerCompleter,
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
     .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;

538 539 540 541 542 543 544 545
#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; \
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    }

    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) {
565 566
        vshError(ctl, "%s", _("--min-workers must be less than or equal to "
                              "--max-workers"));
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
        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;
}

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
/* ------------------------
 * Command srv-clients-list
 * ------------------------
 */

static const vshCmdInfo info_srv_clients_list[] = {
    {.name = "help",
     .data = N_("list clients connected to <server>")
    },
    {.name = "desc",
     .data = N_("List all manageable clients connected to <server>.")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_srv_clients_list[] = {
    {.name = "server",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
612
     .completer = vshAdmServerCompleter,
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
     .help = N_("server which to list connected clients from"),
    },
    {.name = NULL}
};

static bool
cmdSrvClientsList(vshControl *ctl, const vshCmd *cmd)
{
    int nclts = 0;
    size_t i;
    bool ret = false;
    const char *srvname = NULL;
    unsigned long long id;
    virClientTransport transport;
    virAdmServerPtr srv = NULL;
    virAdmClientPtr *clts = NULL;
    vshAdmControlPtr priv = ctl->privData;
630
    vshTablePtr table = NULL;
631 632 633 634 635 636 637 638 639 640 641 642 643 644

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

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

    /* Obtain a list of clients connected to server @srv */
    if ((nclts = virAdmServerListClients(srv, &clts, 0)) < 0) {
        vshError(ctl, _("failed to obtain list of connected clients "
                        "from server '%s'"), virAdmServerGetName(srv));
        goto cleanup;
    }

645
    table = vshTableNew(_("Id"), _("Transport"), _("Connected since"), NULL);
646 647
    if (!table)
        goto cleanup;
648 649

    for (i = 0; i < nclts; i++) {
650 651
        g_autofree char *timestr = NULL;
        g_autofree char *idStr = NULL;
652 653 654 655 656 657 658
        virAdmClientPtr client = clts[i];
        id = virAdmClientGetID(client);
        transport = virAdmClientGetTransport(client);
        if (vshAdmGetTimeStr(ctl, virAdmClientGetTimestamp(client),
                             &timestr) < 0)
            goto cleanup;

659 660 661 662 663 664
        if (virAsprintf(&idStr, "%llu", id) < 0)
            goto cleanup;
        if (vshTableRowAppend(table, idStr,
                              vshAdmClientTransportToString(transport),
                              timestr, NULL) < 0)
            goto cleanup;
665 666
    }

667 668
    vshTablePrintToStdout(table, ctl);

669 670 671
    ret = true;

 cleanup:
672
    vshTableFree(table);
673 674 675 676 677 678 679 680 681
    if (clts) {
        for (i = 0; i < nclts; i++)
            virAdmClientFree(clts[i]);
        VIR_FREE(clts);
    }
    virAdmServerFree(srv);
    return ret;
}

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
/* -------------------
 * Command client-info
 * -------------------
 */

static const vshCmdInfo info_client_info[] = {
    {.name = "help",
     .data = N_("retrieve client's identity info from server")
    },
    {.name = "desc",
     .data = N_("Retrieve identity details about <client> from <server>")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_client_info[] = {
    {.name = "server",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
701
     .completer = vshAdmServerCompleter,
702 703 704 705 706 707 708 709 710 711 712 713 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
     .help = N_("server to which <client> is connected to"),
    },
    {.name = "client",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("client which to retrieve identity information for"),
    },
    {.name = NULL}
};

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

    if (vshCommandOptULongLong(ctl, cmd, "client", &id) < 0)
        return false;

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

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

    /* Retrieve client identity info */
    if (virAdmClientGetInfo(clnt, &params, &nparams, 0) < 0) {
        vshError(ctl, _("failed to retrieve client identity information for "
                        "client '%llu' connected to server '%s'"),
                        id, virAdmServerGetName(srv));
        goto cleanup;
    }

    if (vshAdmGetTimeStr(ctl, virAdmClientGetTimestamp(clnt), &timestr) < 0)
        goto cleanup;

    /* this info is provided by the client object itself */
    vshPrint(ctl, "%-15s: %llu\n", "id", virAdmClientGetID(clnt));
    vshPrint(ctl, "%-15s: %s\n", "connection_time", timestr);
    vshPrint(ctl, "%-15s: %s\n", "transport",
             vshAdmClientTransportToString(virAdmClientGetTransport(clnt)));

    for (i = 0; i < nparams; i++) {
        char *str = vshGetTypedParamValue(ctl, &params[i]);
        vshPrint(ctl, "%-15s: %s\n", params[i].field, str);
        VIR_FREE(str);
    }

    ret = true;

 cleanup:
    virTypedParamsFree(params, nparams);
    virAdmServerFree(srv);
    virAdmClientFree(clnt);
    VIR_FREE(timestr);
    return ret;
}
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

/* -------------------------
 * Command client-disconnect
 * -------------------------
 */

static const vshCmdInfo info_client_disconnect[] = {
    {.name = "help",
     .data = N_("force disconnect a client from the given server")
    },
    {.name = "desc",
     .data = N_("Force close a specific client's connection to the given "
                "server.")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_client_disconnect[] = {
    {.name = "server",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
789
     .completer = vshAdmServerCompleter,
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
     .help = N_("server which the client is currently connected to"),
    },
    {.name = "client",
     .type = VSH_OT_INT,
     .flags = VSH_OFLAG_REQ,
     .help = N_("client which to disconnect, specified by ID"),
    },
    {.name = NULL}
};

static bool
cmdClientDisconnect(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    const char *srvname = NULL;
    unsigned long long id = 0;
    virAdmServerPtr srv = NULL;
    virAdmClientPtr client = NULL;
    vshAdmControlPtr priv = ctl->privData;

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

    if (vshCommandOptULongLongWrap(ctl, cmd, "client", &id) < 0)
        return false;

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

    if (!(client = virAdmServerLookupClient(srv, id, 0)))
        goto cleanup;

    if (virAdmClientClose(client, 0) < 0) {
        vshError(ctl, _("Failed to disconnect client '%llu' from server %s"),
                 id, virAdmServerGetName(srv));
        goto cleanup;
    }

    vshPrint(ctl, _("Client '%llu' disconnected"), id);
    ret = true;
 cleanup:
    virAdmClientFree(client);
    virAdmServerFree(srv);
    return ret;
}

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
/* ------------------------
 * Command srv-clients-info
 * ------------------------
 */

static const vshCmdInfo info_srv_clients_info[] = {
    {.name = "help",
     .data = N_("get server's client-related configuration limits")
    },
    {.name = "desc",
     .data = N_("Retrieve server's client-related configuration limits ")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_srv_clients_info[] = {
    {.name = "server",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
855
     .completer = vshAdmServerCompleter,
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
     .help = N_("Server to retrieve the client limits from."),
    },
    {.name = NULL}
};

static bool
cmdSrvClientsInfo(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 (virAdmServerGetClientLimits(srv, &params, &nparams, 0) < 0) {
        vshError(ctl, "%s", _("Unable to retrieve client limits "
                              "from server's configuration"));
        goto cleanup;
    }

    for (i = 0; i < nparams; i++)
885
        vshPrint(ctl, "%-20s: %u\n", params[i].field, params[i].value.ui);
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

    ret = true;

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

/* -----------------------
 * Command srv-clients-set
 * -----------------------
 */

static const vshCmdInfo info_srv_clients_set[] = {
    {.name = "help",
     .data = N_("set server's client-related configuration limits")
    },
    {.name = "desc",
     .data = N_("Tune server's client-related configuration limits. "
                "See OPTIONS for currently supported attributes.")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_srv_clients_set[] = {
    {.name = "server",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
915
     .completer = vshAdmServerCompleter,
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
     .help = N_("Server to alter the client-related configuration limits on."),
    },
    {.name = "max-clients",
     .type = VSH_OT_INT,
     .help = N_("Change the upper limit to overall number of clients "
                "connected to the server."),
    },
    {.name = "max-unauth-clients",
     .type = VSH_OT_INT,
     .help = N_("Change the upper limit to number of clients waiting for "
                "authentication to be connected to the server"),
    },
    {.name = NULL}
};

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

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

947 948 949 950 951 952 953 954
#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; \
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    }

    PARSE_CMD_TYPED_PARAM("max-clients", VIR_SERVER_CLIENTS_MAX);
    PARSE_CMD_TYPED_PARAM("max-unauth-clients", VIR_SERVER_CLIENTS_UNAUTH_MAX);

#undef PARSE_CMD_TYPED_PARAM

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

    if (virTypedParamsGetUInt(params, nparams,
                              VIR_SERVER_CLIENTS_MAX, &max) &&
        virTypedParamsGetUInt(params, nparams,
                              VIR_SERVER_CLIENTS_UNAUTH_MAX, &unauth_max) &&
        unauth_max > max) {
973
        vshError(ctl, "%s", _("--max-unauth-clients must be less than or equal to "
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
                              "--max-clients"));
        goto cleanup;
    }

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

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

    ret = true;

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

 save_error:
    vshSaveLibvirtError();

 error:
    vshError(ctl, "%s", _("Unable to change server's client-related "
                          "configuration limits"));
    goto cleanup;
}

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
/* --------------------------
 * Command daemon-log-filters
 * --------------------------
 */
static const vshCmdInfo info_daemon_log_filters[] = {
    {.name = "help",
     .data = N_("fetch or set the currently defined set of logging filters on "
                "daemon")
    },
    {.name = "desc",
     .data = N_("Depending on whether run with or without options, the command "
                "fetches or redefines the existing active set of filters on "
                "daemon.")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_daemon_log_filters[] = {
    {.name = "filters",
     .type = VSH_OT_STRING,
     .help = N_("redefine the existing set of logging filters"),
     .flags = VSH_OFLAG_EMPTY_OK
    },
    {.name = NULL}
};

static bool
cmdDaemonLogFilters(vshControl *ctl, const vshCmd *cmd)
{
    int nfilters;
    char *filters = NULL;
    vshAdmControlPtr priv = ctl->privData;

    if (vshCommandOptBool(cmd, "filters")) {
        if ((vshCommandOptStringReq(ctl, cmd, "filters",
                                    (const char **) &filters) < 0 ||
             virAdmConnectSetLoggingFilters(priv->conn, filters, 0) < 0)) {
            vshError(ctl, _("Unable to change daemon logging settings"));
            return false;
        }
    } else {
        if ((nfilters = virAdmConnectGetLoggingFilters(priv->conn,
                                                       &filters, 0)) < 0) {
            vshError(ctl, _("Unable to get daemon logging filters information"));
            return false;
        }

        vshPrintExtra(ctl, " %-15s", _("Logging filters: "));
J
Ján Tomko 已提交
1048
        vshPrint(ctl, "%s\n", NULLSTR_EMPTY(filters));
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    }

    return true;
}

/* --------------------------
 * Command daemon-log-outputs
 * --------------------------
 */
static const vshCmdInfo info_daemon_log_outputs[] = {
    {.name = "help",
     .data = N_("fetch or set the currently defined set of logging outputs on "
                "daemon")
    },
    {.name = "desc",
     .data = N_("Depending on whether run with or without options, the command "
                "fetches or redefines the existing active set of outputs on "
                "daemon.")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_daemon_log_outputs[] = {
    {.name = "outputs",
     .type = VSH_OT_STRING,
     .help = N_("redefine the existing set of logging outputs"),
     .flags = VSH_OFLAG_EMPTY_OK
    },
    {.name = NULL}
};

static bool
cmdDaemonLogOutputs(vshControl *ctl, const vshCmd *cmd)
{
    int noutputs;
    char *outputs = NULL;
    vshAdmControlPtr priv = ctl->privData;

    if (vshCommandOptBool(cmd, "outputs")) {
        if ((vshCommandOptStringReq(ctl, cmd, "outputs",
                                    (const char **) &outputs) < 0 ||
             virAdmConnectSetLoggingOutputs(priv->conn, outputs, 0) < 0)) {
            vshError(ctl, _("Unable to change daemon logging settings"));
            return false;
        }
    } else {
        if ((noutputs = virAdmConnectGetLoggingOutputs(priv->conn,
                                                       &outputs, 0)) < 0) {
            vshError(ctl, _("Unable to get daemon logging outputs information"));
            return false;
        }

        vshPrintExtra(ctl, " %-15s", _("Logging outputs: "));
J
Ján Tomko 已提交
1102
        vshPrint(ctl, "%s\n", NULLSTR_EMPTY(outputs));
1103 1104 1105 1106 1107
    }

    return true;
}

1108
static void *
1109
vshAdmConnectionHandler(vshControl *ctl)
1110 1111 1112
{
    vshAdmControlPtr priv = ctl->privData;

1113
    if (!virAdmConnectIsAlive(priv->conn))
1114 1115
        vshAdmReconnect(ctl);

1116
    if (!virAdmConnectIsAlive(priv->conn)) {
1117 1118 1119 1120
        vshError(ctl, "%s", _("no valid connection"));
        return NULL;
    }

1121
    return priv->conn;
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
}

/*
 * 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);

1137
    if (priv->conn)
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
        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;

1150
    if (ctl->connname) {
1151 1152 1153 1154 1155 1156 1157
        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).
         */
1158
        if (!priv->conn) {
1159 1160 1161 1162 1163 1164 1165 1166 1167
            vshReportError(ctl);
            return false;
        }
    }

    return true;
}

static void
J
Ján Tomko 已提交
1168
vshAdmDeinitTimer(int timer G_GNUC_UNUSED, void *opaque G_GNUC_UNUSED)
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
{
    /* nothing to be done here */
}

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

    vshDeinit(ctl);
1182
    VIR_FREE(ctl->connname);
1183

1184
    if (priv->conn)
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 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
        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
J
Ján Tomko 已提交
1256
vshAdmShowVersion(vshControl *ctl G_GNUC_UNUSED)
1257 1258 1259
{
    /* FIXME - list a copyright blurb, as in GNU programs?  */
    vshPrint(ctl, _("Virt-admin command line tool of libvirt %s\n"), VERSION);
1260
    vshPrint(ctl, _("See web site at %s\n\n"), "https://libvirt.org/");
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 1294 1295 1296

    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':
1297
            VIR_FREE(ctl->connname);
J
Ján Tomko 已提交
1298
            ctl->connname = g_strdup(optarg);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            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);
J
Ján Tomko 已提交
1318
            ctl->logfile = g_strdup(optarg);
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
            vshOpenLogFile(ctl);
            break;
        case 'q':
            ctl->quiet = true;
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
1329
            G_GNUC_FALLTHROUGH;
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
        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]);
1364
            return vshCommandStringParse(ctl, argv[optind], NULL);
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        } 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,
M
Michal Privoznik 已提交
1379
    VSH_CMD_SELF_TEST,
1380
    VSH_CMD_COMPLETE,
1381 1382 1383 1384 1385 1386
    {.name = "uri",
     .handler = cmdURI,
     .opts = NULL,
     .info = info_uri,
     .flags = 0
    },
1387 1388 1389 1390 1391 1392
    {.name = "version",
     .handler = cmdVersion,
     .opts = NULL,
     .info = info_version,
     .flags = 0
    },
1393 1394 1395 1396 1397 1398 1399 1400 1401
    {.name = "connect",
     .handler = cmdConnect,
     .opts = opts_connect,
     .info = info_connect,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = NULL}
};

E
Erik Skultety 已提交
1402 1403
static const vshCmdDef monitoringCmds[] = {
    {.name = "srv-list",
1404 1405 1406 1407
     .flags = VSH_CMD_FLAG_ALIAS,
     .alias = "server-list"
    },
    {.name = "server-list",
E
Erik Skultety 已提交
1408 1409 1410 1411 1412
     .handler = cmdSrvList,
     .opts = NULL,
     .info = info_srv_list,
     .flags = 0
    },
1413
    {.name = "srv-threadpool-info",
1414 1415 1416 1417
     .flags = VSH_CMD_FLAG_ALIAS,
     .alias = "server-threadpool-info"
    },
    {.name = "server-threadpool-info",
1418 1419 1420 1421 1422
     .handler = cmdSrvThreadpoolInfo,
     .opts = opts_srv_threadpool_info,
     .info = info_srv_threadpool_info,
     .flags = 0
    },
1423
    {.name = "srv-clients-list",
1424 1425 1426 1427
     .flags = VSH_CMD_FLAG_ALIAS,
     .alias = "client-list"
    },
    {.name = "client-list",
1428 1429 1430 1431 1432
     .handler = cmdSrvClientsList,
     .opts = opts_srv_clients_list,
     .info = info_srv_clients_list,
     .flags = 0
    },
1433 1434 1435 1436 1437 1438
    {.name = "client-info",
     .handler = cmdClientInfo,
     .opts = opts_client_info,
     .info = info_client_info,
     .flags = 0
    },
1439
    {.name = "srv-clients-info",
1440 1441 1442 1443
     .flags = VSH_CMD_FLAG_ALIAS,
     .alias = "server-clients-info"
    },
    {.name = "server-clients-info",
1444 1445 1446 1447 1448
     .handler = cmdSrvClientsInfo,
     .opts = opts_srv_clients_info,
     .info = info_srv_clients_info,
     .flags = 0
    },
1449 1450 1451 1452 1453
    {.name = NULL}
};

static const vshCmdDef managementCmds[] = {
    {.name = "srv-threadpool-set",
1454 1455 1456 1457
     .flags = VSH_CMD_FLAG_ALIAS,
     .alias = "server-threadpool-set"
    },
    {.name = "server-threadpool-set",
1458 1459 1460 1461 1462
     .handler = cmdSrvThreadpoolSet,
     .opts = opts_srv_threadpool_set,
     .info = info_srv_threadpool_set,
     .flags = 0
    },
1463 1464 1465 1466 1467 1468
    {.name = "client-disconnect",
     .handler = cmdClientDisconnect,
     .opts = opts_client_disconnect,
     .info = info_client_disconnect,
     .flags = 0
    },
1469
    {.name = "srv-clients-set",
1470 1471 1472 1473
     .flags = VSH_CMD_FLAG_ALIAS,
     .alias = "server-clients-set"
    },
    {.name = "server-clients-set",
1474 1475 1476 1477 1478
     .handler = cmdSrvClientsSet,
     .opts = opts_srv_clients_set,
     .info = info_srv_clients_set,
     .flags = 0
    },
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    {.name = "daemon-log-filters",
     .handler = cmdDaemonLogFilters,
     .opts = opts_daemon_log_filters,
     .info = info_daemon_log_filters,
     .flags = 0
    },
    {.name = "daemon-log-outputs",
     .handler = cmdDaemonLogOutputs,
     .opts = opts_daemon_log_outputs,
     .info = info_daemon_log_outputs,
     .flags = 0
    },
E
Erik Skultety 已提交
1491 1492 1493
    {.name = NULL}
};

1494 1495
static const vshCmdGrp cmdGroups[] = {
    {"Virt-admin itself", "virt-admin", vshAdmCmds},
E
Erik Skultety 已提交
1496
    {"Monitoring commands", "monitor", monitoringCmds},
1497
    {"Management commands", "management", managementCmds},
1498 1499 1500 1501
    {NULL, NULL, NULL}
};

static const vshClientHooks hooks = {
1502
    .connHandler = vshAdmConnectionHandler
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
};

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 */
1515
    ctl->env_prefix = "VIRT_ADMIN";
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    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;

1530
    if (virGettextInitialize() < 0)
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
        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;
    }

1547 1548 1549 1550 1551
    if (virAdmInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

1552
    virFileActivateDirOverrideForProg(argv[0]);
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584

    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
1585
                if (vshCommandStringParse(ctl, ctl->cmdstr, NULL))
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
                    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);
}