virsh.c 60.2 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
 * Karel Zak <kzak@redhat.com>
K
Karel Zak 已提交
10 11
 * Daniel P. Berrange <berrange@redhat.com>
 *
K
Karel Zak 已提交
12 13
 *
 * $Id$
14 15
 */

16
#define _GNU_SOURCE             /* isblank() */
K
Karel Zak 已提交
17

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

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

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

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)

52 53 54 55
/*
 * The error handler for virtsh
 */
static void
56 57
virshErrorHandler(void *unused, virErrorPtr error)
{
58 59 60 61 62 63 64 65 66 67
    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 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81
/*
 * 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>
 *        
82 83 84
 *    keyword         =     [a-zA-Z]
 *    number          =     [0-9]+
 *    string          =     [^[:blank:]] | "[[:alnum:]]"$
K
Karel Zak 已提交
85 86 87 88 89
 *
 */

/*
 * vshCmdOptType - command option type 
90
 */
K
Karel Zak 已提交
91
typedef enum {
92 93 94 95 96
    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 已提交
97 98 99 100 101
} vshCmdOptType;

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

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

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

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

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

/*
 * vshCmdDef - command definition
 */
139 140 141 142 143
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 已提交
144 145 146 147 148 149
} vshCmdDef;

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

/*
 * vshControl
 */
typedef struct __vshControl {
K
Karel Zak 已提交
159
    char *name;                 /* connection name */
160 161 162 163 164 165 166 167
    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 已提交
168
} __vshControl;
169

170

K
Karel Zak 已提交
171 172
static vshCmdDef commands[];

173 174 175 176 177
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 已提交
178

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

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

185 186 187 188 189
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);
K
Karel Zak 已提交
190 191 192 193 194 195 196 197 198 199 200 201

#define VSH_DOMBYID     (1 << 1)
#define VSH_DOMBYUUID   (1 << 2)
#define VSH_DOMBYNAME   (1 << 3)

static virDomainPtr vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd,
                            const char *optname, char **name, int flag);

/* default is lookup by Id, Name and UUID */
#define vshCommandOptDomain(_ctl, _cmd, _optname, _name) \
                            vshCommandOptDomainBy(_ctl, _cmd, _optname, _name,\
                                        VSH_DOMBYID|VSH_DOMBYUUID|VSH_DOMBYNAME)
K
Karel Zak 已提交
202

K
Karel Zak 已提交
203 204
static void vshPrintExtra(vshControl * ctl, const char *format, ...);
static void vshDebug(vshControl * ctl, int level, const char *format, ...);
K
Karel Zak 已提交
205 206

/* XXX: add batch support */
K
Karel Zak 已提交
207
#define vshPrint(_ctl, ...)   fprintf(stdout, __VA_ARGS__)
K
Karel Zak 已提交
208

K
Karel Zak 已提交
209
static const char *vshDomainStateToString(int state);
210
static const char *vshDomainVcpuStateToString(int state);
211 212
static int vshConnectionUsability(vshControl * ctl, virConnectPtr conn,
                                  int showerror);
K
Karel Zak 已提交
213

214 215 216 217 218 219 220 221 222
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 已提交
223 224 225 226 227 228 229 230 231
/* ---------------
 * Commands
 * ---------------
 */

/*
 * "help" command 
 */
static vshCmdInfo info_help[] = {
232 233 234
    {"syntax", "help [<command>]"},
    {"help", "print help"},
    {"desc", "Prints global help or command specific help."},
235
    {"version", "Prints version information."},
236
    {NULL, NULL}
K
Karel Zak 已提交
237 238 239
};

