virsh.c 50.6 KB
Newer Older
1
/*
2
 * virsh.c: a Xen shell used to exercise the libvir API
3 4 5 6 7 8
 *
 * Copyright (C) 2005 Red Hat, Inc.
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
K
Karel Zak 已提交
9 10 11
 * Karel Zak <kzak@redhat.com>
 *
 * $Id$
12 13
 */

14
#define _GNU_SOURCE             /* isblank() */
K
Karel Zak 已提交
15

16
#include "libvirt.h"
17
#include "virterror.h"
18
#include <stdio.h>
K
Karel Zak 已提交
19 20 21
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
22
#include <unistd.h>
K
Karel Zak 已提交
23
#include <getopt.h>
24
#include <sys/types.h>
K
Karel Zak 已提交
25
#include <sys/time.h>
K
Karel Zak 已提交
26
#include <ctype.h>
27
#include <fcntl.h>
K
Karel Zak 已提交
28 29 30 31 32

#include <readline/readline.h>
#include <readline/history.h>

#include "config.h"
33
#include "internal.h"
K
Karel Zak 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

static char *progname;

#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif

#define VSH_PROMPT_RW    "virsh # "
#define VSH_PROMPT_RO    "virsh > "

#define GETTIMEOFDAY(T) gettimeofday(T, NULL)
#define DIFF_MSEC(T, U) \
        ((((int) ((T)->tv_sec - (U)->tv_sec)) * 1000000.0 + \
          ((int) ((T)->tv_usec - (U)->tv_usec))) / 1000.0)

50 51 52 53
/*
 * The error handler for virtsh
 */
static void
54 55
virshErrorHandler(void *unused, virErrorPtr error)
{
56 57 58 59 60 61 62 63 64 65
    if ((unused != NULL) || (error == NULL))
        return;

    /* Suppress the VIR_ERR_NO_XEN error which fails as non-root */
    if ((error->code == VIR_ERR_NO_XEN) || (error->code == VIR_ERR_OK))
        return;

    virDefaultErrorFunc(error);
}

K
Karel Zak 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79
/*
 * virsh command line grammar:
 *
 *    command_line    =     <command>\n | <command>; <command>; ...
 *
 *    command         =    <keyword> <option> <data>
 *
 *    option          =     <bool_option> | <int_option> | <string_option>
 *    data            =     <string>
 *
 *    bool_option     =     --optionname
 *    int_option      =     --optionname <number>
 *    string_option   =     --optionname <string>
 *        
80 81 82
 *    keyword         =     [a-zA-Z]
 *    number          =     [0-9]+
 *    string          =     [^[:blank:]] | "[[:alnum:]]"$
K
Karel Zak 已提交
83 84 85 86 87
 *
 */

/*
 * vshCmdOptType - command option type 
88
 */
K
Karel Zak 已提交
89
typedef enum {
90 91 92 93 94
    VSH_OT_NONE = 0,            /* none */
    VSH_OT_BOOL,                /* boolean option */
    VSH_OT_STRING,              /* string option */
    VSH_OT_INT,                 /* int option */
    VSH_OT_DATA                 /* string data (as non-option) */
K
Karel Zak 已提交
95 96 97 98 99
} vshCmdOptType;

/*
 * Command Option Flags
 */
100 101
#define VSH_OFLAG_NONE    0     /* without flags */
#define VSH_OFLAG_REQ    (1 << 1)       /* option required */
K
Karel Zak 已提交
102 103 104 105 106 107 108 109

/* dummy */
typedef struct __vshControl vshControl;
typedef struct __vshCmd vshCmd;

/*
 * vshCmdInfo -- information about command
 */
