virsh.c 69.1 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>
30
#include <locale.h>
K
Karel Zak 已提交
31 32 33 34 35

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

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

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)

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

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

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

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

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

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

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

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

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

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

171

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

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

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

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

186 187 188 189 190
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 已提交
191 192 193 194 195 196 197 198 199 200 201 202

#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 已提交
203

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

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

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

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

/*
 * "help" command 
 */
static vshCmdInfo info_help[] = {
233
    {"syntax", "help [<command>]"},
234 235 236
    {"help", gettext_noop("print help")},
    {"desc", gettext_noop("Prints global help or command specific help.")},

237
    {NULL, NULL}
K
Karel Zak 已提交
238 239 240
};

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

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

    if (!cmdname) {
        vshCmdDef *def;
252

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

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

static vshCmdOptDef opts_connect[] = {
274 275
    {"name",     VSH_OT_DATA, 0, gettext_noop("hypervisor connection URI")},
    {"readonly", VSH_OT_BOOL, 0, gettext_noop("read-only connection")},
276
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
277 278 279
};

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

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

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

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

/*
 * "list" command
 */
static vshCmdInfo info_list[] = {
312
    {"syntax", "list [--inactive | --all]"},
313 314
    {"help", gettext_noop("list domains")},
    {"desc", gettext_noop("Returns list of domains.")},
315
    {NULL, NULL}
K
Karel Zak 已提交
316 317
};

318
static vshCmdOptDef opts_list[] = {
319 320
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive domains")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active domains")},
321 322 323
    {NULL, 0, 0, NULL}
};

K
Karel Zak 已提交
324

325 326 327 328 329 330 331 332 333 334 335 336 337
static int domidsorter(const void *a, const void *b) {
  const int *ia = (const int *)a;
  const int *ib = (const int *)b;

  if (*ia > *ib)
    return 1;
  else if (*ia < *ib)
    return -1;
  return 0;
}
static int domnamesorter(const void *a, const void *b) {
  const char **sa = (const char**)a;
  const char **sb = (const char**)b;
K
Karel Zak 已提交
338

339 340
  return strcasecmp(*sa, *sb);
}
K
Karel Zak 已提交
341
static int
342 343
cmdList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
344 345 346 347 348 349 350
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int *ids = NULL, maxid = 0, i;
    const char **names = NULL;
    int maxname = 0;
    inactive |= all;
K
Karel Zak 已提交
351 352 353

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
354 355 356 357
    
    if (active) {
      maxid = virConnectNumOfDomains(ctl->conn);
      if (maxid < 0) {
358
        vshError(ctl, FALSE, _("Failed to list active domains"));
K
Karel Zak 已提交
359
        return FALSE;
360 361
      }
      if (maxid) {
362
        ids = vshMalloc(ctl, sizeof(int) * maxid);
363
	
364
        if ((maxid = virConnectListDomains(ctl->conn, &ids[0], maxid)) < 0) {
365
	  vshError(ctl, FALSE, _("Failed to list active domains"));
366 367
	  free(ids);
	  return FALSE;
368
        }
369 370
	
	qsort(&ids[0], maxid, sizeof(int), domidsorter);
371 372 373 374 375
      }
    }
    if (inactive) {
      maxname = virConnectNumOfDefinedDomains(ctl->conn);
      if (maxname < 0) {
376
        vshError(ctl, FALSE, _("Failed to list inactive domains"));
377 378 379 380 381
	if (ids)
	  free(ids);
        return FALSE;
      }
      if (maxname) {
382
        names = vshMalloc(ctl, sizeof(char *) * maxname);
383
	
384
        if ((maxname = virConnectListDefinedDomains(ctl->conn, names, maxname)) < 0) {
385
	  vshError(ctl, FALSE, _("Failed to list inactive domains"));
386 387 388 389 390
	  if (ids)
	    free(ids);
	  free(names);
	  return FALSE;
        }
391 392

	qsort(&names[0], maxname, sizeof(char*), domnamesorter);
393
      }
394
    }
395
    vshPrintExtra(ctl, "%3s %-20s %s\n", _("Id"), _("Name"), _("State"));
K
Karel Zak 已提交
396
    vshPrintExtra(ctl, "----------------------------------\n");
397 398

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
399 400 401
        int ret;
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
402 403

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
404 405 406
        if (!dom)
            continue;
        ret = virDomainGetInfo(dom, &info);
407

K
Karel Zak 已提交
408
        vshPrint(ctl, "%3d %-20s %s\n",
409 410 411
                 virDomainGetID(dom),
                 virDomainGetName(dom),
                 ret <
412
                 0 ? _("no state") : _N(vshDomainStateToString(info.state)));
413
        virDomainFree(dom);
K
Karel Zak 已提交
414
    }
415 416
    for (i = 0; i < maxname; i++) {
        int ret;
417
        unsigned int id;
418 419 420 421
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByName(ctl->conn, names[i]);

        /* this kind of work with domains is not atomic operation */
422 423
        if (!dom) {
	    free(names[i]);
424
            continue;
425
	}
426
        ret = virDomainGetInfo(dom, &info);
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
	id = virDomainGetID(dom);

	if (id == ((unsigned int)-1)) {
	  vshPrint(ctl, "%3s %-20s %s\n",
		   "-",
		   names[i],
		   ret <
		   0 ? "no state" : vshDomainStateToString(info.state));
	} else {
	  vshPrint(ctl, "%3d %-20s %s\n",
		   id,
		   names[i],
		   ret <
		   0 ? "no state" : vshDomainStateToString(info.state));
	}
442

443
        virDomainFree(dom);
444
	free(names[i]);
445
    }
446 447
    if (ids)
        free(ids);
448 449
    if (names)
        free(names);
K
Karel Zak 已提交
450 451 452 453
    return TRUE;
}

/*
K
Karel Zak 已提交
454
 * "domstate" command
K
Karel Zak 已提交
455
 */
K
Karel Zak 已提交
456 457
static vshCmdInfo info_domstate[] = {
    {"syntax", "domstate <domain>"},
458 459
    {"help", gettext_noop("domain state")},
    {"desc", gettext_noop("Returns state about a running domain.")},
460
    {NULL, NULL}
K
Karel Zak 已提交
461 462
};

K
Karel Zak 已提交
463
static vshCmdOptDef opts_domstate[] = {
464
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
465
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
466 467 468
};

static int
K
Karel Zak 已提交
469
cmdDomstate(vshControl * ctl, vshCmd * cmd)
470
{
471
    virDomainInfo info;
K
Karel Zak 已提交
472
    virDomainPtr dom;
K
Karel Zak 已提交
473
    int ret = TRUE;
474

K
Karel Zak 已提交
475 476
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
477

K
Karel Zak 已提交
478
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
479
        return FALSE;
480 481

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
482
        vshPrint(ctl, "%s\n",
483
                 _N(vshDomainStateToString(info.state)));
K
Karel Zak 已提交
484 485
    else
        ret = FALSE;
486

487 488 489 490 491 492 493 494
    virDomainFree(dom);
    return ret;
}

/*
 * "suspend" command
 */
static vshCmdInfo info_suspend[] = {
495
    {"syntax", "suspend <domain>"},
496 497
    {"help", gettext_noop("suspend a domain")},
    {"desc", gettext_noop("Suspend a running domain.")},
498
    {NULL, NULL}
499 500 501
};

static vshCmdOptDef opts_suspend[] = {
502
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
503
    {NULL, 0, 0, NULL}
504 505 506
};