static vshCmdOptDef opts_help[] = {
240 241
    {"command", VSH_OT_DATA, 0, "name of command"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
242 243 244
};

static int
245 246
cmdHelp(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
247
    const char *cmdname = vshCommandOptString(cmd, "command", NULL);
K
Karel Zak 已提交
248 249 250

    if (!cmdname) {
        vshCmdDef *def;
251

K
Karel Zak 已提交
252
        vshPrint(ctl, "Commands:\n\n");
253
        for (def = commands; def->name; def++)
K
Karel Zak 已提交
254
            vshPrint(ctl, "    %-15s %s\n", def->name,
255
                     vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
256 257 258 259 260 261 262 263 264
        return TRUE;
    }
    return vshCmddefHelp(ctl, cmdname, FALSE);
}

/*
 * "connect" command 
 */
static vshCmdInfo info_connect[] = {
K
Karel Zak 已提交
265
    {"syntax", "connect [name] [--readonly]"},
266 267 268 269
    {"help", "(re)connect to hypervisor"},
    {"desc",
     "Connect to local hypervisor. This is build-in command after shell start up."},
    {NULL, NULL}
K
Karel Zak 已提交
270 271 272
};

static vshCmdOptDef opts_connect[] = {
K
Karel Zak 已提交
273
    {"name",     VSH_OT_DATA, 0, "optional argument currently unused (or used for tests only)"},
274 275
    {"readonly", VSH_OT_BOOL, 0, "read-only connection"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
276 277 278
};

static int
279 280
cmdConnect(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
281
    int ro = vshCommandOptBool(cmd, "readonly");
K
Karel Zak 已提交
282
    
K
Karel Zak 已提交
283
    if (ctl->conn) {
284 285 286
        if (virConnectClose(ctl->conn) != 0) {
            vshError(ctl, FALSE,
                     "failed to disconnect from the hypervisor");
K
Karel Zak 已提交
287 288 289 290
            return FALSE;
        }
        ctl->conn = NULL;
    }
K
Karel Zak 已提交
291 292 293 294 295
    
    if (ctl->name)
        free(ctl->name);
    ctl->name = vshCommandOptString(cmd, "name", NULL);

K
Karel Zak 已提交
296
    if (!ro)
K
Karel Zak 已提交
297
        ctl->conn = virConnectOpen(ctl->name);
K
Karel Zak 已提交
298
    else
K
Karel Zak 已提交
299
        ctl->conn = virConnectOpenReadOnly(ctl->name);
K
Karel Zak 已提交
300 301 302

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

K
Karel Zak 已提交
304 305 306 307 308 309 310
    return ctl->conn ? TRUE : FALSE;
}

/*
 * "list" command
 */
static vshCmdInfo info_list[] = {
311 312 313 314
    {"syntax", "list"},
    {"help", "list domains"},
    {"desc", "Returns list of domains."},
    {NULL, NULL}
K
Karel Zak 已提交
315 316 317 318 319
};



static int
320 321
cmdList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
322 323 324 325
    int *ids, maxid, i;

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

K
Karel Zak 已提交
327 328 329 330 331 332
    maxid = virConnectNumOfDomains(ctl->conn);
    if (maxid <= 0) {
        /* strange, there should be at least dom0... */
        vshError(ctl, FALSE, "failed to list active domains.");
        return FALSE;
    }
333 334
    ids = vshMalloc(ctl, sizeof(int) * maxid);

335 336 337 338
    if (virConnectListDomains(ctl->conn, &ids[0], maxid) < 0) {
        vshError(ctl, FALSE, "failed to list active domains.");
        return FALSE;
    }
339

K
Karel Zak 已提交
340 341
    vshPrintExtra(ctl, "%3s %-20s %s\n", "Id", "Name", "State");
    vshPrintExtra(ctl, "----------------------------------\n");
342 343

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
344 345 346
        int ret;
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
347 348

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
349 350 351
        if (!dom)
            continue;
        ret = virDomainGetInfo(dom, &info);
352

K
Karel Zak 已提交
353
        vshPrint(ctl, "%3d %-20s %s\n",
354 355 356 357
                 virDomainGetID(dom),
                 virDomainGetName(dom),
                 ret <
                 0 ? "no state" : vshDomainStateToString(info.state));
358
        virDomainFree(dom);
K
Karel Zak 已提交
359 360 361 362 363 364
    }
    free(ids);
    return TRUE;
}

/*
K
Karel Zak 已提交
365
 * "domstate" command
K
Karel Zak 已提交
366
 */
K
Karel Zak 已提交
367 368
static vshCmdInfo info_domstate[] = {
    {"syntax", "domstate <domain>"},
369 370 371
    {"help", "domain state"},
    {"desc", "Returns state about a running domain."},
    {NULL, NULL}
K
Karel Zak 已提交
372 373
};

K
Karel Zak 已提交
374
static vshCmdOptDef opts_domstate[] = {
K
Karel Zak 已提交
375
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
376
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
377 378 379
};

static int
K
Karel Zak 已提交
380
cmdDomstate(vshControl * ctl, vshCmd * cmd)
381
{
382
    virDomainInfo info;
K
Karel Zak 已提交
383
    virDomainPtr dom;
K
Karel Zak 已提交
384
    int ret = TRUE;
385

K
Karel Zak 已提交
386 387
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
388

K
Karel Zak 已提交
389
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
390
        return FALSE;
391 392

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
393
        vshPrint(ctl, "%s\n",
394
                 vshDomainStateToString(info.state));
K
Karel Zak 已提交
395 396
    else
        ret = FALSE;
397

398 399 400 401 402 403 404 405
    virDomainFree(dom);
    return ret;
}

/*
 * "suspend" command
 */
static vshCmdInfo info_suspend[] = {
406 407 408 409
    {"syntax", "suspend <domain>"},
    {"help", "suspend a domain"},
    {"desc", "Suspend a running domain."},
    {NULL, NULL}
410 411 412
};

static vshCmdOptDef opts_suspend[] = {
K
Karel Zak 已提交
413
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
414
    {NULL, 0, 0, NULL}
415 416 417
};

static int
418 419
cmdSuspend(vshControl * ctl, vshCmd * cmd)
{
420
    virDomainPtr dom;
K
Karel Zak 已提交
421 422
    char *name;
    int ret = TRUE;
423

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

K
Karel Zak 已提交
427
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
428
        return FALSE;
429 430

    if (virDomainSuspend(dom) == 0) {
K
Karel Zak 已提交
431
        vshPrint(ctl, "Domain %s suspended\n", name);
432 433 434 435
    } else {
        vshError(ctl, FALSE, "Failed to suspend domain\n");
        ret = FALSE;
    }
436

437 438 439 440
    virDomainFree(dom);
    return ret;
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
/*
 * "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 已提交
487
        vshPrint(ctl, "Domain %s created from %s\n", 
488 489 490 491 492 493 494 495
                 virDomainGetName(dom), from);
    } else {
        vshError(ctl, FALSE, "Failed to create domain\n");
        ret = FALSE;
    }
    return ret;
}

496 497 498 499
/*
 * "save" command
 */
static vshCmdInfo info_save[] = {
500 501 502 503
    {"syntax", "save <domain> <file>"},
    {"help", "save a domain state to a file"},
    {"desc", "Save a running domain."},
    {NULL, NULL}
504 505 506
};

static vshCmdOptDef opts_save[] = {
K
Karel Zak 已提交
507
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
508 509
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, "where to save the data"},
    {NULL, 0, 0, NULL}
510 511 512
};

static int
513 514
cmdSave(vshControl * ctl, vshCmd * cmd)
{
515 516 517 518
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
519

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

523
    if (!(to = vshCommandOptString(cmd, "file", NULL)))
524
        return FALSE;
525

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

    if (virDomainSave(dom, to) == 0) {
K
Karel Zak 已提交
530
        vshPrint(ctl, "Domain %s saved\n", name);
531 532 533 534
    } else {
        vshError(ctl, FALSE, "Failed to save domain\n");
        ret = FALSE;
    }
535

536 537 538 539 540 541 542 543
    virDomainFree(dom);
    return ret;
}

/*
 * "restore" command
 */
static vshCmdInfo info_restore[] = {
544 545 546 547
    {"syntax", "restore a domain from <file>"},
    {"help", "restore a domain from a saved state in a file"},
    {"desc", "Restore a domain."},
    {NULL, NULL}
548 549 550
};

static vshCmdOptDef opts_restore[] = {
551 552
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, "the state to restore"},
    {NULL, 0, 0, NULL}
553 554 555
};

static int
556 557
cmdRestore(vshControl * ctl, vshCmd * cmd)
{
558 559 560
    char *from;
    int found;
    int ret = TRUE;
561

562 563 564 565 566 567
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
K
Karel Zak 已提交
570
        vshPrint(ctl, "Domain restored from %s\n", from);
571 572 573 574 575 576 577
    } else {
        vshError(ctl, FALSE, "Failed to restore domain\n");
        ret = FALSE;
    }
    return ret;
}

578 579 580 581
/*
 * "resume" command
 */
static vshCmdInfo info_resume[] = {
582 583 584 585
    {"syntax", "resume <domain>"},
    {"help", "resume a domain"},
    {"desc", "Resume a previously suspended domain."},
    {NULL, NULL}
586 587 588
};

static vshCmdOptDef opts_resume[] = {
K
Karel Zak 已提交
589
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
590
    {NULL, 0, 0, NULL}
591 592 593
};

static int
594 595
cmdResume(vshControl * ctl, vshCmd * cmd)
{
596
    virDomainPtr dom;
K
Karel Zak 已提交
597 598
    int ret = TRUE;
    char *name;
599

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

K
Karel Zak 已提交
603
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
604
        return FALSE;
605 606

    if (virDomainResume(dom) == 0) {
K
Karel Zak 已提交
607
        vshPrint(ctl, "Domain %s resumed\n", name);
608 609 610 611
    } else {
        vshError(ctl, FALSE, "Failed to resume domain\n");
        ret = FALSE;
    }
612

613 614 615 616
    virDomainFree(dom);
    return ret;
}

617 618 619 620
/*
 * "shutdown" command
 */
static vshCmdInfo info_shutdown[] = {
621 622 623 624
    {"syntax", "shutdown <domain>"},
    {"help", "gracefully shutdown a domain"},
    {"desc", "Run shutdown in the targetted domain"},
    {NULL, NULL}
625 626 627
};

static vshCmdOptDef opts_shutdown[] = {
K
Karel Zak 已提交
628
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
629
    {NULL, 0, 0, NULL}
630 631 632
};

static int
633 634
cmdShutdown(vshControl * ctl, vshCmd * cmd)
{
635 636 637
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
638

639 640 641 642 643
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainShutdown(dom) == 0) {
K
Karel Zak 已提交
646
        vshPrint(ctl, "Domain %s is being shutdown\n", name);
647 648 649 650
    } else {
        vshError(ctl, FALSE, "Failed to shutdown domain\n");
        ret = FALSE;
    }
