virsh.c 73.2 KB
Newer Older
1
/*
2
 * virsh.c: a Xen shell used to exercise the libvirt 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 <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

K
Karel Zak 已提交
36 37 38 39
#include <readline/readline.h>
#include <readline/history.h>

#include "config.h"
40
#include "internal.h"
41
#include "console.h"
K
Karel Zak 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

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)

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

/*
 * vshCmdOptType - command option type 
96
 */
K
Karel Zak 已提交
97
typedef enum {
98 99 100 101 102
    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 已提交
103 104 105 106 107
} vshCmdOptType;

/*
 * Command Option Flags
 */
108 109
#define VSH_OFLAG_NONE    0     /* without flags */
#define VSH_OFLAG_REQ    (1 << 1)       /* option required */
K
Karel Zak 已提交
110 111 112 113 114 115 116 117

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

/*
 * vshCmdInfo -- information about command
 */
118 119 120
typedef struct {
    const char *name;           /* name of information */
    const char *data;           /* information */
K
Karel Zak 已提交
121 122 123 124 125
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
126 127 128 129 130
typedef struct {
    const char *name;           /* the name of option */
    vshCmdOptType type;         /* option type */
    int flag;                   /* flags */
    const char *help;           /* help string */
K
Karel Zak 已提交
131 132 133 134 135 136
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
 */
typedef struct vshCmdOpt {
137 138 139
    vshCmdOptDef *def;          /* pointer to relevant option */
    char *data;                 /* allocated data */
    struct vshCmdOpt *next;
K
Karel Zak 已提交
140 141 142 143 144
} vshCmdOpt;

/*
 * vshCmdDef - command definition
 */
145 146 147 148 149
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 已提交
150 151 152 153 154 155
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
156 157 158
    vshCmdDef *def;             /* command definition */
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
159 160 161 162 163 164
} __vshCmd;

/*
 * vshControl
 */
typedef struct __vshControl {
K
Karel Zak 已提交
165
    char *name;                 /* connection name */
166 167 168 169 170 171 172 173
    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 已提交
174
} __vshControl;
175

176

K
Karel Zak 已提交
177 178
static vshCmdDef commands[];

179 180 181 182 183
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 已提交
184

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

187
static const char *vshCmddefGetInfo(vshCmdDef * cmd, const char *info);
K
Karel Zak 已提交
188
static vshCmdDef *vshCmddefSearch(const char *cmdname);
189
static int vshCmddefHelp(vshControl * ctl, const char *name, int withprog);
K
Karel Zak 已提交
190

191 192 193 194 195
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 已提交
196 197 198 199 200 201 202 203 204 205 206 207

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

K
Karel Zak 已提交
209 210
static void vshPrintExtra(vshControl * ctl, const char *format, ...);
static void vshDebug(vshControl * ctl, int level, const char *format, ...);
K
Karel Zak 已提交
211 212

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

K
Karel Zak 已提交
215
static const char *vshDomainStateToString(int state);
216
static const char *vshDomainVcpuStateToString(int state);
217 218
static int vshConnectionUsability(vshControl * ctl, virConnectPtr conn,
                                  int showerror);
K
Karel Zak 已提交
219

220 221 222 223 224 225 226 227 228
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 已提交
229 230 231 232 233 234 235 236 237
/* ---------------
 * Commands
 * ---------------
 */

/*
 * "help" command 
 */
static vshCmdInfo info_help[] = {
238
    {"syntax", "help [<command>]"},
239 240 241
    {"help", gettext_noop("print help")},
    {"desc", gettext_noop("Prints global help or command specific help.")},

242
    {NULL, NULL}
K
Karel Zak 已提交
243 244 245
};

static vshCmdOptDef opts_help[] = {
246 247
    {"command", VSH_OT_DATA, 0, "name of command"},
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
248 249 250
};

static int
251 252
cmdHelp(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
253
    const char *cmdname = vshCommandOptString(cmd, "command", NULL);
K
Karel Zak 已提交
254 255 256

    if (!cmdname) {
        vshCmdDef *def;
257

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

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

static vshCmdOptDef opts_connect[] = {
279 280
    {"name",     VSH_OT_DATA, 0, gettext_noop("hypervisor connection URI")},
    {"readonly", VSH_OT_BOOL, 0, gettext_noop("read-only connection")},
281
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
282 283 284
};

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

K
Karel Zak 已提交
302
    if (!ro)
K
Karel Zak 已提交
303
        ctl->conn = virConnectOpen(ctl->name);
K
Karel Zak 已提交
304
    else
K
Karel Zak 已提交
305
        ctl->conn = virConnectOpenReadOnly(ctl->name);
K
Karel Zak 已提交
306 307

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

K
Karel Zak 已提交
310 311 312
    return ctl->conn ? TRUE : FALSE;
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
/*
 * "console" command 
 */
static vshCmdInfo info_console[] = {
    {"syntax", "console <domain>"},
    {"help", gettext_noop("connect to the guest console")},
    {"desc",
     gettext_noop("Connect the virtual serial console for the guest")},
    {NULL, NULL}
};

static vshCmdOptDef opts_console[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
cmdConsole(vshControl * ctl, vshCmd * cmd)
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    int ret = FALSE;
    char *doc;

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

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

    doc = virDomainGetXMLDesc(dom, 0);
    if (!doc)
	goto cleanup;

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
		     XML_PARSE_NOENT | XML_PARSE_NONET |
		     XML_PARSE_NOWARNING);
    free(doc);
    if (!xml)
        goto cleanup;
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt)
        goto cleanup;

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/console/@tty)", ctxt);
    if ((obj != NULL) && ((obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0))) {
        if (virRunConsole((const char *)obj->stringval) == 0)
            ret = TRUE;
    } else {
        vshPrintExtra(ctl, _("No console available for domain\n"));
    }
    xmlXPathFreeObject(obj);

 cleanup:
    if (ctxt)
        xmlXPathFreeContext(ctxt);
    if (xml)
        xmlFreeDoc(xml);
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
378 379 380 381
/*
 * "list" command
 */
static vshCmdInfo info_list[] = {
382
    {"syntax", "list [--inactive | --all]"},
383 384
    {"help", gettext_noop("list domains")},
    {"desc", gettext_noop("Returns list of domains.")},
385
    {NULL, NULL}
K
Karel Zak 已提交
386 387
};

388
static vshCmdOptDef opts_list[] = {
389 390
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive domains")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active domains")},
391 392 393
    {NULL, 0, 0, NULL}
};

K
Karel Zak 已提交
394

395 396 397 398 399 400 401 402 403 404 405 406 407
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 已提交
408

409 410
  return strcasecmp(*sa, *sb);
}
K
Karel Zak 已提交
411
static int
412 413
cmdList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
414 415 416 417 418 419 420
    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 已提交
421 422 423

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
424 425 426 427
    
    if (active) {
      maxid = virConnectNumOfDomains(ctl->conn);
      if (maxid < 0) {
428
        vshError(ctl, FALSE, _("Failed to list active domains"));
K
Karel Zak 已提交
429
        return FALSE;
430 431
      }
      if (maxid) {
432
        ids = vshMalloc(ctl, sizeof(int) * maxid);
433
	
434
        if ((maxid = virConnectListDomains(ctl->conn, &ids[0], maxid)) < 0) {
435
	  vshError(ctl, FALSE, _("Failed to list active domains"));
436 437
	  free(ids);
	  return FALSE;
438
        }
439 440
	
	qsort(&ids[0], maxid, sizeof(int), domidsorter);
441 442 443 444 445
      }
    }
    if (inactive) {
      maxname = virConnectNumOfDefinedDomains(ctl->conn);
      if (maxname < 0) {
446
        vshError(ctl, FALSE, _("Failed to list inactive domains"));
447 448 449 450 451
	if (ids)
	  free(ids);
        return FALSE;
      }
      if (maxname) {
452
        names = vshMalloc(ctl, sizeof(char *) * maxname);
453
	
454
        if ((maxname = virConnectListDefinedDomains(ctl->conn, names, maxname)) < 0) {
455
	  vshError(ctl, FALSE, _("Failed to list inactive domains"));
456 457 458 459 460
	  if (ids)
	    free(ids);
	  free(names);
	  return FALSE;
        }
461 462

	qsort(&names[0], maxname, sizeof(char*), domnamesorter);
463
      }
464
    }