static int
507 508
cmdSuspend(vshControl * ctl, vshCmd * cmd)
{
509
    virDomainPtr dom;
K
Karel Zak 已提交
510 511
    char *name;
    int ret = TRUE;
512

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

K
Karel Zak 已提交
516
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
517
        return FALSE;
518 519

    if (virDomainSuspend(dom) == 0) {
520
        vshPrint(ctl, _("Domain %s suspended\n"), name);
521
    } else {
522
        vshError(ctl, FALSE, _("Failed to suspend domain %s"), name);
523 524
        ret = FALSE;
    }
525

526 527 528 529
    virDomainFree(dom);
    return ret;
}

530 531 532 533 534
/*
 * "create" command
 */
static vshCmdInfo info_create[] = {
    {"syntax", "create a domain from an XML <file>"},
535 536
    {"help", gettext_noop("create a domain from an XML file")},
    {"desc", gettext_noop("Create a domain.")},
537 538 539 540
    {NULL, NULL}
};

static vshCmdOptDef opts_create[] = {
541
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file conatining an XML domain description")},
542 543 544 545 546 547 548 549 550 551
    {NULL, 0, 0, NULL}
};

static int
cmdCreate(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
552
    char buffer[BUFSIZ];
553 554 555 556 557 558 559 560 561 562 563
    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) {
564
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
565 566 567 568
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
569
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
570 571 572 573 574 575
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    dom = virDomainCreateLinux(ctl->conn, &buffer[0], 0);
    if (dom != NULL) {
576
        vshPrint(ctl, _("Domain %s created from %s\n"),
577 578
                 virDomainGetName(dom), from);
    } else {
579
        vshError(ctl, FALSE, _("Failed to create domain from %s"), from);
580 581 582 583 584
        ret = FALSE;
    }
    return ret;
}

585 586 587 588 589
/*
 * "define" command
 */
static vshCmdInfo info_define[] = {
    {"syntax", "define a domain from an XML <file>"},
590 591
    {"help", gettext_noop("define (but don't start) a domain from an XML file")},
    {"desc", gettext_noop("Define a domain.")},
592 593 594 595
    {NULL, NULL}
};

static vshCmdOptDef opts_define[] = {
596
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file conatining an XML domain description")},
597 598 599 600 601 602 603 604 605 606
    {NULL, 0, 0, NULL}
};

static int
cmdDefine(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
607
    char buffer[BUFSIZ];
608 609 610 611 612 613 614 615 616 617 618
    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) {
619
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
620 621 622 623
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
624
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
625 626 627 628 629 630
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    dom = virDomainDefineXML(ctl->conn, &buffer[0]);
    if (dom != NULL) {
631
        vshPrint(ctl, _("Domain %s defined from %s\n"),
632 633
                 virDomainGetName(dom), from);
    } else {
634
        vshError(ctl, FALSE, _("Failed to define domain from %s"), from);
635 636 637 638 639 640 641 642 643 644
        ret = FALSE;
    }
    return ret;
}

/*
 * "undefine" command
 */
static vshCmdInfo info_undefine[] = {
    {"syntax", "undefine <domain>"},
645 646
    {"help", gettext_noop("undefine an inactive domain")},
    {"desc", gettext_noop("Undefine the configuration for an inactive domain.")},
647 648 649 650
    {NULL, NULL}
};

static vshCmdOptDef opts_undefine[] = {
651
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    {NULL, 0, 0, NULL}
};

static int
cmdUndefine(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 (virDomainUndefine(dom) == 0) {
669
        vshPrint(ctl, _("Domain %s has been undefined\n"), name);
670
    } else {
671
        vshError(ctl, FALSE, _("Failed to undefine domain %s"), name);
672 673 674 675 676 677 678 679 680 681 682
        ret = FALSE;
    }

    return ret;
}


/*
 * "start" command
 */
static vshCmdInfo info_start[] = {
683
    {"syntax", "start <domain>"},
684 685
    {"help", gettext_noop("start a (previously defined) inactive domain")},
    {"desc", gettext_noop("Start a domain.")},
686 687 688 689
    {NULL, NULL}
};

static vshCmdOptDef opts_start[] = {
690
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive domain")},
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
    {NULL, 0, 0, NULL}
};

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

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

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

    dom = virDomainLookupByName(ctl->conn, name);
    if (!dom)
        return FALSE;

    if (virDomainGetID(dom) != (unsigned int)-1) {
714
        vshError(ctl, FALSE, _("Domain is already active"));
715 716 717 718
        return FALSE;
    }

    if (virDomainCreate(dom) == 0) {
719
        vshPrint(ctl, _("Domain %s started\n"),
720 721
                 name);
    } else {
722
      vshError(ctl, FALSE, _("Failed to start domain %s"), name);
723 724 725 726 727
        ret = FALSE;
    }
    return ret;
}

728 729 730 731
/*
 * "save" command
 */
static vshCmdInfo info_save[] = {
732
    {"syntax", "save <domain> <file>"},
733 734
    {"help", gettext_noop("save a domain state to a file")},
    {"desc", gettext_noop("Save a running domain.")},
735
    {NULL, NULL}
736 737 738
};

static vshCmdOptDef opts_save[] = {
739 740
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("where to save the data")},
741
    {NULL, 0, 0, NULL}
742 743 744
};

static int
745 746
cmdSave(vshControl * ctl, vshCmd * cmd)
{
747 748 749 750
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
751

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

755
    if (!(to = vshCommandOptString(cmd, "file", NULL)))
756
        return FALSE;
757

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

    if (virDomainSave(dom, to) == 0) {
762
        vshPrint(ctl, _("Domain %s saved to %s\n"), name, to);
763
    } else {
764
        vshError(ctl, FALSE, _("Failed to save domain %s to %s"), name, to);
765 766
        ret = FALSE;
    }
767

768 769 770 771 772 773 774 775
    virDomainFree(dom);
    return ret;
}

/*
 * "restore" command
 */
static vshCmdInfo info_restore[] = {
776
    {"syntax", "restore a domain from <file>"},
777 778
    {"help", gettext_noop("restore a domain from a saved state in a file")},
    {"desc", gettext_noop("Restore a domain.")},
779
    {NULL, NULL}
780 781 782
};

static vshCmdOptDef opts_restore[] = {
783
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("the state to restore")},
784
    {NULL, 0, 0, NULL}
785 786 787
};

static int
788 789
cmdRestore(vshControl * ctl, vshCmd * cmd)
{
790 791 792
    char *from;
    int found;
    int ret = TRUE;
793

794 795 796 797 798 799
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
802
        vshPrint(ctl, _("Domain restored from %s\n"), from);
803
    } else {
804
        vshError(ctl, FALSE, _("Failed to restore domain from %s"), from);
805 806 807 808 809
        ret = FALSE;
    }
    return ret;
}

D
Daniel Veillard 已提交
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
/*
 * "dump" command
 */
