You need to sign in or sign up before continuing.
virsh.c 28.3 KB
Newer Older
1
/*
2
 * virsh.c: a shell to exercise the libvirt API
3
 *
4
 * Copyright (C) 2005, 2007-2015 Red Hat, Inc.
5
 *
O
Osier Yang 已提交
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
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20
 *
 * Daniel Veillard <veillard@redhat.com>
K
Karel Zak 已提交
21
 * Karel Zak <kzak@redhat.com>
K
Karel Zak 已提交
22
 * Daniel P. Berrange <berrange@redhat.com>
23 24
 */

25
#include <config.h>
E
Eric Blake 已提交
26
#include "virsh.h"
27

28
#include <stdio.h>
K
Karel Zak 已提交
29 30 31
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
32
#include <unistd.h>
33
#include <errno.h>
K
Karel Zak 已提交
34
#include <getopt.h>
K
Karel Zak 已提交
35
#include <sys/time.h>
36
#include <fcntl.h>
37
#include <time.h>
38
#include <limits.h>
39
#include <sys/stat.h>
40
#include <inttypes.h>
41
#include <signal.h>
K
Karel Zak 已提交
42

43
#if WITH_READLINE
44 45
# include <readline/readline.h>
# include <readline/history.h>
46
#endif
K
Karel Zak 已提交
47

48
#include "internal.h"
49
#include "virerror.h"
50
#include "virbuffer.h"
51
#include "viralloc.h"
52 53
#include <libvirt/libvirt-qemu.h>
#include <libvirt/libvirt-lxc.h>
E
Eric Blake 已提交
54
#include "virfile.h"
55
#include "virthread.h"
56
#include "vircommand.h"
H
Hu Tao 已提交
57
#include "conf/domain_conf.h"
58
#include "virtypedparam.h"
59
#include "virstring.h"
60
#include "virgettext.h"
K
Karel Zak 已提交
61

62
#include "virsh-console.h"
E
Eric Blake 已提交
63
#include "virsh-domain.h"
64
#include "virsh-domain-monitor.h"
E
Eric Blake 已提交
65
#include "virsh-host.h"
E
Eric Blake 已提交
66
#include "virsh-interface.h"
E
Eric Blake 已提交
67
#include "virsh-network.h"
E
Eric Blake 已提交
68
#include "virsh-nodedev.h"
E
Eric Blake 已提交
69
#include "virsh-nwfilter.h"
E
Eric Blake 已提交
70
#include "virsh-pool.h"
E
Eric Blake 已提交
71
#include "virsh-secret.h"
E
Eric Blake 已提交
72
#include "virsh-snapshot.h"
E
Eric Blake 已提交
73
#include "virsh-volume.h"
E
Eric Blake 已提交
74

75 76 77 78 79
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

K
Karel Zak 已提交
80 81
static char *progname;

82
static const vshCmdGrp cmdGroups[];
83
static const vshClientHooks hooks;
J
John Levon 已提交
84

85 86 87
/*
 * Detection of disconnections and automatic reconnection support
 */
88
static int disconnected; /* we may have been disconnected */
89 90

/*
91
 * virshCatchDisconnect:
92
 *
93 94
 * We get here when the connection was closed.  We can't do much in the
 * handler, just save the fact it was raised.
95
 */
L
Laine Stump 已提交
96
static void
97
virshCatchDisconnect(virConnectPtr conn,
98
                     int reason,
99
                     void *opaque)
100
{
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    if (reason != VIR_CONNECT_CLOSE_REASON_CLIENT) {
        vshControl *ctl = opaque;
        const char *str = "unknown reason";
        virErrorPtr error;
        char *uri;

        error = virSaveLastError();
        uri = virConnectGetURI(conn);

        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;
J
John Ferlan 已提交
120
        /* coverity[dead_error_condition] */
121 122 123 124 125
        case VIR_CONNECT_CLOSE_REASON_CLIENT:
        case VIR_CONNECT_CLOSE_REASON_LAST:
            break;
        }
        vshError(ctl, _(str), NULLSTR(uri));
126
        VIR_FREE(uri);
127 128 129 130 131

        if (error) {
            virSetError(error);
            virFreeError(error);
        }
132
        disconnected++;
133
        vshEventDone(ctl);
134
    }