465
    vshPrintExtra(ctl, "%3s %-20s %s\n", _("Id"), _("Name"), _("State"));
K
Karel Zak 已提交
466
    vshPrintExtra(ctl, "----------------------------------\n");
467 468

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
469 470 471
        int ret;
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
472 473

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
474 475 476
        if (!dom)
            continue;
        ret = virDomainGetInfo(dom, &info);
477

K
Karel Zak 已提交
478
        vshPrint(ctl, "%3d %-20s %s\n",
479 480 481
                 virDomainGetID(dom),
                 virDomainGetName(dom),
                 ret <
482
                 0 ? _("no state") : _N(vshDomainStateToString(info.state)));
483
        virDomainFree(dom);
K
Karel Zak 已提交
484
    }
485 486
    for (i = 0; i < maxname; i++) {
        int ret;
487
        unsigned int id;
488 489 490 491
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByName(ctl->conn, names[i]);

        /* this kind of work with domains is not atomic operation */
492 493
        if (!dom) {
	    free(names[i]);
494
            continue;
495
	}
496
        ret = virDomainGetInfo(dom, &info);
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
	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));
	}
512

513
        virDomainFree(dom);
514
	free(names[i]);
515
    }
516 517
    if (ids)
        free(ids);
518 519
    if (names)
        free(names);
K
Karel Zak 已提交
520 521 522 523
    return TRUE;
}

/*
K
Karel Zak 已提交
524
 * "domstate" command
K
Karel Zak 已提交
525
 */
K
Karel Zak 已提交
526 527
static vshCmdInfo info_domstate[] = {
    {"syntax", "domstate <domain>"},
528 529
    {"help", gettext_noop("domain state")},
    {"desc", gettext_noop("Returns state about a running domain.")},
530
    {NULL, NULL}
K
Karel Zak 已提交
531 532
};

K
Karel Zak 已提交
533
static vshCmdOptDef opts_domstate[] = {
534
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
535
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
536 537 538
};

static int
K
Karel Zak 已提交
539
cmdDomstate(vshControl * ctl, vshCmd * cmd)
540
{
541
    virDomainInfo info;
K
Karel Zak 已提交
542
    virDomainPtr dom;
K
Karel Zak 已提交
543
    int ret = TRUE;
544

K
Karel Zak 已提交
545 546
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
547

K
Karel Zak 已提交
548
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
549
        return FALSE;
550 551

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
552
        vshPrint(ctl, "%s\n",
553
                 _N(vshDomainStateToString(info.state)));
K
Karel Zak 已提交
554 555
    else
        ret = FALSE;
556

557 558 559 560 561 562 563 564
    virDomainFree(dom);
    return ret;
}

/*
 * "suspend" command
 */
static vshCmdInfo info_suspend[] = {
565
    {"syntax", "suspend <domain>"},
566 567
    {"help", gettext_noop("suspend a domain")},
    {"desc", gettext_noop("Suspend a running domain.")},
568
    {NULL, NULL}
569 570 571
};

static vshCmdOptDef opts_suspend[] = {
572
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
573
    {NULL, 0, 0, NULL}
574 575 576
};

static int
577 578
cmdSuspend(vshControl * ctl, vshCmd * cmd)
{
579
    virDomainPtr dom;
K
Karel Zak 已提交
580 581
    char *name;
    int ret = TRUE;
582

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

K
Karel Zak 已提交
586
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
587
        return FALSE;
588 589

    if (virDomainSuspend(dom) == 0) {
590
        vshPrint(ctl, _("Domain %s suspended\n"), name);
591
    } else {
592
        vshError(ctl, FALSE, _("Failed to suspend domain %s"), name);
593 594
        ret = FALSE;
    }
595

596 597 598 599
    virDomainFree(dom);
    return ret;
}

600 601 602 603 604
/*
 * "create" command
 */
static vshCmdInfo info_create[] = {
    {"syntax", "create a domain from an XML <file>"},
605 606
    {"help", gettext_noop("create a domain from an XML file")},
    {"desc", gettext_noop("Create a domain.")},
607 608 609 610
    {NULL, NULL}
};

static vshCmdOptDef opts_create[] = {
611
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file conatining an XML domain description")},
612 613 614 615 616 617 618 619 620 621
    {NULL, 0, 0, NULL}
};

static int
cmdCreate(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
622
    char buffer[BUFSIZ];
623 624 625 626 627 628 629 630 631 632 633
    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) {
634
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
635 636 637 638
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
639
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
640 641 642 643 644 645
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    dom = virDomainCreateLinux(ctl->conn, &buffer[0], 0);
    if (dom != NULL) {
646
        vshPrint(ctl, _("Domain %s created from %s\n"),
647 648
                 virDomainGetName(dom), from);
    } else {
649
        vshError(ctl, FALSE, _("Failed to create domain from %s"), from);
650 651 652 653 654
        ret = FALSE;
    }
    return ret;
}

655 656 657 658 659
/*
 * "define" command
 */
static vshCmdInfo info_define[] = {
    {"syntax", "define a domain from an XML <file>"},
660 661
    {"help", gettext_noop("define (but don't start) a domain from an XML file")},
    {"desc", gettext_noop("Define a domain.")},
662 663 664 665
    {NULL, NULL}
};

static vshCmdOptDef opts_define[] = {
666
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file conatining an XML domain description")},
667 668 669 670 671 672 673 674 675 676
    {NULL, 0, 0, NULL}
};

static int
cmdDefine(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
677
    char buffer[BUFSIZ];
678 679 680 681 682 683 684 685 686 687 688
    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) {
689
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
690 691 692 693
        return(FALSE);
    }
    l = read(fd, &buffer[0], sizeof(buffer));
    if ((l <= 0) || (l >= (int) sizeof(buffer))) {
694
        vshError(ctl, FALSE, _("Failed to read description file %s"), from);
695 696 697 698 699 700
        close(fd);
        return(FALSE);
    }
    buffer[l] = 0;
    dom = virDomainDefineXML(ctl->conn, &buffer[0]);
    if (dom != NULL) {
701
        vshPrint(ctl, _("Domain %s defined from %s\n"),
702 703
                 virDomainGetName(dom), from);
    } else {
704
        vshError(ctl, FALSE, _("Failed to define domain from %s"), from);
705 706 707 708 709 710 711 712 713 714
        ret = FALSE;
    }
    return ret;
}

/*
 * "undefine" command
 */
static vshCmdInfo info_undefine[] = {
    {"syntax", "undefine <domain>"},
715 716
    {"help", gettext_noop("undefine an inactive domain")},
    {"desc", gettext_noop("Undefine the configuration for an inactive domain.")},
717 718 719 720
    {NULL, NULL}
};

static vshCmdOptDef opts_undefine[] = {
721
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    {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) {
739
        vshPrint(ctl, _("Domain %s has been undefined\n"), name);
740
    } else {
741
        vshError(ctl, FALSE, _("Failed to undefine domain %s"), name);
742 743 744 745 746 747 748 749 750 751 752
        ret = FALSE;
    }

    return ret;
}


/*
 * "start" command
 */
static vshCmdInfo info_start[] = {
753
    {"syntax", "start <domain>"},
754 755
    {"help", gettext_noop("start a (previously defined) inactive domain")},
    {"desc", gettext_noop("Start a domain.")},
756 757 758 759
    {NULL, NULL}
};