static vshCmdInfo info_dump[] = {
    {"syntax", "dump <domain> <file>"},
    {"help", gettext_noop("dump the core of a domain to a file for analysis")},
    {"desc", gettext_noop("Core dump a domain.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_dump[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("where to dump the core")},
    {NULL, 0, 0, NULL}
};

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

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

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

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

    if (virDomainCoreDump(dom, to, 0) == 0) {
        vshPrint(ctl, _("Domain %s dumpd to %s\n"), name, to);
    } else {
        vshError(ctl, FALSE, _("Failed to core dump domain %s to %s"),
                 name, to);
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

855 856 857 858
/*
 * "resume" command
 */
static vshCmdInfo info_resume[] = {
859
    {"syntax", "resume <domain>"},
860 861
    {"help", gettext_noop("resume a domain")},
    {"desc", gettext_noop("Resume a previously suspended domain.")},
862
    {NULL, NULL}
863 864 865
};

static vshCmdOptDef opts_resume[] = {
866
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
867
    {NULL, 0, 0, NULL}
868 869 870
};

static int
871 872
cmdResume(vshControl * ctl, vshCmd * cmd)
{
873
    virDomainPtr dom;
K
Karel Zak 已提交
874 875
    int ret = TRUE;
    char *name;
876

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

K
Karel Zak 已提交
880
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
881
        return FALSE;
882 883

    if (virDomainResume(dom) == 0) {
884
        vshPrint(ctl, _("Domain %s resumed\n"), name);
885
    } else {
886
        vshError(ctl, FALSE, _("Failed to resume domain %s"), name);
887 888
        ret = FALSE;
    }
889

890 891 892 893
    virDomainFree(dom);
    return ret;
}

894 895 896 897
/*
 * "shutdown" command
 */
static vshCmdInfo info_shutdown[] = {
898
    {"syntax", "shutdown <domain>"},
899 900
    {"help", gettext_noop("gracefully shutdown a domain")},
    {"desc", gettext_noop("Run shutdown in the target domain.")},
901
    {NULL, NULL}
902 903 904
};

static vshCmdOptDef opts_shutdown[] = {
905
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
906
    {NULL, 0, 0, NULL}
907 908 909
};

static int
910 911
cmdShutdown(vshControl * ctl, vshCmd * cmd)
{
912 913 914
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
915

916 917 918 919 920
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainShutdown(dom) == 0) {
923
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
924
    } else {
925
        vshError(ctl, FALSE, _("Failed to shutdown domain %s"), name);
926 927
        ret = FALSE;
    }
928

929 930 931 932
    virDomainFree(dom);
    return ret;
}

933 934 935 936 937
/*
 * "reboot" command
 */
static vshCmdInfo info_reboot[] = {
    {"syntax", "reboot <domain>"},
938 939
    {"help", gettext_noop("reboot a domain")},
    {"desc", gettext_noop("Run a reboot command in the target domain.")},
940 941 942 943
    {NULL, NULL}
};

static vshCmdOptDef opts_reboot[] = {
944
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    {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) {
962
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
963
    } else {
964
        vshError(ctl, FALSE, _("Failed to reboot domain %s"), name);
965 966 967 968 969 970 971
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

972 973 974 975
/*
 * "destroy" command
 */
static vshCmdInfo info_destroy[] = {
976
    {"syntax", "destroy <domain>"},
977 978
    {"help", gettext_noop("destroy a domain")},
    {"desc", gettext_noop("Destroy a given domain.")},
979
    {NULL, NULL}
980 981 982
};

static vshCmdOptDef opts_destroy[] = {
983
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
984
    {NULL, 0, 0, NULL}
985 986 987
};

static int
988 989
cmdDestroy(vshControl * ctl, vshCmd * cmd)
{
990
    virDomainPtr dom;
K
Karel Zak 已提交
991 992
    int ret = TRUE;
    char *name;
993

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

K
Karel Zak 已提交
997
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
998
        return FALSE;
999 1000

    if (virDomainDestroy(dom) == 0) {
1001
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
1002
    } else {
1003
        vshError(ctl, FALSE, _("Failed to destroy domain %s"), name);
1004 1005 1006
        ret = FALSE;
        virDomainFree(dom);
    }
1007

K
Karel Zak 已提交
1008 1009 1010 1011
    return ret;
}

/*
1012
 * "dominfo" command
K
Karel Zak 已提交
1013
 */
1014 1015
static vshCmdInfo info_dominfo[] = {
    {"syntax", "dominfo <domain>"},
1016 1017
    {"help", gettext_noop("domain information")},
    {"desc", gettext_noop("Returns basic information about the domain.")},
1018
    {NULL, NULL}
K
Karel Zak 已提交
1019 1020
};

1021
static vshCmdOptDef opts_dominfo[] = {
1022
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1023
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1024 1025 1026
};

static int
1027
cmdDominfo(vshControl * ctl, vshCmd * cmd)
1028
{
K
Karel Zak 已提交
1029 1030
    virDomainInfo info;
    virDomainPtr dom;
K
Karel Zak 已提交
1031
    int ret = TRUE;
1032
    unsigned int id;
K
Karel Zak 已提交
1033
    char *str, uuid[37];
1034

K
Karel Zak 已提交
1035 1036 1037
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
1038
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
1039
        return FALSE;
1040

1041 1042
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1043
      vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
1044
    else
1045 1046 1047
      vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
1048
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
1049
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
1050 1051

    if ((str = virDomainGetOSType(dom))) {
1052
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
1053 1054 1055 1056
        free(str);
    }

    if (virDomainGetInfo(dom, &info) == 0) {
1057 1058
        vshPrint(ctl, "%-15s %s\n", _("State:"),
                 _N(vshDomainStateToString(info.state)));
1059

1060
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
1061 1062

        if (info.cpuTime != 0) {
1063
	    double cpuUsed = info.cpuTime;
1064

1065
            cpuUsed /= 1000000000.0;
1066

1067
            vshPrint(ctl, "%-15s %.1lfs\n", _("CPU time:"), cpuUsed);
K
Karel Zak 已提交
1068
        }
1069

1070
        vshPrint(ctl, "%-15s %lu kB\n", _("Max memory:"),
1071
                 info.maxMem);
1072
	vshPrint(ctl, "%-15s %lu kB\n", _("Used memory:"),
1073 1074
                 info.memory);

K
Karel Zak 已提交
1075 1076 1077
    } else {
        ret = FALSE;
    }
1078

1079
    virDomainFree(dom);
K
Karel Zak 已提交
1080 1081 1082
    return ret;
}

1083 1084 1085 1086 1087
/*
 * "vcpuinfo" command
 */
static vshCmdInfo info_vcpuinfo[] = {
    {"syntax", "vcpuinfo <domain>"},
1088 1089
    {"help", gettext_noop("domain vcpu information")},
    {"desc", gettext_noop("Returns basic information about the domain virtual CPUs.")},
1090 1091 1092 1093
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpuinfo[] = {
1094
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    {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;
1136 1137 1138 1139
	    vshPrint(ctl, "%-15s %d\n", _("VCPU:"), n);
	    vshPrint(ctl, "%-15s %d\n", _("CPU:"), cpuinfo[n].cpu);
	    vshPrint(ctl, "%-15s %s\n", _("State:"),
		     _N(vshDomainVcpuStateToString(cpuinfo[n].state)));
1140 1141 1142 1143 1144
	    if (cpuinfo[n].cpuTime != 0) {
	        double cpuUsed = cpuinfo[n].cpuTime;
		
		cpuUsed /= 1000000000.0;
		
1145
		vshPrint(ctl, "%-15s %.1lfs\n", _("CPU time:"), cpuUsed);
1146
	    }
1147
	    vshPrint(ctl, "%-15s ", _("CPU Affinity:"));
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
	    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>"},
1171 1172
    {"help", gettext_noop("control domain vcpu affinity")},
    {"desc", gettext_noop("Pin domain VCPUs to host physical CPUs.")},
1173 1174 1175 1176
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpupin[] = {
1177 1178 1179
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"vcpu", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vcpu number")},
    {"cpulist", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("host cpu number(s) (comma separated)")},
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    {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;
}

1252 1253 1254 1255 1256
/*
 * "setvcpus" command
 */
static vshCmdInfo info_setvcpus[] = {
    {"syntax", "setvcpus <domain> <count>"},
1257 1258
    {"help", gettext_noop("change number of virtual CPUs")},
    {"desc", gettext_noop("Change the number of virtual CPUs active in the guest domain.")},
1259 1260 1261 1262
    {NULL, NULL}
};

static vshCmdOptDef opts_setvcpus[] = {
1263 1264
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"count", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("number of virtual CPUs")},
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    {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>"},
1300 1301
    {"help", gettext_noop("change memory allocation")},
    {"desc", gettext_noop("Change the current memory allocation in the guest domain.")},
1302 1303 1304 1305
    {NULL, NULL}
};

static vshCmdOptDef opts_setmem[] = {
1306 1307
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"bytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("number of bytes of memory")},
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    {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>"},
1343 1344
    {"help", gettext_noop("change maximum memory limit")},
    {"desc", gettext_noop("Change the maximum memory allocation limit in the guest domain.")},
1345 1346 1347 1348
    {NULL, NULL}
};

static vshCmdOptDef opts_setmaxmem[] = {
1349 1350
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"bytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("maxmimum memory limit in bytes")},
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    {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;
}

1381 1382 1383 1384 1385
/*
 * "nodeinfo" command
 */
static vshCmdInfo info_nodeinfo[] = {
    {"syntax", "nodeinfo"},
1386 1387
    {"help", gettext_noop("node information")},
    {"desc", gettext_noop("Returns basic information about the node.")},
1388 1389 1390 1391 1392 1393 1394
    {NULL, NULL}
};

static int
cmdNodeinfo(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    virNodeInfo info;
1395

1396 1397 1398 1399
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
        vshError(ctl, FALSE, _("failed to get node information"));
        return FALSE;
    }
    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);

1412 1413 1414
    return TRUE;
}

1415 1416 1417 1418
/*
 * "dumpxml" command
 */
static vshCmdInfo info_dumpxml[] = {
1419
    {"syntax", "dumpxml <name>"},
1420 1421
    {"help", gettext_noop("domain information in XML")},
    {"desc", gettext_noop("Ouput the domain information as an XML dump to stdout.")},
1422
    {NULL, NULL}
1423 1424 1425
};

static vshCmdOptDef opts_dumpxml[] = {
1426
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1427
    {NULL, 0, 0, NULL}
1428 1429 1430
};

static int
1431 1432
cmdDumpXML(vshControl * ctl, vshCmd * cmd)
{
1433
    virDomainPtr dom;
K
Karel Zak 已提交
1434
    int ret = TRUE;
1435
    char *dump;
1436

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

K
Karel Zak 已提交
1440
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
1441
        return FALSE;
1442

1443 1444 1445 1446 1447 1448 1449
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
1450

1451 1452 1453 1454
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
1455
/*
K
Karel Zak 已提交
1456
 * "domname" command
K
Karel Zak 已提交
1457
 */
K
Karel Zak 已提交
1458
static vshCmdInfo info_domname[] = {
K
Karel Zak 已提交
1459
    {"syntax", "domname <domain>"},
1460
    {"help", gettext_noop("convert a domain id or UUID to domain name")},
1461
    {NULL, NULL}
K
Karel Zak 已提交
1462 1463
};

K
Karel Zak 已提交
1464
static vshCmdOptDef opts_domname[] = {
1465
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or uuid")},
1466
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1467 1468 1469
};

static int
K
Karel Zak 已提交
1470
cmdDomname(vshControl * ctl, vshCmd * cmd)
1471
{
K
Karel Zak 已提交
1472 1473 1474 1475
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
K
Karel Zak 已提交
1476 1477
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL, 
                                    VSH_DOMBYID|VSH_DOMBYUUID)))
K
Karel Zak 已提交
1478
        return FALSE;
1479

K
Karel Zak 已提交
1480 1481
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
K
Karel Zak 已提交
1482 1483 1484 1485
    return TRUE;
}

/*
K
Karel Zak 已提交
1486
 * "domid" command
K
Karel Zak 已提交
1487
 */
K
Karel Zak 已提交
1488
static vshCmdInfo info_domid[] = {
K
Karel Zak 已提交
1489
    {"syntax", "domid <domain>"},
1490
    {"help", gettext_noop("convert a domain name or UUID to domain id")},
1491
    {NULL, NULL}
K
Karel Zak 已提交
1492 1493
};

K
Karel Zak 已提交
1494
static vshCmdOptDef opts_domid[] = {
1495
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
1496
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1497 1498 1499
};

static int
K
Karel Zak 已提交
1500
cmdDomid(vshControl * ctl, vshCmd * cmd)
1501
{
1502
    virDomainPtr dom;
1503
    unsigned int id;
K
Karel Zak 已提交
1504 1505 1506

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
K
Karel Zak 已提交
1507 1508
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL, 
                                    VSH_DOMBYNAME|VSH_DOMBYUUID)))
K
Karel Zak 已提交
1509
        return FALSE;
K
Karel Zak 已提交
1510
    
1511 1512 1513 1514 1515
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
      vshPrint(ctl, "%s\n", "-");
    else
      vshPrint(ctl, "%d\n", id);
K
Karel Zak 已提交
1516 1517 1518
    virDomainFree(dom);
    return TRUE;
}
1519

K
Karel Zak 已提交
1520 1521 1522 1523 1524
/*
 * "domuuid" command
 */
static vshCmdInfo info_domuuid[] = {
    {"syntax", "domuuid <domain>"},
1525
    {"help", gettext_noop("convert a domain name or id to domain UUID")},
K
Karel Zak 已提交
1526 1527 1528 1529
    {NULL, NULL}
};

static vshCmdOptDef opts_domuuid[] = {
1530
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or name")},
K
Karel Zak 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
    {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 已提交
1541
        return FALSE;
1542
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
K
Karel Zak 已提交
1543 1544
                                    VSH_DOMBYNAME|VSH_DOMBYID)))
        return FALSE;
1545

K
Karel Zak 已提交
1546 1547 1548
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
1549 1550
        vshError(ctl, FALSE, _("failed to get domain UUID"));

K
Karel Zak 已提交
1551 1552 1553
    return TRUE;
}

K
Karel Zak 已提交
1554

1555 1556 1557 1558
/*
 * "version" command
 */
static vshCmdInfo info_version[] = {
1559
    {"syntax", "version"},
1560 1561
    {"help", gettext_noop("show version")},
    {"desc", gettext_noop("Display the system version information.")},
1562
    {NULL, NULL}
1563 1564 1565 1566
};


static int
1567 1568
cmdVersion(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
1569 1570
    unsigned long hvVersion;
    const char *hvType;
1571 1572 1573 1574 1575 1576 1577
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
1578 1579 1580

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

1582 1583
    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
1584
        vshError(ctl, FALSE, _("failed to get hypervisor type"));
1585 1586 1587
        return FALSE;
    }

1588 1589 1590 1591 1592
    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
1593
    vshPrint(ctl, _("Compiled against library: libvir %d.%d.%d\n"),
1594 1595 1596 1597
             major, minor, rel);

    ret = virGetVersion(&libVersion, hvType, &apiVersion);
    if (ret < 0) {
1598
        vshError(ctl, FALSE, _("failed to get the library version"));
1599 1600 1601 1602 1603 1604
        return FALSE;
    }
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
1605
    vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"),
1606
             major, minor, rel);