110 111 112
typedef struct {
    const char *name;           /* name of information */
    const char *data;           /* information */
K
Karel Zak 已提交
113 114 115 116 117
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
118 119 120 121 122
typedef struct {
    const char *name;           /* the name of option */
    vshCmdOptType type;         /* option type */
    int flag;                   /* flags */
    const char *help;           /* help string */
K
Karel Zak 已提交
123 124 125 126 127 128
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
 */
typedef struct vshCmdOpt {
129 130 131
    vshCmdOptDef *def;          /* pointer to relevant option */
    char *data;                 /* allocated data */
    struct vshCmdOpt *next;
K
Karel Zak 已提交
132 133 134 135 136
} vshCmdOpt;

/*
 * vshCmdDef - command definition
 */
137 138 139 140 141
typedef struct {
    const char *name;
    int (*handler) (vshControl *, vshCmd *);    /* command handler */
    vshCmdOptDef *opts;         /* definition of command options */
    vshCmdInfo *info;           /* details about command */
K
Karel Zak 已提交
142 143 144 145 146 147
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
148 149 150
    vshCmdDef *def;             /* command definition */
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
151 152 153 154 155 156
} __vshCmd;

/*
 * vshControl
 */
typedef struct __vshControl {
157 158 159 160 161 162 163 164
    virConnectPtr conn;         /* connection to hypervisor */
    vshCmd *cmd;                /* the current command */
    char *cmdstr;               /* string with command */
    uid_t uid;                  /* process owner */
    int imode;                  /* interactive mode? */
    int quiet;                  /* quiet mode */
    int debug;                  /* print debug messages? */
    int timing;                 /* print timing info? */
K
Karel Zak 已提交
165
} __vshControl;
166

167

K
Karel Zak 已提交
168 169
static vshCmdDef commands[];

170 171 172 173 174
static void vshError(vshControl * ctl, int doexit, const char *format,
                     ...);
static int vshInit(vshControl * ctl);
static int vshDeinit(vshControl * ctl);
static void vshUsage(vshControl * ctl, const char *cmdname);
K
Karel Zak 已提交
175

176
static int vshParseArgv(vshControl * ctl, int argc, char **argv);
K
Karel Zak 已提交
177

178
static const char *vshCmddefGetInfo(vshCmdDef * cmd, const char *info);
K
Karel Zak 已提交
179
static vshCmdDef *vshCmddefSearch(const char *cmdname);
180
static int vshCmddefHelp(vshControl * ctl, const char *name, int withprog);
K
Karel Zak 已提交
181

182 183 184 185 186 187 188
static vshCmdOpt *vshCommandOpt(vshCmd * cmd, const char *name);
static int vshCommandOptInt(vshCmd * cmd, const char *name, int *found);
static char *vshCommandOptString(vshCmd * cmd, const char *name,
                                 int *found);
static int vshCommandOptBool(vshCmd * cmd, const char *name);
static virDomainPtr vshCommandOptDomain(vshControl * ctl, vshCmd * cmd,
                                        const char *optname, char **name);
K
Karel Zak 已提交
189

K
Karel Zak 已提交
190 191 192
static void vshPrintExtra(vshControl * ctl, const char *format, ...);
static void vshDebug(vshControl * ctl, int level, const char *format, ...);
#define vshPrint(_ctl, ...)   fprintf(stdout, __VA_ARGS__)
K
Karel Zak 已提交
193

K
Karel Zak 已提交
194
static const char *vshDomainStateToString(int state);
195 196
static int vshConnectionUsability(vshControl * ctl, virConnectPtr conn,
                                  int showerror);
K
Karel Zak 已提交
197

198 199 200 201 202 203 204 205 206
static void *_vshMalloc(vshControl * ctl, size_t sz, const char *filename, int line);
#define vshMalloc(_ctl, _sz)    _vshMalloc(_ctl, _sz, __FILE__, __LINE__)

static void *_vshCalloc(vshControl * ctl, size_t nmemb, size_t sz, const char *filename, int line);
#define vshCalloc(_ctl, _nmemb, _sz)    _vshCalloc(_ctl, _nmemb, _sz, __FILE__, __LINE__)

static char *_vshStrdup(vshControl * ctl, const char *s, const char *filename, int line);
#define vshStrdup(_ctl, _s)    _vshStrdup(_ctl, _s, __FILE__, __LINE__)

K
Karel Zak 已提交
207 208 209 210 211 212 213 214 215
/* ---------------
 * Commands
 * ---------------
 */

/*
 * "help" command 
 */
static vshCmdInfo info_help[] = {
216 217 218 219 220
    {"syntax", "help [<command>]"},
    {"help", "print help"},
    {"desc", "Prints global help or command specific help."},
    {"version", "Prints versionning informations."},
    {NULL, NULL}
K
Karel Zak 已提交
221 222 223
};

static vshCmdOptDef opts_help[] = {
224 225
    {"command", VSH_OT_DATA, 0, "name of command"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
226 227 228
};

static int
229 230
cmdHelp(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
231
    const char *cmdname = vshCommandOptString(cmd, "command", NULL);
K
Karel Zak 已提交
232 233 234

    if (!cmdname) {
        vshCmdDef *def;
235

K
Karel Zak 已提交
236
        vshPrint(ctl, "Commands:\n\n");
237
        for (def = commands; def->name; def++)
K
Karel Zak 已提交
238
            vshPrint(ctl, "    %-15s %s\n", def->name,
239
                     vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
240 241 242 243 244 245 246 247 248
        return TRUE;
    }
    return vshCmddefHelp(ctl, cmdname, FALSE);
}

/*
 * "connect" command 
 */
static vshCmdInfo info_connect[] = {
249 250 251 252 253
    {"syntax", "connect [--readonly]"},
    {"help", "(re)connect to hypervisor"},
    {"desc",
     "Connect to local hypervisor. This is build-in command after shell start up."},
    {NULL, NULL}
K
Karel Zak 已提交
254 255 256
};

static vshCmdOptDef opts_connect[] = {
257 258
    {"readonly", VSH_OT_BOOL, 0, "read-only connection"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
259 260 261
};

static int
262 263
cmdConnect(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
264
    int ro = vshCommandOptBool(cmd, "readonly");
265

K
Karel Zak 已提交
266
    if (ctl->conn) {
267 268 269
        if (virConnectClose(ctl->conn) != 0) {
            vshError(ctl, FALSE,
                     "failed to disconnect from the hypervisor");
K
Karel Zak 已提交
270 271 272 273 274 275 276 277 278 279 280
            return FALSE;
        }
        ctl->conn = NULL;
    }
    if (!ro)
        ctl->conn = virConnectOpen(NULL);
    else
        ctl->conn = virConnectOpenReadOnly(NULL);

    if (!ctl->conn)
        vshError(ctl, FALSE, "failed to connect to the hypervisor");
281

K
Karel Zak 已提交
282 283 284 285 286 287 288
    return ctl->conn ? TRUE : FALSE;
}

/*
 * "list" command
 */
static vshCmdInfo info_list[] = {
289 290 291 292
    {"syntax", "list"},
    {"help", "list domains"},
    {"desc", "Returns list of domains."},
    {NULL, NULL}
K
Karel Zak 已提交
293 294 295 296 297
};



static int
298 299
cmdList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
300 301 302 303
    int *ids, maxid, i;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
304

K
Karel Zak 已提交
305 306 307 308 309 310
    maxid = virConnectNumOfDomains(ctl->conn);
    if (maxid <= 0) {
        /* strange, there should be at least dom0... */
        vshError(ctl, FALSE, "failed to list active domains.");
        return FALSE;
    }
311 312
    ids = vshMalloc(ctl, sizeof(int) * maxid);

K
Karel Zak 已提交
313
    virConnectListDomains(ctl->conn, &ids[0], maxid);
314

K
Karel Zak 已提交
315 316
    vshPrintExtra(ctl, "%3s %-20s %s\n", "Id", "Name", "State");
    vshPrintExtra(ctl, "----------------------------------\n");
317 318

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
319 320 321
        int ret;
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
322 323

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
324 325 326
        if (!dom)
            continue;
        ret = virDomainGetInfo(dom, &info);
327

K
Karel Zak 已提交
328
        vshPrint(ctl, "%3d %-20s %s\n",
329 330 331 332
                 virDomainGetID(dom),
                 virDomainGetName(dom),
                 ret <
                 0 ? "no state" : vshDomainStateToString(info.state));
333
        virDomainFree(dom);
K
Karel Zak 已提交
334 335 336 337 338 339
    }
    free(ids);
    return TRUE;
}

/*
K
Karel Zak 已提交
340
 * "domstate" command
K
Karel Zak 已提交
341
 */
K
Karel Zak 已提交
342 343
static vshCmdInfo info_domstate[] = {
    {"syntax", "domstate <domain>"},
344 345 346
    {"help", "domain state"},
    {"desc", "Returns state about a running domain."},
    {NULL, NULL}
K
Karel Zak 已提交
347 348
};

K
Karel Zak 已提交
349
static vshCmdOptDef opts_domstate[] = {
350 351
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
352 353 354
};

static int
K
Karel Zak 已提交
355
cmdDomstate(vshControl * ctl, vshCmd * cmd)
356
{
357
    virDomainInfo info;
K
Karel Zak 已提交
358
    virDomainPtr dom;
K
Karel Zak 已提交
359
    int ret = TRUE;
360

K
Karel Zak 已提交
361 362
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
363

K
Karel Zak 已提交
364
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
365
        return FALSE;
366 367

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
368
        vshPrint(ctl, "%s\n",
369
                 vshDomainStateToString(info.state));
K
Karel Zak 已提交
370 371
    else
        ret = FALSE;
372

373 374 375 376 377 378 379 380
    virDomainFree(dom);
    return ret;
}

/*
 * "suspend" command
 */
static vshCmdInfo info_suspend[] = {
381 382 383 384
    {"syntax", "suspend <domain>"},
    {"help", "suspend a domain"},
    {"desc", "Suspend a running domain."},
    {NULL, NULL}
385 386 387
};

static vshCmdOptDef opts_suspend[] = {
388 389
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
390 391 392
};

static int
393 394
cmdSuspend(vshControl * ctl, vshCmd * cmd)
{
395
    virDomainPtr dom;
K
Karel Zak 已提交
396 397
    char *name;
    int ret = TRUE;
398

399 400 401
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
402
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
403
        return FALSE;
404 405

    if (virDomainSuspend(dom) == 0) {
K
Karel Zak 已提交
406
        vshPrint(ctl, "Domain %s suspended\n", name);
407 408 409 410
    } else {
        vshError(ctl, FALSE, "Failed to suspend domain\n");
        ret = FALSE;
    }
411

412 413 414 415
    virDomainFree(dom);
    return ret;
}

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
/*
 * "create" command
 */
static vshCmdInfo info_create[] = {
    {"syntax", "create a domain from an XML <file>"},
    {"help", "create a domain from an XML file"},
    {"desc", "Create a domain."},
    {NULL, NULL}
};

static vshCmdOptDef opts_create[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, "file conatining an XML domain description"},
    {NULL, 0, 0, NULL}
};

static int
cmdCreate(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
    char buffer[4096];
    int fd, l;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    from = vshCommandOptString(cmd, "file", &found);
    if (!found)
        return FALSE;

    fd = open(from, O_RDONLY);
    if (fd < 0) {
        vshError(ctl, FALSE, "Failed to read description file %s\n", from);
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
        vshError(ctl, FALSE, "Failed to read description file %s\n", from);
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    dom = virDomainCreateLinux(ctl->conn, &buffer[0], 0);
    if (dom != NULL) {
K
Karel Zak 已提交
462
        vshPrint(ctl, "Domain %s created from %s\n", 
463 464 465 466 467 468 469 470
                 virDomainGetName(dom), from);
    } else {
        vshError(ctl, FALSE, "Failed to create domain\n");
        ret = FALSE;
    }
    return ret;
}

471 472 473 474
/*
 * "save" command
 */
static vshCmdInfo info_save[] = {
475 476 477 478
    {"syntax", "save <domain> <file>"},
    {"help", "save a domain state to a file"},
    {"desc", "Save a running domain."},
    {NULL, NULL}
479 480 481
};

static vshCmdOptDef opts_save[] = {
482 483 484
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, "where to save the data"},
    {NULL, 0, 0, NULL}
485 486 487
};

static int
488 489
cmdSave(vshControl * ctl, vshCmd * cmd)
{
490 491 492 493
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
494

495 496 497
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

498
    if (!(to = vshCommandOptString(cmd, "file", NULL)))
499
        return FALSE;
500

501 502
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
        return FALSE;
503 504

    if (virDomainSave(dom, to) == 0) {
K
Karel Zak 已提交
505
        vshPrint(ctl, "Domain %s saved\n", name);
506 507 508 509
    } else {
        vshError(ctl, FALSE, "Failed to save domain\n");
        ret = FALSE;
    }
510

511 512 513 514 515 516 517 518
    virDomainFree(dom);
    return ret;
}

/*
 * "restore" command
 */
static vshCmdInfo info_restore[] = {
519 520 521 522
    {"syntax", "restore a domain from <file>"},
    {"help", "restore a domain from a saved state in a file"},
    {"desc", "Restore a domain."},
    {NULL, NULL}
523 524 525
};

static vshCmdOptDef opts_restore[] = {
526 527
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, "the state to restore"},
    {NULL, 0, 0, NULL}
528 529 530
};

static int
531 532
cmdRestore(vshControl * ctl, vshCmd * cmd)
{
533 534 535
    char *from;
    int found;
    int ret = TRUE;
536

537 538 539 540 541 542
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    from = vshCommandOptString(cmd, "file", &found);
    if (!found)
        return FALSE;
543 544

    if (virDomainRestore(ctl->conn, from) == 0) {
K
Karel Zak 已提交
545
        vshPrint(ctl, "Domain restored from %s\n", from);
546 547 548 549 550 551 552
    } else {
        vshError(ctl, FALSE, "Failed to restore domain\n");
        ret = FALSE;
    }
    return ret;
}

553 554 555 556
/*
 * "resume" command
 */
static vshCmdInfo info_resume[] = {
557 558 559 560
    {"syntax", "resume <domain>"},
    {"help", "resume a domain"},
    {"desc", "Resume a previously suspended domain."},
    {NULL, NULL}
561 562 563
};

static vshCmdOptDef opts_resume[] = {
564 565
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
566 567 568
};

static int
569 570
cmdResume(vshControl * ctl, vshCmd * cmd)
{
571
    virDomainPtr dom;
K
Karel Zak 已提交
572 573
    int ret = TRUE;
    char *name;
574

575 576 577
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
578
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
579
        return FALSE;
580 581

    if (virDomainResume(dom) == 0) {
K
Karel Zak 已提交
582
        vshPrint(ctl, "Domain %s resumed\n", name);
583 584 585 586
    } else {
        vshError(ctl, FALSE, "Failed to resume domain\n");
        ret = FALSE;
    }
587

588 589 590 591
    virDomainFree(dom);
    return ret;
}

592 593 594 595
/*
 * "shutdown" command
 */
static vshCmdInfo info_shutdown[] = {
596 597 598 599
    {"syntax", "shutdown <domain>"},
    {"help", "gracefully shutdown a domain"},
    {"desc", "Run shutdown in the targetted domain"},
    {NULL, NULL}
600 601 602
};

static vshCmdOptDef opts_shutdown[] = {
603 604
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
605 606 607
};

static int
608 609
cmdShutdown(vshControl * ctl, vshCmd * cmd)
{
610 611 612
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
613

614 615 616 617 618
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
        return FALSE;
619 620

    if (virDomainShutdown(dom) == 0) {
K
Karel Zak 已提交
621
        vshPrint(ctl, "Domain %s is being shutdown\n", name);
622 623 624 625
    } else {
        vshError(ctl, FALSE, "Failed to shutdown domain\n");
        ret = FALSE;
    }
626

627 628 629 630
    virDomainFree(dom);
    return ret;
}

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
/*
 * "reboot" command
 */
static vshCmdInfo info_reboot[] = {
    {"syntax", "reboot <domain>"},
    {"help", "reboot a domain"},
    {"desc", "Run a reboot command in the targetted domain"},
    {NULL, NULL}
};

static vshCmdOptDef opts_reboot[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
};

static int
cmdReboot(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    int ret = TRUE;
    char *name;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
        return FALSE;

    if (virDomainReboot(dom, 0) == 0) {
K
Karel Zak 已提交
660
        vshPrint(ctl, "Domain %s is being rebooted\n", name);
661 662 663 664 665 666 667 668 669
    } else {
        vshError(ctl, FALSE, "Failed to reboot domain\n");
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

670 671 672 673
/*
 * "destroy" command
 */
static vshCmdInfo info_destroy[] = {
674 675 676 677
    {"syntax", "destroy <domain>"},
    {"help", "destroy a domain"},
    {"desc", "Destroy a given domain."},
    {NULL, NULL}
678 679 680
};

static vshCmdOptDef opts_destroy[] = {
681 682
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
683 684 685
};

static int
686 687
cmdDestroy(vshControl * ctl, vshCmd * cmd)
{
688
    virDomainPtr dom;
K
Karel Zak 已提交
689 690
    int ret = TRUE;
    char *name;
691

692 693 694
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
695
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
696
        return FALSE;
697 698

    if (virDomainDestroy(dom) == 0) {
K
Karel Zak 已提交
699
        vshPrint(ctl, "Domain %s destroyed\n", name);
700 701 702 703 704
    } else {
        vshError(ctl, FALSE, "Failed to destroy domain\n");
        ret = FALSE;
        virDomainFree(dom);
    }
705

K
Karel Zak 已提交
706 707 708 709
    return ret;
}

/*
710
 * "dominfo" command
K
Karel Zak 已提交
711
 */
712 713
static vshCmdInfo info_dominfo[] = {
    {"syntax", "dominfo <domain>"},
714 715 716
    {"help", "domain information"},
    {"desc", "Returns basic information about the domain."},
    {NULL, NULL}
K
Karel Zak 已提交
717 718
};

719
static vshCmdOptDef opts_dominfo[] = {
720 721
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
722 723 724
};

static int
725
cmdDominfo(vshControl * ctl, vshCmd * cmd)
726
{
K
Karel Zak 已提交
727 728
    virDomainInfo info;
    virDomainPtr dom;
K
Karel Zak 已提交
729
    int ret = TRUE;
K
Karel Zak 已提交
730
    char *str, uuid[37];
731

K
Karel Zak 已提交
732 733 734
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
735
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
736
        return FALSE;
737

K
Karel Zak 已提交
738 739 740 741
    vshPrint(ctl, "%-15s %d\n", "Id:", virDomainGetID(dom));
    vshPrint(ctl, "%-15s %s\n", "Name:", virDomainGetName(dom));
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
        vshPrint(ctl, "%-15s %s\n", "UUID:", uuid);
742 743

    if ((str = virDomainGetOSType(dom))) {
K
Karel Zak 已提交
744
        vshPrint(ctl, "%-15s %s\n", "OS Type:", str);
745 746 747 748
        free(str);
    }

    if (virDomainGetInfo(dom, &info) == 0) {
K
Karel Zak 已提交
749
        vshPrint(ctl, "%-15s %s\n", "State:",
750 751
                 vshDomainStateToString(info.state));

K
Karel Zak 已提交
752
        vshPrint(ctl, "%-15s %d\n", "CPU(s):", info.nrVirtCpu);
753 754

        if (info.cpuTime != 0) {
K
Karel Zak 已提交
755
            float cpuUsed = info.cpuTime;
756

K
Karel Zak 已提交
757
            cpuUsed /= 1000000000;
758

K
Karel Zak 已提交
759
            vshPrint(ctl, "%-15s %.1fs\n", "CPU time:", cpuUsed);
K
Karel Zak 已提交
760
        }
761

K
Karel Zak 已提交
762
        vshPrint(ctl, "%-15s %lu kB\n", "Max memory:",
763
                 info.maxMem);
K
Karel Zak 已提交
764
        vshPrint(ctl, "%-15s %lu kB\n", "Used memory:",
765 766
                 info.memory);

K
Karel Zak 已提交
767 768 769
    } else {
        ret = FALSE;
    }
770

771
    virDomainFree(dom);
K
Karel Zak 已提交
772 773 774
    return ret;
}

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
/*
 * "nodeinfo" command
 */
static vshCmdInfo info_nodeinfo[] = {
    {"syntax", "nodeinfo"},
    {"help", "node information"},
    {"desc", "Returns basic information about the node."},
    {NULL, NULL}
};

static int
cmdNodeinfo(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    virNodeInfo info;
        
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
        vshError(ctl, FALSE, "failed to get node information");
        return FALSE;
    }    
K
Karel Zak 已提交
797 798 799 800 801 802 803 804
    vshPrint(ctl, "%-20s %s\n", "CPU model:", info.model);
    vshPrint(ctl, "%-20s %d\n", "CPU(s):", info.cpus);
    vshPrint(ctl, "%-20s %d MHz\n", "CPU frequency:", info.mhz);
    vshPrint(ctl, "%-20s %d\n", "CPU socket(s):", info.sockets);
    vshPrint(ctl, "%-20s %d\n", "Core(s) per socket:", info.cores);
    vshPrint(ctl, "%-20s %d\n", "Thread(s) per core:", info.threads);
    vshPrint(ctl, "%-20s %d\n", "NUMA cell(s):", info.nodes);
    vshPrint(ctl, "%-20s %lu kB\n", "Memory size:", info.memory);
805 806 807 808
        
    return TRUE;
}

809 810 811 812
/*
 * "dumpxml" command
 */
static vshCmdInfo info_dumpxml[] = {
813 814 815 816
    {"syntax", "dumpxml <name>"},
    {"help", "domain information in XML"},
    {"desc", "Ouput the domain informations as an XML dump to stdout"},
    {NULL, NULL}
817 818 819
};

static vshCmdOptDef opts_dumpxml[] = {
820 821
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or id"},
    {NULL, 0, 0, NULL}
822 823 824
};

static int
825 826
cmdDumpXML(vshControl * ctl, vshCmd * cmd)
{
827
    virDomainPtr dom;
K
Karel Zak 已提交
828
    int ret = TRUE;
829
    char *dump;
830

831 832 833
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
834
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
835
        return FALSE;
836

837 838 839 840 841 842 843
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
844

845 846 847 848
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
849
/*
K
Karel Zak 已提交
850
 * "domname" command
K
Karel Zak 已提交
851
 */
K
Karel Zak 已提交
852 853
static vshCmdInfo info_domname[] = {
    {"syntax", "domname <id>"},
854 855
    {"help", "convert a domain Id to domain name"},
    {NULL, NULL}
K
Karel Zak 已提交
856 857
};

K
Karel Zak 已提交
858
static vshCmdOptDef opts_domname[] = {
859 860
    {"id", VSH_OT_DATA, VSH_OFLAG_REQ, "domain Id"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
861 862 863
};

static int
K
Karel Zak 已提交
864
cmdDomname(vshControl * ctl, vshCmd * cmd)
865
{
K
Karel Zak 已提交
866 867 868 869 870 871 872 873
    int found;
    int id = vshCommandOptInt(cmd, "id", &found);
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!found)
        return FALSE;
874

K
Karel Zak 已提交
875 876
    dom = virDomainLookupByID(ctl->conn, id);
    if (dom) {
K
Karel Zak 已提交
877
        vshPrint(ctl, "%s\n", virDomainGetName(dom));
878
        virDomainFree(dom);
K
Karel Zak 已提交
879 880 881 882 883 884 885 886
    } else {
        vshError(ctl, FALSE, "failed to get domain '%d'", id);
        return FALSE;
    }
    return TRUE;
}

/*
K
Karel Zak 已提交
887
 * "domid" command
K
Karel Zak 已提交
888
 */
K
Karel Zak 已提交
889 890
static vshCmdInfo info_domid[] = {
    {"syntax", "domid <name>"},
891 892
    {"help", "convert a domain name to domain Id"},
    {NULL, NULL}
K
Karel Zak 已提交
893 894
};

K
Karel Zak 已提交
895
static vshCmdOptDef opts_domid[] = {
896 897
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
898 899 900
};

static int
K
Karel Zak 已提交
901
cmdDomid(vshControl * ctl, vshCmd * cmd)
902
{
K
Karel Zak 已提交
903
    char *name = vshCommandOptString(cmd, "name", NULL);
904
    virDomainPtr dom;
K
Karel Zak 已提交
905 906 907 908 909

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!name)
        return FALSE;
910

K
Karel Zak 已提交
911 912
    dom = virDomainLookupByName(ctl->conn, name);
    if (dom) {
K
Karel Zak 已提交
913
        vshPrint(ctl, "%d\n", virDomainGetID(dom));
914
        virDomainFree(dom);
K
Karel Zak 已提交
915 916 917 918 919 920 921
    } else {
        vshError(ctl, FALSE, "failed to get domain '%s'", name);
        return FALSE;
    }
    return TRUE;
}

922 923 924 925
/*
 * "version" command
 */
static vshCmdInfo info_version[] = {
926 927 928 929
    {"syntax", "version"},
    {"help", "show versions"},
    {"desc", "Display the version informations available"},
    {NULL, NULL}
930 931 932 933
};


static int
934 935
cmdVersion(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
936 937
    unsigned long hvVersion;
    const char *hvType;
938 939 940 941 942 943 944
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
945 946 947

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
948

949 950
    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
K
Karel Zak 已提交
951
        vshError(ctl, FALSE, "failed to get hypervisor type\n");
952 953 954
        return FALSE;
    }

955 956 957 958 959
    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
K
Karel Zak 已提交
960
    vshPrint(ctl, "Compiled against library: libvir %d.%d.%d\n",
961 962 963 964 965 966 967 968 969 970 971
             major, minor, rel);

    ret = virGetVersion(&libVersion, hvType, &apiVersion);
    if (ret < 0) {
        vshError(ctl, FALSE, "failed to get the library version");
        return FALSE;
    }
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
K
Karel Zak 已提交
972
    vshPrint(ctl, "Using library: libvir %d.%d.%d\n",
973
             major, minor, rel);
974

975 976 977 978
    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
K
Karel Zak 已提交
979
    vshPrint(ctl, "Using API: %s %d.%d.%d\n", hvType,
980 981
             major, minor, rel);

982
    ret = virConnectGetVersion(ctl->conn, &hvVersion);
983 984
    if (ret < 0) {
        vshError(ctl, FALSE, "failed to get the hypervisor version");
985 986 987
        return FALSE;
    }
    if (hvVersion == 0) {
K
Karel Zak 已提交
988
        vshPrint(ctl,
989
                 "cannot extract running %s hypervisor version\n", hvType);
990
    } else {
991
        major = hvVersion / 1000000;
992
        hvVersion %= 1000000;
993 994
        minor = hvVersion / 1000;
        rel = hvVersion % 1000;
995

K
Karel Zak 已提交
996
        vshPrint(ctl, "Running hypervisor: %s %d.%d.%d\n",
997
                 hvType, major, minor, rel);
998 999 1000 1001
    }
    return TRUE;
}

K
Karel Zak 已提交
1002 1003 1004 1005
/*
 * "quit" command
 */
static vshCmdInfo info_quit[] = {
1006 1007 1008
    {"syntax", "quit"},
    {"help", "quit this interactive terminal"},
    {NULL, NULL}
K
Karel Zak 已提交
1009 1010 1011
};

static int
1012 1013
cmdQuit(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
1014 1015 1016 1017 1018 1019 1020 1021
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
static vshCmdDef commands[] = {
1022
    {"connect", cmdConnect, opts_connect, info_connect},
1023
    {"create", cmdCreate, opts_create, info_create},
K
Karel Zak 已提交
1024 1025
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
    {"domid", cmdDomid, opts_domid, info_domid},
1026
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
1027 1028
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
1029
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
K
Karel Zak 已提交
1030 1031 1032 1033 1034 1035
    {"help", cmdHelp, opts_help, info_help},
    {"list", cmdList, NULL, info_list},
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
    {"quit", cmdQuit, NULL, info_quit},
    {"reboot", cmdReboot, opts_reboot, info_reboot},
    {"restore", cmdRestore, opts_restore, info_restore},
1036 1037 1038
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
K
Karel Zak 已提交
1039
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
1040 1041
    {"version", cmdVersion, NULL, info_version},
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
1042 1043 1044 1045 1046 1047
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
1048
static const char *
1049 1050
vshCmddefGetInfo(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1051
    vshCmdInfo *info;
1052

K
Karel Zak 已提交
1053
    for (info = cmd->info; info && info->name; info++) {
1054
        if (strcmp(info->name, name) == 0)
K
Karel Zak 已提交
1055 1056 1057 1058 1059 1060
            return info->data;
    }
    return NULL;
}

static vshCmdOptDef *
1061 1062
vshCmddefGetOption(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1063
    vshCmdOptDef *opt;
1064

K
Karel Zak 已提交
1065
    for (opt = cmd->opts; opt && opt->name; opt++)
1066
        if (strcmp(opt->name, name) == 0)
K
Karel Zak 已提交
1067 1068 1069 1070 1071
            return opt;
    return NULL;
}

static vshCmdOptDef *
1072 1073
vshCmddefGetData(vshCmdDef * cmd, int data_ct)
{
K
Karel Zak 已提交
1074 1075
    vshCmdOptDef *opt;

1076
    for (opt = cmd->opts; opt && opt->name; opt++) {
1077 1078
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
1079 1080 1081 1082 1083
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
1084 1085 1086
    return NULL;
}

1087 1088 1089
/*
 * Checks for required options
 */
1090 1091
static int
vshCommandCheckOpts(vshControl * ctl, vshCmd * cmd)
1092 1093 1094
{
    vshCmdDef *def = cmd->def;
    vshCmdOptDef *d;
1095
    int err = 0;
1096 1097 1098 1099

    for (d = def->opts; d && d->name; d++) {
        if (d->flag & VSH_OFLAG_REQ) {
            vshCmdOpt *o = cmd->opts;
1100 1101 1102
            int ok = 0;

            while (o && ok == 0) {
1103
                if (o->def == d)
1104
                    ok = 1;
1105 1106 1107
                o = o->next;
            }
            if (!ok) {
1108 1109 1110 1111 1112
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
                         "command '%s' requires <%s> option" :
                         "command '%s' requires --%s option",
                         def->name, d->name);
1113 1114
                err = 1;
            }
1115

1116 1117 1118 1119 1120
        }
    }
    return !err;
}

K
Karel Zak 已提交
1121
static vshCmdDef *
1122 1123
vshCmddefSearch(const char *cmdname)
{
K
Karel Zak 已提交
1124
    vshCmdDef *c;
1125

K
Karel Zak 已提交
1126
    for (c = commands; c->name; c++)
1127
        if (strcmp(c->name, cmdname) == 0)
K
Karel Zak 已提交
1128 1129 1130 1131 1132
            return c;
    return NULL;
}

static int
1133 1134
vshCmddefHelp(vshControl * ctl, const char *cmdname, int withprog)
{
K
Karel Zak 已提交
1135
    vshCmdDef *def = vshCmddefSearch(cmdname);
1136

K
Karel Zak 已提交
1137
    if (!def) {
1138 1139 1140
        vshError(ctl, FALSE, "command '%s' doesn't exist", cmdname);
        return FALSE;
    } else {
K
Karel Zak 已提交
1141
        vshCmdOptDef *opt;
K
Karel Zak 已提交
1142 1143 1144
        const char *desc = vshCmddefGetInfo(def, "desc");
        const char *help = vshCmddefGetInfo(def, "help");
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
1145 1146

        fputs("  NAME\n", stdout);
1147 1148
        fprintf(stdout, "    %s - %s\n", def->name, help);

K
Karel Zak 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
        if (syntax) {
            fputs("\n  SYNOPSIS\n", stdout);
            if (!withprog)
                fprintf(stdout, "    %s\n", syntax);
            else
                fprintf(stdout, "    %s %s\n", progname, syntax);
        }
        if (desc) {
            fputs("\n  DESCRIPTION\n", stdout);
            fprintf(stdout, "    %s\n", desc);
        }
        if (def->opts) {
            fputs("\n  OPTIONS\n", stdout);
1162
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
1163
                char buf[256];
1164 1165

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
1166
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1167
                else if (opt->type == VSH_OT_INT)
K
Karel Zak 已提交
1168
                    snprintf(buf, sizeof(buf), "--%s <number>", opt->name);
1169
                else if (opt->type == VSH_OT_STRING)
K
Karel Zak 已提交
1170
                    snprintf(buf, sizeof(buf), "--%s <string>", opt->name);
1171
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
1172
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
1173

K
Karel Zak 已提交
1174
                fprintf(stdout, "    %-15s  %s\n", buf, opt->help);
1175
            }
K
Karel Zak 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1186 1187 1188
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1189 1190
    vshCmdOpt *a = arg;

1191
    while (a) {
K
Karel Zak 已提交
1192
        vshCmdOpt *tmp = a;
1193

K
Karel Zak 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202
        a = a->next;

        if (tmp->data)
            free(tmp->data);
        free(tmp);
    }
}

static void
1203 1204
vshCommandFree(vshCmd * cmd)
{
K
Karel Zak 已提交
1205 1206
    vshCmd *c = cmd;

1207
    while (c) {
K
Karel Zak 已提交
1208
        vshCmd *tmp = c;
1209

K
Karel Zak 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
        free(tmp);
    }
}

/*
 * Returns option by name
 */
static vshCmdOpt *
1222 1223
vshCommandOpt(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
1224
    vshCmdOpt *opt = cmd->opts;
1225 1226 1227

    while (opt) {
        if (opt->def && strcmp(opt->def->name, name) == 0)
K
Karel Zak 已提交
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
1238 1239
vshCommandOptInt(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
1240 1241
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
    int res = 0;
1242

K
Karel Zak 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
    if (arg)
        res = atoi(arg->data);
    if (found)
        *found = arg ? TRUE : FALSE;
    return res;
}

/*
 * Returns option as STRING
 */
static char *
1254 1255
vshCommandOptString(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
1256
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
1257

K
Karel Zak 已提交
1258 1259
    if (found)
        *found = arg ? TRUE : FALSE;
1260 1261

    return arg && arg->data && *arg->data ? arg->data : NULL;
K
Karel Zak 已提交
1262 1263 1264 1265 1266 1267
}

/*
 * Returns TRUE/FALSE if the option exists
 */
static int
1268 1269
vshCommandOptBool(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
1270 1271 1272
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

1273

K
Karel Zak 已提交
1274
static virDomainPtr
1275 1276 1277
vshCommandOptDomain(vshControl * ctl, vshCmd * cmd, const char *optname,
                    char **name)
{
K
Karel Zak 已提交
1278 1279 1280
    virDomainPtr dom = NULL;
    char *n, *end = NULL;
    int id;
1281

K
Karel Zak 已提交
1282 1283
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
        vshError(ctl, FALSE, "undefined domain name or id");
1284
        return NULL;
K
Karel Zak 已提交
1285
    }
1286

K
Karel Zak 已提交
1287
    vshDebug(ctl, 5, "%s: found option <%s>: %s\n",
1288 1289
             cmd->def->name, optname, n);

K
Karel Zak 已提交
1290 1291
    if (name)
        *name = n;
1292

K
Karel Zak 已提交
1293 1294
    /* try it by ID */
    id = (int) strtol(n, &end, 10);
1295
    if (id >= 0 && end && *end == '\0') {
K
Karel Zak 已提交
1296
        vshDebug(ctl, 5, "%s: <%s> seems like domain ID\n",
1297
                 cmd->def->name, optname);
K
Karel Zak 已提交
1298
        dom = virDomainLookupByID(ctl->conn, id);
1299
    }
1300

K
Karel Zak 已提交
1301 1302 1303 1304 1305 1306 1307
    /* try it by UUID */
    if (dom==NULL && strlen(n)==36) {
        vshDebug(ctl, 5, "%s: <%s> tring as domain UUID\n",
                cmd->def->name, optname);
        dom = virDomainLookupByUUIDString(ctl->conn, (const unsigned char *) n);
    }
    
K
Karel Zak 已提交
1308
    /* try it by NAME */
1309
    if (!dom) {
K
Karel Zak 已提交
1310
        vshDebug(ctl, 5, "%s: <%s> tring as domain NAME\n",
1311
                 cmd->def->name, optname);
K
Karel Zak 已提交
1312
        dom = virDomainLookupByName(ctl->conn, n);
1313
    }
K
Karel Zak 已提交
1314

1315
    if (!dom)
K
Karel Zak 已提交
1316
        vshError(ctl, FALSE, "failed to get domain '%s'", n);
1317

K
Karel Zak 已提交
1318 1319 1320
    return dom;
}

K
Karel Zak 已提交
1321 1322 1323 1324
/*
 * Executes command(s) and returns return code from last command
 */
static int
1325 1326
vshCommandRun(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
1327
    int ret = TRUE;
1328 1329

    while (cmd) {
K
Karel Zak 已提交
1330
        struct timeval before, after;
1331

K
Karel Zak 已提交
1332 1333
        if (ctl->timing)
            GETTIMEOFDAY(&before);
1334

K
Karel Zak 已提交
1335 1336 1337 1338
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
1339 1340

        if (strcmp(cmd->def->name, "quit") == 0)        /* hack ... */
K
Karel Zak 已提交
1341 1342 1343
            return ret;

        if (ctl->timing)
K
Karel Zak 已提交
1344
            vshPrint(ctl, "\n(Time: %.3f ms)\n\n",
1345 1346
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
1347
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
 * Command string parsing
 * ---------------
 */
#define VSH_TK_ERROR    -1
#define VSH_TK_NONE    0
#define VSH_TK_OPTION    1
#define VSH_TK_DATA    2
#define VSH_TK_END    3

1363 1364 1365
static int
vshCommandGetToken(vshControl * ctl, char *str, char **end, char **res)
{
K
Karel Zak 已提交
1366 1367 1368 1369 1370
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
1371

K
Karel Zak 已提交
1372
    *end = NULL;
1373 1374

    while (p && *p && isblank((unsigned char) *p))
K
Karel Zak 已提交
1375
        p++;
1376 1377

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
1378
        return VSH_TK_END;
1379 1380
    if (*p == ';') {
        *end = ++p;             /* = \0 or begi of next command */
K
Karel Zak 已提交
1381 1382
        return VSH_TK_END;
    }
1383
    while (*p) {
K
Karel Zak 已提交
1384
        /* end of token is blank space or ';' */
1385
        if ((quote == FALSE && isblank((unsigned char) *p)) || *p == ';')
K
Karel Zak 已提交
1386
            break;
1387

1388
        /* end of option name could be '=' */
1389 1390
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
1391 1392
            break;
        }
1393 1394 1395 1396

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
                && isalnum((unsigned char) *(p + 2))) {
K
Karel Zak 已提交
1397
                tk = VSH_TK_OPTION;
1398
                p += 2;
K
Karel Zak 已提交
1399 1400
            } else {
                tk = VSH_TK_DATA;
1401 1402
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
1403 1404 1405 1406 1407
                    p++;
                } else {
                    quote = FALSE;
                }
            }
1408 1409
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
1410 1411
            quote = FALSE;
            p++;
1412
            break;              /* end of "..." token */
K
Karel Zak 已提交
1413 1414 1415 1416 1417 1418 1419 1420
        }
        p++;
        sz++;
    }
    if (quote) {
        vshError(ctl, FALSE, "missing \"");
        return VSH_TK_ERROR;
    }
1421
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
1422
        return VSH_TK_END;
1423
    if (sz == 0)
K
Karel Zak 已提交
1424
        return VSH_TK_END;
1425

1426
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
1427
    memcpy(*res, tkstr, sz);
1428
    *(*res + sz) = '\0';
K
Karel Zak 已提交
1429 1430 1431 1432 1433 1434

    *end = p;
    return tk;
}

static int
1435 1436
vshCommandParse(vshControl * ctl, char *cmdstr)
{
K
Karel Zak 已提交
1437 1438 1439 1440
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1441

K
Karel Zak 已提交
1442 1443 1444 1445
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1446 1447

    if (cmdstr == NULL || *cmdstr == '\0')
K
Karel Zak 已提交
1448
        return FALSE;
1449

K
Karel Zak 已提交
1450
    str = cmdstr;
1451
    while (str && *str) {
K
Karel Zak 已提交
1452 1453 1454
        vshCmdOpt *last = NULL;
        vshCmdDef *cmd = NULL;
        int tk = VSH_TK_NONE;
1455
        int data_ct = 0;
1456

K
Karel Zak 已提交
1457
        first = NULL;
1458 1459

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
1460 1461
            char *end = NULL;
            vshCmdOptDef *opt = NULL;
1462

K
Karel Zak 已提交
1463
            tkdata = NULL;
1464

K
Karel Zak 已提交
1465 1466
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
1467

K
Karel Zak 已提交
1468
            str = end;
1469 1470

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
1471
                break;
1472
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1473
                goto syntaxError;
1474 1475

            if (cmd == NULL) {
K
Karel Zak 已提交
1476
                /* first token must be command name */
1477 1478 1479 1480
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
                             "unexpected token (command name): '%s'",
                             tkdata);
K
Karel Zak 已提交
1481 1482 1483
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
1484 1485
                    vshError(ctl, FALSE, "unknown command: '%s'", tkdata);
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1486 1487
                }
                free(tkdata);
1488
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
1489 1490
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
1491 1492
                             "command '%s' doesn't support option --%s",
                             cmd->name, tkdata);
K
Karel Zak 已提交
1493 1494
                    goto syntaxError;
                }
1495
                free(tkdata);   /* option name */
K
Karel Zak 已提交
1496 1497 1498 1499 1500
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
1501 1502
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1503
                        goto syntaxError;
1504
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
1505
                        vshError(ctl, FALSE,
1506 1507 1508 1509
                                 "expected syntax: --%s <%s>",
                                 opt->name,
                                 opt->type ==
                                 VSH_OT_INT ? "number" : "string");
K
Karel Zak 已提交
1510 1511 1512
                        goto syntaxError;
                    }
                }
1513
            } else if (tk == VSH_TK_DATA) {
1514
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
1515
                    vshError(ctl, FALSE, "unexpected data '%s'", tkdata);
K
Karel Zak 已提交
1516 1517 1518 1519 1520
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
1521
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
1522

K
Karel Zak 已提交
1523 1524 1525 1526
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
1527

K
Karel Zak 已提交
1528 1529 1530 1531 1532
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
1533

K
Karel Zak 已提交
1534
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
1535 1536 1537 1538
                         cmd->name,
                         opt->name,
                         tk == VSH_TK_OPTION ? "OPTION" : "DATA",
                         arg->data);
K
Karel Zak 已提交
1539 1540 1541 1542
            }
            if (!str)
                break;
        }