static vshCmdOptDef opts_start[] = {
760
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive domain")},
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    {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) {
784
        vshError(ctl, FALSE, _("Domain is already active"));
785 786 787 788
        return FALSE;
    }

    if (virDomainCreate(dom) == 0) {
789
        vshPrint(ctl, _("Domain %s started\n"),
790 791
                 name);
    } else {
792
      vshError(ctl, FALSE, _("Failed to start domain %s"), name);
793 794 795 796 797
        ret = FALSE;
    }
    return ret;
}

798 799 800 801
/*
 * "save" command
 */
static vshCmdInfo info_save[] = {
802
    {"syntax", "save <domain> <file>"},
803 804
    {"help", gettext_noop("save a domain state to a file")},
    {"desc", gettext_noop("Save a running domain.")},
805
    {NULL, NULL}
806 807 808
};

static vshCmdOptDef opts_save[] = {
809 810
    {"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")},
811
    {NULL, 0, 0, NULL}
812 813 814
};

static int
815 816
cmdSave(vshControl * ctl, vshCmd * cmd)
{
817 818 819 820
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
821

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

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

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

    if (virDomainSave(dom, to) == 0) {
832
        vshPrint(ctl, _("Domain %s saved to %s\n"), name, to);
833
    } else {
834
        vshError(ctl, FALSE, _("Failed to save domain %s to %s"), name, to);
835 836
        ret = FALSE;
    }
837

838 839 840 841 842 843 844 845
    virDomainFree(dom);
    return ret;
}

/*
 * "restore" command
 */
static vshCmdInfo info_restore[] = {
846
    {"syntax", "restore a domain from <file>"},
847 848
    {"help", gettext_noop("restore a domain from a saved state in a file")},
    {"desc", gettext_noop("Restore a domain.")},
849
    {NULL, NULL}
850 851 852
};

static vshCmdOptDef opts_restore[] = {
853
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("the state to restore")},
854
    {NULL, 0, 0, NULL}
855 856 857
};

static int
858 859
cmdRestore(vshControl * ctl, vshCmd * cmd)
{
860 861 862
    char *from;
    int found;
    int ret = TRUE;
863

864 865 866 867 868 869
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
872
        vshPrint(ctl, _("Domain restored from %s\n"), from);
873
    } else {
874
        vshError(ctl, FALSE, _("Failed to restore domain from %s"), from);
875 876 877 878 879
        ret = FALSE;
    }
    return ret;
}

D
Daniel Veillard 已提交
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
/*
 * "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;
}

925 926 927 928
/*
 * "resume" command
 */
static vshCmdInfo info_resume[] = {
929
    {"syntax", "resume <domain>"},
930 931
    {"help", gettext_noop("resume a domain")},
    {"desc", gettext_noop("Resume a previously suspended domain.")},
932
    {NULL, NULL}
933 934 935
};

static vshCmdOptDef opts_resume[] = {
936
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
937
    {NULL, 0, 0, NULL}
938 939 940
};

static int
941 942
cmdResume(vshControl * ctl, vshCmd * cmd)
{
943
    virDomainPtr dom;
K
Karel Zak 已提交
944 945
    int ret = TRUE;
    char *name;
946

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

K
Karel Zak 已提交
950
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
951
        return FALSE;
952 953

    if (virDomainResume(dom) == 0) {
954
        vshPrint(ctl, _("Domain %s resumed\n"), name);
955
    } else {
956
        vshError(ctl, FALSE, _("Failed to resume domain %s"), name);
957 958
        ret = FALSE;
    }
959

960 961 962 963
    virDomainFree(dom);
    return ret;
}

964 965 966 967
/*
 * "shutdown" command
 */
static vshCmdInfo info_shutdown[] = {
968
    {"syntax", "shutdown <domain>"},
969 970
    {"help", gettext_noop("gracefully shutdown a domain")},
    {"desc", gettext_noop("Run shutdown in the target domain.")},
971
    {NULL, NULL}
972 973 974
};

static vshCmdOptDef opts_shutdown[] = {
975
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
976
    {NULL, 0, 0, NULL}
977 978 979
};

static int
980 981
cmdShutdown(vshControl * ctl, vshCmd * cmd)
{
982 983 984
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
985

986 987 988 989 990
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainShutdown(dom) == 0) {
993
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
994
    } else {
995
        vshError(ctl, FALSE, _("Failed to shutdown domain %s"), name);
996 997
        ret = FALSE;
    }
998

999 1000 1001 1002
    virDomainFree(dom);
    return ret;
}

1003 1004 1005 1006 1007
/*
 * "reboot" command
 */
static vshCmdInfo info_reboot[] = {
    {"syntax", "reboot <domain>"},
1008 1009
    {"help", gettext_noop("reboot a domain")},
    {"desc", gettext_noop("Run a reboot command in the target domain.")},
1010 1011 1012 1013
    {NULL, NULL}
};

static vshCmdOptDef opts_reboot[] = {
1014
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    {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) {
1032
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
1033
    } else {
1034
        vshError(ctl, FALSE, _("Failed to reboot domain %s"), name);
1035 1036 1037 1038 1039 1040 1041
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1042 1043 1044 1045
/*
 * "destroy" command
 */
static vshCmdInfo info_destroy[] = {
1046
    {"syntax", "destroy <domain>"},
1047 1048
    {"help", gettext_noop("destroy a domain")},
    {"desc", gettext_noop("Destroy a given domain.")},
1049
    {NULL, NULL}
1050 1051 1052
};

static vshCmdOptDef opts_destroy[] = {
1053
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1054
    {NULL, 0, 0, NULL}
1055 1056 1057
};

static int
1058 1059
cmdDestroy(vshControl * ctl, vshCmd * cmd)
{
1060
    virDomainPtr dom;
K
Karel Zak 已提交
1061 1062
    int ret = TRUE;
    char *name;
1063

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

K
Karel Zak 已提交
1067
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1068
        return FALSE;
1069 1070

    if (virDomainDestroy(dom) == 0) {
1071
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
1072
    } else {
1073
        vshError(ctl, FALSE, _("Failed to destroy domain %s"), name);
1074 1075 1076
        ret = FALSE;
        virDomainFree(dom);
    }
1077

K
Karel Zak 已提交
1078 1079 1080 1081
    return ret;
}

/*
1082
 * "dominfo" command
K
Karel Zak 已提交
1083
 */
1084 1085
static vshCmdInfo info_dominfo[] = {
    {"syntax", "dominfo <domain>"},
1086 1087
    {"help", gettext_noop("domain information")},
    {"desc", gettext_noop("Returns basic information about the domain.")},
1088
    {NULL, NULL}
K
Karel Zak 已提交
1089 1090
};

1091
static vshCmdOptDef opts_dominfo[] = {
1092
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1093
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1094 1095 1096
};

static int
1097
cmdDominfo(vshControl * ctl, vshCmd * cmd)
1098
{
K
Karel Zak 已提交
1099 1100
    virDomainInfo info;
    virDomainPtr dom;
K
Karel Zak 已提交
1101
    int ret = TRUE;
1102
    unsigned int id;
1103
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
1104

K
Karel Zak 已提交
1105 1106 1107
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
1108
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
1109
        return FALSE;
1110

1111 1112
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1113
      vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
1114
    else
1115 1116 1117
      vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
1118
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
1119
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
1120 1121

    if ((str = virDomainGetOSType(dom))) {
1122
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
1123 1124 1125 1126
        free(str);
    }

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

1130
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
1131 1132

        if (info.cpuTime != 0) {
1133
	    double cpuUsed = info.cpuTime;
1134

1135
            cpuUsed /= 1000000000.0;
1136

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

1140
        vshPrint(ctl, "%-15s %lu kB\n", _("Max memory:"),
1141
                 info.maxMem);
1142
	vshPrint(ctl, "%-15s %lu kB\n", _("Used memory:"),
1143 1144
                 info.memory);

K
Karel Zak 已提交
1145 1146 1147
    } else {
        ret = FALSE;
    }
1148

1149
    virDomainFree(dom);
K
Karel Zak 已提交
1150 1151 1152
    return ret;
}

1153 1154 1155 1156 1157
/*
 * "vcpuinfo" command
 */
static vshCmdInfo info_vcpuinfo[] = {
    {"syntax", "vcpuinfo <domain>"},
1158 1159
    {"help", gettext_noop("domain vcpu information")},
    {"desc", gettext_noop("Returns basic information about the domain virtual CPUs.")},
1160 1161 1162 1163
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpuinfo[] = {
1164
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 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
    {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;
1206 1207 1208 1209
	    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)));
1210 1211 1212 1213 1214
	    if (cpuinfo[n].cpuTime != 0) {
	        double cpuUsed = cpuinfo[n].cpuTime;
		
		cpuUsed /= 1000000000.0;
		
1215
		vshPrint(ctl, "%-15s %.1lfs\n", _("CPU time:"), cpuUsed);
1216
	    }
1217
	    vshPrint(ctl, "%-15s ", _("CPU Affinity:"));
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
	    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>"},
1241 1242
    {"help", gettext_noop("control domain vcpu affinity")},
    {"desc", gettext_noop("Pin domain VCPUs to host physical CPUs.")},
1243 1244 1245 1246
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpupin[] = {
1247 1248 1249
    {"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)")},
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 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 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    {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;
}

1322 1323 1324 1325 1326
/*
 * "setvcpus" command
 */
static vshCmdInfo info_setvcpus[] = {
    {"syntax", "setvcpus <domain> <count>"},
1327 1328
    {"help", gettext_noop("change number of virtual CPUs")},
    {"desc", gettext_noop("Change the number of virtual CPUs active in the guest domain.")},
1329 1330 1331 1332
    {NULL, NULL}
};

static vshCmdOptDef opts_setvcpus[] = {
1333 1334
    {"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")},
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
    {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>"},
1370 1371
    {"help", gettext_noop("change memory allocation")},
    {"desc", gettext_noop("Change the current memory allocation in the guest domain.")},
1372 1373 1374 1375
    {NULL, NULL}
};

static vshCmdOptDef opts_setmem[] = {
1376 1377
    {"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")},
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
    {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>"},
1413 1414
    {"help", gettext_noop("change maximum memory limit")},
    {"desc", gettext_noop("Change the maximum memory allocation limit in the guest domain.")},
1415 1416 1417 1418
    {NULL, NULL}
};

static vshCmdOptDef opts_setmaxmem[] = {
1419 1420
    {"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")},
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    {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;
}

1451 1452 1453 1454 1455
/*
 * "nodeinfo" command
 */
static vshCmdInfo info_nodeinfo[] = {
    {"syntax", "nodeinfo"},
1456 1457
    {"help", gettext_noop("node information")},
    {"desc", gettext_noop("Returns basic information about the node.")},
1458 1459 1460 1461 1462 1463 1464
    {NULL, NULL}
};

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

1466 1467 1468 1469
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
        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);

1482 1483 1484
    return TRUE;
}