1607

1608 1609 1610 1611
    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
1612
    vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType,
1613 1614
             major, minor, rel);

1615
    ret = virConnectGetVersion(ctl->conn, &hvVersion);
1616
    if (ret < 0) {
1617
        vshError(ctl, FALSE, _("failed to get the hypervisor version"));
1618 1619 1620
        return FALSE;
    }
    if (hvVersion == 0) {
K
Karel Zak 已提交
1621
        vshPrint(ctl,
1622
                 _("Cannot extract running %s hypervisor version\n"), hvType);
1623
    } else {
1624
        major = hvVersion / 1000000;
1625
        hvVersion %= 1000000;
1626 1627
        minor = hvVersion / 1000;
        rel = hvVersion % 1000;
1628

1629
        vshPrint(ctl, _("Running hypervisor: %s %d.%d.%d\n"),
1630
                 hvType, major, minor, rel);
1631 1632 1633 1634
    }
    return TRUE;
}

K
Karel Zak 已提交
1635 1636 1637 1638
/*
 * "quit" command
 */
static vshCmdInfo info_quit[] = {
1639
    {"syntax", "quit"},
1640
    {"help", gettext_noop("quit this interactive terminal")},
1641
    {NULL, NULL}
K
Karel Zak 已提交
1642 1643 1644
};