1543

K
Karel Zak 已提交
1544 1545
        /* commad parsed -- allocate new struct for the command */
        if (cmd) {
1546
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
1547

K
Karel Zak 已提交
1548 1549 1550 1551
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

1552 1553
            if (!vshCommandCheckOpts(ctl, c))
                goto syntaxError;
1554

K
Karel Zak 已提交
1555 1556 1557 1558 1559 1560 1561
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
1562

K
Karel Zak 已提交
1563 1564
    return TRUE;

1565
  syntaxError:
K
Karel Zak 已提交
1566 1567 1568 1569 1570 1571
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
    if (tkdata)
        free(tkdata);
1572
    return FALSE;
K
Karel Zak 已提交
1573 1574 1575 1576 1577 1578 1579
}


/* ---------------
 * Misc utils  
 * ---------------
 */
K
Karel Zak 已提交
1580
static const char *
1581 1582
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
1583 1584
    switch (state) {
        case VIR_DOMAIN_RUNNING:
1585
            return "running ";
K
Karel Zak 已提交
1586 1587 1588 1589 1590 1591 1592 1593
        case VIR_DOMAIN_BLOCKED:
            return "blocked ";
        case VIR_DOMAIN_PAUSED:
            return "paused ";
        case VIR_DOMAIN_SHUTDOWN:
            return "in shutdown";
        case VIR_DOMAIN_SHUTOFF:
            return "shut off";
K
Karel Zak 已提交
1594 1595
        case VIR_DOMAIN_CRASHED:
            return "crashed";
K
Karel Zak 已提交
1596
        default:
1597
            return "no state";  /* = dom0 state */
K
Karel Zak 已提交
1598 1599 1600 1601 1602
    }
    return NULL;
}