1485 1486 1487 1488
/*
 * "dumpxml" command
 */
static vshCmdInfo info_dumpxml[] = {
1489
    {"syntax", "dumpxml <name>"},
1490 1491
    {"help", gettext_noop("domain information in XML")},
    {"desc", gettext_noop("Ouput the domain information as an XML dump to stdout.")},
1492
    {NULL, NULL}
1493 1494 1495
};

static vshCmdOptDef opts_dumpxml[] = {
1496
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1497
    {NULL, 0, 0, NULL}
1498 1499 1500
};

static int
1501 1502
cmdDumpXML(vshControl * ctl, vshCmd * cmd)
{
1503
    virDomainPtr dom;
K
Karel Zak 已提交
1504
    int ret = TRUE;
1505
    char *dump;
1506

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

K
Karel Zak 已提交
1510
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
1511
        return FALSE;
1512

1513 1514 1515 1516 1517 1518 1519
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
1520

1521 1522 1523 1524
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
1525
/*
K
Karel Zak 已提交
1526
 * "domname" command
K
Karel Zak 已提交
1527
 */
K
Karel Zak 已提交
1528
static vshCmdInfo info_domname[] = {
K
Karel Zak 已提交
1529
    {"syntax", "domname <domain>"},
1530
    {"help", gettext_noop("convert a domain id or UUID to domain name")},
1531
    {NULL, NULL}
K
Karel Zak 已提交
1532 1533
};

K
Karel Zak 已提交
1534
static vshCmdOptDef opts_domname[] = {
1535
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or uuid")},
1536
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1537 1538 1539
};

static int
K
Karel Zak 已提交
1540
cmdDomname(vshControl * ctl, vshCmd * cmd)
1541
{
K
Karel Zak 已提交
1542 1543 1544 1545
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
K
Karel Zak 已提交
1546 1547
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL, 
                                    VSH_DOMBYID|VSH_DOMBYUUID)))
K
Karel Zak 已提交
1548
        return FALSE;
1549

K
Karel Zak 已提交
1550 1551
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
K
Karel Zak 已提交
1552 1553 1554 1555
    return TRUE;
}

/*
K
Karel Zak 已提交
1556
 * "domid" command
K
Karel Zak 已提交
1557
 */
K
Karel Zak 已提交
1558
static vshCmdInfo info_domid[] = {
K
Karel Zak 已提交
1559
    {"syntax", "domid <domain>"},
1560
    {"help", gettext_noop("convert a domain name or UUID to domain id")},
1561
    {NULL, NULL}
K
Karel Zak 已提交
1562 1563
};

K
Karel Zak 已提交
1564
static vshCmdOptDef opts_domid[] = {
1565
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
1566
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1567 1568 1569
};

static int
K
Karel Zak 已提交
1570
cmdDomid(vshControl * ctl, vshCmd * cmd)
1571
{
1572
    virDomainPtr dom;
1573
    unsigned int id;
K
Karel Zak 已提交
1574 1575 1576

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
K
Karel Zak 已提交
1577 1578
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL, 
                                    VSH_DOMBYNAME|VSH_DOMBYUUID)))
K
Karel Zak 已提交
1579
        return FALSE;
K
Karel Zak 已提交
1580
    
1581 1582 1583 1584 1585
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
      vshPrint(ctl, "%s\n", "-");
    else
      vshPrint(ctl, "%d\n", id);
K
Karel Zak 已提交
1586 1587 1588
    virDomainFree(dom);
    return TRUE;
}
1589

K
Karel Zak 已提交
1590 1591 1592 1593 1594
/*
 * "domuuid" command
 */
static vshCmdInfo info_domuuid[] = {
    {"syntax", "domuuid <domain>"},
1595
    {"help", gettext_noop("convert a domain name or id to domain UUID")},
K
Karel Zak 已提交
1596 1597 1598 1599
    {NULL, NULL}
};

static vshCmdOptDef opts_domuuid[] = {
1600
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or name")},
K
Karel Zak 已提交
1601 1602 1603 1604 1605 1606 1607
    {NULL, 0, 0, NULL}
};

static int
cmdDomuuid(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
1608
    char uuid[VIR_UUID_STRING_BUFLEN];
K
Karel Zak 已提交
1609 1610

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
K
Karel Zak 已提交
1611
        return FALSE;
1612
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
K
Karel Zak 已提交
1613 1614
                                    VSH_DOMBYNAME|VSH_DOMBYID)))
        return FALSE;
1615

K
Karel Zak 已提交
1616 1617 1618
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
1619 1620
        vshError(ctl, FALSE, _("failed to get domain UUID"));

K
Karel Zak 已提交
1621 1622 1623
    return TRUE;
}

K
Karel Zak 已提交
1624

1625 1626 1627 1628
/*
 * "version" command
 */
static vshCmdInfo info_version[] = {
1629
    {"syntax", "version"},
1630 1631
    {"help", gettext_noop("show version")},
    {"desc", gettext_noop("Display the system version information.")},
1632
    {NULL, NULL}
1633 1634 1635 1636
};