651

652 653 654 655
    virDomainFree(dom);
    return ret;
}

656 657 658 659 660 661 662 663 664 665 666
/*
 * "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[] = {
K
Karel Zak 已提交
667
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    {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 已提交
685
        vshPrint(ctl, "Domain %s is being rebooted\n", name);
686 687 688 689 690 691 692 693 694
    } else {
        vshError(ctl, FALSE, "Failed to reboot domain\n");
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

695 696 697 698
/*
 * "destroy" command
 */
static vshCmdInfo info_destroy[] = {
699 700 701 702
    {"syntax", "destroy <domain>"},
    {"help", "destroy a domain"},
    {"desc", "Destroy a given domain."},
    {NULL, NULL}
703 704 705
};

static vshCmdOptDef opts_destroy[] = {
K
Karel Zak 已提交
706
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
707
    {NULL, 0, 0, NULL}
708 709 710
};

static int
711 712
cmdDestroy(vshControl * ctl, vshCmd * cmd)
{
713
    virDomainPtr dom;
K
Karel Zak 已提交
714 715
    int ret = TRUE;
    char *name;
716

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

K
Karel Zak 已提交
720
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
721
        return FALSE;
722 723

    if (virDomainDestroy(dom) == 0) {
K
Karel Zak 已提交
724
        vshPrint(ctl, "Domain %s destroyed\n", name);
725 726 727 728 729
    } else {
        vshError(ctl, FALSE, "Failed to destroy domain\n");
        ret = FALSE;
        virDomainFree(dom);
    }
730

K
Karel Zak 已提交
731 732 733 734
    return ret;
}

/*
735
 * "dominfo" command
K
Karel Zak 已提交
736
 */
737 738
static vshCmdInfo info_dominfo[] = {
    {"syntax", "dominfo <domain>"},
739 740 741
    {"help", "domain information"},
    {"desc", "Returns basic information about the domain."},
    {NULL, NULL}
K
Karel Zak 已提交
742 743
};

744
static vshCmdOptDef opts_dominfo[] = {
K
Karel Zak 已提交
745
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
746
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
747 748 749
};

static int
750
cmdDominfo(vshControl * ctl, vshCmd * cmd)
751
{
K
Karel Zak 已提交
752 753
    virDomainInfo info;
    virDomainPtr dom;
K
Karel Zak 已提交
754
    int ret = TRUE;
K
Karel Zak 已提交
755
    char *str, uuid[37];
756

K
Karel Zak 已提交
757 758 759
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
760
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
761
        return FALSE;
762

K
Karel Zak 已提交
763 764 765 766
    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);
767 768

    if ((str = virDomainGetOSType(dom))) {
K
Karel Zak 已提交
769
        vshPrint(ctl, "%-15s %s\n", "OS Type:", str);
770 771 772 773
        free(str);
    }

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

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

        if (info.cpuTime != 0) {
780
	    double cpuUsed = info.cpuTime;
781

782
            cpuUsed /= 1000000000.0;
783

784
            vshPrint(ctl, "%-15s %.1lfs\n", "CPU time:", cpuUsed);
K
Karel Zak 已提交
785
        }
786

K
Karel Zak 已提交
787
        vshPrint(ctl, "%-15s %lu kB\n", "Max memory:",
788
                 info.maxMem);
K
Karel Zak 已提交
789
        vshPrint(ctl, "%-15s %lu kB\n", "Used memory:",
790 791
                 info.memory);

K
Karel Zak 已提交
792 793 794
    } else {
        ret = FALSE;
    }
795

796
    virDomainFree(dom);
K
Karel Zak 已提交
797 798 799
    return ret;
}

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
/*
 * "vcpuinfo" command
 */
static vshCmdInfo info_vcpuinfo[] = {
    {"syntax", "vcpuinfo <domain>"},
    {"help", "domain vcpu information"},
    {"desc", "Returns basic information about the domain virtual CPUs."},
    {NULL, NULL}
};

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

static int
cmdVcpuinfo(vshControl * ctl, vshCmd * cmd)
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    virVcpuInfoPtr cpuinfo;
    unsigned char *cpumap;
    int ncpus;
    size_t cpumaplen;
    int ret = TRUE;

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

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

    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
	return FALSE;
    }

    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
        return FALSE;
    }

    cpuinfo = malloc(sizeof(virVcpuInfo)*info.nrVirtCpu);
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
    cpumap = malloc(info.nrVirtCpu * cpumaplen);

    if ((ncpus = virDomainGetVcpus(dom, 
				   cpuinfo, info.nrVirtCpu,
				   cpumap, cpumaplen)) >= 0) {
        int n;
	for (n = 0 ; n < ncpus ; n++) {
	    unsigned int m;
	    vshPrint(ctl, "%-15s %d\n", "VCPU:", n);
	    vshPrint(ctl, "%-15s %d\n", "CPU:", cpuinfo[n].cpu);
	    vshPrint(ctl, "%-15s %s\n", "State:",
		     vshDomainVcpuStateToString(cpuinfo[n].state));
	    if (cpuinfo[n].cpuTime != 0) {
	        double cpuUsed = cpuinfo[n].cpuTime;
		
		cpuUsed /= 1000000000.0;
		
		vshPrint(ctl, "%-15s %.1lfs\n", "CPU time:", cpuUsed);
	    }
	    vshPrint(ctl, "%-15s ", "CPU Affinity:");
	    for (m = 0 ; m < VIR_NODEINFO_MAXCPUS(nodeinfo) ; m++) {
	        vshPrint(ctl, "%c", VIR_CPU_USABLE(cpumap, cpumaplen, n, m) ? 'y' : '-');
	    }
	    vshPrint(ctl, "\n");
	    if (n < (ncpus - 1)) {
	        vshPrint(ctl, "\n");
	    }
	}
    } else {
        ret = FALSE;
    }

    free(cpumap);
    free(cpuinfo);
    virDomainFree(dom);
    return ret;
}

/*
 * "vcpupin" command
 */
static vshCmdInfo info_vcpupin[] = {
    {"syntax", "vcpupin <domain>"},
    {"help", "control domain vcpu affinity"},
    {"desc", "Pin domain VCPUs to host physical CPUs"},
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpupin[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
    {"vcpu", VSH_OT_DATA, VSH_OFLAG_REQ, "vcpu number"},
    {"cpulist", VSH_OT_DATA, VSH_OFLAG_REQ, "host cpu number(s) (comma separated)"},
    {NULL, 0, 0, NULL}
};

static int
cmdVcpupin(vshControl * ctl, vshCmd * cmd)
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    int vcpu;
    char *cpulist;
    int ret = TRUE;
    int vcpufound = 0;
    unsigned char *cpumap;
    int cpumaplen;

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

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

    vcpu = vshCommandOptInt(cmd, "vcpu", &vcpufound);
    if (!vcpufound) {
        virDomainFree(dom);
        return FALSE;
    }

    if (!(cpulist = vshCommandOptString(cmd, "cpulist", NULL))) {
        virDomainFree(dom);
        return FALSE;
    }
      
    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
        return FALSE;
    }

    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
        return FALSE;
    }

    if (vcpu >= info.nrVirtCpu) {
        virDomainFree(dom);
        return FALSE;
    }

    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
    cpumap = malloc(cpumaplen);
    memset(cpumap, 0, cpumaplen);

    do {
        unsigned int cpu = atoi(cpulist);

        if (cpu < VIR_NODEINFO_MAXCPUS(nodeinfo)) {
            VIR_USE_CPU(cpumap, cpu);
        }
        cpulist = index(cpulist, ',');
        if (cpulist)
            cpulist++;
    } while (cpulist);

    if (virDomainPinVcpu(dom, vcpu, cpumap, cpumaplen) != 0) {
        ret = FALSE;
    }

    free(cpumap);
    virDomainFree(dom);
    return ret;
}

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
/*
 * "setvcpus" command
 */