135 136
}

137 138 139
/* Main Function which should be used for connecting.
 * This function properly handles keepalive settings. */
virConnectPtr
140
virshConnect(vshControl *ctl, const char *uri, bool readonly)
141 142 143 144 145
{
    virConnectPtr c = NULL;
    int interval = 5; /* Default */
    int count = 6;    /* Default */
    bool keepalive_forced = false;
146 147
    virPolkitAgentPtr pkagent = NULL;
    int authfail = 0;
148 149 150 151 152 153 154 155 156 157

    if (ctl->keepalive_interval >= 0) {
        interval = ctl->keepalive_interval;
        keepalive_forced = true;
    }
    if (ctl->keepalive_count >= 0) {
        count = ctl->keepalive_count;
        keepalive_forced = true;
    }

158 159 160 161 162 163 164 165 166 167 168 169 170
    do {
        virErrorPtr err;

        if ((c = virConnectOpenAuth(uri, virConnectAuthPtrDefault,
                                    readonly ? VIR_CONNECT_RO : 0)))
            break;

        if (readonly)
            goto cleanup;

        err = virGetLastError();
        if (err && err->domain == VIR_FROM_POLKIT &&
            err->code == VIR_ERR_AUTH_UNAVAILABLE) {
171
            if (!pkagent && !(pkagent = virPolkitAgentCreate()))
172 173 174 175 176 177 178 179 180 181 182 183 184
                goto cleanup;
        } else if (err && err->domain == VIR_FROM_POLKIT &&
                   err->code == VIR_ERR_AUTH_FAILED) {
            authfail++;
        } else {
            goto cleanup;
        }
        virResetLastError();
        /* Failure to authenticate 5 times should be enough.
         * No sense prolonging the agony.
         */
    } while (authfail < 5);

185
    if (!c)
186
        goto cleanup;
187 188 189 190 191 192 193 194

    if (interval > 0 &&
        virConnectSetKeepAlive(c, interval, count) != 0) {
        if (keepalive_forced) {
            vshError(ctl, "%s",
                     _("Cannot setup keepalive on connection "
                       "as requested, disconnecting"));
            virConnectClose(c);
195 196
            c = NULL;
            goto cleanup;
197 198 199 200 201
        }
        vshDebug(ctl, VSH_ERR_INFO, "%s",
                 _("Failed to setup keepalive on connection\n"));
    }

202 203
 cleanup:
    virPolkitAgentDestroy(pkagent);
204 205 206
    return c;
}

207
/*
208
 * virshReconnect:
209
 *
L
Laine Stump 已提交
210
 * Reconnect after a disconnect from libvirtd
211 212
 *
 */
213
static int
M
Martin Kletzander 已提交
214
virshReconnect(vshControl *ctl, const char *name, bool readonly, bool force)
215 216
{
    bool connected = false;
217
    virshControlPtr priv = ctl->privData;
M
Martin Kletzander 已提交
218
    bool ro = name ? readonly : priv->readonly;
219

220
    if (priv->conn) {
221
        int ret;
222
        connected = true;
223

224 225
        virConnectUnregisterCloseCallback(priv->conn, virshCatchDisconnect);
        ret = virConnectClose(priv->conn);
226 227 228 229 230
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
231
    }
232

M
Martin Kletzander 已提交
233
    priv->conn = virshConnect(ctl, name ? name : ctl->connname, ro);
234

235
    if (!priv->conn) {
236 237 238 239
        if (disconnected)
            vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
        else
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
240
        return -1;
241
    } else {
M
Martin Kletzander 已提交
242 243 244 245 246
        if (name) {
            VIR_FREE(ctl->connname);
            ctl->connname = vshStrdup(ctl, name);
            priv->readonly = readonly;
        }
247
        if (virConnectRegisterCloseCallback(priv->conn, virshCatchDisconnect,
248
                                            ctl, NULL) < 0)
249
            vshError(ctl, "%s", _("Unable to register disconnect callback"));
M
Martin Kletzander 已提交
250
        if (connected && !force)
251 252
            vshError(ctl, "%s", _("Reconnected to the hypervisor"));
    }
253
    disconnected = 0;
254 255 256
    priv->useGetInfo = false;
    priv->useSnapshotOld = false;
    priv->blockJobNoBytes = false;
257
    return 0;
258
}
259