static int
1637 1638
cmdVersion(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
1639 1640
    unsigned long hvVersion;
    const char *hvType;
1641 1642 1643 1644 1645 1646 1647
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
1648 1649 1650

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

1652 1653
    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
1654
        vshError(ctl, FALSE, _("failed to get hypervisor type"));
1655 1656 1657
        return FALSE;
    }

1658 1659 1660 1661 1662
    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
1663
    vshPrint(ctl, _("Compiled against library: libvir %d.%d.%d\n"),
1664 1665 1666 1667
             major, minor, rel);

    ret = virGetVersion(&libVersion, hvType, &apiVersion);
    if (ret < 0) {
1668
        vshError(ctl, FALSE, _("failed to get the library version"));
1669 1670 1671 1672 1673 1674
        return FALSE;
    }
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
1675
    vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"),
1676
             major, minor, rel);
1677

1678 1679 1680 1681
    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
1682
    vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType,
1683 1684
             major, minor, rel);

1685
    ret = virConnectGetVersion(ctl->conn, &hvVersion);
1686
    if (ret < 0) {
1687
        vshError(ctl, FALSE, _("failed to get the hypervisor version"));
1688 1689 1690
        return FALSE;
    }
    if (hvVersion == 0) {
K
Karel Zak 已提交
1691
        vshPrint(ctl,
1692
                 _("Cannot extract running %s hypervisor version\n"), hvType);
1693
    } else {
1694
        major = hvVersion / 1000000;
1695
        hvVersion %= 1000000;
1696 1697
        minor = hvVersion / 1000;
        rel = hvVersion % 1000;
1698

1699
        vshPrint(ctl, _("Running hypervisor: %s %d.%d.%d\n"),
1700
                 hvType, major, minor, rel);
1701 1702 1703 1704
    }
    return TRUE;
}

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
/*
 * "dumpxml" command
 */
static vshCmdInfo info_vncdisplay[] = {
    {"syntax", "vncdisplay <domain>"},
    {"help", gettext_noop("vnc display")},
    {"desc", gettext_noop("Ouput the IP address and port number for the VNC display.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_vncdisplay[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
cmdVNCDisplay(vshControl * ctl, vshCmd * cmd)
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    int ret = FALSE;
    int port = 0;
    char *doc;

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

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

    doc = virDomainGetXMLDesc(dom, 0);
    if (!doc)
	goto cleanup;

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
		     XML_PARSE_NOENT | XML_PARSE_NONET |
		     XML_PARSE_NOWARNING);
    free(doc);
    if (!xml)
        goto cleanup;
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt)
        goto cleanup;

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@port)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
	(obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        goto cleanup;
    }
    port = strtol((const char *)obj->stringval, NULL, 10);
    if (port == -1) {
      goto cleanup;
    }
    xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@listen)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
	(obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        goto cleanup;
    }
    if (!strcmp((const char*)obj->stringval, "0.0.0.0")) {
        vshPrint(ctl, ":%d\n", port-5900);
    } else {
        vshPrint(ctl, "%s:%d\n", (const char *)obj->stringval, port-5900);
    }
    xmlXPathFreeObject(obj);
    obj = NULL;

 cleanup:
    if (obj)
      xmlXPathFreeObject(obj);
    if (ctxt)
        xmlXPathFreeContext(ctxt);
    if (xml)
        xmlFreeDoc(xml);
    virDomainFree(dom);
    return ret;
}


K
Karel Zak 已提交
1787 1788 1789 1790
/*
 * "quit" command
 */
static vshCmdInfo info_quit[] = {
1791
    {"syntax", "quit"},
1792
    {"help", gettext_noop("quit this interactive terminal")},
1793
    {NULL, NULL}
K
Karel Zak 已提交
1794 1795 1796
};

static int
1797 1798
cmdQuit(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
1799 1800 1801 1802 1803 1804 1805 1806
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
static vshCmdDef commands[] = {
1807
    {"connect", cmdConnect, opts_connect, info_connect},
1808
    {"console", cmdConsole, opts_console, info_console},
1809
    {"create", cmdCreate, opts_create, info_create},
1810
    {"start", cmdStart, opts_start, info_start},
K
Karel Zak 已提交
1811
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
1812
    {"define", cmdDefine, opts_define, info_define},
K
Karel Zak 已提交
1813
    {"domid", cmdDomid, opts_domid, info_domid},
K
Karel Zak 已提交
1814
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid},
1815
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
1816 1817
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
1818
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
K
Karel Zak 已提交
1819
    {"help", cmdHelp, opts_help, info_help},
1820
    {"list", cmdList, opts_list, info_list},
K
Karel Zak 已提交
1821 1822 1823 1824
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
    {"quit", cmdQuit, NULL, info_quit},
    {"reboot", cmdReboot, opts_reboot, info_reboot},
    {"restore", cmdRestore, opts_restore, info_restore},
1825 1826
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
D
Daniel Veillard 已提交
1827
    {"dump", cmdDump, opts_dump, info_dump},
1828
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
1829 1830 1831
    {"setmem", cmdSetmem, opts_setmem, info_setmem},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus},
K
Karel Zak 已提交
1832
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
1833
    {"undefine", cmdUndefine, opts_undefine, info_undefine},
1834 1835
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
1836
    {"version", cmdVersion, NULL, info_version},
1837
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay},
1838
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
1839 1840 1841 1842 1843 1844
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
1845
static const char *
1846 1847
vshCmddefGetInfo(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1848
    vshCmdInfo *info;
1849

K
Karel Zak 已提交
1850
    for (info = cmd->info; info && info->name; info++) {
1851
        if (strcmp(info->name, name) == 0)
K
Karel Zak 已提交
1852 1853 1854 1855 1856 1857
            return info->data;
    }
    return NULL;
}

static vshCmdOptDef *
1858 1859
vshCmddefGetOption(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
1860
    vshCmdOptDef *opt;
1861

K
Karel Zak 已提交
1862
    for (opt = cmd->opts; opt && opt->name; opt++)
1863
        if (strcmp(opt->name, name) == 0)
K
Karel Zak 已提交
1864 1865 1866 1867 1868
            return opt;
    return NULL;
}

static vshCmdOptDef *
1869 1870
vshCmddefGetData(vshCmdDef * cmd, int data_ct)
{
K
Karel Zak 已提交
1871 1872
    vshCmdOptDef *opt;

1873
    for (opt = cmd->opts; opt && opt->name; opt++) {
1874 1875
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
1876 1877 1878 1879 1880
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
1881 1882 1883
    return NULL;
}

1884 1885 1886
/*
 * Checks for required options
 */
1887 1888
static int
vshCommandCheckOpts(vshControl * ctl, vshCmd * cmd)
1889 1890 1891
{
    vshCmdDef *def = cmd->def;
    vshCmdOptDef *d;
1892
    int err = 0;
1893 1894 1895 1896

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

            while (o && ok == 0) {
1900
                if (o->def == d)
1901
                    ok = 1;
1902 1903 1904
                o = o->next;
            }
            if (!ok) {
1905 1906
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
1907 1908
                         _("command '%s' requires <%s> option") :
			 _("command '%s' requires --%s option"),
1909
                         def->name, d->name);
1910 1911
                err = 1;
            }
1912

1913 1914 1915 1916 1917
        }
    }
    return !err;
}

K
Karel Zak 已提交
1918
static vshCmdDef *
1919 1920
vshCmddefSearch(const char *cmdname)
{
K
Karel Zak 已提交
1921
    vshCmdDef *c;
1922

K
Karel Zak 已提交
1923
    for (c = commands; c->name; c++)
1924
        if (strcmp(c->name, cmdname) == 0)
K
Karel Zak 已提交
1925 1926 1927 1928 1929
            return c;
    return NULL;
}