static int
1603 1604
vshConnectionUsability(vshControl * ctl, virConnectPtr conn, int showerror)
{
K
Karel Zak 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    /* TODO: use something like virConnectionState() to 
     *       check usability of the connection 
     */
    if (!conn) {
        if (showerror)
            vshError(ctl, FALSE, "no valid connection.");
        return FALSE;
    }
    return TRUE;
}

K
Karel Zak 已提交
1616 1617
static void
vshDebug(vshControl * ctl, int level, const char *format, ...)
1618
{
K
Karel Zak 已提交
1619 1620 1621 1622 1623 1624 1625 1626
    va_list ap;

    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
1627 1628 1629
}

static void
K
Karel Zak 已提交
1630
vshPrintExtra(vshControl * ctl, const char *format, ...)
1631
{
K
Karel Zak 已提交
1632
    va_list ap;
1633

K
Karel Zak 已提交
1634
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
1635
        return;
1636

K
Karel Zak 已提交
1637
    va_start(ap, format);
1638
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
1639 1640 1641
    va_end(ap);
}

K
Karel Zak 已提交
1642

K
Karel Zak 已提交
1643
static void
1644 1645
vshError(vshControl * ctl, int doexit, const char *format, ...)
{
K
Karel Zak 已提交
1646
    va_list ap;
1647

K
Karel Zak 已提交
1648 1649 1650 1651
    if (doexit)
        fprintf(stderr, "%s: error: ", progname);
    else
        fputs("error: ", stderr);
1652

K
Karel Zak 已提交
1653 1654 1655 1656 1657
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
1658

K
Karel Zak 已提交
1659
    if (doexit) {
1660 1661
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
1662 1663 1664 1665
        exit(EXIT_FAILURE);
    }
}