static int
1645 1646
cmdQuit(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
1647 1648 1649 1650 1651 1652 1653 1654
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
static vshCmdDef commands[] = {
1655
    {"connect", cmdConnect, opts_connect, info_connect},
1656
    {"create", cmdCreate, opts_create, info_create},
1657
    {"start", cmdStart, opts_start, info_start},
K
Karel Zak 已提交
1658
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
1659
    {"define", cmdDefine, opts_define, info_define},
K
Karel Zak 已提交
1660
    {"domid", cmdDomid, opts_domid, info_domid},
K
Karel Zak 已提交
1661
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid},
1662
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
1663 1664
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
1665
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
K
Karel Zak 已提交
1666
    {"help", cmdHelp, opts_help, info_help},
1667
    {"list", cmdList, opts_list, info_list},
K
Karel Zak 已提交
1668 1669 1670 1671
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
    {"quit", cmdQuit, NULL, info_quit},
    {"reboot", cmdReboot, opts_reboot, info_reboot},
    {"restore", cmdRestore, opts_restore, info_restore},
1672 1673
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
D
Daniel Veillard 已提交
1674
    {"dump", cmdDump, opts_dump, info_dump},
1675
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
1676 1677 1678
    {"setmem", cmdSetmem, opts_setmem, info_setmem},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus},
K
Karel Zak 已提交
1679
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
1680
    {"undefine", cmdUndefine, opts_undefine, info_undefine},
1681 1682
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
1683 1684
    {"version", cmdVersion, NULL, info_version},
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
1685 1686 1687 1688 1689 1690
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
1691
static const char *
1692 1693
vshCmddefGetInfo(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1694
    vshCmdInfo *info;
1695

K
Karel Zak 已提交
1696
    for (info = cmd->info; info && info->name; info++) {
1697
        if (strcmp(info->name, name) == 0)
K
Karel Zak 已提交
1698 1699 1700 1701 1702 1703
            return info->data;
    }
    return NULL;
}

static vshCmdOptDef *
1704 1705
vshCmddefGetOption(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1706
    vshCmdOptDef *opt;
1707

K
Karel Zak 已提交
1708
    for (opt = cmd->opts; opt && opt->name; opt++)
1709
        if (strcmp(opt->name, name) == 0)
K
Karel Zak 已提交
1710 1711 1712 1713 1714
            return opt;
    return NULL;
}

static vshCmdOptDef *
1715 1716
vshCmddefGetData(vshCmdDef * cmd, int data_ct)
{
K
Karel Zak 已提交
1717 1718
    vshCmdOptDef *opt;

1719
    for (opt = cmd->opts; opt && opt->name; opt++) {
1720 1721
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
1722 1723 1724 1725 1726
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
1727 1728 1729
    return NULL;
}

1730 1731 1732
/*
 * Checks for required options
 */
1733 1734
static int
vshCommandCheckOpts(vshControl * ctl, vshCmd * cmd)
1735 1736 1737
{
    vshCmdDef *def = cmd->def;
    vshCmdOptDef *d;
1738
    int err = 0;
1739 1740 1741 1742

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

            while (o && ok == 0) {
1746
                if (o->def == d)
1747
                    ok = 1;
1748 1749 1750
                o = o->next;
            }
            if (!ok) {
1751 1752
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
1753 1754
                         _("command '%s' requires <%s> option") :
			 _("command '%s' requires --%s option"),
1755
                         def->name, d->name);
1756 1757
                err = 1;
            }
1758

1759 1760 1761 1762 1763
        }
    }
    return !err;
}

K
Karel Zak 已提交
1764
static vshCmdDef *
1765 1766
vshCmddefSearch(const char *cmdname)
{
K
Karel Zak 已提交
1767
    vshCmdDef *c;
1768

K
Karel Zak 已提交
1769
    for (c = commands; c->name; c++)
1770
        if (strcmp(c->name, cmdname) == 0)
K
Karel Zak 已提交
1771 1772 1773 1774 1775
            return c;
    return NULL;
}