static int
1930 1931
vshCmddefHelp(vshControl * ctl, const char *cmdname, int withprog)
{
K
Karel Zak 已提交
1932
    vshCmdDef *def = vshCmddefSearch(cmdname);
1933

K
Karel Zak 已提交
1934
    if (!def) {
1935
        vshError(ctl, FALSE, _("command '%s' doesn't exist"), cmdname);
1936 1937
        return FALSE;
    } else {
K
Karel Zak 已提交
1938
        vshCmdOptDef *opt;
1939 1940
        const char *desc = _N(vshCmddefGetInfo(def, "desc"));
        const char *help = _N(vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
1941
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
1942

1943
        fputs(_("  NAME\n"), stdout);
1944 1945
        fprintf(stdout, "    %s - %s\n", def->name, help);

K
Karel Zak 已提交
1946
        if (syntax) {
1947
            fputs(("\n  SYNOPSIS\n"), stdout);
K
Karel Zak 已提交
1948 1949 1950 1951 1952 1953
            if (!withprog)
                fprintf(stdout, "    %s\n", syntax);
            else
                fprintf(stdout, "    %s %s\n", progname, syntax);
        }
        if (desc) {
1954
            fputs(_("\n  DESCRIPTION\n"), stdout);
K
Karel Zak 已提交
1955 1956 1957
            fprintf(stdout, "    %s\n", desc);
        }
        if (def->opts) {
1958
            fputs(_("\n  OPTIONS\n"), stdout);
1959
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
1960
                char buf[256];
1961 1962

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
1963
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1964
                else if (opt->type == VSH_OT_INT)
1965
                    snprintf(buf, sizeof(buf), _("--%s <number>"), opt->name);
1966
                else if (opt->type == VSH_OT_STRING)
1967
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1968
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
1969
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
1970

K
Karel Zak 已提交
1971
                fprintf(stdout, "    %-15s  %s\n", buf, opt->help);
1972
            }
K
Karel Zak 已提交
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1983 1984 1985
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1986 1987
    vshCmdOpt *a = arg;

1988
    while (a) {
K
Karel Zak 已提交
1989
        vshCmdOpt *tmp = a;
1990

K
Karel Zak 已提交
1991 1992 1993 1994 1995 1996 1997 1998 1999
        a = a->next;

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

static void
2000 2001
vshCommandFree(vshCmd * cmd)
{
K
Karel Zak 已提交
2002 2003
    vshCmd *c = cmd;

2004
    while (c) {
K
Karel Zak 已提交
2005
        vshCmd *tmp = c;
2006

K
Karel Zak 已提交
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
2019 2020
vshCommandOpt(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
2021
    vshCmdOpt *opt = cmd->opts;
2022 2023 2024

    while (opt) {
        if (opt->def && strcmp(opt->def->name, name) == 0)
K
Karel Zak 已提交
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
2035 2036
vshCommandOptInt(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
2037 2038
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
    int res = 0;
2039

K
Karel Zak 已提交
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
    if (arg)
        res = atoi(arg->data);
    if (found)
        *found = arg ? TRUE : FALSE;
    return res;
}

/*
 * Returns option as STRING
 */
static char *
2051 2052
vshCommandOptString(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
2053
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
2054

K
Karel Zak 已提交
2055 2056
    if (found)
        *found = arg ? TRUE : FALSE;
2057 2058

    return arg && arg->data && *arg->data ? arg->data : NULL;
K
Karel Zak 已提交
2059 2060 2061 2062 2063 2064
}

/*
 * Returns TRUE/FALSE if the option exists
 */
static int
2065 2066
vshCommandOptBool(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
2067 2068 2069
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

2070

K
Karel Zak 已提交
2071
static virDomainPtr
K
Karel Zak 已提交
2072 2073
vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd, const char *optname,
                    char **name, int flag)
2074
{
K
Karel Zak 已提交
2075 2076 2077
    virDomainPtr dom = NULL;
    char *n, *end = NULL;
    int id;
2078

K
Karel Zak 已提交
2079
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
2080
        vshError(ctl, FALSE, _("undefined domain name or id"));
2081
        return NULL;
K
Karel Zak 已提交
2082
    }
2083

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

K
Karel Zak 已提交
2087 2088
    if (name)
        *name = n;
2089

K
Karel Zak 已提交
2090
    /* try it by ID */
K
Karel Zak 已提交
2091 2092 2093 2094 2095 2096 2097
    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);
        }
2098
    }
K
Karel Zak 已提交
2099
    /* try it by UUID */
2100
    if (dom==NULL && (flag & VSH_DOMBYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
K
Karel Zak 已提交
2101 2102
        vshDebug(ctl, 5, "%s: <%s> tring as domain UUID\n",
                cmd->def->name, optname);
K
Karel Zak 已提交
2103
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
2104
    }
K
Karel Zak 已提交
2105
    /* try it by NAME */
K
Karel Zak 已提交
2106
    if (dom==NULL && (flag & VSH_DOMBYNAME)) {
K
Karel Zak 已提交
2107
        vshDebug(ctl, 5, "%s: <%s> tring as domain NAME\n",
2108
                 cmd->def->name, optname);
K
Karel Zak 已提交
2109
        dom = virDomainLookupByName(ctl->conn, n);
2110
    }
K
Karel Zak 已提交
2111

2112
    if (!dom)
2113
        vshError(ctl, FALSE, _("failed to get domain '%s'"), n);
2114

K
Karel Zak 已提交
2115 2116 2117
    return dom;
}

K
Karel Zak 已提交
2118 2119 2120 2121
/*
 * Executes command(s) and returns return code from last command
 */
static int
2122 2123
vshCommandRun(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
2124
    int ret = TRUE;
2125 2126

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

K
Karel Zak 已提交
2129 2130
        if (ctl->timing)
            GETTIMEOFDAY(&before);
2131

K
Karel Zak 已提交
2132 2133 2134 2135
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
2136 2137

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

        if (ctl->timing)
2141
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
2142 2143
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
2144
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
        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

2160 2161 2162
static int
vshCommandGetToken(vshControl * ctl, char *str, char **end, char **res)
{
K
Karel Zak 已提交
2163 2164 2165 2166 2167
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
2168

K
Karel Zak 已提交
2169
    *end = NULL;
2170 2171

    while (p && *p && isblank((unsigned char) *p))
K
Karel Zak 已提交
2172
        p++;
2173 2174

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
2175
        return VSH_TK_END;
2176 2177
    if (*p == ';') {
        *end = ++p;             /* = \0 or begi of next command */
K
Karel Zak 已提交
2178 2179
        return VSH_TK_END;
    }
2180
    while (*p) {
K
Karel Zak 已提交
2181
        /* end of token is blank space or ';' */
2182
        if ((quote == FALSE && isblank((unsigned char) *p)) || *p == ';')
K
Karel Zak 已提交
2183
            break;
2184

2185
        /* end of option name could be '=' */
2186 2187
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
2188 2189
            break;
        }
2190 2191 2192 2193

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
                && isalnum((unsigned char) *(p + 2))) {
K
Karel Zak 已提交
2194
                tk = VSH_TK_OPTION;
2195
                p += 2;
K
Karel Zak 已提交
2196 2197
            } else {
                tk = VSH_TK_DATA;
2198 2199
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
2200 2201 2202 2203 2204
                    p++;
                } else {
                    quote = FALSE;
                }
            }
2205 2206
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
2207 2208
            quote = FALSE;
            p++;
2209
            break;              /* end of "..." token */
K
Karel Zak 已提交
2210 2211 2212 2213 2214
        }
        p++;
        sz++;
    }
    if (quote) {
2215
        vshError(ctl, FALSE, _("missing \""));
K
Karel Zak 已提交
2216 2217
        return VSH_TK_ERROR;
    }
2218
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
2219
        return VSH_TK_END;
2220
    if (sz == 0)
K
Karel Zak 已提交
2221
        return VSH_TK_END;
2222

2223
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
2224
    memcpy(*res, tkstr, sz);
2225
    *(*res + sz) = '\0';
K
Karel Zak 已提交
2226 2227 2228 2229 2230 2231

    *end = p;
    return tk;
}

static int
2232 2233
vshCommandParse(vshControl * ctl, char *cmdstr)
{
K
Karel Zak 已提交
2234 2235 2236 2237
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
2238

K
Karel Zak 已提交
2239 2240 2241 2242
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
2243 2244

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

K
Karel Zak 已提交
2247
    str = cmdstr;
2248
    while (str && *str) {
K
Karel Zak 已提交
2249 2250 2251
        vshCmdOpt *last = NULL;
        vshCmdDef *cmd = NULL;
        int tk = VSH_TK_NONE;
2252
        int data_ct = 0;
2253

K
Karel Zak 已提交
2254
        first = NULL;
2255 2256

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
2257 2258
            char *end = NULL;
            vshCmdOptDef *opt = NULL;
2259

K
Karel Zak 已提交
2260
            tkdata = NULL;
2261

K
Karel Zak 已提交
2262 2263
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
2264

K
Karel Zak 已提交
2265
            str = end;
2266 2267

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
2268
                break;
2269
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2270
                goto syntaxError;
2271 2272

            if (cmd == NULL) {
K
Karel Zak 已提交
2273
                /* first token must be command name */
2274 2275
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
2276
                             _("unexpected token (command name): '%s'"),
2277
                             tkdata);
K
Karel Zak 已提交
2278 2279 2280
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
2281
                    vshError(ctl, FALSE, _("unknown command: '%s'"), tkdata);
2282
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
2283 2284
                }
                free(tkdata);
2285
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
2286 2287
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
2288
                             _("command '%s' doesn't support option --%s"),
2289
                             cmd->name, tkdata);
K
Karel Zak 已提交
2290 2291
                    goto syntaxError;
                }
2292
                free(tkdata);   /* option name */
K
Karel Zak 已提交
2293 2294 2295 2296 2297
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
2298 2299
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2300
                        goto syntaxError;
2301
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
2302
                        vshError(ctl, FALSE,
2303
                                 _("expected syntax: --%s <%s>"),
2304 2305
                                 opt->name,
                                 opt->type ==
2306
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
2307 2308 2309
                        goto syntaxError;
                    }
                }