1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
static void *
_vshMalloc(vshControl * ctl, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = malloc(size)))
        return x;
    vshError(ctl, TRUE, "%s: %d: failed to allocate %d bytes\n", 
                filename, line, (int) size);
    return NULL;
}

static void *
_vshCalloc(vshControl * ctl, size_t nmemb, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = calloc(nmemb, size)))
        return x;
    vshError(ctl, TRUE, "%s: %d: failed to allocate %d bytes\n", 
                filename, line, (int) (size*nmemb));
    return NULL;
}

static char *
_vshStrdup(vshControl * ctl, const char *s, const char *filename, int line)
{
    char *x;

    if ((x = strdup(s)))
        return x;
    vshError(ctl, TRUE, "%s: %d: failed to allocate %d bytes\n", 
                filename, line, strlen(s));
    return NULL;
}

K
Karel Zak 已提交
1702 1703 1704 1705
/*
 * Initialize vistsh
 */
static int
1706 1707
vshInit(vshControl * ctl)
{
K
Karel Zak 已提交
1708 1709 1710 1711
    if (ctl->conn)
        return FALSE;

    ctl->uid = getuid();
1712

1713 1714
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
1715

K
Karel Zak 已提交
1716 1717 1718 1719 1720
    /* basic connection to hypervisor */
    if (ctl->uid == 0)
        ctl->conn = virConnectOpen(NULL);
    else
        ctl->conn = virConnectOpenReadOnly(NULL);
1721

K
Karel Zak 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
    if (!ctl->conn)
        vshError(ctl, TRUE, "failed to connect to the hypervisor");

    return TRUE;
}