static vshCmdInfo info_setvcpus[] = {
    {"syntax", "setvcpus <domain> <count>"},
    {"help", "change number of virtual CPUs"},
    {"desc", "Change the number of virtual CPUs active in the guest domain"},
    {NULL, NULL}
};

static vshCmdOptDef opts_setvcpus[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
    {"count", VSH_OT_DATA, VSH_OFLAG_REQ, "number of virtual CPUs"},
    {NULL, 0, 0, NULL}
};

static int
cmdSetvcpus(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    int count;
    int ret = TRUE;

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

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

    count = vshCommandOptInt(cmd, "count", &count);
    if (!count) {
        virDomainFree(dom);
        return FALSE;
    }

    if (virDomainSetVcpus(dom, count) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmemory" command
 */
static vshCmdInfo info_setmem[] = {
    {"syntax", "setmem <domain> <bytes>"},
    {"help", "change memory allocation"},
    {"desc", "Change the current memory allocation in the guest domain"},
    {NULL, NULL}
};

static vshCmdOptDef opts_setmem[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
    {"bytes", VSH_OT_DATA, VSH_OFLAG_REQ, "number of bytes of memory"},
    {NULL, 0, 0, NULL}
};

static int
cmdSetmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    int bytes;
    int ret = TRUE;

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

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

    bytes = vshCommandOptInt(cmd, "bytes", &bytes);
    if (!bytes) {
        virDomainFree(dom);
        return FALSE;
    }

    if (virDomainSetMemory(dom, bytes) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmaxmem" command
 */
static vshCmdInfo info_setmaxmem[] = {
    {"syntax", "setmaxmem <domain> <bytes>"},
    {"help", "change maximum memory limit"},
    {"desc", "Change the maximum memory allocation limit in the guest domain"},
    {NULL, NULL}
};

static vshCmdOptDef opts_setmaxmem[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id or uuid"},
    {"bytes", VSH_OT_DATA, VSH_OFLAG_REQ, "maxmimum memory limit in bytes"},
    {NULL, 0, 0, NULL}
};

static int
cmdSetmaxmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    int bytes;
    int ret = TRUE;

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

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

    bytes = vshCommandOptInt(cmd, "bytes", &bytes);
    if (!bytes) {
        virDomainFree(dom);
        return FALSE;
    }

    if (virDomainSetMaxMemory(dom, bytes) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
/*
 * "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 已提交
1120 1121 1122 1123 1124 1125 1126 1127
    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);
1128 1129 1130 1131
        
    return TRUE;
}

1132 1133 1134 1135
/*
 * "dumpxml" command
 */
static vshCmdInfo info_dumpxml[] = {
1136 1137
    {"syntax", "dumpxml <name>"},
    {"help", "domain information in XML"},
1138
    {"desc", "Ouput the domain information as an XML dump to stdout"},
1139
    {NULL, NULL}
1140 1141 1142
};

static vshCmdOptDef opts_dumpxml[] = {
K
Karel Zak 已提交
1143
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name, id, uuid"},
1144
    {NULL, 0, 0, NULL}
1145 1146 1147
};

static int
1148 1149
cmdDumpXML(vshControl * ctl, vshCmd * cmd)
{
1150
    virDomainPtr dom;
K
Karel Zak 已提交
1151
    int ret = TRUE;
1152
    char *dump;
1153

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

K
Karel Zak 已提交
1157
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
1158
        return FALSE;
1159

1160 1161 1162 1163 1164 1165 1166
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
1167

1168 1169 1170 1171
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
1172
/*
K
Karel Zak 已提交
1173
 * "domname" command
K
Karel Zak 已提交
1174
 */
K
Karel Zak 已提交
1175
static vshCmdInfo info_domname[] = {
K
Karel Zak 已提交
1176 1177
    {"syntax", "domname <domain>"},
    {"help", "convert a domain Id or UUID to domain name"},
1178
    {NULL, NULL}
K
Karel Zak 已提交
1179 1180
};

K
Karel Zak 已提交
1181
static vshCmdOptDef opts_domname[] = {
K
Karel Zak 已提交
1182
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain id or uuid"},
1183
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1184 1185 1186
};

static int
K
Karel Zak 已提交
1187
cmdDomname(vshControl * ctl, vshCmd * cmd)
1188
{
K
Karel Zak 已提交
1189 1190 1191 1192
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
K
Karel Zak 已提交
1193 1194
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL, 
                                    VSH_DOMBYID|VSH_DOMBYUUID)))
K
Karel Zak 已提交
1195
        return FALSE;
1196

K
Karel Zak 已提交
1197 1198
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
K
Karel Zak 已提交
1199 1200 1201 1202
    return TRUE;
}

/*
K
Karel Zak 已提交
1203
 * "domid" command
K
Karel Zak 已提交
1204
 */
K
Karel Zak 已提交
1205
static vshCmdInfo info_domid[] = {
K
Karel Zak 已提交
1206 1207
    {"syntax", "domid <domain>"},
    {"help", "convert a domain name or UUID to domain Id"},
1208
    {NULL, NULL}
K
Karel Zak 已提交
1209 1210
};

K
Karel Zak 已提交
1211
static vshCmdOptDef opts_domid[] = {
K
Karel Zak 已提交
1212
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, "domain name or uuid"},
1213
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1214 1215 1216
};

static int
K
Karel Zak 已提交
1217
cmdDomid(vshControl * ctl, vshCmd * cmd)
1218
{
1219
    virDomainPtr dom;
K
Karel Zak 已提交
1220 1221 1222

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
K
Karel Zak 已提交
1223 1224
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL, 
                                    VSH_DOMBYNAME|VSH_DOMBYUUID)))
K
Karel Zak 已提交
1225
        return FALSE;
K
Karel Zak 已提交
1226 1227 1228 1229 1230
    
    vshPrint(ctl, "%d\n", virDomainGetID(dom));
    virDomainFree(dom);
    return TRUE;
}
1231

K
Karel Zak 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
/*
 * "domuuid" command
 */
static vshCmdInfo info_domuuid[] = {
    {"syntax", "domuuid <domain>"},
    {"help", "convert a domain name or id to domain UUID"},
    {NULL, NULL}
};

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

