virsh.c 26.5 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
    bool agentCreated = false;
149 150 151 152 153 154 155 156 157 158

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

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

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

        if (readonly)
            goto cleanup;

        err = virGetLastError();
170 171
        if (!agentCreated &&
            err && err->domain == VIR_FROM_POLKIT &&
172
            err->code == VIR_ERR_AUTH_UNAVAILABLE) {
173
            if (!pkagent && !(pkagent = virPolkitAgentCreate()))
174
                goto cleanup;
175
            agentCreated = true;
176 177 178 179 180 181 182 183 184 185 186 187
        } 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);

188
    if (!c)
189
        goto cleanup;
190 191 192 193 194 195 196 197

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

205 206
 cleanup:
    virPolkitAgentDestroy(pkagent);
207 208 209
    return c;
}

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

223
    if (priv->conn) {
224
        int ret;
225
        connected = true;
226

227 228
        virConnectUnregisterCloseCallback(priv->conn, virshCatchDisconnect);
        ret = virConnectClose(priv->conn);
229 230 231 232 233
        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"));
234
    }
235

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

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

263 264 265
/* ---------------
 * Command Connect
 * ---------------
266 267 268 269
 */

static const vshCmdOptDef opts_connect[] = {
    {.name = "name",
270
     .type = VSH_OT_STRING,
271 272 273 274 275 276 277 278 279 280
     .flags = VSH_OFLAG_EMPTY_OK,
     .help = N_("hypervisor connection URI")
    },
    {.name = "readonly",
     .type = VSH_OT_BOOL,
     .help = N_("read-only connection")
    },
    {.name = NULL}
};

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

E
Eric Blake 已提交
292
static bool
293
cmdConnect(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
294
{
295 296
    bool ro = vshCommandOptBool(cmd, "readonly");
    const char *name = NULL;
297 298 299 300

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

301 302
    if (virshReconnect(ctl, name, ro, true) < 0)
        return false;
303

304
    return true;
305 306
}

307 308 309 310
/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
311

312 313
static bool
virshConnectionUsability(vshControl *ctl, virConnectPtr conn)
314
{
315 316 317 318
    if (!conn ||
        virConnectIsAlive(conn) == 0) {
        vshError(ctl, "%s", _("no valid connection"));
        return false;
319 320
    }

321 322 323 324
    /* The connection is considered dead only if
     * virConnectIsAlive() successfuly says so.
     */
    vshResetLibvirtError();
325

326
    return true;
327 328
}

329 330
static void *
virshConnectionHandler(vshControl *ctl)
331
{
332
    virshControlPtr priv = ctl->privData;
333

334 335 336
    if ((!priv->conn || disconnected) &&
        virshReconnect(ctl, NULL, false, false) < 0)
        return NULL;
337

338 339
    if (virshConnectionUsability(ctl, priv->conn))
        return priv->conn;
340

341
    return NULL;
342 343
}

J
Ján Tomko 已提交
344

M
Martin Kletzander 已提交
345 346 347 348
/*
 * Initialize connection.
 */
static bool
349
virshInit(vshControl *ctl)
M
Martin Kletzander 已提交
350
{
351 352
    virshControlPtr priv = ctl->privData;

M
Martin Kletzander 已提交
353
    /* Since we have the commandline arguments parsed, we need to
E
Erik Skultety 已提交
354 355 356
     * reload our initial settings to make debugging and readline
     * work properly */
    vshInitReload(ctl);
M
Martin Kletzander 已提交
357

358
    if (priv->conn)
M
Martin Kletzander 已提交
359
        return false;
360

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

364 365
    if (virEventRegisterDefaultImpl() < 0) {
        vshReportError(ctl);
E
Eric Blake 已提交
366
        return false;
367
    }
368

369 370
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0) {
        vshReportError(ctl);
J
Jiri Denemark 已提交
371
        return false;
372
    }
J
Jiri Denemark 已提交
373 374
    ctl->eventLoopStarted = true;

375
    if ((ctl->eventTimerId = virEventAddTimeout(-1, vshEventTimeout, ctl,
376 377
                                                NULL)) < 0) {
        vshReportError(ctl);
378
        return false;
379
    }
380

381
    if (ctl->connname) {
382 383 384 385 386 387
        /* 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).
         */
388
        if (virshReconnect(ctl, NULL, false, false) < 0) {
E
Eric Blake 已提交
389
            vshReportError(ctl);
390 391
            return false;
        }
392
    }
K
Karel Zak 已提交
393

E
Eric Blake 已提交
394
    return true;
K
Karel Zak 已提交
395 396
}