2310
            } else if (tk == VSH_TK_DATA) {
2311
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
2312
                    vshError(ctl, FALSE, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
2313 2314 2315 2316 2317
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
2318
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
2319

K
Karel Zak 已提交
2320 2321 2322 2323
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
2324

K
Karel Zak 已提交
2325 2326 2327 2328 2329
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
2330

K
Karel Zak 已提交
2331
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
2332 2333
                         cmd->name,
                         opt->name,
2334
                         tk == VSH_TK_OPTION ? _("OPTION") : _("DATA"),
2335
                         arg->data);
K
Karel Zak 已提交
2336 2337 2338 2339
            }
            if (!str)
                break;
        }
2340

K
Karel Zak 已提交
2341 2342
        /* commad parsed -- allocate new struct for the command */
        if (cmd) {
2343
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
2344

K
Karel Zak 已提交
2345 2346 2347 2348
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

2349 2350
            if (!vshCommandCheckOpts(ctl, c))
                goto syntaxError;
2351

K
Karel Zak 已提交
2352 2353 2354 2355 2356 2357 2358
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
2359

K
Karel Zak 已提交
2360 2361
    return TRUE;

2362
  syntaxError:
K
Karel Zak 已提交
2363 2364 2365 2366 2367 2368
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
    if (tkdata)
        free(tkdata);
2369
    return FALSE;
K
Karel Zak 已提交
2370 2371 2372 2373 2374 2375 2376
}


/* ---------------
 * Misc utils  
 * ---------------
 */
K
Karel Zak 已提交
2377
static const char *
2378 2379
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
2380 2381
    switch (state) {
        case VIR_DOMAIN_RUNNING:
2382
            return gettext_noop("running");
K
Karel Zak 已提交
2383
        case VIR_DOMAIN_BLOCKED:
2384
            return gettext_noop("blocked");
K
Karel Zak 已提交
2385
        case VIR_DOMAIN_PAUSED:
2386
            return gettext_noop("paused");
K
Karel Zak 已提交
2387
        case VIR_DOMAIN_SHUTDOWN:
2388
            return gettext_noop("in shutdown");
K
Karel Zak 已提交
2389
        case VIR_DOMAIN_SHUTOFF:
2390
            return gettext_noop("shut off");
K
Karel Zak 已提交
2391
        case VIR_DOMAIN_CRASHED:
2392
            return gettext_noop("crashed");
K
Karel Zak 已提交
2393
        default:
2394
            return gettext_noop("no state");  /* = dom0 state */
K
Karel Zak 已提交
2395 2396 2397 2398
    }
    return NULL;
}

2399 2400 2401 2402 2403
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
        case VIR_VCPU_OFFLINE:
2404
            return gettext_noop("offline");
2405
        case VIR_VCPU_BLOCKED:
2406
            return gettext_noop("blocked");
2407
        case VIR_VCPU_RUNNING:
2408
            return gettext_noop("running");
2409
        default:
2410
            return gettext_noop("no state");
2411 2412 2413 2414
    }
    return NULL;
}

K
Karel Zak 已提交
2415
static int
2416 2417
vshConnectionUsability(vshControl * ctl, virConnectPtr conn, int showerror)
{
K
Karel Zak 已提交
2418 2419 2420 2421 2422
    /* TODO: use something like virConnectionState() to 
     *       check usability of the connection 
     */
    if (!conn) {
        if (showerror)
2423
            vshError(ctl, FALSE, _("no valid connection"));
K
Karel Zak 已提交
2424 2425 2426 2427 2428
        return FALSE;
    }
    return TRUE;
}

K
Karel Zak 已提交
2429 2430
static void
vshDebug(vshControl * ctl, int level, const char *format, ...)
2431
{
K
Karel Zak 已提交
2432 2433 2434 2435 2436 2437 2438 2439
    va_list ap;

    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
2440 2441 2442
}

static void
K
Karel Zak 已提交
2443
vshPrintExtra(vshControl * ctl, const char *format, ...)
2444
{
K
Karel Zak 已提交
2445
    va_list ap;
2446

K
Karel Zak 已提交
2447
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
2448
        return;
2449

K
Karel Zak 已提交
2450
    va_start(ap, format);
2451
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
2452 2453 2454
    va_end(ap);
}

K
Karel Zak 已提交
2455

K
Karel Zak 已提交
2456
static void
2457 2458
vshError(vshControl * ctl, int doexit, const char *format, ...)
{
K
Karel Zak 已提交
2459
    va_list ap;
2460

K
Karel Zak 已提交
2461
    if (doexit)
2462
        fprintf(stderr, _("%s: error: "), progname);
K
Karel Zak 已提交
2463
    else
2464
        fputs(_("error: "), stderr);
2465

K
Karel Zak 已提交
2466 2467 2468 2469 2470
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
2471

K
Karel Zak 已提交
2472
    if (doexit) {
2473 2474
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
2475 2476 2477 2478
        exit(EXIT_FAILURE);
    }
}

2479 2480 2481 2482 2483 2484 2485
static void *
_vshMalloc(vshControl * ctl, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = malloc(size)))
        return x;
2486 2487
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
	     filename, line, (int) size);
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
    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;
2498 2499
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
	     filename, line, (int) (size*nmemb));
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
    return NULL;
}

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

    if ((x = strdup(s)))
        return x;
2510 2511
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
	     filename, line, strlen(s));
2512 2513 2514
    return NULL;
}

K
Karel Zak 已提交
2515 2516 2517 2518
/*
 * Initialize vistsh
 */