static int
cmdDomuuid(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char uuid[37];

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
K
Karel Zak 已提交
1253
        return FALSE;
K
Karel Zak 已提交
1254 1255 1256 1257 1258 1259 1260 1261 1262
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL, 
                                    VSH_DOMBYNAME|VSH_DOMBYID)))
        return FALSE;
    
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
        vshError(ctl, FALSE, "failed to get domain UUID");
    
K
Karel Zak 已提交
1263 1264 1265
    return TRUE;
}

K
Karel Zak 已提交
1266

1267 1268 1269 1270
/*
 * "version" command
 */
static vshCmdInfo info_version[] = {
1271 1272
    {"syntax", "version"},
    {"help", "show versions"},
1273
    {"desc", "Display the version information available"},
1274
    {NULL, NULL}
1275 1276 1277 1278
};


static int
1279 1280
cmdVersion(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
1281 1282
    unsigned long hvVersion;
    const char *hvType;
1283 1284 1285 1286 1287 1288 1289
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
1290 1291 1292

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

1294 1295
    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
K
Karel Zak 已提交
1296
        vshError(ctl, FALSE, "failed to get hypervisor type\n");
1297 1298 1299
        return FALSE;
    }

1300 1301 1302 1303 1304
    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
K
Karel Zak 已提交
1305
    vshPrint(ctl, "Compiled against library: libvir %d.%d.%d\n",
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
             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 已提交
1317
    vshPrint(ctl, "Using library: libvir %d.%d.%d\n",
1318
             major, minor, rel);
1319

1320 1321 1322 1323
    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
K
Karel Zak 已提交
1324
    vshPrint(ctl, "Using API: %s %d.%d.%d\n", hvType,
1325 1326
             major, minor, rel);

1327
    ret = virConnectGetVersion(ctl->conn, &hvVersion);
1328 1329
    if (ret < 0) {
        vshError(ctl, FALSE, "failed to get the hypervisor version");
1330 1331 1332
        return FALSE;
    }
    if (hvVersion == 0) {
K
Karel Zak 已提交
1333
        vshPrint(ctl,
1334
                 "cannot extract running %s hypervisor version\n", hvType);
1335
    } else {
1336
        major = hvVersion / 1000000;
1337
        hvVersion %= 1000000;
1338 1339
        minor = hvVersion / 1000;
        rel = hvVersion % 1000;
1340

K
Karel Zak 已提交
1341
        vshPrint(ctl, "Running hypervisor: %s %d.%d.%d\n",
1342
                 hvType, major, minor, rel);
1343 1344 1345 1346
    }
    return TRUE;
}

K
Karel Zak 已提交
1347 1348 1349 1350
/*
 * "quit" command
 */
static vshCmdInfo info_quit[] = {
1351 1352 1353
    {"syntax", "quit"},
    {"help", "quit this interactive terminal"},
    {NULL, NULL}
K
Karel Zak 已提交
1354 1355 1356
};

static int
1357 1358
cmdQuit(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
1359 1360 1361 1362 1363 1364 1365 1366
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
static vshCmdDef commands[] = {
1367
    {"connect", cmdConnect, opts_connect, info_connect},
1368
    {"create", cmdCreate, opts_create, info_create},
K
Karel Zak 已提交
1369 1370
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
    {"domid", cmdDomid, opts_domid, info_domid},
K
Karel Zak 已提交
1371
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid},
1372
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
1373 1374
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
1375
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
K
Karel Zak 已提交
1376 1377 1378 1379 1380 1381
    {"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},
1382 1383 1384
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
1385 1386 1387
    {"setmem", cmdSetmem, opts_setmem, info_setmem},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus},
K
Karel Zak 已提交
1388
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
1389 1390
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
1391 1392
    {"version", cmdVersion, NULL, info_version},
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
1393 1394 1395 1396 1397 1398
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
1399
static const char *
1400 1401
vshCmddefGetInfo(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1402
    vshCmdInfo *info;
1403

K
Karel Zak 已提交
1404
    for (info = cmd->info; info && info->name; info++) {
1405
        if (strcmp(info->name, name) == 0)
K
Karel Zak 已提交
1406 1407 1408 1409 1410 1411
            return info->data;
    }
    return NULL;
}

static vshCmdOptDef *
1412 1413
vshCmddefGetOption(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1414
    vshCmdOptDef *opt;
1415

K
Karel Zak 已提交
1416
    for (opt = cmd->opts; opt && opt->name; opt++)
1417
        if (strcmp(opt->name, name) == 0)
K
Karel Zak 已提交
1418 1419 1420 1421 1422
            return opt;
    return NULL;
}

static vshCmdOptDef *
1423 1424
vshCmddefGetData(vshCmdDef * cmd, int data_ct)
{
K
Karel Zak 已提交
1425 1426
    vshCmdOptDef *opt;

1427
    for (opt = cmd->opts; opt && opt->name; opt++) {
1428 1429
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
1430 1431 1432 1433 1434
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
1435 1436 1437
    return NULL;
}

1438 1439 1440
/*
 * Checks for required options
 */
1441 1442
static int
vshCommandCheckOpts(vshControl * ctl, vshCmd * cmd)
1443 1444 1445
{
    vshCmdDef *def = cmd->def;
    vshCmdOptDef *d;
1446
    int err = 0;
1447 1448 1449 1450

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

            while (o && ok == 0) {
1454
                if (o->def == d)
1455
                    ok = 1;
1456 1457 1458
                o = o->next;
            }
            if (!ok) {
1459 1460 1461 1462 1463
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
                         "command '%s' requires <%s> option" :
                         "command '%s' requires --%s option",
                         def->name, d->name);
1464 1465
                err = 1;
            }
1466

1467 1468 1469 1470 1471
        }
    }
    return !err;
}

K
Karel Zak 已提交
1472
static vshCmdDef *
1473 1474
vshCmddefSearch(const char *cmdname)
{
K
Karel Zak 已提交
1475
    vshCmdDef *c;
1476

K
Karel Zak 已提交
1477
    for (c = commands; c->name; c++)
1478
        if (strcmp(c->name, cmdname) == 0)
K
Karel Zak 已提交
1479 1480 1481 1482 1483
            return c;
    return NULL;
}

static int
1484 1485
vshCmddefHelp(vshControl * ctl, const char *cmdname, int withprog)
{
K
Karel Zak 已提交
1486
    vshCmdDef *def = vshCmddefSearch(cmdname);
1487

K
Karel Zak 已提交
1488
    if (!def) {
1489 1490 1491
        vshError(ctl, FALSE, "command '%s' doesn't exist", cmdname);
        return FALSE;
    } else {
K
Karel Zak 已提交
1492
        vshCmdOptDef *opt;
K
Karel Zak 已提交
1493 1494 1495
        const char *desc = vshCmddefGetInfo(def, "desc");
        const char *help = vshCmddefGetInfo(def, "help");
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
1496 1497

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

K
Karel Zak 已提交
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
        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);
1513
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
1514
                char buf[256];
1515 1516

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
1517
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1518
                else if (opt->type == VSH_OT_INT)
K
Karel Zak 已提交
1519
                    snprintf(buf, sizeof(buf), "--%s <number>", opt->name);
1520
                else if (opt->type == VSH_OT_STRING)
K
Karel Zak 已提交
1521
                    snprintf(buf, sizeof(buf), "--%s <string>", opt->name);
1522
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
1523
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
1524

K
Karel Zak 已提交
1525
                fprintf(stdout, "    %-15s  %s\n", buf, opt->help);
1526
            }