397
static void
398
virshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
399 400 401 402
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
403
/*
J
Jim Meyering 已提交
404
 * Deinitialize virsh
K
Karel Zak 已提交
405
 */
E
Eric Blake 已提交
406
static bool
407
virshDeinit(vshControl *ctl)
408
{
409 410 411
    virshControlPtr priv = ctl->privData;

    vshDeinit(ctl);
412
    VIR_FREE(ctl->connname);
413
    if (priv->conn) {
414
        int ret;
415 416
        virConnectUnregisterCloseCallback(priv->conn, virshCatchDisconnect);
        ret = virConnectClose(priv->conn);
417 418 419 420 421
        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 已提交
422
    }
D
Daniel P. Berrange 已提交
423 424
    virResetLastError();

J
Jiri Denemark 已提交
425
    if (ctl->eventLoopStarted) {
426 427 428 429
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
430
        /* HACK: Add a dummy timeout to break event loop */
431
        timer = virEventAddTimeout(0, virshDeinitTimer, NULL, NULL);
432 433 434 435
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
436 437 438
        if (timer != -1)
            virEventRemoveTimeout(timer);

439 440 441
        if (ctl->eventTimerId != -1)
            virEventRemoveTimeout(ctl->eventTimerId);

J
Jiri Denemark 已提交
442 443 444
        ctl->eventLoopStarted = false;
    }

445 446
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
447
    return true;
K
Karel Zak 已提交
448
}
449

K
Karel Zak 已提交
450 451 452
/*
 * Print usage
 */
E
Eric Blake 已提交
453
static void
454
virshUsage(void)
455
{
456
    const vshCmdGrp *grp;
457
    const vshCmdDef *cmd;
458

L
Lai Jiangshan 已提交
459 460
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
461
                      "  options:\n"
462 463
                      "    -c | --connect=URI      hypervisor connection URI\n"
                      "    -d | --debug=NUM        debug level [0-4]\n"
464
                      "    -e | --escape <char>    set escape sequence for console\n"
465
                      "    -h | --help             this help\n"
466 467 468 469
                      "    -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"
470
                      "    -l | --log=FILE         output logging to file\n"
471
                      "    -q | --quiet            quiet mode\n"
472
                      "    -r | --readonly         connect readonly\n"
473
                      "    -t | --timing           print timing information\n"
474 475 476
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
477 478
                      "  commands (non interactive mode):\n\n"), progname,
            progname);
479

480
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
481 482 483 484 485
        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;
486
            fprintf(stdout,
E
Eric Blake 已提交
487 488 489
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
490 491 492 493 494
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
495 496 497
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
498 499
}

500 501 502 503
/*
 * Show version and options compiled in
 */