static int
2519 2520
vshInit(vshControl * ctl)
{
K
Karel Zak 已提交
2521 2522 2523 2524
    if (ctl->conn)
        return FALSE;

    ctl->uid = getuid();
2525

2526 2527
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2528

2529 2530 2531 2532
    /* 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 已提交
2533
        ctl->conn = virConnectOpen(ctl->name);
K
Karel Zak 已提交
2534
    else
K
Karel Zak 已提交
2535
        ctl->conn = virConnectOpenReadOnly(ctl->name);
2536

K
Karel Zak 已提交
2537
    if (!ctl->conn)
2538
        vshError(ctl, TRUE, _("failed to connect to the hypervisor"));
K
Karel Zak 已提交
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553

    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 *
2554 2555
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2556
    static int list_index, len;
K
Karel Zak 已提交
2557
    const char *name;
K
Karel Zak 已提交
2558 2559 2560 2561 2562 2563 2564

    /* 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;
2565
        len = strlen(text);
K
Karel Zak 已提交
2566 2567 2568 2569 2570
    }

    /* Return the next name which partially matches from the
     * command list. 
     */
K
Karel Zak 已提交
2571
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
2572
        list_index++;
2573
        if (strncmp(name, text, len) == 0)
2574
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
2575 2576 2577 2578 2579 2580 2581
    }

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

static char *
2582 2583
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2584 2585
    static int list_index, len;
    static vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2586
    const char *name;
K
Karel Zak 已提交
2587 2588 2589 2590 2591 2592 2593 2594 2595

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

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

2596
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2597
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2598 2599 2600

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2601
        len = strlen(text);
K
Karel Zak 已提交
2602 2603 2604 2605 2606
        free(cmdname);
    }

    if (!cmd)
        return NULL;
2607

K
Karel Zak 已提交
2608
    while ((name = cmd->opts[list_index].name)) {
K
Karel Zak 已提交
2609 2610
        vshCmdOptDef *opt = &cmd->opts[list_index];
        char *res;
2611

K
Karel Zak 已提交
2612
        list_index++;
2613

K
Karel Zak 已提交
2614
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
2615 2616
            /* ignore non --option */
            continue;
2617

K
Karel Zak 已提交
2618
        if (len > 2) {
2619
            if (strncmp(name, text + 2, len - 2))
K
Karel Zak 已提交
2620 2621
                continue;
        }
2622
        res = vshMalloc(NULL, strlen(name) + 3);
K
Karel Zak 已提交
2623 2624 2625 2626 2627 2628 2629 2630 2631
        sprintf(res, "--%s", name);
        return res;
    }

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

static char **
2632 2633 2634
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2635 2636
    char **matches = (char **) NULL;

2637
    if (start == 0)
K
Karel Zak 已提交
2638
        /* command name generator */
2639
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2640 2641
    else
        /* commands options */
2642
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2643 2644 2645 2646 2647
    return matches;
}


static void
2648 2649
vshReadlineInit(void)
{
K
Karel Zak 已提交
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
    /* 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
2661 2662
vshDeinit(vshControl * ctl)
{
K
Karel Zak 已提交
2663
    if (ctl->conn) {
2664 2665 2666 2667
        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 已提交
2668 2669 2670 2671
        }
    }
    return TRUE;
}
2672

K
Karel Zak 已提交
2673 2674 2675 2676
/*
 * Print usage
 */
static void
2677 2678
vshUsage(vshControl * ctl, const char *cmdname)
{
K
Karel Zak 已提交
2679
    vshCmdDef *cmd;
2680

K
Karel Zak 已提交
2681 2682
    /* global help */
    if (!cmdname) {
2683 2684 2685 2686 2687 2688 2689 2690 2691
        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);
2692 2693 2694

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

        fprintf(stdout,
2699
                _("\n  (specify --help <command> for details about the command)\n\n"));
K
Karel Zak 已提交
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
2711 2712
vshParseArgv(vshControl * ctl, int argc, char **argv)
{
K
Karel Zak 已提交
2713 2714
    char *last = NULL;
    int i, end = 0, help = 0;
2715
    int arg, idx = 0;
K
Karel Zak 已提交
2716
    struct option opt[] = {
2717 2718 2719 2720 2721
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
2722
        {"connect", 1, 0, 'c'},
K
Karel Zak 已提交
2723
        {0, 0, 0, 0}
2724 2725
    };

K
Karel Zak 已提交
2726 2727

    if (argc < 2)
K
Karel Zak 已提交
2728
        return TRUE;
2729

2730
    /* look for begin of the command, for example:
K
Karel Zak 已提交
2731 2732 2733 2734
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
2735
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
2736 2737
        if (*argv[i] != '-') {
            int valid = FALSE;
2738

K
Karel Zak 已提交
2739 2740 2741 2742
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
2743 2744 2745

                for (o = opt; o->name; o++) {
                    if (sz == 2 && *(last + 1) == o->val)
K
Karel Zak 已提交
2746 2747
                        /* valid virsh short option */
                        valid = TRUE;
2748
                    else if (sz > 2 && strcmp(o->name, last + 2) == 0)
K
Karel Zak 已提交
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
                        /* valid virsh long option */
                        valid = TRUE;
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
    end = end ? : argc;
2761

K
Karel Zak 已提交
2762
    /* standard (non-command) options */
2763
    while ((arg = getopt_long(end, argv, "d:hqtcv", opt, &idx)) != -1) {
2764
        switch (arg) {
K
Karel Zak 已提交
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
            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 已提交
2777 2778 2779
            case 'c':
                ctl->name = vshStrdup(ctl, optarg);
                break;
K
Karel Zak 已提交
2780 2781 2782 2783
            case 'v':
                fprintf(stdout, "%s\n", VERSION);
                exit(EXIT_SUCCESS);
            default:
2784
                vshError(ctl, TRUE,
2785
			 _("unsupported option '-%c'. See --help."), arg);
K
Karel Zak 已提交
2786 2787 2788 2789 2790 2791 2792 2793
                break;
        }
    }

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

K
Karel Zak 已提交
2796 2797 2798
    if (argc > end) {
        /* parse command */
        char *cmdstr;
2799 2800
        int sz = 0, ret;

K
Karel Zak 已提交
2801 2802
        ctl->imode = FALSE;

2803 2804 2805
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

2806
        cmdstr = vshCalloc(ctl, sz + 1, 1);
2807 2808

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
2809 2810 2811 2812
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
2813
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
2814
        ret = vshCommandParse(ctl, cmdstr);
2815

K
Karel Zak 已提交
2816 2817 2818 2819 2820 2821
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

2822 2823 2824 2825
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
2826
    char *defaultConn;
K
Karel Zak 已提交
2827 2828
    int ret = TRUE;

2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
    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;
    }

2842
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
2843 2844 2845
        progname = argv[0];
    else
        progname++;
2846

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

2850 2851 2852 2853
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
      ctl->name = strdup(defaultConn);
    }

K
Karel Zak 已提交
2854 2855
    if (!vshParseArgv(ctl, argc, argv))
        exit(EXIT_FAILURE);
2856

K
Karel Zak 已提交
2857 2858
    if (!vshInit(ctl))
        exit(EXIT_FAILURE);
2859

K
Karel Zak 已提交
2860
    if (!ctl->imode) {
2861
        ret = vshCommandRun(ctl, ctl->cmd);
2862
    } else {
K
Karel Zak 已提交
2863 2864
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
2865
            vshPrint(ctl,
2866
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
2867
                     progname);
K
Karel Zak 已提交
2868
            vshPrint(ctl,
2869 2870
                     _("Type:  'help' for help with commands\n"
		       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
2871
        }
K
Karel Zak 已提交
2872
        vshReadlineInit();
K
Karel Zak 已提交
2873
        do {
2874 2875 2876 2877
            ctl->cmdstr =
                readline(ctl->uid == 0 ? VSH_PROMPT_RW : VSH_PROMPT_RO);
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
2878 2879 2880 2881 2882 2883 2884
            if (*ctl->cmdstr) {
                add_history(ctl->cmdstr);
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
2885
        } while (ctl->imode);
K
Karel Zak 已提交
2886

2887 2888
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
2889
    }
2890

K
Karel Zak 已提交
2891 2892
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
2893
}
K
Karel Zak 已提交
2894 2895 2896 2897 2898 2899

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