K
Karel Zak 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1537 1538 1539
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1540 1541
    vshCmdOpt *a = arg;

1542
    while (a) {
K
Karel Zak 已提交
1543
        vshCmdOpt *tmp = a;
1544

K
Karel Zak 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553
        a = a->next;

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

static void
1554 1555
vshCommandFree(vshCmd * cmd)
{
K
Karel Zak 已提交
1556 1557
    vshCmd *c = cmd;

1558
    while (c) {
K
Karel Zak 已提交
1559
        vshCmd *tmp = c;
1560

K
Karel Zak 已提交
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
1573 1574
vshCommandOpt(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
1575
    vshCmdOpt *opt = cmd->opts;
1576 1577 1578

    while (opt) {
        if (opt->def && strcmp(opt->def->name, name) == 0)
K
Karel Zak 已提交
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
1589 1590
vshCommandOptInt(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
1591 1592
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
    int res = 0;
1593

K
Karel Zak 已提交
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    if (arg)
        res = atoi(arg->data);
    if (found)
        *found = arg ? TRUE : FALSE;
    return res;
}

/*
 * Returns option as STRING
 */
static char *
1605 1606
vshCommandOptString(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
1607
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
1608

K
Karel Zak 已提交
1609 1610
    if (found)
        *found = arg ? TRUE : FALSE;
1611 1612

    return arg && arg->data && *arg->data ? arg->data : NULL;
K
Karel Zak 已提交
1613 1614 1615 1616 1617 1618
}

/*
 * Returns TRUE/FALSE if the option exists
 */
static int
1619 1620
vshCommandOptBool(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
1621 1622 1623
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

1624

K
Karel Zak 已提交
1625
static virDomainPtr
K
Karel Zak 已提交
1626 1627
vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd, const char *optname,
                    char **name, int flag)
1628
{
K
Karel Zak 已提交
1629 1630 1631
    virDomainPtr dom = NULL;
    char *n, *end = NULL;
    int id;
1632

K
Karel Zak 已提交
1633 1634
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
        vshError(ctl, FALSE, "undefined domain name or id");
1635
        return NULL;
K
Karel Zak 已提交
1636
    }
1637

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

K
Karel Zak 已提交
1641 1642
    if (name)
        *name = n;
1643

K
Karel Zak 已提交
1644
    /* try it by ID */
K
Karel Zak 已提交
1645 1646 1647 1648 1649 1650 1651
    if (flag & VSH_DOMBYID) {
        id = (int) strtol(n, &end, 10);
        if (id >= 0 && end && *end == '\0') {
            vshDebug(ctl, 5, "%s: <%s> seems like domain ID\n",
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
1652
    }
K
Karel Zak 已提交
1653
    /* try it by UUID */
K
Karel Zak 已提交
1654
    if (dom==NULL && (flag & VSH_DOMBYUUID) && strlen(n)==36) {
K
Karel Zak 已提交
1655 1656
        vshDebug(ctl, 5, "%s: <%s> tring as domain UUID\n",
                cmd->def->name, optname);
K
Karel Zak 已提交
1657
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
1658
    }
K
Karel Zak 已提交
1659
    /* try it by NAME */
K
Karel Zak 已提交
1660
    if (dom==NULL && (flag & VSH_DOMBYNAME)) {
K
Karel Zak 已提交
1661
        vshDebug(ctl, 5, "%s: <%s> tring as domain NAME\n",
1662
                 cmd->def->name, optname);
K
Karel Zak 已提交
1663
        dom = virDomainLookupByName(ctl->conn, n);
1664
    }
K
Karel Zak 已提交
1665

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

K
Karel Zak 已提交
1669 1670 1671
    return dom;
}

K
Karel Zak 已提交
1672 1673 1674 1675
/*
 * Executes command(s) and returns return code from last command
 */
static int
1676 1677
vshCommandRun(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
1678
    int ret = TRUE;
1679 1680

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

K
Karel Zak 已提交
1683 1684
        if (ctl->timing)
            GETTIMEOFDAY(&before);
1685

K
Karel Zak 已提交
1686 1687 1688 1689
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
1690 1691

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

        if (ctl->timing)
K
Karel Zak 已提交
1695
            vshPrint(ctl, "\n(Time: %.3f ms)\n\n",
1696 1697
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
1698
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
        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

1714 1715 1716
static int
vshCommandGetToken(vshControl * ctl, char *str, char **end, char **res)
{
K
Karel Zak 已提交
1717 1718 1719 1720 1721
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
1722

K
Karel Zak 已提交
1723
    *end = NULL;
1724 1725

    while (p && *p && isblank((unsigned char) *p))
K
Karel Zak 已提交
1726
        p++;
1727 1728

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
1729
        return VSH_TK_END;
1730 1731
    if (*p == ';') {
        *end = ++p;             /* = \0 or begi of next command */
K
Karel Zak 已提交
1732 1733
        return VSH_TK_END;
    }
1734
    while (*p) {
K
Karel Zak 已提交
1735
        /* end of token is blank space or ';' */
1736
        if ((quote == FALSE && isblank((unsigned char) *p)) || *p == ';')
K
Karel Zak 已提交
1737
            break;
1738

1739
        /* end of option name could be '=' */
1740 1741
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
1742 1743
            break;
        }
1744 1745 1746 1747

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
                && isalnum((unsigned char) *(p + 2))) {
K
Karel Zak 已提交
1748
                tk = VSH_TK_OPTION;
1749
                p += 2;
K
Karel Zak 已提交
1750 1751
            } else {
                tk = VSH_TK_DATA;
1752 1753
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
1754 1755 1756 1757 1758
                    p++;
                } else {
                    quote = FALSE;
                }
            }
1759 1760
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
1761 1762
            quote = FALSE;
            p++;
1763
            break;              /* end of "..." token */
K
Karel Zak 已提交
1764 1765 1766 1767 1768 1769 1770 1771
        }
        p++;
        sz++;
    }
    if (quote) {
        vshError(ctl, FALSE, "missing \"");
        return VSH_TK_ERROR;
    }
1772
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
1773
        return VSH_TK_END;
1774
    if (sz == 0)
K
Karel Zak 已提交
1775
        return VSH_TK_END;
1776

1777
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
1778
    memcpy(*res, tkstr, sz);
1779
    *(*res + sz) = '\0';
K
Karel Zak 已提交
1780 1781 1782 1783 1784 1785

    *end = p;
    return tk;
}

static int
1786 1787
vshCommandParse(vshControl * ctl, char *cmdstr)
{
K
Karel Zak 已提交
1788 1789 1790 1791
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1792

K
Karel Zak 已提交
1793 1794 1795 1796
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1797 1798

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

K
Karel Zak 已提交
1801
    str = cmdstr;
1802
    while (str && *str) {
K
Karel Zak 已提交
1803 1804 1805
        vshCmdOpt *last = NULL;
        vshCmdDef *cmd = NULL;
        int tk = VSH_TK_NONE;
1806
        int data_ct = 0;
1807

K
Karel Zak 已提交
1808
        first = NULL;
1809 1810

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
1811 1812
            char *end = NULL;
            vshCmdOptDef *opt = NULL;
1813

K
Karel Zak 已提交
1814
            tkdata = NULL;
1815

K
Karel Zak 已提交
1816 1817
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
1818

K
Karel Zak 已提交
1819
            str = end;
1820 1821

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
1822
                break;
1823
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1824
                goto syntaxError;
1825 1826

            if (cmd == NULL) {
K
Karel Zak 已提交
1827
                /* first token must be command name */
1828 1829 1830 1831
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
                             "unexpected token (command name): '%s'",
                             tkdata);
K
Karel Zak 已提交
1832 1833 1834
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
1835 1836
                    vshError(ctl, FALSE, "unknown command: '%s'", tkdata);
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1837 1838
                }
                free(tkdata);
1839
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
1840 1841
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
1842 1843
                             "command '%s' doesn't support option --%s",
                             cmd->name, tkdata);
K
Karel Zak 已提交
1844 1845
                    goto syntaxError;
                }
1846
                free(tkdata);   /* option name */
K
Karel Zak 已提交
1847 1848 1849 1850 1851
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
1852 1853
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1854
                        goto syntaxError;
1855
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
1856
                        vshError(ctl, FALSE,
1857 1858 1859 1860
                                 "expected syntax: --%s <%s>",
                                 opt->name,
                                 opt->type ==
                                 VSH_OT_INT ? "number" : "string");
K
Karel Zak 已提交
1861 1862 1863
                        goto syntaxError;
                    }
                }
1864
            } else if (tk == VSH_TK_DATA) {
1865
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
1866
                    vshError(ctl, FALSE, "unexpected data '%s'", tkdata);
K
Karel Zak 已提交
1867 1868 1869 1870 1871
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
1872
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
1873

K
Karel Zak 已提交
1874 1875 1876 1877
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
1878

K
Karel Zak 已提交
1879 1880 1881 1882 1883
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
1884

K
Karel Zak 已提交
1885
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
1886 1887 1888 1889
                         cmd->name,
                         opt->name,
                         tk == VSH_TK_OPTION ? "OPTION" : "DATA",
                         arg->data);