/* -----------------
 * Readline stuff
 * -----------------
 */

/* 
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
 * (i.e. STATE == 0), then we start at the top of the list. 
 */
static char *
1739 1740
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
1741
    static int list_index, len;
K
Karel Zak 已提交
1742
    const char *name;
K
Karel Zak 已提交
1743 1744 1745 1746 1747 1748 1749

    /* If this is a new word to complete, initialize now.  This
     * includes saving the length of TEXT for efficiency, and
     * initializing the index variable to 0. 
     */
    if (!state) {
        list_index = 0;
1750
        len = strlen(text);
K
Karel Zak 已提交
1751 1752 1753 1754 1755
    }

    /* Return the next name which partially matches from the
     * command list. 
     */
K
Karel Zak 已提交
1756
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
1757
        list_index++;
1758
        if (strncmp(name, text, len) == 0)
1759
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
1760 1761 1762 1763 1764 1765 1766
    }

    /* If no names matched, then return NULL. */
    return NULL;
}

static char *
1767 1768
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
1769 1770
    static int list_index, len;
    static vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
1771
    const char *name;
K
Karel Zak 已提交
1772 1773 1774 1775 1776 1777 1778 1779 1780

    if (!state) {
        /* determine command name */
        char *p;
        char *cmdname;

        if (!(p = strchr(rl_line_buffer, ' ')))
            return NULL;

1781
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
1782
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
1783 1784 1785

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
1786
        len = strlen(text);
K
Karel Zak 已提交
1787 1788 1789 1790 1791
        free(cmdname);
    }

    if (!cmd)
        return NULL;