260 261 262 263 264 265 266
int virshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                    const char *bytes, size_t nbytes, void *opaque)
{
    int *fd = opaque;

    return safewrite(*fd, bytes, nbytes);
}
267

268 269 270
/* ---------------
 * Command Connect
 * ---------------
271 272 273 274
 */

static const vshCmdOptDef opts_connect[] = {
    {.name = "name",
275
     .type = VSH_OT_STRING,
276 277 278 279 280 281 282 283 284 285
     .flags = VSH_OFLAG_EMPTY_OK,
     .help = N_("hypervisor connection URI")
    },
    {.name = "readonly",
     .type = VSH_OT_BOOL,
     .help = N_("read-only connection")
    },
    {.name = NULL}
};

286
static const vshCmdInfo info_connect[] = {
287
    {.name = "help",
288
     .data = N_("(re)connect to hypervisor")
289 290
    },
    {.name = "desc",
291 292
     .data = N_("Connect to local hypervisor. This is built-in "
                "command after shell start up.")
293 294
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
295 296
};

E
Eric Blake 已提交
297
static bool
298
cmdConnect(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
299
{
300 301
    bool ro = vshCommandOptBool(cmd, "readonly");
    const char *name = NULL;
302 303 304 305

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

306 307
    if (virshReconnect(ctl, name, ro, true) < 0)
        return false;
308

309
    return true;
310 311
}

312 313 314 315
/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
316

317 318
static bool
virshConnectionUsability(vshControl *ctl, virConnectPtr conn)
319
{
320 321 322 323
    if (!conn ||
        virConnectIsAlive(conn) == 0) {
        vshError(ctl, "%s", _("no valid connection"));
        return false;
324 325
    }

326 327 328 329
    /* The connection is considered dead only if
     * virConnectIsAlive() successfuly says so.
     */
    vshResetLibvirtError();
330

331
    return true;
332 333
}

334 335
static void *
virshConnectionHandler(vshControl *ctl)
336
{
337
    virshControlPtr priv = ctl->privData;
338

339 340 341
    if ((!priv->conn || disconnected) &&
        virshReconnect(ctl, NULL, false, false) < 0)
        return NULL;
342

343 344
    if (virshConnectionUsability(ctl, priv->conn))
        return priv->conn;
345

346
    return NULL;
347 348
}

J
Ján Tomko 已提交
349 350 351 352 353 354 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
/* -----------------
 * Command self-test
 * ----------------- */

static const vshCmdInfo info_selftest[] = {
    {.name = "help",
     .data = N_("internal command for testing virsh")
    },
    {.name = "desc",
     .data = N_("internal use only")
    },
    {.name = NULL}
};

/* Prints help for every command.
 * That runs vshCmddefOptParse which validates
 * the per-command options structure. */
static bool
cmdSelfTest(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    const vshCmdGrp *grp;
    const vshCmdDef *def;

    vshPrint(ctl, "Do not use the following output:\n\n");

    for (grp = cmdGroups; grp->name; grp++) {
        for (def = grp->commands; def->name; def++) {
            if (def->flags & VSH_CMD_FLAG_ALIAS)
                continue;

            if (!vshCmddefHelp(ctl, def->name))
                return false;
        }
    }

    return true;
}


388 389 390
/* ---------------
 * Misc utils
 * ---------------
391
 */
392 393
int
virshDomainState(vshControl *ctl, virDomainPtr dom, int *reason)
394
{
395 396
    virDomainInfo info;
    virshControlPtr priv = ctl->privData;
397

398 399
    if (reason)
        *reason = -1;
400

401 402 403 404 405 406 407 408 409 410
    if (!priv->useGetInfo) {
        int state;
        if (virDomainGetState(dom, &state, reason, 0) < 0) {
            virErrorPtr err = virGetLastError();
            if (err && err->code == VIR_ERR_NO_SUPPORT)
                priv->useGetInfo = true;
            else
                return -1;
        } else {
            return state;
411 412 413
        }
    }

414 415 416 417 418
    /* fall back to virDomainGetInfo if virDomainGetState is not supported */
    if (virDomainGetInfo(dom, &info) < 0)
        return -1;
    else
        return info.state;
M
Martin Kletzander 已提交
419 420 421 422 423 424
}

/*
 * Initialize connection.
 */
static bool
425
virshInit(vshControl *ctl)
M
Martin Kletzander 已提交
426
{
427 428
    virshControlPtr priv = ctl->privData;

M
Martin Kletzander 已提交
429
    /* Since we have the commandline arguments parsed, we need to
E
Erik Skultety 已提交
430 431 432
     * reload our initial settings to make debugging and readline
     * work properly */
    vshInitReload(ctl);
M
Martin Kletzander 已提交
433

434
    if (priv->conn)
M
Martin Kletzander 已提交
435
        return false;
436

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

440
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
441
        return false;
442

J
Jiri Denemark 已提交
443 444 445 446
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

447 448 449 450
    if ((ctl->eventTimerId = virEventAddTimeout(-1, vshEventTimeout, ctl,
                                                NULL)) < 0)
        return false;

451
    if (ctl->connname) {
452 453 454 455 456 457
        /* 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).
         */
458
        if (virshReconnect(ctl, NULL, false, false) < 0) {
E
Eric Blake 已提交
459
            vshReportError(ctl);
460 461
            return false;
        }
462
    }
K
Karel Zak 已提交
463

E
Eric Blake 已提交
464
    return true;
K
Karel Zak 已提交
465 466
}

467
static void
468
virshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
469 470 471 472
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
473
/*
J
Jim Meyering 已提交
474
 * Deinitialize virsh
K
Karel Zak 已提交
475
 */
E
Eric Blake 已提交
476
static bool
477
virshDeinit(vshControl *ctl)
478
{
479 480 481
    virshControlPtr priv = ctl->privData;

    vshDeinit(ctl);
482
    VIR_FREE(ctl->connname);
483
    if (priv->conn) {
484
        int ret;
485 486
        virConnectUnregisterCloseCallback(priv->conn, virshCatchDisconnect);
        ret = virConnectClose(priv->conn);
487 488 489 490 491
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
K
Karel Zak 已提交
492
    }
D
Daniel P. Berrange 已提交
493 494
    virResetLastError();

J
Jiri Denemark 已提交
495
    if (ctl->eventLoopStarted) {
496 497 498 499
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
500
        /* HACK: Add a dummy timeout to break event loop */
501
        timer = virEventAddTimeout(0, virshDeinitTimer, NULL, NULL);
502 503 504 505
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
506 507 508
        if (timer != -1)
            virEventRemoveTimeout(timer);

509 510 511
        if (ctl->eventTimerId != -1)
            virEventRemoveTimeout(ctl->eventTimerId);

J
Jiri Denemark 已提交
512 513 514
        ctl->eventLoopStarted = false;
    }

515 516
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
517
    return true;
K
Karel Zak 已提交
518
}
519

K
Karel Zak 已提交
520 521 522
/*
 * Print usage
 */
E
Eric Blake 已提交
523
static void
524
virshUsage(void)
525
{
526
    const vshCmdGrp *grp;
527
    const vshCmdDef *cmd;
528

L
Lai Jiangshan 已提交
529 530
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
531
                      "  options:\n"
532 533
                      "    -c | --connect=URI      hypervisor connection URI\n"
                      "    -d | --debug=NUM        debug level [0-4]\n"
534
                      "    -e | --escape <char>    set escape sequence for console\n"
535
                      "    -h | --help             this help\n"
536 537 538 539
                      "    -k | --keepalive-interval=NUM\n"
                      "                            keepalive interval in seconds, 0 for disable\n"
                      "    -K | --keepalive-count=NUM\n"
                      "                            number of possible missed keepalive messages\n"
540
                      "    -l | --log=FILE         output logging to file\n"
541
                      "    -q | --quiet            quiet mode\n"
542
                      "    -r | --readonly         connect readonly\n"
543
                      "    -t | --timing           print timing information\n"
544 545 546
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
547 548
                      "  commands (non interactive mode):\n\n"), progname,
            progname);
549

550
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
551 552 553 554 555
        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;
556
            fprintf(stdout,
E
Eric Blake 已提交
557 558 559
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
560 561 562 563 564
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
565 566 567
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
568 569
}

570 571 572 573
/*
 * Show version and options compiled in
 */
static void
574
virshShowVersion(vshControl *ctl ATTRIBUTE_UNUSED)
575 576 577 578 579
{
    /* FIXME - list a copyright blurb, as in GNU programs?  */
    vshPrint(ctl, _("Virsh command line tool of libvirt %s\n"), VERSION);
    vshPrint(ctl, _("See web site at %s\n\n"), "http://libvirt.org/");

L
Laine Stump 已提交
580 581
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
582
#ifdef WITH_QEMU
583
    vshPrint(ctl, " QEMU/KVM");
584
#endif
D
Doug Goldstein 已提交
585 586 587
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
588 589 590
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
591 592 593 594 595 596
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
597 598 599
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
600 601 602
#ifdef WITH_VZ
    vshPrint(ctl, " Virtuozzo");
#endif
D
Doug Goldstein 已提交
603
#ifdef WITH_VMWARE
J
Ján Tomko 已提交
604
    vshPrint(ctl, " VMware");
605
#endif
D
Doug Goldstein 已提交
606 607
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
608
#endif
D
Doug Goldstein 已提交
609 610
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
611 612 613 614
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
615 616
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
617
#endif
D
Doug Goldstein 已提交
618 619
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
620
#endif
621 622 623
#ifdef WITH_BHYVE
    vshPrint(ctl, " Bhyve");
#endif
624 625 626 627 628
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
629
    vshPrint(ctl, "%s", _(" Networking:"));
630 631 632 633 634 635 636 637 638
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
639
#if defined(WITH_INTERFACE)
D
Doug Goldstein 已提交
640
    vshPrint(ctl, " Interface");
641 642
# if defined(WITH_NETCF)
    vshPrint(ctl, " netcf");
643
# elif defined(WITH_UDEV)
644
    vshPrint(ctl, " udev");
645
# endif
646 647 648 649 650 651 652 653 654
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
655
    vshPrint(ctl, "%s", _(" Storage:"));
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
#ifdef WITH_STORAGE_DIR
    vshPrint(ctl, " Dir");
#endif
#ifdef WITH_STORAGE_DISK
    vshPrint(ctl, " Disk");
#endif
#ifdef WITH_STORAGE_FS
    vshPrint(ctl, " Filesystem");
#endif
#ifdef WITH_STORAGE_SCSI
    vshPrint(ctl, " SCSI");
#endif
#ifdef WITH_STORAGE_MPATH
    vshPrint(ctl, " Multipath");
#endif
#ifdef WITH_STORAGE_ISCSI
    vshPrint(ctl, " iSCSI");
#endif
#ifdef WITH_STORAGE_LVM
    vshPrint(ctl, " LVM");
676 677 678
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
679 680 681
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
682 683 684
#endif
#ifdef WITH_STORAGE_GLUSTER
    vshPrint(ctl, " Gluster");
685 686 687
#endif
#ifdef WITH_STORAGE_ZFS
    vshPrint(ctl, " ZFS");
688 689 690
#endif
    vshPrint(ctl, "\n");

691
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
692 693 694
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
#ifdef WITH_NODE_DEVICES
    vshPrint(ctl, " Nodedev");
#endif
#ifdef WITH_SECDRIVER_APPARMOR
    vshPrint(ctl, " AppArmor");
#endif
#ifdef WITH_SECDRIVER_SELINUX
    vshPrint(ctl, " SELinux");
#endif
#ifdef WITH_SECRETS
    vshPrint(ctl, " Secrets");
#endif
#ifdef ENABLE_DEBUG
    vshPrint(ctl, " Debug");
#endif
#ifdef WITH_DTRACE_PROBES
    vshPrint(ctl, " DTrace");
#endif
713
#if WITH_READLINE
714 715 716 717 718 719 720 721 722
    vshPrint(ctl, " Readline");
#endif
#ifdef WITH_DRIVER_MODULES
    vshPrint(ctl, " Modular");
#endif
    vshPrint(ctl, "\n");
}

static bool
723
virshAllowedEscapeChar(char c)
724 725 726 727 728 729 730 731 732 733 734 735
{
    /* Allowed escape characters:
     * a-z A-Z @ [ \ ] ^ _
     */
    return ('a' <= c && c <= 'z') ||
        ('@' <= c && c <= '_');
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
E
Eric Blake 已提交
736
static bool
737
virshParseArgv(vshControl *ctl, int argc, char **argv)
738
{
739
    int arg, len, debug, keepalive;
740
    size_t i;
741
    int longindex = -1;
742
    virshControlPtr priv = ctl->privData;
743
    struct option opt[] = {
744
        {"connect", required_argument, NULL, 'c'},
745
        {"debug", required_argument, NULL, 'd'},
746
        {"escape", required_argument, NULL, 'e'},
747
        {"help", no_argument, NULL, 'h'},
748 749
        {"keepalive-interval", required_argument, NULL, 'k'},
        {"keepalive-count", required_argument, NULL, 'K'},
750
        {"log", required_argument, NULL, 'l'},
751
        {"quiet", no_argument, NULL, 'q'},
752
        {"readonly", no_argument, NULL, 'r'},
753 754 755 756 757 758 759 760
        {"timing", no_argument, NULL, 't'},
        {"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 virsh options. */
761
    while ((arg = getopt_long(argc, argv, "+:c:d:e:hk:K:l:qrtvV", opt, &longindex)) != -1) {
762
        switch (arg) {
763
        case 'c':
764 765
            VIR_FREE(ctl->connname);
            ctl->connname = vshStrdup(ctl, optarg);
766
            break;
767
        case 'd':
768
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
769 770
                vshError(ctl, _("option %s takes a numeric argument"),
                         longindex == -1 ? "-d" : "--debug");
771 772
                exit(EXIT_FAILURE);
            }
773 774 775 776 777
            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;
778
            break;
779 780 781 782
        case 'e':
            len = strlen(optarg);

            if ((len == 2 && *optarg == '^' &&
783
                 virshAllowedEscapeChar(optarg[1])) ||
784
                (len == 1 && *optarg != '^')) {
785
                priv->escapeChar = optarg;
786 787 788 789 790 791
            } else {
                vshError(ctl, _("Invalid string '%s' for escape sequence"),
                         optarg);
                exit(EXIT_FAILURE);
            }
            break;
792
        case 'h':
793
            virshUsage();
794 795
            exit(EXIT_SUCCESS);
            break;
796
        case 'k':
E
Erik Skultety 已提交
797 798 799 800 801 802 803 804 805 806
            if (virStrToLong_i(optarg, NULL, 0, &keepalive) < 0) {
                vshError(ctl,
                         _("Invalid value for option %s"),
                         longindex == -1 ? "-k" : "--keepalive-interval");
                exit(EXIT_FAILURE);
            }

            if (keepalive < 0) {
                vshError(ctl,
                         _("option %s requires a positive integer argument"),
807 808 809 810 811 812
                         longindex == -1 ? "-k" : "--keepalive-interval");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_interval = keepalive;
            break;
        case 'K':
E
Erik Skultety 已提交
813 814 815 816 817 818 819 820 821 822
            if (virStrToLong_i(optarg, NULL, 0, &keepalive) < 0) {
                vshError(ctl,
                         _("Invalid value for option %s"),
                         longindex == -1 ? "-K" : "--keepalive-count");
                exit(EXIT_FAILURE);
            }

            if (keepalive < 0) {
                vshError(ctl,
                         _("option %s requires a positive integer argument"),
823 824 825 826 827
                         longindex == -1 ? "-K" : "--keepalive-count");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_count = keepalive;
            break;
828 829 830 831 832
        case 'l':
            vshCloseLogFile(ctl);
            ctl->logfile = vshStrdup(ctl, optarg);
            vshOpenLogFile(ctl);
            break;
833 834 835 836 837 838
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
839
        case 'r':
840
            priv->readonly = true;
841 842 843 844 845 846 847 848
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
849
            virshShowVersion(ctl);
850
            exit(EXIT_SUCCESS);
851
        case ':':
852
            for (i = 0; opt[i].name != NULL; i++) {
853 854
                if (opt[i].val == optopt)
                    break;
855
            }
856 857 858 859 860 861
            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);
862
        case '?':
863 864 865 866
            if (optopt)
                vshError(ctl, _("unsupported option '-%c'. See --help."), optopt);
            else
                vshError(ctl, _("unsupported option '%s'. See --help."), argv[optind - 1]);
867
            exit(EXIT_FAILURE);
868
        default:
869
            vshError(ctl, _("unknown option"));
870 871
            exit(EXIT_FAILURE);
        }
872
        longindex = -1;
873 874
    }

875 876 877
    if (argc == optind) {
        ctl->imode = true;
    } else {
878 879 880 881 882 883 884 885 886 887 888 889 890
        /* 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 virshCmds[] = {
891 892 893 894 895 896
    VSH_CMD_CD,
    VSH_CMD_ECHO,
    VSH_CMD_EXIT,
    VSH_CMD_HELP,
    VSH_CMD_PWD,
    VSH_CMD_QUIT,
897 898 899 900 901
    {.name = "connect",
     .handler = cmdConnect,
     .opts = opts_connect,
     .info = info_connect,
     .flags = VSH_CMD_FLAG_NOCONNECT
902
    },
J
Ján Tomko 已提交
903 904 905 906 907 908
    {.name = "self-test",
     .handler = cmdSelfTest,
     .opts = NULL,
     .info = info_selftest,
     .flags = VSH_CMD_FLAG_NOCONNECT | VSH_CMD_FLAG_ALIAS
    },
909
    {.name = NULL}
910
};
911

912
static const vshCmdGrp cmdGroups[] = {
913 914 915 916 917 918 919 920 921 922 923 924
    {VIRSH_CMD_GRP_DOM_MANAGEMENT, "domain", domManagementCmds},
    {VIRSH_CMD_GRP_DOM_MONITORING, "monitor", domMonitoringCmds},
    {VIRSH_CMD_GRP_HOST_AND_HV, "host", hostAndHypervisorCmds},
    {VIRSH_CMD_GRP_IFACE, "interface", ifaceCmds},
    {VIRSH_CMD_GRP_NWFILTER, "filter", nwfilterCmds},
    {VIRSH_CMD_GRP_NETWORK, "network", networkCmds},
    {VIRSH_CMD_GRP_NODEDEV, "nodedev", nodedevCmds},
    {VIRSH_CMD_GRP_SECRET, "secret", secretCmds},
    {VIRSH_CMD_GRP_SNAPSHOT, "snapshot", snapshotCmds},
    {VIRSH_CMD_GRP_STORAGE_POOL, "pool", storagePoolCmds},
    {VIRSH_CMD_GRP_STORAGE_VOL, "volume", storageVolCmds},
    {VIRSH_CMD_GRP_VIRSH, "virsh", virshCmds},
925 926
    {NULL, NULL, NULL}
};
K
Karel Zak 已提交
927

928 929 930 931
static const vshClientHooks hooks = {
    .connHandler = virshConnectionHandler
};

932 933 934 935
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
936
    virshControl virshCtl;
E
Eric Blake 已提交
937
    bool ret = true;
K
Karel Zak 已提交
938

939
    memset(ctl, 0, sizeof(vshControl));
940 941
    memset(&virshCtl, 0, sizeof(virshControl));
    ctl->name = "virsh";        /* hardcoded name of the binary */
942
    ctl->env_prefix = "VIRSH";
943
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
944
    ctl->debug = VSH_DEBUG_DEFAULT;
945
    ctl->hooks = &hooks;
946 947 948 949 950

    /* In order to distinguish default from setting to 0 */
    ctl->keepalive_interval = -1;
    ctl->keepalive_count = -1;

951 952 953
    ctl->eventPipe[0] = -1;
    ctl->eventPipe[1] = -1;
    ctl->eventTimerId = -1;
954 955 956 957 958 959 960 961
    virshCtl.escapeChar = "^]";     /* Same default as telnet */
    ctl->privData = &virshCtl;

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

963
    if (virGettextInitialize() < 0)
E
Eric Blake 已提交
964
        return EXIT_FAILURE;
965

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

969
#ifndef WIN32
970 971
        if (tcgetattr(STDIN_FILENO, &ctl->termattr) < 0)
            ctl->istty = false;
972
#endif
973 974
    }

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

980 981 982 983 984
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

985 986
    virFileActivateDirOverride(argv[0]);

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

990 991 992
    if (!virshParseArgv(ctl, argc, argv) ||
        !virshInit(ctl)) {
        virshDeinit(ctl);
K
Karel Zak 已提交
993
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
994
    }
995

996 997 998 999
    if (!ctl->connname)
        ctl->connname = vshStrdup(ctl,
                                  virGetEnvBlockSUID("VIRSH_DEFAULT_CONNECT_URI"));

K
Karel Zak 已提交
1000
    if (!ctl->imode) {
1001
        ret = vshCommandRun(ctl, ctl->cmd);
1002
    } else {
K
Karel Zak 已提交
1003 1004
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
1005
            vshPrint(ctl,
1006
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
1007
                     progname);
J
Jim Meyering 已提交
1008
            vshPrint(ctl, "%s",
1009
                     _("Type:  'help' for help with commands\n"
1010
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
1011
        }
1012

K
Karel Zak 已提交
1013
        do {
1014 1015
            const char *prompt = virshCtl.readonly ? VIRSH_PROMPT_RO
                : VIRSH_PROMPT_RW;
1016
            ctl->cmdstr =
1017
                vshReadline(ctl, prompt);
1018 1019
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
1020
            if (*ctl->cmdstr) {
1021
#if WITH_READLINE
K
Karel Zak 已提交
1022
                add_history(ctl->cmdstr);
1023
#endif
1024
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
1025 1026
                    vshCommandRun(ctl, ctl->cmd);
            }
1027
            VIR_FREE(ctl->cmdstr);
1028
        } while (ctl->imode);
K
Karel Zak 已提交
1029

1030 1031
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
1032
    }
1033

1034
    virshDeinit(ctl);
K
Karel Zak 已提交
1035
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
1036
}