static int
1776 1777
vshCmddefHelp(vshControl * ctl, const char *cmdname, int withprog)
{
K
Karel Zak 已提交
1778
    vshCmdDef *def = vshCmddefSearch(cmdname);
1779

K
Karel Zak 已提交
1780
    if (!def) {
1781
        vshError(ctl, FALSE, _("command '%s' doesn't exist"), cmdname);
1782 1783
        return FALSE;
    } else {
K
Karel Zak 已提交
1784
        vshCmdOptDef *opt;
1785 1786
        const char *desc = _N(vshCmddefGetInfo(def, "desc"));
        const char *help = _N(vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
1787
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
1788

1789
        fputs(_("  NAME\n"), stdout);
1790 1791
        fprintf(stdout, "    %s - %s\n", def->name, help);

K
Karel Zak 已提交
1792
        if (syntax) {
1793
            fputs(("\n  SYNOPSIS\n"), stdout);
K
Karel Zak 已提交
1794 1795 1796 1797 1798 1799
            if (!withprog)
                fprintf(stdout, "    %s\n", syntax);
            else
                fprintf(stdout, "    %s %s\n", progname, syntax);
        }
        if (desc) {
1800
            fputs(_("\n  DESCRIPTION\n"), stdout);
K
Karel Zak 已提交
1801 1802 1803
            fprintf(stdout, "    %s\n", desc);
        }
        if (def->opts) {
1804
            fputs(_("\n  OPTIONS\n"), stdout);
1805
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
1806
                char buf[256];
1807 1808

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
1809
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1810
                else if (opt->type == VSH_OT_INT)
1811
                    snprintf(buf, sizeof(buf), _("--%s <number>"), opt->name);
1812
                else if (opt->type == VSH_OT_STRING)
1813
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1814
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
1815
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
1816

K
Karel Zak 已提交
1817
                fprintf(stdout, "    %-15s  %s\n", buf, opt->help);
1818
            }
K
Karel Zak 已提交
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1829 1830 1831
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1832 1833
    vshCmdOpt *a = arg;

1834
    while (a) {
K
Karel Zak 已提交
1835
        vshCmdOpt *tmp = a;
1836

K
Karel Zak 已提交
1837 1838 1839 1840 1841 1842 1843 1844 1845
        a = a->next;

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

static void
1846 1847
vshCommandFree(vshCmd * cmd)
{
K
Karel Zak 已提交
1848 1849
    vshCmd *c = cmd;

1850
    while (c) {
K
Karel Zak 已提交
1851
        vshCmd *tmp = c;
1852

K
Karel Zak 已提交
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
1865 1866
vshCommandOpt(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
1867
    vshCmdOpt *opt = cmd->opts;
1868 1869 1870

    while (opt) {
        if (opt->def && strcmp(opt->def->name, name) == 0)
K
Karel Zak 已提交
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
1881 1882
vshCommandOptInt(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
1883 1884
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
    int res = 0;
1885

K
Karel Zak 已提交
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
    if (arg)
        res = atoi(arg->data);
    if (found)
        *found = arg ? TRUE : FALSE;
    return res;
}

/*
 * Returns option as STRING
 */
static char *
1897 1898
vshCommandOptString(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
1899
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
1900

K
Karel Zak 已提交
1901 1902
    if (found)
        *found = arg ? TRUE : FALSE;
1903 1904

    return arg && arg->data && *arg->data ? arg->data : NULL;
K
Karel Zak 已提交
1905 1906 1907 1908 1909 1910
}

/*
 * Returns TRUE/FALSE if the option exists
 */
static int
1911 1912
vshCommandOptBool(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
1913 1914 1915
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

1916

K
Karel Zak 已提交
1917
static virDomainPtr
K
Karel Zak 已提交
1918 1919
vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd, const char *optname,
                    char **name, int flag)
1920
{
K
Karel Zak 已提交
1921 1922 1923
    virDomainPtr dom = NULL;
    char *n, *end = NULL;
    int id;
1924

K
Karel Zak 已提交
1925
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
1926
        vshError(ctl, FALSE, _("undefined domain name or id"));
1927
        return NULL;
K
Karel Zak 已提交
1928
    }
1929

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

K
Karel Zak 已提交
1933 1934
    if (name)
        *name = n;
1935

K
Karel Zak 已提交
1936
    /* try it by ID */
K
Karel Zak 已提交
1937 1938 1939 1940 1941 1942 1943
    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);
        }
1944
    }
K
Karel Zak 已提交
1945
    /* try it by UUID */
K
Karel Zak 已提交
1946
    if (dom==NULL && (flag & VSH_DOMBYUUID) && strlen(n)==36) {
K
Karel Zak 已提交
1947 1948
        vshDebug(ctl, 5, "%s: <%s> tring as domain UUID\n",
                cmd->def->name, optname);
K
Karel Zak 已提交
1949
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
1950
    }
K
Karel Zak 已提交
1951
    /* try it by NAME */
K
Karel Zak 已提交
1952
    if (dom==NULL && (flag & VSH_DOMBYNAME)) {
K
Karel Zak 已提交
1953
        vshDebug(ctl, 5, "%s: <%s> tring as domain NAME\n",
1954
                 cmd->def->name, optname);
K
Karel Zak 已提交
1955
        dom = virDomainLookupByName(ctl->conn, n);
1956
    }
K
Karel Zak 已提交
1957

1958
    if (!dom)
1959
        vshError(ctl, FALSE, _("failed to get domain '%s'"), n);
1960

K
Karel Zak 已提交
1961 1962 1963
    return dom;
}

K
Karel Zak 已提交
1964 1965 1966 1967
/*
 * Executes command(s) and returns return code from last command
 */
static int
1968 1969
vshCommandRun(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
1970
    int ret = TRUE;
1971 1972

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

K
Karel Zak 已提交
1975 1976
        if (ctl->timing)
            GETTIMEOFDAY(&before);
1977

K
Karel Zak 已提交
1978 1979 1980 1981
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
1982 1983

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

        if (ctl->timing)
1987
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
1988 1989
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
1990
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
        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

2006 2007 2008
static int
vshCommandGetToken(vshControl * ctl, char *str, char **end, char **res)
{
K
Karel Zak 已提交
2009 2010 2011 2012 2013
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
2014

K
Karel Zak 已提交
2015
    *end = NULL;
2016 2017

    while (p && *p && isblank((unsigned char) *p))
K
Karel Zak 已提交
2018
        p++;
2019 2020

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
2021
        return VSH_TK_END;
2022 2023
    if (*p == ';') {
        *end = ++p;             /* = \0 or begi of next command */
K
Karel Zak 已提交
2024 2025
        return VSH_TK_END;
    }
2026
    while (*p) {
K
Karel Zak 已提交
2027
        /* end of token is blank space or ';' */
2028
        if ((quote == FALSE && isblank((unsigned char) *p)) || *p == ';')
K
Karel Zak 已提交
2029
            break;
2030

2031
        /* end of option name could be '=' */
2032 2033
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
2034 2035
            break;
        }
2036 2037 2038 2039

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
                && isalnum((unsigned char) *(p + 2))) {
K
Karel Zak 已提交
2040
                tk = VSH_TK_OPTION;
2041
                p += 2;
K
Karel Zak 已提交
2042 2043
            } else {
                tk = VSH_TK_DATA;
2044 2045
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
2046 2047 2048 2049 2050
                    p++;
                } else {
                    quote = FALSE;
                }
            }
2051 2052
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
2053 2054
            quote = FALSE;
            p++;
2055
            break;              /* end of "..." token */
K
Karel Zak 已提交
2056 2057 2058 2059 2060
        }
        p++;
        sz++;
    }
    if (quote) {
2061
        vshError(ctl, FALSE, _("missing \""));
K
Karel Zak 已提交
2062 2063
        return VSH_TK_ERROR;
    }
2064
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
2065
        return VSH_TK_END;
2066
    if (sz == 0)
K
Karel Zak 已提交
2067
        return VSH_TK_END;
2068

2069
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
2070
    memcpy(*res, tkstr, sz);
2071
    *(*res + sz) = '\0';
K
Karel Zak 已提交
2072 2073 2074 2075 2076 2077

    *end = p;
    return tk;
}

static int
2078 2079
vshCommandParse(vshControl * ctl, char *cmdstr)
{
K
Karel Zak 已提交
2080 2081 2082 2083
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
2084

K
Karel Zak 已提交
2085 2086 2087 2088
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
2089 2090

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

K
Karel Zak 已提交
2093
    str = cmdstr;
2094
    while (str && *str) {
K
Karel Zak 已提交
2095 2096 2097
        vshCmdOpt *last = NULL;
        vshCmdDef *cmd = NULL;
        int tk = VSH_TK_NONE;
2098
        int data_ct = 0;
2099

K
Karel Zak 已提交
2100
        first = NULL;
2101 2102

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
2103 2104
            char *end = NULL;
            vshCmdOptDef *opt = NULL;
2105

K
Karel Zak 已提交
2106
            tkdata = NULL;
2107

K
Karel Zak 已提交
2108 2109
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
2110

K
Karel Zak 已提交
2111
            str = end;
2112 2113

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
2114
                break;
2115
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2116
                goto syntaxError;
2117 2118

            if (cmd == NULL) {
K
Karel Zak 已提交
2119
                /* first token must be command name */
2120 2121
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
2122
                             _("unexpected token (command name): '%s'"),
2123
                             tkdata);
K
Karel Zak 已提交
2124 2125 2126
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
2127
                    vshError(ctl, FALSE, _("unknown command: '%s'"), tkdata);
2128
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
2129 2130
                }
                free(tkdata);
2131
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
2132 2133
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
2134
                             _("command '%s' doesn't support option --%s"),
2135
                             cmd->name, tkdata);
K
Karel Zak 已提交
2136 2137
                    goto syntaxError;
                }