static void
504
virshShowVersion(vshControl *ctl ATTRIBUTE_UNUSED)
505 506 507 508 509
{
    /* 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 已提交
510 511
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
512
#ifdef WITH_QEMU
513
    vshPrint(ctl, " QEMU/KVM");
514
#endif
D
Doug Goldstein 已提交
515 516 517
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
518 519 520
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
521 522 523 524 525 526
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
527 528 529
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
530 531 532
#ifdef WITH_VZ
    vshPrint(ctl, " Virtuozzo");
#endif
D
Doug Goldstein 已提交
533
#ifdef WITH_VMWARE
J
Ján Tomko 已提交
534
    vshPrint(ctl, " VMware");
535
#endif
D
Doug Goldstein 已提交
536 537
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
538
#endif
D
Doug Goldstein 已提交
539 540
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
541 542 543 544
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
545 546
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
547
#endif
D
Doug Goldstein 已提交
548 549
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
550
#endif
551 552 553
#ifdef WITH_BHYVE
    vshPrint(ctl, " Bhyve");
#endif
554 555 556 557 558
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
559
    vshPrint(ctl, "%s", _(" Networking:"));
560 561 562 563 564 565 566 567 568
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
569
#if defined(WITH_INTERFACE)
D
Doug Goldstein 已提交
570
    vshPrint(ctl, " Interface");
571 572
# if defined(WITH_NETCF)
    vshPrint(ctl, " netcf");
573
# elif defined(WITH_UDEV)
574
    vshPrint(ctl, " udev");
575
# endif
576 577 578 579 580 581 582 583 584
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
585
    vshPrint(ctl, "%s", _(" Storage:"));
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
#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");
606 607 608
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
609 610 611
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
612 613 614
#endif
#ifdef WITH_STORAGE_GLUSTER
    vshPrint(ctl, " Gluster");
615 616 617
#endif
#ifdef WITH_STORAGE_ZFS
    vshPrint(ctl, " ZFS");
618 619 620
#endif
#ifdef WITH_STORAGE_VSTORAGE
    vshPrint(ctl, "Virtuozzo Storage");
621 622 623
#endif
    vshPrint(ctl, "\n");

624
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
625 626 627
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
#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
646
#if WITH_READLINE
647 648 649 650 651 652
    vshPrint(ctl, " Readline");
#endif
    vshPrint(ctl, "\n");
}

static bool
653
virshAllowedEscapeChar(char c)
654 655 656 657 658 659 660 661 662 663 664 665
{
    /* Allowed escape characters:
     * a-z A-Z @ [ \ ] ^ _
     */
    return ('a' <= c && c <= 'z') ||
        ('@' <= c && c <= '_');
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
E
Eric Blake 已提交
666
static bool
667
virshParseArgv(vshControl *ctl, int argc, char **argv)
668
{
669
    int arg, len, debug, keepalive;
670
    size_t i;
671
    int longindex = -1;
672
    virshControlPtr priv = ctl->privData;
673
    struct option opt[] = {
674
        {"connect", required_argument, NULL, 'c'},
675
        {"debug", required_argument, NULL, 'd'},
676
        {"escape", required_argument, NULL, 'e'},
677
        {"help", no_argument, NULL, 'h'},
678 679
        {"keepalive-interval", required_argument, NULL, 'k'},
        {"keepalive-count", required_argument, NULL, 'K'},
680
        {"log", required_argument, NULL, 'l'},
681
        {"quiet", no_argument, NULL, 'q'},
682
        {"readonly", no_argument, NULL, 'r'},
683 684 685 686 687 688 689 690
        {"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. */
691
    while ((arg = getopt_long(argc, argv, "+:c:d:e:hk:K:l:qrtvV", opt, &longindex)) != -1) {
692
        switch (arg) {
693
        case 'c':
694 695
            VIR_FREE(ctl->connname);
            ctl->connname = vshStrdup(ctl, optarg);
696
            break;
697
        case 'd':
698
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
699 700
                vshError(ctl, _("option %s takes a numeric argument"),
                         longindex == -1 ? "-d" : "--debug");
701 702
                exit(EXIT_FAILURE);
            }
703 704 705 706 707
            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;
708
            break;
709 710 711 712
        case 'e':
            len = strlen(optarg);

            if ((len == 2 && *optarg == '^' &&
713
                 virshAllowedEscapeChar(optarg[1])) ||
714
                (len == 1 && *optarg != '^')) {
715
                priv->escapeChar = optarg;
716 717 718 719 720 721
            } else {
                vshError(ctl, _("Invalid string '%s' for escape sequence"),
                         optarg);
                exit(EXIT_FAILURE);
            }
            break;
722
        case 'h':
723
            virshUsage();
724 725
            exit(EXIT_SUCCESS);
            break;
726
        case 'k':
E
Erik Skultety 已提交
727 728 729 730 731 732 733 734 735 736
            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"),
737 738 739 740 741 742
                         longindex == -1 ? "-k" : "--keepalive-interval");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_interval = keepalive;
            break;
        case 'K':
E
Erik Skultety 已提交
743 744 745 746 747 748 749 750 751 752
            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"),
753 754 755 756 757
                         longindex == -1 ? "-K" : "--keepalive-count");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_count = keepalive;
            break;
758 759 760 761 762
        case 'l':
            vshCloseLogFile(ctl);
            ctl->logfile = vshStrdup(ctl, optarg);
            vshOpenLogFile(ctl);
            break;
763 764 765 766 767 768
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
769
        case 'r':
770
            priv->readonly = true;
771 772 773 774 775 776
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
M
Marc Hartmayer 已提交
777
            ATTRIBUTE_FALLTHROUGH;
778
        case 'V':
779
            virshShowVersion(ctl);
780
            exit(EXIT_SUCCESS);
781
        case ':':
782
            for (i = 0; opt[i].name != NULL; i++) {
783 784
                if (opt[i].val == optopt)
                    break;
785
            }
786 787 788 789 790 791
            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);
792
        case '?':
793 794 795 796
            if (optopt)
                vshError(ctl, _("unsupported option '-%c'. See --help."), optopt);
            else
                vshError(ctl, _("unsupported option '%s'. See --help."), argv[optind - 1]);
797
            exit(EXIT_FAILURE);
798
        default:
799
            vshError(ctl, _("unknown option"));
800 801
            exit(EXIT_FAILURE);
        }
802
        longindex = -1;
803 804
    }