K
Karel Zak 已提交
1890 1891 1892 1893
            }
            if (!str)
                break;
        }
1894

K
Karel Zak 已提交
1895 1896
        /* commad parsed -- allocate new struct for the command */
        if (cmd) {
1897
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
1898

K
Karel Zak 已提交
1899 1900 1901 1902
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

1903 1904
            if (!vshCommandCheckOpts(ctl, c))
                goto syntaxError;
1905

K
Karel Zak 已提交
1906 1907 1908 1909 1910 1911 1912
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
1913

K
Karel Zak 已提交
1914 1915
    return TRUE;

1916
  syntaxError:
K
Karel Zak 已提交
1917 1918 1919 1920 1921 1922
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
    if (tkdata)
        free(tkdata);
1923
    return FALSE;
K
Karel Zak 已提交
1924 1925 1926 1927 1928 1929 1930
}


/* ---------------
 * Misc utils  
 * ---------------
 */
K
Karel Zak 已提交
1931
static const char *
1932 1933
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
1934 1935
    switch (state) {
        case VIR_DOMAIN_RUNNING:
1936
            return "running ";
K
Karel Zak 已提交
1937 1938 1939 1940 1941 1942 1943 1944
        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 已提交
1945 1946
        case VIR_DOMAIN_CRASHED:
            return "crashed";
K
Karel Zak 已提交
1947
        default:
1948
            return "no state";  /* = dom0 state */
K
Karel Zak 已提交
1949 1950 1951 1952
    }
    return NULL;
}

1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
        case VIR_VCPU_OFFLINE:
            return "offline";
        case VIR_VCPU_BLOCKED:
            return "blocked";
        case VIR_VCPU_RUNNING:
            return "running";
        default:
            return "no state";
    }
    return NULL;
}

K
Karel Zak 已提交
1969
static int
1970 1971
vshConnectionUsability(vshControl * ctl, virConnectPtr conn, int showerror)
{
K
Karel Zak 已提交
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
    /* 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 已提交
1983 1984
static void
vshDebug(vshControl * ctl, int level, const char *format, ...)
1985
{
K
Karel Zak 已提交
1986 1987 1988 1989 1990 1991 1992 1993
    va_list ap;

    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
1994 1995 1996
}

static void
K
Karel Zak 已提交
1997
vshPrintExtra(vshControl * ctl, const char *format, ...)
1998
{
K
Karel Zak 已提交
1999
    va_list ap;
2000

K
Karel Zak 已提交
2001
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
2002
        return;
2003

K
Karel Zak 已提交
2004
    va_start(ap, format);
2005
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
2006 2007 2008
    va_end(ap);
}

K
Karel Zak 已提交
2009

K
Karel Zak 已提交
2010
static void
2011 2012
vshError(vshControl * ctl, int doexit, const char *format, ...)
{
K
Karel Zak 已提交
2013
    va_list ap;
2014

K
Karel Zak 已提交
2015 2016 2017 2018
    if (doexit)
        fprintf(stderr, "%s: error: ", progname);
    else
        fputs("error: ", stderr);
2019

K
Karel Zak 已提交
2020 2021 2022 2023 2024
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
2025

K
Karel Zak 已提交
2026
    if (doexit) {
2027 2028
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
2029 2030 2031 2032
        exit(EXIT_FAILURE);
    }
}

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
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 已提交
2069 2070 2071 2072
/*
 * Initialize vistsh
 */
static int
2073 2074
vshInit(vshControl * ctl)
{
K
Karel Zak 已提交
2075 2076 2077 2078
    if (ctl->conn)
        return FALSE;

    ctl->uid = getuid();
2079

2080 2081
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2082

2083 2084 2085 2086
    /* basic connection to hypervisor, for Xen connections unless
       we're root open a read only connections. Allow 'test' HV
       to be RW all the time though */
    if (ctl->uid == 0 || (ctl->name && !strncmp(ctl->name, "test", 4)))
K
Karel Zak 已提交
2087
        ctl->conn = virConnectOpen(ctl->name);
K
Karel Zak 已提交
2088
    else
K
Karel Zak 已提交
2089
        ctl->conn = virConnectOpenReadOnly(ctl->name);
2090

K
Karel Zak 已提交
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
    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 *
2108 2109
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2110
    static int list_index, len;
K
Karel Zak 已提交
2111
    const char *name;
K
Karel Zak 已提交
2112 2113 2114 2115 2116 2117 2118

    /* 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;
2119
        len = strlen(text);
K
Karel Zak 已提交
2120 2121 2122 2123 2124
    }

    /* Return the next name which partially matches from the
     * command list. 
     */
K
Karel Zak 已提交
2125
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
2126
        list_index++;
2127
        if (strncmp(name, text, len) == 0)
2128
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
2129 2130 2131 2132 2133 2134 2135
    }

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

static char *
2136 2137
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2138 2139
    static int list_index, len;
    static vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2140
    const char *name;
K
Karel Zak 已提交
2141 2142 2143 2144 2145 2146 2147 2148 2149

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

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

2150
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2151
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2152 2153 2154

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2155
        len = strlen(text);
K
Karel Zak 已提交
2156 2157 2158 2159 2160
        free(cmdname);
    }

    if (!cmd)
        return NULL;