2138
                free(tkdata);   /* option name */
K
Karel Zak 已提交
2139 2140 2141 2142 2143
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
2144 2145
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2146
                        goto syntaxError;
2147
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
2148
                        vshError(ctl, FALSE,
2149
                                 _("expected syntax: --%s <%s>"),
2150 2151
                                 opt->name,
                                 opt->type ==
2152
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
2153 2154 2155
                        goto syntaxError;
                    }
                }
2156
            } else if (tk == VSH_TK_DATA) {
2157
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
2158
                    vshError(ctl, FALSE, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
2159 2160 2161 2162 2163
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
2164
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
2165

K
Karel Zak 已提交
2166 2167 2168 2169
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
2170

K
Karel Zak 已提交
2171 2172 2173 2174 2175
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
2176

K
Karel Zak 已提交
2177
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
2178 2179
                         cmd->name,
                         opt->name,
2180
                         tk == VSH_TK_OPTION ? _("OPTION") : _("DATA"),
2181
                         arg->data);
K
Karel Zak 已提交
2182 2183 2184 2185
            }
            if (!str)
                break;
        }
2186

K
Karel Zak 已提交
2187 2188
        /* commad parsed -- allocate new struct for the command */
        if (cmd) {
2189
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
2190

K
Karel Zak 已提交
2191 2192 2193 2194
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

2195 2196
            if (!vshCommandCheckOpts(ctl, c))
                goto syntaxError;
2197

K
Karel Zak 已提交
2198 2199 2200 2201 2202 2203 2204
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
2205

K
Karel Zak 已提交
2206 2207
    return TRUE;

2208
  syntaxError:
K
Karel Zak 已提交
2209 2210 2211 2212 2213 2214
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
    if (tkdata)
        free(tkdata);
2215
    return FALSE;
K
Karel Zak 已提交
2216 2217 2218 2219 2220 2221 2222
}


/* ---------------
 * Misc utils  
 * ---------------
 */
K
Karel Zak 已提交
2223
static const char *
2224 2225
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
2226 2227
    switch (state) {
        case VIR_DOMAIN_RUNNING:
2228
            return gettext_noop("running");
K
Karel Zak 已提交
2229
        case VIR_DOMAIN_BLOCKED:
2230
            return gettext_noop("blocked");
K
Karel Zak 已提交
2231
        case VIR_DOMAIN_PAUSED:
2232
            return gettext_noop("paused");
K
Karel Zak 已提交
2233
        case VIR_DOMAIN_SHUTDOWN:
2234
            return gettext_noop("in shutdown");
K
Karel Zak 已提交
2235
        case VIR_DOMAIN_SHUTOFF:
2236
            return gettext_noop("shut off");
K
Karel Zak 已提交
2237
        case VIR_DOMAIN_CRASHED:
2238
            return gettext_noop("crashed");
K
Karel Zak 已提交
2239
        default:
2240
            return gettext_noop("no state");  /* = dom0 state */
K
Karel Zak 已提交
2241 2242 2243 2244
    }
    return NULL;
}

2245 2246 2247 2248 2249
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
        case VIR_VCPU_OFFLINE:
2250
            return gettext_noop("offline");
2251
        case VIR_VCPU_BLOCKED:
2252
            return gettext_noop("blocked");
2253
        case VIR_VCPU_RUNNING:
2254
            return gettext_noop("running");
2255
        default:
2256
            return gettext_noop("no state");
2257 2258 2259 2260
    }
    return NULL;
}

K
Karel Zak 已提交
2261
static int
2262 2263
vshConnectionUsability(vshControl * ctl, virConnectPtr conn, int showerror)
{
K
Karel Zak 已提交
2264 2265 2266 2267 2268
    /* TODO: use something like virConnectionState() to 
     *       check usability of the connection 
     */
    if (!conn) {
        if (showerror)
2269
            vshError(ctl, FALSE, _("no valid connection"));
K
Karel Zak 已提交
2270 2271 2272 2273 2274
        return FALSE;
    }
    return TRUE;
}

K
Karel Zak 已提交
2275 2276
static void
vshDebug(vshControl * ctl, int level, const char *format, ...)
2277
{
K
Karel Zak 已提交
2278 2279 2280 2281 2282 2283 2284 2285
    va_list ap;

    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
2286 2287 2288
}

static void
K
Karel Zak 已提交
2289
vshPrintExtra(vshControl * ctl, const char *format, ...)
2290
{
K
Karel Zak 已提交
2291
    va_list ap;
2292

K
Karel Zak 已提交
2293
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
2294
        return;
2295

K
Karel Zak 已提交
2296
    va_start(ap, format);
2297
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
2298 2299 2300
    va_end(ap);
}

K
Karel Zak 已提交
2301

K
Karel Zak 已提交
2302
static void
2303 2304
vshError(vshControl * ctl, int doexit, const char *format, ...)
{
K
Karel Zak 已提交
2305
    va_list ap;
2306

K
Karel Zak 已提交
2307
    if (doexit)
2308
        fprintf(stderr, _("%s: error: "), progname);
K
Karel Zak 已提交
2309
    else
2310
        fputs(_("error: "), stderr);
2311

K
Karel Zak 已提交
2312 2313 2314 2315 2316
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
2317

K
Karel Zak 已提交
2318
    if (doexit) {
2319 2320
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
2321 2322 2323 2324
        exit(EXIT_FAILURE);
    }
}

2325 2326 2327 2328 2329 2330 2331
static void *
_vshMalloc(vshControl * ctl, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = malloc(size)))
        return x;
2332 2333
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
	     filename, line, (int) size);
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
    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;
2344 2345
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
	     filename, line, (int) (size*nmemb));
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
    return NULL;
}

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

    if ((x = strdup(s)))
        return x;
2356 2357
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
	     filename, line, strlen(s));
2358 2359 2360
    return NULL;
}

K
Karel Zak 已提交
2361 2362 2363 2364
/*
 * Initialize vistsh
 */
static int
2365 2366
vshInit(vshControl * ctl)
{
K
Karel Zak 已提交
2367 2368 2369 2370
    if (ctl->conn)
        return FALSE;

    ctl->uid = getuid();
2371

2372 2373
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2374

2375 2376 2377 2378
    /* 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 已提交
2379
        ctl->conn = virConnectOpen(ctl->name);
K
Karel Zak 已提交
2380
    else
K
Karel Zak 已提交
2381
        ctl->conn = virConnectOpenReadOnly(ctl->name);
2382

K
Karel Zak 已提交
2383
    if (!ctl->conn)
2384
        vshError(ctl, TRUE, _("failed to connect to the hypervisor"));
K
Karel Zak 已提交
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399

    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 *
2400 2401
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2402
    static int list_index, len;
K
Karel Zak 已提交
2403
    const char *name;
K
Karel Zak 已提交
2404 2405 2406 2407 2408 2409 2410

    /* 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;
2411
        len = strlen(text);
K
Karel Zak 已提交
2412 2413 2414 2415 2416
    }

    /* Return the next name which partially matches from the
     * command list. 
     */
K
Karel Zak 已提交
2417
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
2418
        list_index++;
2419
        if (strncmp(name, text, len) == 0)
2420
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
2421 2422 2423 2424 2425 2426 2427
    }

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

static char *
2428 2429
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2430 2431
    static int list_index, len;
    static vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2432
    const char *name;