1792

K
Karel Zak 已提交
1793
    while ((name = cmd->opts[list_index].name)) {
K
Karel Zak 已提交
1794 1795
        vshCmdOptDef *opt = &cmd->opts[list_index];
        char *res;
1796

K
Karel Zak 已提交
1797
        list_index++;
1798

K
Karel Zak 已提交
1799
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
1800 1801
            /* ignore non --option */
            continue;
1802

K
Karel Zak 已提交
1803
        if (len > 2) {
1804
            if (strncmp(name, text + 2, len - 2))
K
Karel Zak 已提交
1805 1806
                continue;
        }
1807
        res = vshMalloc(NULL, strlen(name) + 3);
K
Karel Zak 已提交
1808 1809 1810 1811 1812 1813 1814 1815 1816
        sprintf(res, "--%s", name);
        return res;
    }

    /* If no names matched, then return NULL. */
    return NULL;
}

static char **
1817 1818 1819
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
1820 1821
    char **matches = (char **) NULL;

1822
    if (start == 0)
K
Karel Zak 已提交
1823
        /* command name generator */
1824
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
1825 1826
    else
        /* commands options */
1827
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
1828 1829 1830 1831 1832
    return matches;
}


static void
1833 1834
vshReadlineInit(void)
{
K
Karel Zak 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
    /* Allow conditional parsing of the ~/.inputrc file. */
    rl_readline_name = "virsh";

    /* Tell the completer that we want a crack first. */
    rl_attempted_completion_function = vshReadlineCompletion;
}