2161

K
Karel Zak 已提交
2162
    while ((name = cmd->opts[list_index].name)) {
K
Karel Zak 已提交
2163 2164
        vshCmdOptDef *opt = &cmd->opts[list_index];
        char *res;
2165

K
Karel Zak 已提交
2166
        list_index++;
2167

K
Karel Zak 已提交
2168
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
2169 2170
            /* ignore non --option */
            continue;
2171

K
Karel Zak 已提交
2172
        if (len > 2) {
2173
            if (strncmp(name, text + 2, len - 2))
K
Karel Zak 已提交
2174 2175
                continue;
        }
2176
        res = vshMalloc(NULL, strlen(name) + 3);
K
Karel Zak 已提交
2177 2178 2179 2180 2181 2182 2183 2184 2185
        sprintf(res, "--%s", name);
        return res;
    }

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

static char **
2186 2187 2188
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2189 2190
    char **matches = (char **) NULL;

2191
    if (start == 0)
K
Karel Zak 已提交
2192
        /* command name generator */
2193
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2194 2195
    else
        /* commands options */
2196
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2197 2198 2199 2200 2201
    return matches;
}


static void
2202 2203
vshReadlineInit(void)
{
K
Karel Zak 已提交
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
    /* 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
2215 2216
vshDeinit(vshControl * ctl)
{
K
Karel Zak 已提交
2217
    if (ctl->conn) {
2218 2219 2220 2221
        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 已提交
2222 2223 2224 2225
        }
    }
    return TRUE;
}
2226

K
Karel Zak 已提交
2227 2228 2229 2230
/*
 * Print usage
 */
static void
2231 2232
vshUsage(vshControl * ctl, const char *cmdname)
{
K
Karel Zak 已提交
2233
    vshCmdDef *cmd;
2234

K
Karel Zak 已提交
2235 2236 2237 2238
    /* global help */
    if (!cmdname) {
        fprintf(stdout, "\n%s [options] [commands]\n\n"
                "  options:\n"
K
Karel Zak 已提交
2239
                "    -c | --connect <name>   optional argument currently unused (or used for tests only)\n"
K
Karel Zak 已提交
2240 2241 2242 2243 2244 2245
                "    -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);
2246 2247 2248 2249 2250 2251 2252 2253

        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 已提交
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
2265 2266
vshParseArgv(vshControl * ctl, int argc, char **argv)
{
K
Karel Zak 已提交
2267 2268
    char *last = NULL;
    int i, end = 0, help = 0;
2269
    int arg, idx = 0;
K
Karel Zak 已提交
2270
    struct option opt[] = {
2271 2272 2273 2274 2275
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
2276
        {"connect", 1, 0, 'c'},
K
Karel Zak 已提交
2277
        {0, 0, 0, 0}
2278 2279
    };

K
Karel Zak 已提交
2280 2281

    if (argc < 2)
K
Karel Zak 已提交
2282
        return TRUE;
2283

2284
    /* look for begin of the command, for example:
K
Karel Zak 已提交
2285 2286 2287 2288
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
2289
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
2290 2291
        if (*argv[i] != '-') {
            int valid = FALSE;
2292

K
Karel Zak 已提交
2293 2294 2295 2296
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
2297 2298 2299

                for (o = opt; o->name; o++) {
                    if (sz == 2 && *(last + 1) == o->val)
K
Karel Zak 已提交
2300 2301
                        /* valid virsh short option */
                        valid = TRUE;
2302
                    else if (sz > 2 && strcmp(o->name, last + 2) == 0)
K
Karel Zak 已提交
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
                        /* valid virsh long option */
                        valid = TRUE;
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
    end = end ? : argc;
2315

K
Karel Zak 已提交
2316
    /* standard (non-command) options */
2317 2318
    while ((arg = getopt_long(end, argv, "d:hqtv", opt, &idx)) != -1) {
        switch (arg) {
K
Karel Zak 已提交
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
            case 'd':
                ctl->debug = atoi(optarg);
                break;
            case 'h':
                help = 1;
                break;
            case 'q':
                ctl->quiet = TRUE;
                break;
            case 't':
                ctl->timing = TRUE;
                break;
K
Karel Zak 已提交
2331 2332 2333
            case 'c':
                ctl->name = vshStrdup(ctl, optarg);
                break;
K
Karel Zak 已提交
2334 2335 2336 2337
            case 'v':
                fprintf(stdout, "%s\n", VERSION);
                exit(EXIT_SUCCESS);
            default:
2338 2339
                vshError(ctl, TRUE,
                  "unsupported option '-%c'. See --help.", arg);
K
Karel Zak 已提交
2340 2341 2342 2343 2344 2345 2346 2347
                break;
        }
    }

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

K
Karel Zak 已提交
2350 2351 2352
    if (argc > end) {
        /* parse command */
        char *cmdstr;
2353 2354
        int sz = 0, ret;

K
Karel Zak 已提交
2355 2356
        ctl->imode = FALSE;

2357 2358 2359
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

2360
        cmdstr = vshCalloc(ctl, sz + 1, 1);
2361 2362

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
2363 2364 2365 2366
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
2367
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
2368
        ret = vshCommandParse(ctl, cmdstr);
2369

K
Karel Zak 已提交
2370 2371 2372 2373 2374 2375
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

2376 2377 2378 2379
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
K
Karel Zak 已提交
2380 2381
    int ret = TRUE;

2382
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
2383 2384 2385
        progname = argv[0];
    else
        progname++;
2386

K
Karel Zak 已提交
2387
    memset(ctl, 0, sizeof(vshControl));
2388
    ctl->imode = TRUE;          /* default is interactive mode */
K
Karel Zak 已提交
2389 2390 2391

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

K
Karel Zak 已提交
2393 2394
    if (!vshInit(ctl))
        exit(EXIT_FAILURE);
2395

K
Karel Zak 已提交
2396
    if (!ctl->imode) {
2397
        ret = vshCommandRun(ctl, ctl->cmd);
2398
    } else {
K
Karel Zak 已提交
2399 2400
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
2401
            vshPrint(ctl,
2402 2403
                     "Welcome to %s, the virtualization interactive terminal.\n\n",
                     progname);
K
Karel Zak 已提交
2404
            vshPrint(ctl,
2405 2406
                     "Type:  'help' for help with commands\n"
                     "       'quit' to quit\n\n");
K
Karel Zak 已提交
2407
        }
K
Karel Zak 已提交
2408
        vshReadlineInit();
K
Karel Zak 已提交
2409
        do {
2410 2411 2412 2413
            ctl->cmdstr =
                readline(ctl->uid == 0 ? VSH_PROMPT_RW : VSH_PROMPT_RO);
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
2414 2415 2416 2417 2418 2419 2420
            if (*ctl->cmdstr) {
                add_history(ctl->cmdstr);
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
2421
        } while (ctl->imode);
K
Karel Zak 已提交
2422

2423 2424
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
2425
    }
2426

K
Karel Zak 已提交
2427 2428
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
2429
}
K
Karel Zak 已提交
2430 2431 2432 2433 2434 2435

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