805 806 807
    if (argc == optind) {
        ctl->imode = true;
    } else {
808 809 810 811 812 813 814 815 816 817 818 819 820
        /* 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[] = {
821 822 823 824 825 826
    VSH_CMD_CD,
    VSH_CMD_ECHO,
    VSH_CMD_EXIT,
    VSH_CMD_HELP,
    VSH_CMD_PWD,
    VSH_CMD_QUIT,
827
    VSH_CMD_SELF_TEST,
828 829 830 831 832
    {.name = "connect",
     .handler = cmdConnect,
     .opts = opts_connect,
     .info = info_connect,
     .flags = VSH_CMD_FLAG_NOCONNECT
833 834
    },
    {.name = NULL}
835
};
836

837
static const vshCmdGrp cmdGroups[] = {
838 839 840 841 842 843 844 845 846 847 848 849
    {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},
850 851
    {NULL, NULL, NULL}
};
K
Karel Zak 已提交
852

853 854 855 856
static const vshClientHooks hooks = {
    .connHandler = virshConnectionHandler
};

857 858 859 860
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
861
    virshControl virshCtl;
E
Eric Blake 已提交
862
    bool ret = true;
K
Karel Zak 已提交
863

864
    memset(ctl, 0, sizeof(vshControl));
865 866
    memset(&virshCtl, 0, sizeof(virshControl));
    ctl->name = "virsh";        /* hardcoded name of the binary */
867
    ctl->env_prefix = "VIRSH";
868
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
869
    ctl->debug = VSH_DEBUG_DEFAULT;
870
    ctl->hooks = &hooks;
871 872 873 874 875

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

876 877 878
    ctl->eventPipe[0] = -1;
    ctl->eventPipe[1] = -1;
    ctl->eventTimerId = -1;
879 880 881 882 883 884 885 886
    virshCtl.escapeChar = "^]";     /* Same default as telnet */
    ctl->privData = &virshCtl;

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

888
    if (virGettextInitialize() < 0)
E
Eric Blake 已提交
889
        return EXIT_FAILURE;
890

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

894
#ifndef WIN32
895 896
        if (tcgetattr(STDIN_FILENO, &ctl->termattr) < 0)
            ctl->istty = false;
897
#endif
898 899
    }

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

905 906 907 908 909
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

910 911
    virFileActivateDirOverride(argv[0]);

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

915 916 917
    if (!virshParseArgv(ctl, argc, argv) ||
        !virshInit(ctl)) {
        virshDeinit(ctl);
K
Karel Zak 已提交
918
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
919
    }
920

921 922 923 924
    if (!ctl->connname)
        ctl->connname = vshStrdup(ctl,
                                  virGetEnvBlockSUID("VIRSH_DEFAULT_CONNECT_URI"));

K
Karel Zak 已提交
925
    if (!ctl->imode) {
926
        ret = vshCommandRun(ctl, ctl->cmd);
927
    } else {
K
Karel Zak 已提交
928 929
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
930
            vshPrint(ctl,
931
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
932
                     progname);
J
Jim Meyering 已提交
933
            vshPrint(ctl, "%s",
934
                     _("Type:  'help' for help with commands\n"
935
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
936
        }
937

K
Karel Zak 已提交
938
        do {
939 940
            const char *prompt = virshCtl.readonly ? VIRSH_PROMPT_RO
                : VIRSH_PROMPT_RW;
941
            ctl->cmdstr =
942
                vshReadline(ctl, prompt);
943 944
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
945
            if (*ctl->cmdstr) {
946
#if WITH_READLINE
K
Karel Zak 已提交
947
                add_history(ctl->cmdstr);
948
#endif
949
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
950 951
                    vshCommandRun(ctl, ctl->cmd);
            }
952
            VIR_FREE(ctl->cmdstr);
953
        } while (ctl->imode);
K
Karel Zak 已提交
954

955 956
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
957
    }
958

959
    virshDeinit(ctl);
K
Karel Zak 已提交
960
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
961
}