/*
 * Deinitliaze virsh
 */
static int
1846 1847
vshDeinit(vshControl * ctl)
{
K
Karel Zak 已提交
1848
    if (ctl->conn) {
1849 1850 1851 1852
        if (virConnectClose(ctl->conn) != 0) {
            ctl->conn = NULL;   /* prevent recursive call from vshError() */
            vshError(ctl, TRUE,
                     "failed to disconnect from the hypervisor");
K
Karel Zak 已提交
1853 1854 1855 1856
        }
    }
    return TRUE;
}
1857

K
Karel Zak 已提交
1858 1859 1860 1861
/*
 * Print usage
 */
static void
1862 1863
vshUsage(vshControl * ctl, const char *cmdname)
{
K
Karel Zak 已提交
1864
    vshCmdDef *cmd;
1865

K
Karel Zak 已提交
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
    /* global help */
    if (!cmdname) {
        fprintf(stdout, "\n%s [options] [commands]\n\n"
                "  options:\n"
                "    -d | --debug <num>      debug level [0-5]\n"
                "    -h | --help             this help\n"
                "    -q | --quiet            quiet mode\n"
                "    -t | --timing           print timing information\n"
                "    -v | --version          program version\n\n"
                "  commands (non interactive mode):\n", progname);
1876 1877 1878 1879 1880 1881 1882 1883

        for (cmd = commands; cmd->name; cmd++)
            fprintf(stdout,
                    "    %-15s %s\n", cmd->name, vshCmddefGetInfo(cmd,
                                                                  "help"));

        fprintf(stdout,
                "\n  (specify --help <command> for details about the command)\n\n");
K
Karel Zak 已提交
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
1895 1896
vshParseArgv(vshControl * ctl, int argc, char **argv)
{
K
Karel Zak 已提交
1897 1898
    char *last = NULL;
    int i, end = 0, help = 0;
1899
    int arg, idx = 0;
K
Karel Zak 已提交
1900
    struct option opt[] = {
1901 1902 1903 1904 1905
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
1906
        {0, 0, 0, 0}
1907 1908
    };

K
Karel Zak 已提交
1909 1910

    if (argc < 2)
K
Karel Zak 已提交
1911
        return TRUE;
1912

1913
    /* look for begin of the command, for example:
K
Karel Zak 已提交
1914 1915 1916 1917
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
1918
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
1919 1920
        if (*argv[i] != '-') {
            int valid = FALSE;
1921

K
Karel Zak 已提交
1922 1923 1924 1925
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
1926 1927 1928

                for (o = opt; o->name; o++) {
                    if (sz == 2 && *(last + 1) == o->val)
K
Karel Zak 已提交
1929 1930
                        /* valid virsh short option */
                        valid = TRUE;
1931
                    else if (sz > 2 && strcmp(o->name, last + 2) == 0)
K
Karel Zak 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
                        /* valid virsh long option */
                        valid = TRUE;
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
    end = end ? : argc;
1944

K
Karel Zak 已提交
1945
    /* standard (non-command) options */
1946 1947
    while ((arg = getopt_long(end, argv, "d:hqtv", opt, &idx)) != -1) {
        switch (arg) {
K
Karel Zak 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
            case 'd':
                ctl->debug = atoi(optarg);
                break;
            case 'h':
                help = 1;
                break;
            case 'q':
                ctl->quiet = TRUE;
                break;
            case 't':
                ctl->timing = TRUE;
                break;
            case 'v':
                fprintf(stdout, "%s\n", VERSION);
                exit(EXIT_SUCCESS);
            default:
1964 1965
                vshError(ctl, TRUE,
                  "unsupported option '-%c'. See --help.", arg);
K
Karel Zak 已提交
1966 1967 1968 1969 1970 1971 1972 1973
                break;
        }
    }

    if (help) {
        /* global or command specific help */
        vshUsage(ctl, argc > end ? argv[end] : NULL);
        exit(EXIT_SUCCESS);
1974 1975
    }

K
Karel Zak 已提交
1976 1977 1978
    if (argc > end) {
        /* parse command */
        char *cmdstr;
1979 1980
        int sz = 0, ret;

K
Karel Zak 已提交
1981 1982
        ctl->imode = FALSE;

1983 1984 1985
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

1986
        cmdstr = vshCalloc(ctl, sz + 1, 1);
1987 1988

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
1989 1990 1991 1992
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
1993
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
1994
        ret = vshCommandParse(ctl, cmdstr);
1995

K
Karel Zak 已提交
1996 1997 1998 1999 2000 2001
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

2002 2003 2004 2005
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
K
Karel Zak 已提交
2006 2007
    int ret = TRUE;

2008
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
2009 2010 2011
        progname = argv[0];
    else
        progname++;
2012

K
Karel Zak 已提交
2013
    memset(ctl, 0, sizeof(vshControl));
2014
    ctl->imode = TRUE;          /* default is interactive mode */
K
Karel Zak 已提交
2015 2016 2017

    if (!vshParseArgv(ctl, argc, argv))
        exit(EXIT_FAILURE);
2018

K
Karel Zak 已提交
2019 2020
    if (!vshInit(ctl))
        exit(EXIT_FAILURE);
2021

K
Karel Zak 已提交
2022
    if (!ctl->imode) {
2023
        ret = vshCommandRun(ctl, ctl->cmd);
2024
    } else {
K
Karel Zak 已提交
2025 2026
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
2027
            vshPrint(ctl,
2028 2029
                     "Welcome to %s, the virtualization interactive terminal.\n\n",
                     progname);
K
Karel Zak 已提交
2030
            vshPrint(ctl,
2031 2032
                     "Type:  'help' for help with commands\n"
                     "       'quit' to quit\n\n");
K
Karel Zak 已提交
2033
        }
K
Karel Zak 已提交
2034
        vshReadlineInit();
K
Karel Zak 已提交
2035
        do {
2036 2037 2038 2039
            ctl->cmdstr =
                readline(ctl->uid == 0 ? VSH_PROMPT_RW : VSH_PROMPT_RO);
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
2040 2041 2042 2043 2044 2045 2046
            if (*ctl->cmdstr) {
                add_history(ctl->cmdstr);
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
2047
        } while (ctl->imode);
K
Karel Zak 已提交
2048

2049 2050
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
2051
    }
2052

K
Karel Zak 已提交
2053 2054
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
2055
}
K
Karel Zak 已提交
2056 2057 2058 2059 2060 2061

/*
 * vim: set tabstop=4:
 * vim: set shiftwidth=4:
 * vim: set expandtab:
 */