K
Karel Zak 已提交
2433 2434 2435 2436 2437 2438 2439 2440 2441

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

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

2442
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2443
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2444 2445 2446

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2447
        len = strlen(text);
K
Karel Zak 已提交
2448 2449 2450 2451 2452
        free(cmdname);
    }

    if (!cmd)
        return NULL;
2453

K
Karel Zak 已提交
2454
    while ((name = cmd->opts[list_index].name)) {
K
Karel Zak 已提交
2455 2456
        vshCmdOptDef *opt = &cmd->opts[list_index];
        char *res;
2457

K
Karel Zak 已提交
2458
        list_index++;
2459

K
Karel Zak 已提交
2460
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
2461 2462
            /* ignore non --option */
            continue;
2463

K
Karel Zak 已提交
2464
        if (len > 2) {
2465
            if (strncmp(name, text + 2, len - 2))
K
Karel Zak 已提交
2466 2467
                continue;
        }
2468
        res = vshMalloc(NULL, strlen(name) + 3);
K
Karel Zak 已提交
2469 2470 2471 2472 2473 2474 2475 2476 2477
        sprintf(res, "--%s", name);
        return res;
    }

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

static char **
2478 2479 2480
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2481 2482
    char **matches = (char **) NULL;

2483
    if (start == 0)
K
Karel Zak 已提交
2484
        /* command name generator */
2485
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2486 2487
    else
        /* commands options */
2488
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2489 2490 2491 2492 2493
    return matches;
}


static void
2494 2495
vshReadlineInit(void)
{
K
Karel Zak 已提交
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
    /* 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
2507 2508
vshDeinit(vshControl * ctl)
{
K
Karel Zak 已提交
2509
    if (ctl->conn) {
2510 2511 2512 2513
        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 已提交
2514 2515 2516 2517
        }
    }
    return TRUE;
}
2518

K
Karel Zak 已提交
2519 2520 2521 2522
/*
 * Print usage
 */
static void
2523 2524
vshUsage(vshControl * ctl, const char *cmdname)
{
K
Karel Zak 已提交
2525
    vshCmdDef *cmd;
2526

K
Karel Zak 已提交
2527 2528
    /* global help */
    if (!cmdname) {
2529 2530 2531 2532 2533 2534 2535 2536 2537
        fprintf(stdout, _("\n%s [options] [commands]\n\n"
			  "  options:\n"
			  "    -c | --connect <uri>    hypervisor connection URI\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);
2538 2539 2540

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

        fprintf(stdout,
2545
                _("\n  (specify --help <command> for details about the command)\n\n"));
K
Karel Zak 已提交
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
2557 2558
vshParseArgv(vshControl * ctl, int argc, char **argv)
{
K
Karel Zak 已提交
2559 2560
    char *last = NULL;
    int i, end = 0, help = 0;
2561
    int arg, idx = 0;
K
Karel Zak 已提交
2562
    struct option opt[] = {
2563 2564 2565 2566 2567
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
2568
        {"connect", 1, 0, 'c'},
K
Karel Zak 已提交
2569
        {0, 0, 0, 0}
2570 2571
    };

K
Karel Zak 已提交
2572 2573

    if (argc < 2)
K
Karel Zak 已提交
2574
        return TRUE;
2575

2576
    /* look for begin of the command, for example:
K
Karel Zak 已提交
2577 2578 2579 2580
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
2581
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
2582 2583
        if (*argv[i] != '-') {
            int valid = FALSE;
2584

K
Karel Zak 已提交
2585 2586 2587 2588
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
2589 2590 2591

                for (o = opt; o->name; o++) {
                    if (sz == 2 && *(last + 1) == o->val)
K
Karel Zak 已提交
2592 2593
                        /* valid virsh short option */
                        valid = TRUE;
2594
                    else if (sz > 2 && strcmp(o->name, last + 2) == 0)
K
Karel Zak 已提交
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
                        /* valid virsh long option */
                        valid = TRUE;
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
    end = end ? : argc;
2607

K
Karel Zak 已提交
2608
    /* standard (non-command) options */
2609 2610
    while ((arg = getopt_long(end, argv, "d:hqtv", opt, &idx)) != -1) {
        switch (arg) {
K
Karel Zak 已提交
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
            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 已提交
2623 2624 2625
            case 'c':
                ctl->name = vshStrdup(ctl, optarg);
                break;
K
Karel Zak 已提交
2626 2627 2628 2629
            case 'v':
                fprintf(stdout, "%s\n", VERSION);
                exit(EXIT_SUCCESS);
            default:
2630
                vshError(ctl, TRUE,
2631
			 _("unsupported option '-%c'. See --help."), arg);
K
Karel Zak 已提交
2632 2633 2634 2635 2636 2637 2638 2639
                break;
        }
    }

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

K
Karel Zak 已提交
2642 2643 2644
    if (argc > end) {
        /* parse command */
        char *cmdstr;
2645 2646
        int sz = 0, ret;

K
Karel Zak 已提交
2647 2648
        ctl->imode = FALSE;

2649 2650 2651
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

2652
        cmdstr = vshCalloc(ctl, sz + 1, 1);
2653 2654

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
2655 2656 2657 2658
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
2659
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
2660
        ret = vshCommandParse(ctl, cmdstr);
2661

K
Karel Zak 已提交
2662 2663 2664 2665 2666 2667
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

2668 2669 2670 2671
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
2672
    char *defaultConn;
K
Karel Zak 已提交
2673 2674
    int ret = TRUE;

2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
	return -1;
    }
    if (!bindtextdomain(GETTEXT_PACKAGE, LOCALEBASEDIR)) {
        perror("bindtextdomain");
	return -1;
    }
    if (!textdomain(GETTEXT_PACKAGE)) {
        perror("textdomain");
	return -1;
    }

2688
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
2689 2690 2691
        progname = argv[0];
    else
        progname++;
2692

K
Karel Zak 已提交
2693
    memset(ctl, 0, sizeof(vshControl));
2694
    ctl->imode = TRUE;          /* default is interactive mode */
K
Karel Zak 已提交
2695

2696 2697 2698 2699
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
      ctl->name = strdup(defaultConn);
    }

K
Karel Zak 已提交
2700 2701
    if (!vshParseArgv(ctl, argc, argv))
        exit(EXIT_FAILURE);
2702

K
Karel Zak 已提交
2703 2704
    if (!vshInit(ctl))
        exit(EXIT_FAILURE);
2705

K
Karel Zak 已提交
2706
    if (!ctl->imode) {
2707
        ret = vshCommandRun(ctl, ctl->cmd);
2708
    } else {
K
Karel Zak 已提交
2709 2710
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
2711
            vshPrint(ctl,
2712
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
2713
                     progname);
K
Karel Zak 已提交
2714
            vshPrint(ctl,
2715 2716
                     _("Type:  'help' for help with commands\n"
		       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
2717
        }
K
Karel Zak 已提交
2718
        vshReadlineInit();
K
Karel Zak 已提交
2719
        do {
2720 2721 2722 2723
            ctl->cmdstr =
                readline(ctl->uid == 0 ? VSH_PROMPT_RW : VSH_PROMPT_RO);
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
2724 2725 2726 2727 2728 2729 2730
            if (*ctl->cmdstr) {
                add_history(ctl->cmdstr);
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
2731
        } while (ctl->imode);
K
Karel Zak 已提交
2732

2733 2734
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
2735
    }
2736

K
Karel Zak 已提交
2737 2738
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
2739
}
K
Karel Zak 已提交
2740 2741 2742 2743 2744 2745

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