virsh.c 124.5 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 17
#include "libvirt/libvirt.h"
#include "libvirt/virterror.h"
18
#include <stdio.h>
K
Karel Zak 已提交
19 20 21
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
22
#include <unistd.h>
23
#include <errno.h>
K
Karel Zak 已提交
24
#include <getopt.h>
25
#include <sys/types.h>
K
Karel Zak 已提交
26
#include <sys/time.h>
K
Karel Zak 已提交
27
#include <ctype.h>
28
#include <fcntl.h>
29
#include <locale.h>
30
#include <limits.h>
31
#include <assert.h>
32 33
#include <errno.h>
#include <sys/stat.h>
K
Karel Zak 已提交
34

35 36 37 38
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

K
Karel Zak 已提交
39 40 41 42
#include <readline/readline.h>
#include <readline/history.h>

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

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)

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/**
 * The log configuration
 */
#define MSG_BUFFER    4096
#define SIGN_NAME     "virsh"
#define DIR_MODE      (S_IWUSR | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)  /* 0755 */
#define FILE_MODE     (S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH)                                /* 0644 */
#define LOCK_MODE     (S_IWUSR | S_IRUSR)                                                    /* 0600 */
#define LVL_DEBUG     "DEBUG"
#define LVL_INFO      "INFO"
#define LVL_NOTICE    "NOTICE"
#define LVL_WARNING   "WARNING"
#define LVL_ERROR     "ERROR"

/**
 * vshErrorLevel:
 *
 * Indicates the level of an log message
 */
typedef enum {
    VSH_ERR_DEBUG = 0,
    VSH_ERR_INFO,
    VSH_ERR_NOTICE,
    VSH_ERR_WARNING,
    VSH_ERR_ERROR
} vshErrorLevel;

88 89 90 91
/*
 * The error handler for virtsh
 */
static void
92 93
virshErrorHandler(void *unused, virErrorPtr error)
{
94 95 96 97 98 99 100 101 102 103
    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 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116
/*
 * 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>
117
 *
118 119 120
 *    keyword         =     [a-zA-Z]
 *    number          =     [0-9]+
 *    string          =     [^[:blank:]] | "[[:alnum:]]"$
K
Karel Zak 已提交
121 122 123 124
 *
 */

/*
125
 * vshCmdOptType - command option type
126
 */
K
Karel Zak 已提交
127
typedef enum {
128 129 130 131 132
    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 已提交
133 134 135 136 137
} vshCmdOptType;

/*
 * Command Option Flags
 */
138 139
#define VSH_OFLAG_NONE    0     /* without flags */
#define VSH_OFLAG_REQ    (1 << 1)       /* option required */
K
Karel Zak 已提交
140 141 142 143 144 145 146 147

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

/*
 * vshCmdInfo -- information about command
 */
148 149 150
typedef struct {
    const char *name;           /* name of information */
    const char *data;           /* information */
K
Karel Zak 已提交
151 152 153 154 155
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
156 157 158 159 160
typedef struct {
    const char *name;           /* the name of option */
    vshCmdOptType type;         /* option type */
    int flag;                   /* flags */
    const char *help;           /* help string */
K
Karel Zak 已提交
161 162 163 164 165 166
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
 */
typedef struct vshCmdOpt {
167 168 169
    vshCmdOptDef *def;          /* pointer to relevant option */
    char *data;                 /* allocated data */
    struct vshCmdOpt *next;
K
Karel Zak 已提交
170 171 172 173 174
} vshCmdOpt;

/*
 * vshCmdDef - command definition
 */
175 176 177 178 179
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 已提交
180 181 182 183 184 185
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
186 187 188
    vshCmdDef *def;             /* command definition */
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
189 190 191 192 193 194
} __vshCmd;

/*
 * vshControl
 */
typedef struct __vshControl {
K
Karel Zak 已提交
195
    char *name;                 /* connection name */
196
    virConnectPtr conn;         /* connection to hypervisor (MAY BE NULL) */
197 198 199 200 201 202 203
    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? */
204 205 206
    int readonly;               /* connect readonly (first time only, not
                                 * during explicit connect command)
                                 */
207 208
    char *logfile;              /* log file name */
    int log_fd;                 /* log file descriptor */
K
Karel Zak 已提交
209
} __vshControl;
210

211

K
Karel Zak 已提交
212 213
static vshCmdDef commands[];

214 215
static void vshError(vshControl * ctl, int doexit, const char *format, ...)
    ATTRIBUTE_FORMAT(printf, 3, 4);
216 217 218
static int vshInit(vshControl * ctl);
static int vshDeinit(vshControl * ctl);
static void vshUsage(vshControl * ctl, const char *cmdname);
219 220 221
static void vshOpenLogFile(vshControl *ctl);
static void vshOutputLogFile(vshControl *ctl, int log_level, const char *format, va_list ap);
static void vshCloseLogFile(vshControl *ctl);
K
Karel Zak 已提交
222

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

225
static const char *vshCmddefGetInfo(vshCmdDef * cmd, const char *info);
K
Karel Zak 已提交
226
static vshCmdDef *vshCmddefSearch(const char *cmdname);
227
static int vshCmddefHelp(vshControl * ctl, const char *name, int withprog);
K
Karel Zak 已提交
228

229 230 231 232 233
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 已提交
234

235 236 237
#define VSH_BYID     (1 << 1)
#define VSH_BYUUID   (1 << 2)
#define VSH_BYNAME   (1 << 3)
K
Karel Zak 已提交
238 239

static virDomainPtr vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd,
240
                                          const char *optname, char **name, int flag);
K
Karel Zak 已提交
241 242

/* default is lookup by Id, Name and UUID */
243 244
#define vshCommandOptDomain(_ctl, _cmd, _optname, _name)            \
    vshCommandOptDomainBy(_ctl, _cmd, _optname, _name,              \
245 246
                          VSH_BYID|VSH_BYUUID|VSH_BYNAME)

247 248 249 250 251 252 253 254
static virNetworkPtr vshCommandOptNetworkBy(vshControl * ctl, vshCmd * cmd,
                            const char *optname, char **name, int flag);

/* default is lookup by Name and UUID */
#define vshCommandOptNetwork(_ctl, _cmd, _optname, _name)           \
    vshCommandOptNetworkBy(_ctl, _cmd, _optname, _name,             \
                           VSH_BYUUID|VSH_BYNAME)

K
Karel Zak 已提交
255 256
static void vshPrintExtra(vshControl * ctl, const char *format, ...);
static void vshDebug(vshControl * ctl, int level, const char *format, ...);
K
Karel Zak 已提交
257 258

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

K
Karel Zak 已提交
261
static const char *vshDomainStateToString(int state);
262
static const char *vshDomainVcpuStateToString(int state);
263 264
static int vshConnectionUsability(vshControl * ctl, virConnectPtr conn,
                                  int showerror);
K
Karel Zak 已提交
265

266 267 268 269 270 271
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__)

272 273 274
static void *_vshRealloc(vshControl * ctl, void *ptr, size_t sz, const char *filename, int line);
#define vshRealloc(_ctl, _ptr, _sz)    _vshRealloc(_ctl, _ptr, _sz, __FILE__, __LINE__)

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

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

static int idsorter(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 namesorter(const void *a, const void *b) {
  const char **sa = (const char**)a;
  const char **sb = (const char**)b;

  return strcasecmp(*sa, *sb);
}


K
Karel Zak 已提交
297 298 299 300 301 302
/* ---------------
 * Commands
 * ---------------
 */

/*
303
 * "help" command
K
Karel Zak 已提交
304 305
 */
static vshCmdInfo info_help[] = {
306
    {"syntax", "help [<command>]"},
307 308 309
    {"help", gettext_noop("print help")},
    {"desc", gettext_noop("Prints global help or command specific help.")},

310
    {NULL, NULL}
K
Karel Zak 已提交
311 312 313
};

static vshCmdOptDef opts_help[] = {
314
    {"command", VSH_OT_DATA, 0, gettext_noop("name of command")},
315
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
316 317 318
};

static int
319 320
cmdHelp(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
321
    const char *cmdname = vshCommandOptString(cmd, "command", NULL);
K
Karel Zak 已提交
322 323 324

    if (!cmdname) {
        vshCmdDef *def;
325

326
        vshPrint(ctl, _("Commands:\n\n"));
327
        for (def = commands; def->name; def++)
K
Karel Zak 已提交
328
            vshPrint(ctl, "    %-15s %s\n", def->name,
329
                     N_(vshCmddefGetInfo(def, "help")));
K
Karel Zak 已提交
330 331 332 333 334
        return TRUE;
    }
    return vshCmddefHelp(ctl, cmdname, FALSE);
}

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
/*
 * "autostart" command
 */
static vshCmdInfo info_autostart[] = {
    {"syntax", "autostart [--disable] <domain>"},
    {"help", gettext_noop("autostart a domain")},
    {"desc",
     gettext_noop("Configure a domain to be automatically started at boot.")},
    {NULL, NULL}
};

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

static int
cmdAutostart(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *name;
    int autostart;

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

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

    autostart = !vshCommandOptBool(cmd, "disable");

    if (virDomainSetAutostart(dom, autostart) < 0) {
368 369 370 371 372 373
        if (autostart)
	    vshError(ctl, FALSE, _("Failed to mark domain %s as autostarted"),
                     name);
	else
	    vshError(ctl, FALSE, _("Failed to unmark domain %s as autostarted"),
                     name);
374 375 376 377
        virDomainFree(dom);
        return FALSE;
    }

378 379 380 381
    if (autostart)
	vshPrint(ctl, _("Domain %s marked as autostarted\n"), name);
    else
	vshPrint(ctl, _("Domain %s unmarked as autostarted\n"), name);
382

383
    virDomainFree(dom);
384 385 386
    return TRUE;
}

K
Karel Zak 已提交
387
/*
388
 * "connect" command
K
Karel Zak 已提交
389 390
 */
static vshCmdInfo info_connect[] = {
K
Karel Zak 已提交
391
    {"syntax", "connect [name] [--readonly]"},
392
    {"help", gettext_noop("(re)connect to hypervisor")},
393
    {"desc",
394
     gettext_noop("Connect to local hypervisor. This is built-in command after shell start up.")},
395
    {NULL, NULL}
K
Karel Zak 已提交
396 397 398
};

static vshCmdOptDef opts_connect[] = {
399 400
    {"name",     VSH_OT_DATA, 0, gettext_noop("hypervisor connection URI")},
    {"readonly", VSH_OT_BOOL, 0, gettext_noop("read-only connection")},
401
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
402 403 404
};

static int
405 406
cmdConnect(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
407
    int ro = vshCommandOptBool(cmd, "readonly");
408

K
Karel Zak 已提交
409
    if (ctl->conn) {
410 411
        if (virConnectClose(ctl->conn) != 0) {
            vshError(ctl, FALSE,
412
                     _("Failed to disconnect from the hypervisor"));
K
Karel Zak 已提交
413 414 415 416
            return FALSE;
        }
        ctl->conn = NULL;
    }
417

K
Karel Zak 已提交
418 419
    if (ctl->name)
        free(ctl->name);
420
    ctl->name = vshStrdup(ctl, vshCommandOptString(cmd, "name", NULL));
K
Karel Zak 已提交
421

422
    if (!ro) {
K
Karel Zak 已提交
423
        ctl->conn = virConnectOpen(ctl->name);
424 425
        ctl->readonly = 0;
    } else {
K
Karel Zak 已提交
426
        ctl->conn = virConnectOpenReadOnly(ctl->name);
427 428
        ctl->readonly = 1;
    }
K
Karel Zak 已提交
429 430

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

K
Karel Zak 已提交
433 434 435
    return ctl->conn ? TRUE : FALSE;
}

436
/*
437
 * "console" command
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
 */
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)
470
        goto cleanup;
471 472

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
473 474
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOWARNING);
475 476 477 478 479 480 481 482 483
    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) &&
484
                          (obj->stringval != NULL) && (obj->stringval[0] != 0))) {
485
        if (vshRunConsole((const char *)obj->stringval) == 0)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
            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 已提交
501 502 503 504
/*
 * "list" command
 */
static vshCmdInfo info_list[] = {
505
    {"syntax", "list [--inactive | --all]"},
506 507
    {"help", gettext_noop("list domains")},
    {"desc", gettext_noop("Returns list of domains.")},
508
    {NULL, NULL}
K
Karel Zak 已提交
509 510
};

511
static vshCmdOptDef opts_list[] = {
512 513
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive domains")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active domains")},
514 515 516
    {NULL, 0, 0, NULL}
};

K
Karel Zak 已提交
517 518

static int
519 520
cmdList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
521 522 523 524
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int *ids = NULL, maxid = 0, i;
525
    char **names = NULL;
526 527
    int maxname = 0;
    inactive |= all;
K
Karel Zak 已提交
528 529 530

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

532
    if (active) {
533 534 535 536 537 538 539 540 541 542 543 544 545 546
        maxid = virConnectNumOfDomains(ctl->conn);
        if (maxid < 0) {
            vshError(ctl, FALSE, _("Failed to list active domains"));
            return FALSE;
        }
        if (maxid) {
            ids = vshMalloc(ctl, sizeof(int) * maxid);

            if ((maxid = virConnectListDomains(ctl->conn, &ids[0], maxid)) < 0) {
                vshError(ctl, FALSE, _("Failed to list active domains"));
                free(ids);
                return FALSE;
            }

547
            qsort(&ids[0], maxid, sizeof(int), idsorter);
548
        }
549 550
    }
    if (inactive) {
551 552 553 554 555 556
        maxname = virConnectNumOfDefinedDomains(ctl->conn);
        if (maxname < 0) {
            vshError(ctl, FALSE, _("Failed to list inactive domains"));
            if (ids)
                free(ids);
            return FALSE;
557
        }
558 559 560 561 562 563 564 565 566 567
        if (maxname) {
            names = vshMalloc(ctl, sizeof(char *) * maxname);

            if ((maxname = virConnectListDefinedDomains(ctl->conn, names, maxname)) < 0) {
                vshError(ctl, FALSE, _("Failed to list inactive domains"));
                if (ids)
                    free(ids);
                free(names);
                return FALSE;
            }
568

569
            qsort(&names[0], maxname, sizeof(char*), namesorter);
570
        }
571
    }
572
    vshPrintExtra(ctl, "%3s %-20s %s\n", _("Id"), _("Name"), _("State"));
K
Karel Zak 已提交
573
    vshPrintExtra(ctl, "----------------------------------\n");
574 575

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
576 577
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
578
        const char *state;
579 580

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
581 582
        if (!dom)
            continue;
583 584 585 586

        if (virDomainGetInfo(dom, &info) < 0)
            state = _("no state");
        else
587
            state = N_(vshDomainStateToString(info.state));
588

K
Karel Zak 已提交
589
        vshPrint(ctl, "%3d %-20s %s\n",
590 591
                 virDomainGetID(dom),
                 virDomainGetName(dom),
592
                 state);
593
        virDomainFree(dom);
K
Karel Zak 已提交
594
    }
595 596 597
    for (i = 0; i < maxname; i++) {
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByName(ctl->conn, names[i]);
598
        const char *state;
599 600

        /* this kind of work with domains is not atomic operation */
601
        if (!dom) {
602
            free(names[i]);
603
            continue;
604
        }
605 606 607 608

        if (virDomainGetInfo(dom, &info) < 0)
            state = _("no state");
        else
609
            state = N_(vshDomainStateToString(info.state));
610 611

        vshPrint(ctl, "%3s %-20s %s\n", "-", names[i], state);
612

613
        virDomainFree(dom);
614
        free(names[i]);
615
    }
616 617
    if (ids)
        free(ids);
618 619
    if (names)
        free(names);
K
Karel Zak 已提交
620 621 622 623
    return TRUE;
}

/*
K
Karel Zak 已提交
624
 * "domstate" command
K
Karel Zak 已提交
625
 */
K
Karel Zak 已提交
626 627
static vshCmdInfo info_domstate[] = {
    {"syntax", "domstate <domain>"},
628 629
    {"help", gettext_noop("domain state")},
    {"desc", gettext_noop("Returns state about a running domain.")},
630
    {NULL, NULL}
K
Karel Zak 已提交
631 632
};

K
Karel Zak 已提交
633
static vshCmdOptDef opts_domstate[] = {
634
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
635
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
636 637 638
};

static int
K
Karel Zak 已提交
639
cmdDomstate(vshControl * ctl, vshCmd * cmd)
640
{
641
    virDomainInfo info;
K
Karel Zak 已提交
642
    virDomainPtr dom;
K
Karel Zak 已提交
643
    int ret = TRUE;
644

K
Karel Zak 已提交
645 646
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
647

K
Karel Zak 已提交
648
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
649
        return FALSE;
650 651

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
652
        vshPrint(ctl, "%s\n",
653
                 N_(vshDomainStateToString(info.state)));
K
Karel Zak 已提交
654 655
    else
        ret = FALSE;
656

657 658 659 660 661 662 663 664
    virDomainFree(dom);
    return ret;
}

/*
 * "suspend" command
 */
static vshCmdInfo info_suspend[] = {
665
    {"syntax", "suspend <domain>"},
666 667
    {"help", gettext_noop("suspend a domain")},
    {"desc", gettext_noop("Suspend a running domain.")},
668
    {NULL, NULL}
669 670 671
};

static vshCmdOptDef opts_suspend[] = {
672
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
673
    {NULL, 0, 0, NULL}
674 675 676
};

static int
677 678
cmdSuspend(vshControl * ctl, vshCmd * cmd)
{
679
    virDomainPtr dom;
K
Karel Zak 已提交
680 681
    char *name;
    int ret = TRUE;
682

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

K
Karel Zak 已提交
686
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
687
        return FALSE;
688 689

    if (virDomainSuspend(dom) == 0) {
690
        vshPrint(ctl, _("Domain %s suspended\n"), name);
691
    } else {
692
        vshError(ctl, FALSE, _("Failed to suspend domain %s"), name);
693 694
        ret = FALSE;
    }
695

696 697 698 699
    virDomainFree(dom);
    return ret;
}

700 701 702 703 704
/*
 * "create" command
 */
static vshCmdInfo info_create[] = {
    {"syntax", "create a domain from an XML <file>"},
705 706
    {"help", gettext_noop("create a domain from an XML file")},
    {"desc", gettext_noop("Create a domain.")},
707 708 709 710
    {NULL, NULL}
};

static vshCmdOptDef opts_create[] = {
711
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
712 713 714
    {NULL, 0, 0, NULL}
};

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
/* Read in a whole file and return it as a string.
 * If it fails, it logs an error and returns NULL.
 * String must be freed by caller.
 */
static char *
readFile (vshControl *ctl, const char *filename)
{
    char *retval;
    int len = 0, fd;

    if ((fd = open(filename, O_RDONLY)) == -1) {
        vshError (ctl, FALSE, _("Failed to open '%s': %s"),
                  filename, strerror (errno));
        return NULL;
    }

    if (!(retval = malloc(len + 1)))
        goto out_of_memory;

    while (1) {
        char buffer[1024];
        char *new;
        int ret;

        if ((ret = read(fd, buffer, sizeof(buffer))) == 0)
            break;

        if (ret == -1) {
            if (errno == EINTR)
                continue;

            vshError (ctl, FALSE, _("Failed to open '%s': read: %s"),
                      filename, strerror (errno));
            goto error;
        }

        if (!(new = realloc(retval, len + ret + 1)))
            goto out_of_memory;

        retval = new;

        memcpy(retval + len, buffer, ret);
        len += ret;
   }

   retval[len] = '\0';
   return retval;

 out_of_memory:
   vshError (ctl, FALSE, _("Error allocating memory: %s"),
             strerror(errno));

 error:
   if (retval)
     free(retval);
   close(fd);

   return NULL;
}

775 776 777 778 779 780 781
static int
cmdCreate(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
782
    char *buffer;
783 784 785 786 787 788 789 790

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

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

791 792 793 794 795 796
    buffer = readFile (ctl, from);
    if (buffer == NULL) return FALSE;

    dom = virDomainCreateLinux(ctl->conn, buffer, 0);
    free (buffer);

797
    if (dom != NULL) {
798
        vshPrint(ctl, _("Domain %s created from %s\n"),
799
                 virDomainGetName(dom), from);
800
	virDomainFree(dom);
801
    } else {
802
        vshError(ctl, FALSE, _("Failed to create domain from %s"), from);
803 804 805 806 807
        ret = FALSE;
    }
    return ret;
}

808 809 810 811 812
/*
 * "define" command
 */
static vshCmdInfo info_define[] = {
    {"syntax", "define a domain from an XML <file>"},
813 814
    {"help", gettext_noop("define (but don't start) a domain from an XML file")},
    {"desc", gettext_noop("Define a domain.")},
815 816 817 818
    {NULL, NULL}
};

static vshCmdOptDef opts_define[] = {
819
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
820 821 822 823 824 825 826 827 828 829
    {NULL, 0, 0, NULL}
};

static int
cmdDefine(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
830
    char *buffer;
831 832 833 834 835 836 837 838

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

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

839 840 841 842 843 844
    buffer = readFile (ctl, from);
    if (buffer == NULL) return FALSE;

    dom = virDomainDefineXML(ctl->conn, buffer);
    free (buffer);

845
    if (dom != NULL) {
846
        vshPrint(ctl, _("Domain %s defined from %s\n"),
847
                 virDomainGetName(dom), from);
848
        virDomainFree(dom);
849
    } else {
850
        vshError(ctl, FALSE, _("Failed to define domain from %s"), from);
851 852 853 854 855 856 857 858 859 860
        ret = FALSE;
    }
    return ret;
}

/*
 * "undefine" command
 */
static vshCmdInfo info_undefine[] = {
    {"syntax", "undefine <domain>"},
861 862
    {"help", gettext_noop("undefine an inactive domain")},
    {"desc", gettext_noop("Undefine the configuration for an inactive domain.")},
863 864 865 866
    {NULL, NULL}
};

static vshCmdOptDef opts_undefine[] = {
867
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    {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) {
885
        vshPrint(ctl, _("Domain %s has been undefined\n"), name);
886
    } else {
887
        vshError(ctl, FALSE, _("Failed to undefine domain %s"), name);
888 889 890
        ret = FALSE;
    }

891
    virDomainFree(dom);
892 893 894 895 896 897 898 899
    return ret;
}


/*
 * "start" command
 */
static vshCmdInfo info_start[] = {
900
    {"syntax", "start <domain>"},
901 902
    {"help", gettext_noop("start a (previously defined) inactive domain")},
    {"desc", gettext_noop("Start a domain.")},
903 904 905 906
    {NULL, NULL}
};

static vshCmdOptDef opts_start[] = {
907
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive domain")},
908 909 910 911 912 913 914 915 916 917 918 919
    {NULL, 0, 0, NULL}
};

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

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

920
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
921 922 923
        return FALSE;

    if (virDomainGetID(dom) != (unsigned int)-1) {
924
        vshError(ctl, FALSE, _("Domain is already active"));
925
	virDomainFree(dom);
926 927 928 929
        return FALSE;
    }

    if (virDomainCreate(dom) == 0) {
930
        vshPrint(ctl, _("Domain %s started\n"),
931
                 virDomainGetName(dom));
932
    } else {
933 934
        vshError(ctl, FALSE, _("Failed to start domain %s"),
                 virDomainGetName(dom));
935 936
        ret = FALSE;
    }
937
    virDomainFree(dom);
938 939 940
    return ret;
}

941 942 943 944
/*
 * "save" command
 */
static vshCmdInfo info_save[] = {
945
    {"syntax", "save <domain> <file>"},
946 947
    {"help", gettext_noop("save a domain state to a file")},
    {"desc", gettext_noop("Save a running domain.")},
948
    {NULL, NULL}
949 950 951
};

static vshCmdOptDef opts_save[] = {
952 953
    {"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")},
954
    {NULL, 0, 0, NULL}
955 956 957
};

static int
958 959
cmdSave(vshControl * ctl, vshCmd * cmd)
{
960 961 962 963
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
964

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

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

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

    if (virDomainSave(dom, to) == 0) {
975
        vshPrint(ctl, _("Domain %s saved to %s\n"), name, to);
976
    } else {
977
        vshError(ctl, FALSE, _("Failed to save domain %s to %s"), name, to);
978 979
        ret = FALSE;
    }
980

981 982 983 984
    virDomainFree(dom);
    return ret;
}

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
/*
 * "schedinfo" command
 */
static vshCmdInfo info_schedinfo[] = {
    {"syntax", "sched <domain>"},
    {"help", gettext_noop("show/set scheduler parameters")},
    {"desc", gettext_noop("Show/Set scheduler parameters.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_schedinfo[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"weight", VSH_OT_INT, VSH_OFLAG_NONE, gettext_noop("weight for XEN_CREDIT")},
    {"cap", VSH_OT_INT, VSH_OFLAG_NONE, gettext_noop("cap for XEN_CREDIT")},
    {NULL, 0, 0, NULL}
};

static int
cmdSchedinfo(vshControl * ctl, vshCmd * cmd)
{
    char *schedulertype;
    virDomainPtr dom;
    virSchedParameterPtr params;
    int i, ret;
    int nparams = 0;
    int nr_inputparams = 0;
    int inputparams = 0;
    int weightfound = 0;
    int weight;
    int capfound = 0;
    int cap;
    char str_weight[] = "weight";
    char str_cap[]    = "cap";

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

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

    /* Currently supports Xen Credit only */
    weight = vshCommandOptInt(cmd, "weight", &weightfound);
    if (weightfound) nr_inputparams++;
            
    cap    = vshCommandOptInt(cmd, "cap", &capfound);
    if (capfound) nr_inputparams++;

    params = vshMalloc(ctl, sizeof (virSchedParameter) * nr_inputparams);
1033 1034 1035 1036
    if (params == NULL) {
	virDomainFree(dom);
        return FALSE;
    }
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

    if (weightfound) {
         strncpy(params[inputparams].field,str_weight,sizeof(str_weight));
         params[inputparams].type = VIR_DOMAIN_SCHED_FIELD_UINT;
         params[inputparams].value.ui = weight;
         inputparams++; 
    }

    if (capfound) {
         strncpy(params[inputparams].field,str_cap,sizeof(str_cap));
         params[inputparams].type = VIR_DOMAIN_SCHED_FIELD_UINT;
         params[inputparams].value.ui = cap;
         inputparams++;
    }
    /* End Currently supports Xen Credit only */

    assert (inputparams == nr_inputparams);

    /* Set SchedulerParameters */
    if (inputparams > 0) {
        ret = virDomainSetSchedulerParameters(dom, params, inputparams);
1058 1059 1060 1061
        if (ret == -1) {
	    virDomainFree(dom);
	    return FALSE;
	}
1062 1063 1064 1065 1066 1067
    }
    free(params);

    /* Print SchedulerType */
    schedulertype = virDomainGetSchedulerType(dom, &nparams);
    if (schedulertype!= NULL){
1068
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"),
1069 1070 1071
             schedulertype);
        free(schedulertype);
    } else {
1072
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"), _("Unknown"));
1073
	virDomainFree(dom);
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
        return FALSE;
    }

    /* Get SchedulerParameters */
    params = vshMalloc(ctl, sizeof(virSchedParameter)* nparams);
    for (i = 0; i < nparams; i++){
        params[i].type = 0;
        memset (params[i].field, 0, sizeof params[i].field);
    }
    ret = virDomainGetSchedulerParameters(dom, params, &nparams);
1084 1085 1086 1087
    if (ret == -1) {
        virDomainFree(dom);
        return FALSE;
    }
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    if(nparams){
        for (i = 0; i < nparams; i++){
            switch (params[i].type) {
            case VIR_DOMAIN_SCHED_FIELD_INT:
                 printf("%-15s: %d\n",  params[i].field, params[i].value.i);
                 break;
            case VIR_DOMAIN_SCHED_FIELD_UINT:
                 printf("%-15s: %u\n",  params[i].field, params[i].value.ui);
                 break;
            case VIR_DOMAIN_SCHED_FIELD_LLONG:
                 printf("%-15s: %Ld\n",  params[i].field, params[i].value.l);
                 break;
            case VIR_DOMAIN_SCHED_FIELD_ULLONG:
                 printf("%-15s: %Lu\n",  params[i].field, params[i].value.ul);
                 break;
            case VIR_DOMAIN_SCHED_FIELD_DOUBLE:
                 printf("%-15s: %f\n",  params[i].field, params[i].value.d);
                 break;
            case VIR_DOMAIN_SCHED_FIELD_BOOLEAN:
                 printf("%-15s: %d\n",  params[i].field, params[i].value.b);
                 break;
            default:
                 printf("not implemented scheduler parameter type\n");
            }
        }
    }
    free(params);
1115
    virDomainFree(dom);
1116 1117 1118
    return TRUE;
}

1119 1120 1121 1122
/*
 * "restore" command
 */
static vshCmdInfo info_restore[] = {
1123
    {"syntax", "restore a domain from <file>"},
1124 1125
    {"help", gettext_noop("restore a domain from a saved state in a file")},
    {"desc", gettext_noop("Restore a domain.")},
1126
    {NULL, NULL}
1127 1128 1129
};

static vshCmdOptDef opts_restore[] = {
1130
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("the state to restore")},
1131
    {NULL, 0, 0, NULL}
1132 1133 1134
};

static int
1135 1136
cmdRestore(vshControl * ctl, vshCmd * cmd)
{
1137 1138 1139
    char *from;
    int found;
    int ret = TRUE;
1140

1141 1142 1143 1144 1145 1146
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
1149
        vshPrint(ctl, _("Domain restored from %s\n"), from);
1150
    } else {
1151
        vshError(ctl, FALSE, _("Failed to restore domain from %s"), from);
1152 1153 1154 1155 1156
        ret = FALSE;
    }
    return ret;
}

D
Daniel Veillard 已提交
1157 1158 1159 1160 1161 1162 1163 1164 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
/*
 * "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;
}

1202 1203 1204 1205
/*
 * "resume" command
 */
static vshCmdInfo info_resume[] = {
1206
    {"syntax", "resume <domain>"},
1207 1208
    {"help", gettext_noop("resume a domain")},
    {"desc", gettext_noop("Resume a previously suspended domain.")},
1209
    {NULL, NULL}
1210 1211 1212
};

static vshCmdOptDef opts_resume[] = {
1213
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1214
    {NULL, 0, 0, NULL}
1215 1216 1217
};

static int
1218 1219
cmdResume(vshControl * ctl, vshCmd * cmd)
{
1220
    virDomainPtr dom;
K
Karel Zak 已提交
1221 1222
    int ret = TRUE;
    char *name;
1223

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

K
Karel Zak 已提交
1227
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1228
        return FALSE;
1229 1230

    if (virDomainResume(dom) == 0) {
1231
        vshPrint(ctl, _("Domain %s resumed\n"), name);
1232
    } else {
1233
        vshError(ctl, FALSE, _("Failed to resume domain %s"), name);
1234 1235
        ret = FALSE;
    }
1236

1237 1238 1239 1240
    virDomainFree(dom);
    return ret;
}

1241 1242 1243 1244
/*
 * "shutdown" command
 */
static vshCmdInfo info_shutdown[] = {
1245
    {"syntax", "shutdown <domain>"},
1246 1247
    {"help", gettext_noop("gracefully shutdown a domain")},
    {"desc", gettext_noop("Run shutdown in the target domain.")},
1248
    {NULL, NULL}
1249 1250 1251
};

static vshCmdOptDef opts_shutdown[] = {
1252
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1253
    {NULL, 0, 0, NULL}
1254 1255 1256
};

static int
1257 1258
cmdShutdown(vshControl * ctl, vshCmd * cmd)
{
1259 1260 1261
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
1262

1263 1264 1265 1266 1267
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainShutdown(dom) == 0) {
1270
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
1271
    } else {
1272
        vshError(ctl, FALSE, _("Failed to shutdown domain %s"), name);
1273 1274
        ret = FALSE;
    }
1275

1276 1277 1278 1279
    virDomainFree(dom);
    return ret;
}

1280 1281 1282 1283 1284
/*
 * "reboot" command
 */
static vshCmdInfo info_reboot[] = {
    {"syntax", "reboot <domain>"},
1285 1286
    {"help", gettext_noop("reboot a domain")},
    {"desc", gettext_noop("Run a reboot command in the target domain.")},
1287 1288 1289 1290
    {NULL, NULL}
};

static vshCmdOptDef opts_reboot[] = {
1291
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    {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) {
1309
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
1310
    } else {
1311
        vshError(ctl, FALSE, _("Failed to reboot domain %s"), name);
1312 1313 1314 1315 1316 1317 1318
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1319 1320 1321 1322
/*
 * "destroy" command
 */
static vshCmdInfo info_destroy[] = {
1323
    {"syntax", "destroy <domain>"},
1324 1325
    {"help", gettext_noop("destroy a domain")},
    {"desc", gettext_noop("Destroy a given domain.")},
1326
    {NULL, NULL}
1327 1328 1329
};

static vshCmdOptDef opts_destroy[] = {
1330
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1331
    {NULL, 0, 0, NULL}
1332 1333 1334
};

static int
1335 1336
cmdDestroy(vshControl * ctl, vshCmd * cmd)
{
1337
    virDomainPtr dom;
K
Karel Zak 已提交
1338 1339
    int ret = TRUE;
    char *name;
1340

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

K
Karel Zak 已提交
1344
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1345
        return FALSE;
1346 1347

    if (virDomainDestroy(dom) == 0) {
1348
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
1349
    } else {
1350
        vshError(ctl, FALSE, _("Failed to destroy domain %s"), name);
1351 1352 1353
        ret = FALSE;
        virDomainFree(dom);
    }
1354

K
Karel Zak 已提交
1355 1356 1357 1358
    return ret;
}

/*
1359
 * "dominfo" command
K
Karel Zak 已提交
1360
 */
1361 1362
static vshCmdInfo info_dominfo[] = {
    {"syntax", "dominfo <domain>"},
1363 1364
    {"help", gettext_noop("domain information")},
    {"desc", gettext_noop("Returns basic information about the domain.")},
1365
    {NULL, NULL}
K
Karel Zak 已提交
1366 1367
};

1368
static vshCmdOptDef opts_dominfo[] = {
1369
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1370
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1371 1372 1373
};

static int
1374
cmdDominfo(vshControl * ctl, vshCmd * cmd)
1375
{
K
Karel Zak 已提交
1376 1377
    virDomainInfo info;
    virDomainPtr dom;
K
Karel Zak 已提交
1378
    int ret = TRUE;
1379
    unsigned int id;
1380
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
1381

K
Karel Zak 已提交
1382 1383 1384
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
1385
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
1386
        return FALSE;
1387

1388 1389
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1390
        vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
1391
    else
1392
        vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
1393 1394
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
1395
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
1396
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
1397 1398

    if ((str = virDomainGetOSType(dom))) {
1399
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
1400 1401 1402 1403
        free(str);
    }

    if (virDomainGetInfo(dom, &info) == 0) {
1404
        vshPrint(ctl, "%-15s %s\n", _("State:"),
1405
                 N_(vshDomainStateToString(info.state)));
1406

1407
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
1408 1409

        if (info.cpuTime != 0) {
1410
            double cpuUsed = info.cpuTime;
1411

1412
            cpuUsed /= 1000000000.0;
1413

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

1417 1418
        if (info.maxMem != UINT_MAX)
            vshPrint(ctl, "%-15s %lu kB\n", _("Max memory:"),
1419
                 info.maxMem);
1420 1421 1422 1423
        else
            vshPrint(ctl, "%-15s %-15s\n", _("Max memory:"),
                 _("no limit"));

1424
        vshPrint(ctl, "%-15s %lu kB\n", _("Used memory:"),
1425 1426
                 info.memory);

K
Karel Zak 已提交
1427 1428 1429
    } else {
        ret = FALSE;
    }
1430

1431
    virDomainFree(dom);
K
Karel Zak 已提交
1432 1433 1434
    return ret;
}

1435 1436 1437 1438 1439
/*
 * "vcpuinfo" command
 */
static vshCmdInfo info_vcpuinfo[] = {
    {"syntax", "vcpuinfo <domain>"},
1440 1441
    {"help", gettext_noop("domain vcpu information")},
    {"desc", gettext_noop("Returns basic information about the domain virtual CPUs.")},
1442 1443 1444 1445
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpuinfo[] = {
1446
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
    {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);
1470
        return FALSE;
1471 1472 1473 1474 1475 1476 1477
    }

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

1478
    cpuinfo = vshMalloc(ctl, sizeof(virVcpuInfo)*info.nrVirtCpu);
1479
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1480
    cpumap = vshMalloc(ctl, info.nrVirtCpu * cpumaplen);
1481

1482 1483 1484
    if ((ncpus = virDomainGetVcpus(dom,
                                   cpuinfo, info.nrVirtCpu,
                                   cpumap, cpumaplen)) >= 0) {
1485
        int n;
1486 1487 1488 1489 1490
        for (n = 0 ; n < ncpus ; n++) {
            unsigned int m;
            vshPrint(ctl, "%-15s %d\n", _("VCPU:"), n);
            vshPrint(ctl, "%-15s %d\n", _("CPU:"), cpuinfo[n].cpu);
            vshPrint(ctl, "%-15s %s\n", _("State:"),
1491
                     N_(vshDomainVcpuStateToString(cpuinfo[n].state)));
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
            if (cpuinfo[n].cpuTime != 0) {
                double cpuUsed = cpuinfo[n].cpuTime;

                cpuUsed /= 1000000000.0;

                vshPrint(ctl, "%-15s %.1lfs\n", _("CPU time:"), cpuUsed);
            }
            vshPrint(ctl, "%-15s ", _("CPU Affinity:"));
            for (m = 0 ; m < VIR_NODEINFO_MAXCPUS(nodeinfo) ; m++) {
                vshPrint(ctl, "%c", VIR_CPU_USABLE(cpumap, cpumaplen, n, m) ? 'y' : '-');
            }
            vshPrint(ctl, "\n");
            if (n < (ncpus - 1)) {
                vshPrint(ctl, "\n");
            }
        }
1508
    } else {
1509 1510 1511 1512
        if (info.state == VIR_DOMAIN_SHUTOFF) {
            vshError(ctl, FALSE,
                 _("Domain shut off, virtual CPUs not present."));
        }
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
        ret = FALSE;
    }

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

/*
 * "vcpupin" command
 */
static vshCmdInfo info_vcpupin[] = {
1526
    {"syntax", "vcpupin <domain> <vcpu> <cpulist>"},
1527 1528
    {"help", gettext_noop("control domain vcpu affinity")},
    {"desc", gettext_noop("Pin domain VCPUs to host physical CPUs.")},
1529 1530 1531 1532
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpupin[] = {
1533 1534 1535
    {"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)")},
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
    {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;
1551 1552
    int i;
    enum { expect_num, expect_num_or_comma } state;
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569

    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;
    }
1570

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    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;
    }

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
    /* Check that the cpulist parameter is a comma-separated list of
     * numbers and give an intelligent error message if not.
     */
    if (cpulist[0] == '\0') {
        vshError(ctl, FALSE, _("cpulist: Invalid format. Empty string."));
        virDomainFree (dom);
        return FALSE;
    }

    state = expect_num;
    for (i = 0; cpulist[i]; i++) {
        switch (state) {
        case expect_num:
            if (!isdigit (cpulist[i])) {
                vshError( ctl, FALSE, _("cpulist: %s: Invalid format. Expecting digit at position %d (near '%c')."), cpulist, i, cpulist[i]);
                virDomainFree (dom);
                return FALSE;
            }
            state = expect_num_or_comma;
            break;
        case expect_num_or_comma:
            if (cpulist[i] == ',')
                state = expect_num;
            else if (!isdigit (cpulist[i])) {
                vshError(ctl, FALSE, _("cpulist: %s: Invalid format. Expecting digit or comma at position %d (near '%c')."), cpulist, i, cpulist[i]);
                virDomainFree (dom);
                return FALSE;
            }
        }
    }
    if (state == expect_num) {
        vshError(ctl, FALSE, _("cpulist: %s: Invalid format. Trailing comma at position %d."), cpulist, i);
        virDomainFree (dom);
        return FALSE;
    }

1622
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1623
    cpumap = vshCalloc(ctl, 1, cpumaplen);
1624 1625 1626 1627 1628 1629

    do {
        unsigned int cpu = atoi(cpulist);

        if (cpu < VIR_NODEINFO_MAXCPUS(nodeinfo)) {
            VIR_USE_CPU(cpumap, cpu);
1630 1631 1632 1633 1634
        } else {
            vshError(ctl, FALSE, _("Physical CPU %d doesn't exist."), cpu);
            free(cpumap);
            virDomainFree(dom);
            return FALSE;
1635
        }
1636
        cpulist = strchr(cpulist, ',');
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
        if (cpulist)
            cpulist++;
    } while (cpulist);

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

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

1650 1651 1652 1653 1654
/*
 * "setvcpus" command
 */
static vshCmdInfo info_setvcpus[] = {
    {"syntax", "setvcpus <domain> <count>"},
1655 1656
    {"help", gettext_noop("change number of virtual CPUs")},
    {"desc", gettext_noop("Change the number of virtual CPUs active in the guest domain.")},
1657 1658 1659 1660
    {NULL, NULL}
};

static vshCmdOptDef opts_setvcpus[] = {
1661 1662
    {"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")},
1663 1664 1665 1666 1667 1668 1669 1670
    {NULL, 0, 0, NULL}
};

static int
cmdSetvcpus(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    int count;
1671
    int maxcpu;
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    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) {
1682
        vshError(ctl, FALSE, _("Invalid number of virtual CPUs."));
1683 1684 1685 1686
        virDomainFree(dom);
        return FALSE;
    }

1687 1688 1689 1690 1691 1692 1693
    maxcpu = virDomainGetMaxVcpus(dom);
    if (!maxcpu) {
        virDomainFree(dom);
        return FALSE;
    }

    if (count > maxcpu) {
1694
        vshError(ctl, FALSE, _("Too many virtual CPUs."));
1695 1696 1697 1698
        virDomainFree(dom);
        return FALSE;
    }

1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
    if (virDomainSetVcpus(dom, count) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmemory" command
 */
static vshCmdInfo info_setmem[] = {
1711
    {"syntax", "setmem <domain> <kilobytes>"},
1712 1713
    {"help", gettext_noop("change memory allocation")},
    {"desc", gettext_noop("Change the current memory allocation in the guest domain.")},
1714 1715 1716 1717
    {NULL, NULL}
};

static vshCmdOptDef opts_setmem[] = {
1718
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1719
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("number of kilobytes of memory")},
1720 1721 1722 1723 1724 1725 1726
    {NULL, 0, 0, NULL}
};

static int
cmdSetmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
1727
    virDomainInfo info;
1728
    int kilobytes;
1729 1730 1731 1732 1733 1734 1735 1736
    int ret = TRUE;

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

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

1737 1738
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1739
        virDomainFree(dom);
1740
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1741 1742 1743
        return FALSE;
    }

1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
        vshError(ctl, FALSE, _("Unable to verify MaxMemorySize"));
        return FALSE;
    }

    if (kilobytes > info.maxMem) {
        virDomainFree(dom);
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
        return FALSE;
    }

1756
    if (virDomainSetMemory(dom, kilobytes) != 0) {
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmaxmem" command
 */
static vshCmdInfo info_setmaxmem[] = {
1768
    {"syntax", "setmaxmem <domain> <kilobytes>"},
1769 1770
    {"help", gettext_noop("change maximum memory limit")},
    {"desc", gettext_noop("Change the maximum memory allocation limit in the guest domain.")},
1771 1772 1773 1774
    {NULL, NULL}
};

static vshCmdOptDef opts_setmaxmem[] = {
1775
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1776
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("maximum memory limit in kilobytes")},
1777 1778 1779 1780 1781 1782 1783
    {NULL, 0, 0, NULL}
};

static int
cmdSetmaxmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
1784
    virDomainInfo info;
1785
    int kilobytes;
1786 1787 1788 1789 1790 1791 1792 1793
    int ret = TRUE;

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

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

1794 1795
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1796
        virDomainFree(dom);
1797
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1798 1799 1800
        return FALSE;
    }

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
        vshError(ctl, FALSE, _("Unable to verify current MemorySize"));
        return FALSE;
    }

    if (kilobytes < info.memory) {
        if (virDomainSetMemory(dom, kilobytes) != 0) {
            virDomainFree(dom);
            vshError(ctl, FALSE, _("Unable to shrink current MemorySize"));
            return FALSE;
        }
    }

1815
    if (virDomainSetMaxMemory(dom, kilobytes) != 0) {
1816
        vshError(ctl, FALSE, _("Unable to change MaxMemorySize"));
1817 1818 1819 1820 1821 1822 1823
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1824 1825 1826 1827 1828
/*
 * "nodeinfo" command
 */
static vshCmdInfo info_nodeinfo[] = {
    {"syntax", "nodeinfo"},
1829 1830
    {"help", gettext_noop("node information")},
    {"desc", gettext_noop("Returns basic information about the node.")},
1831 1832 1833 1834 1835 1836 1837
    {NULL, NULL}
};

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

1839 1840 1841 1842
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
        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);

1855 1856 1857
    return TRUE;
}

1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
/*
 * "capabilities" command
 */
static vshCmdInfo info_capabilities[] = {
    {"syntax", "capabilities"},
    {"help", gettext_noop("capabilities")},
    {"desc", gettext_noop("Returns capabilities of hypervisor/driver.")},
    {NULL, NULL}
};

static int
cmdCapabilities (vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    char *caps;

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

    if ((caps = virConnectGetCapabilities (ctl->conn)) == NULL) {
        vshError(ctl, FALSE, _("failed to get capabilities"));
        return FALSE;
    }
    vshPrint (ctl, "%s\n", caps);

    return TRUE;
}

1885 1886 1887 1888
/*
 * "dumpxml" command
 */
static vshCmdInfo info_dumpxml[] = {
1889
    {"syntax", "dumpxml <domain>"},
1890
    {"help", gettext_noop("domain information in XML")},
1891
    {"desc", gettext_noop("Output the domain information as an XML dump to stdout.")},
1892
    {NULL, NULL}
1893 1894 1895
};

static vshCmdOptDef opts_dumpxml[] = {
1896
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1897
    {NULL, 0, 0, NULL}
1898 1899 1900
};

static int
1901 1902
cmdDumpXML(vshControl * ctl, vshCmd * cmd)
{
1903
    virDomainPtr dom;
K
Karel Zak 已提交
1904
    int ret = TRUE;
1905
    char *dump;
1906

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

K
Karel Zak 已提交
1910
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
1911
        return FALSE;
1912

1913 1914 1915 1916 1917 1918 1919
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
1920

1921 1922 1923 1924
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
1925
/*
K
Karel Zak 已提交
1926
 * "domname" command
K
Karel Zak 已提交
1927
 */
K
Karel Zak 已提交
1928
static vshCmdInfo info_domname[] = {
K
Karel Zak 已提交
1929
    {"syntax", "domname <domain>"},
1930
    {"help", gettext_noop("convert a domain id or UUID to domain name")},
1931
    {NULL, NULL}
K
Karel Zak 已提交
1932 1933
};

K
Karel Zak 已提交
1934
static vshCmdOptDef opts_domname[] = {
1935
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or uuid")},
1936
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1937 1938 1939
};

static int
K
Karel Zak 已提交
1940
cmdDomname(vshControl * ctl, vshCmd * cmd)
1941
{
K
Karel Zak 已提交
1942 1943 1944 1945
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
1946
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
1947
                                      VSH_BYID|VSH_BYUUID)))
K
Karel Zak 已提交
1948
        return FALSE;
1949

K
Karel Zak 已提交
1950 1951
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
K
Karel Zak 已提交
1952 1953 1954 1955
    return TRUE;
}

/*
K
Karel Zak 已提交
1956
 * "domid" command
K
Karel Zak 已提交
1957
 */
K
Karel Zak 已提交
1958
static vshCmdInfo info_domid[] = {
K
Karel Zak 已提交
1959
    {"syntax", "domid <domain>"},
1960
    {"help", gettext_noop("convert a domain name or UUID to domain id")},
1961
    {NULL, NULL}
K
Karel Zak 已提交
1962 1963
};

K
Karel Zak 已提交
1964
static vshCmdOptDef opts_domid[] = {
1965
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
1966
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1967 1968 1969
};

static int
K
Karel Zak 已提交
1970
cmdDomid(vshControl * ctl, vshCmd * cmd)
1971
{
1972
    virDomainPtr dom;
1973
    unsigned int id;
K
Karel Zak 已提交
1974 1975 1976

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
1977
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
1978
                                      VSH_BYNAME|VSH_BYUUID)))
K
Karel Zak 已提交
1979
        return FALSE;
1980

1981 1982
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1983
        vshPrint(ctl, "%s\n", "-");
1984
    else
1985
        vshPrint(ctl, "%d\n", id);
K
Karel Zak 已提交
1986 1987 1988
    virDomainFree(dom);
    return TRUE;
}
1989

K
Karel Zak 已提交
1990 1991 1992 1993 1994
/*
 * "domuuid" command
 */
static vshCmdInfo info_domuuid[] = {
    {"syntax", "domuuid <domain>"},
1995
    {"help", gettext_noop("convert a domain name or id to domain UUID")},
K
Karel Zak 已提交
1996 1997 1998 1999
    {NULL, NULL}
};

static vshCmdOptDef opts_domuuid[] = {
2000
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or name")},
K
Karel Zak 已提交
2001 2002 2003 2004 2005 2006 2007
    {NULL, 0, 0, NULL}
};

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

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
K
Karel Zak 已提交
2011
        return FALSE;
2012
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
2013
                                      VSH_BYNAME|VSH_BYID)))
K
Karel Zak 已提交
2014
        return FALSE;
2015

K
Karel Zak 已提交
2016 2017 2018
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
2019 2020
        vshError(ctl, FALSE, _("failed to get domain UUID"));

K
Karel Zak 已提交
2021 2022 2023
    return TRUE;
}

2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
/*
 * "net-autostart" command
 */
static vshCmdInfo info_network_autostart[] = {
    {"syntax", "net-autostart [--disable] <network>"},
    {"help", gettext_noop("autostart a network")},
    {"desc",
     gettext_noop("Configure a network to be automatically started at boot.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_network_autostart[] = {
    {"network",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name or uuid")},
    {"disable", VSH_OT_BOOL, 0, gettext_noop("disable autostarting")},
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkAutostart(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char *name;
    int autostart;

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

    if (!(network = vshCommandOptNetwork(ctl, cmd, "network", &name)))
        return FALSE;

    autostart = !vshCommandOptBool(cmd, "disable");

    if (virNetworkSetAutostart(network, autostart) < 0) {
2057 2058 2059 2060 2061 2062
        if (autostart)
	    vshError(ctl, FALSE, _("failed to mark network %s as autostarted"),
                                   name);
	else
	    vshError(ctl, FALSE,_("failed to unmark network %s as autostarted"),
                                   name);
2063 2064 2065 2066
        virNetworkFree(network);
        return FALSE;
    }

2067 2068 2069 2070
    if (autostart)
	vshPrint(ctl, _("Network %s marked as autostarted\n"), name);
    else
	vshPrint(ctl, _("Network %s unmarked as autostarted\n"), name);
2071 2072 2073

    return TRUE;
}
K
Karel Zak 已提交
2074

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
/*
 * "net-create" command
 */
static vshCmdInfo info_network_create[] = {
    {"syntax", "create a network from an XML <file>"},
    {"help", gettext_noop("create a network from an XML file")},
    {"desc", gettext_noop("Create a network.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_network_create[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML network description")},
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkCreate(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
2097
    char *buffer;
2098 2099 2100 2101 2102 2103 2104 2105

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

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

2106 2107 2108 2109 2110 2111
    buffer = readFile (ctl, from);
    if (buffer == NULL) return FALSE;

    network = virNetworkCreateXML(ctl->conn, buffer);
    free (buffer);

2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
    if (network != NULL) {
        vshPrint(ctl, _("Network %s created from %s\n"),
                 virNetworkGetName(network), from);
    } else {
        vshError(ctl, FALSE, _("Failed to create network from %s"), from);
        ret = FALSE;
    }
    return ret;
}


/*
 * "net-define" command
 */
static vshCmdInfo info_network_define[] = {
    {"syntax", "define a network from an XML <file>"},
    {"help", gettext_noop("define (but don't start) a network from an XML file")},
    {"desc", gettext_noop("Define a network.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_network_define[] = {
2134
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML network description")},
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkDefine(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
2145
    char *buffer;
2146 2147 2148 2149 2150 2151 2152 2153

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

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

2154 2155 2156 2157 2158 2159
    buffer = readFile (ctl, from);
    if (buffer == NULL) return FALSE;

    network = virNetworkDefineXML(ctl->conn, buffer);
    free (buffer);

2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
    if (network != NULL) {
        vshPrint(ctl, _("Network %s defined from %s\n"),
                 virNetworkGetName(network), from);
    } else {
        vshError(ctl, FALSE, _("Failed to define network from %s"), from);
        ret = FALSE;
    }
    return ret;
}


/*
 * "net-destroy" command
 */
static vshCmdInfo info_network_destroy[] = {
    {"syntax", "net-destroy <network>"},
    {"help", gettext_noop("destroy a network")},
    {"desc", gettext_noop("Destroy a given network.")},
    {NULL, NULL}
};

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

static int
cmdNetworkDestroy(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    int ret = TRUE;
    char *name;

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

    if (!(network = vshCommandOptNetwork(ctl, cmd, "network", &name)))
        return FALSE;

    if (virNetworkDestroy(network) == 0) {
        vshPrint(ctl, _("Network %s destroyed\n"), name);
    } else {
        vshError(ctl, FALSE, _("Failed to destroy network %s"), name);
        ret = FALSE;
        virNetworkFree(network);
    }

    return ret;
}


/*
 * "net-dumpxml" command
 */
static vshCmdInfo info_network_dumpxml[] = {
2215
    {"syntax", "net-dumpxml <network>"},
2216
    {"help", gettext_noop("network information in XML")},
2217
    {"desc", gettext_noop("Output the network information as an XML dump to stdout.")},
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
    {NULL, NULL}
};

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

static int
cmdNetworkDumpXML(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    int ret = TRUE;
    char *dump;

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

    if (!(network = vshCommandOptNetwork(ctl, cmd, "network", NULL)))
        return FALSE;

    dump = virNetworkGetXMLDesc(network, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }

    virNetworkFree(network);
    return ret;
}


/*
 * "net-list" command
 */
static vshCmdInfo info_network_list[] = {
    {"syntax", "net-list [ --inactive | --all ]"},
    {"help", gettext_noop("list networks")},
    {"desc", gettext_noop("Returns list of networks.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_network_list[] = {
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive networks")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active networks")},
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int maxactive = 0, maxinactive = 0, i;
2275
    char **activeNames = NULL, **inactiveNames = NULL;
2276 2277 2278 2279 2280 2281
    inactive |= all;

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

    if (active) {
2282 2283 2284 2285
        maxactive = virConnectNumOfNetworks(ctl->conn);
        if (maxactive < 0) {
            vshError(ctl, FALSE, _("Failed to list active networks"));
            return FALSE;
2286
        }
2287
        if (maxactive) {
2288
            activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);
2289

2290 2291
            if ((maxactive = virConnectListNetworks(ctl->conn, activeNames,
	                                            maxactive)) < 0) {
2292 2293 2294 2295
                vshError(ctl, FALSE, _("Failed to list active networks"));
                free(activeNames);
                return FALSE;
            }
2296

2297
            qsort(&activeNames[0], maxactive, sizeof(char *), namesorter);
2298
        }
2299 2300
    }
    if (inactive) {
2301 2302 2303 2304 2305 2306
        maxinactive = virConnectNumOfDefinedNetworks(ctl->conn);
        if (maxinactive < 0) {
            vshError(ctl, FALSE, _("Failed to list inactive networks"));
            if (activeNames)
                free(activeNames);
            return FALSE;
2307
        }
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
        if (maxinactive) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive);

            if ((maxinactive = virConnectListDefinedNetworks(ctl->conn, inactiveNames, maxinactive)) < 0) {
                vshError(ctl, FALSE, _("Failed to list inactive networks"));
                if (activeNames)
                    free(activeNames);
                free(inactiveNames);
                return FALSE;
            }
2318

2319 2320
            qsort(&inactiveNames[0], maxinactive, sizeof(char*), namesorter);
        }
2321
    }
2322 2323
    vshPrintExtra(ctl, "%-20s %-10s %-10s\n", _("Name"), _("State"), _("Autostart"));
    vshPrintExtra(ctl, "-----------------------------------------\n");
2324 2325 2326

    for (i = 0; i < maxactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, activeNames[i]);
2327 2328
        const char *autostartStr;
        int autostart = 0;
2329 2330 2331 2332 2333

        /* this kind of work with networks is not atomic operation */
        if (!network) {
            free(activeNames[i]);
            continue;
2334
        }
2335

2336 2337 2338 2339 2340 2341 2342 2343 2344
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %-10s %-10s\n",
                 virNetworkGetName(network),
                 _("active"),
                 autostartStr);
2345 2346 2347 2348 2349
        virNetworkFree(network);
        free(activeNames[i]);
    }
    for (i = 0; i < maxinactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, inactiveNames[i]);
2350 2351
        const char *autostartStr;
        int autostart = 0;
2352 2353 2354 2355 2356

        /* this kind of work with networks is not atomic operation */
        if (!network) {
            free(inactiveNames[i]);
            continue;
2357
        }
2358

2359 2360 2361 2362 2363 2364 2365 2366 2367
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %s %s\n",
                 inactiveNames[i],
                 _("inactive"),
                 autostartStr);
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434

        virNetworkFree(network);
        free(inactiveNames[i]);
    }
    if (activeNames)
        free(activeNames);
    if (inactiveNames)
        free(inactiveNames);
    return TRUE;
}


/*
 * "net-name" command
 */
static vshCmdInfo info_network_name[] = {
    {"syntax", "net-name <network>"},
    {"help", gettext_noop("convert a network UUID to network name")},
    {NULL, NULL}
};

static vshCmdOptDef opts_network_name[] = {
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network uuid")},
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkName(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "network", NULL,
					   VSH_BYUUID)))
        return FALSE;

    vshPrint(ctl, "%s\n", virNetworkGetName(network));
    virNetworkFree(network);
    return TRUE;
}


/*
 * "net-start" command
 */
static vshCmdInfo info_network_start[] = {
    {"syntax", "start <network>"},
    {"help", gettext_noop("start a (previously defined) inactive network")},
    {"desc", gettext_noop("Start a network.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_network_start[] = {
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive network")},
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkStart(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    int ret = TRUE;

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

2435 2436
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
         return FALSE;
2437 2438 2439

    if (virNetworkCreate(network) == 0) {
        vshPrint(ctl, _("Network %s started\n"),
2440
                 virNetworkGetName(network));
2441
    } else {
2442 2443
        vshError(ctl, FALSE, _("Failed to start network %s"),
                 virNetworkGetName(network));
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
        ret = FALSE;
    }
    return ret;
}


/*
 * "net-undefine" command
 */
static vshCmdInfo info_network_undefine[] = {
    {"syntax", "net-undefine <network>"},
    {"help", gettext_noop("undefine an inactive network")},
    {"desc", gettext_noop("Undefine the configuration for an inactive network.")},
    {NULL, NULL}
};

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

static int
cmdNetworkUndefine(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    int ret = TRUE;
    char *name;

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

    if (!(network = vshCommandOptNetwork(ctl, cmd, "network", &name)))
        return FALSE;

    if (virNetworkUndefine(network) == 0) {
        vshPrint(ctl, _("Network %s has been undefined\n"), name);
    } else {
        vshError(ctl, FALSE, _("Failed to undefine network %s"), name);
        ret = FALSE;
    }

    return ret;
}


/*
 * "net-uuid" command
 */
static vshCmdInfo info_network_uuid[] = {
    {"syntax", "net-uuid <network>"},
    {"help", gettext_noop("convert a network name to network UUID")},
    {NULL, NULL}
};

static vshCmdOptDef opts_network_uuid[] = {
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name")},
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkUuid(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char uuid[VIR_UUID_STRING_BUFLEN];

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

    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "network", NULL,
					   VSH_BYNAME)))
        return FALSE;

    if (virNetworkGetUUIDString(network, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
        vshError(ctl, FALSE, _("failed to get network UUID"));

    return TRUE;
}


2525 2526 2527 2528
/*
 * "version" command
 */
static vshCmdInfo info_version[] = {
2529
    {"syntax", "version"},
2530 2531
    {"help", gettext_noop("show version")},
    {"desc", gettext_noop("Display the system version information.")},
2532
    {NULL, NULL}
2533 2534 2535 2536
};


static int
2537 2538
cmdVersion(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
2539 2540
    unsigned long hvVersion;
    const char *hvType;
2541 2542 2543 2544 2545 2546 2547
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;
2548 2549 2550

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

2552 2553
    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
2554
        vshError(ctl, FALSE, _("failed to get hypervisor type"));
2555 2556 2557
        return FALSE;
    }

2558 2559 2560 2561 2562
    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
2563
    vshPrint(ctl, _("Compiled against library: libvir %d.%d.%d\n"),
2564 2565 2566 2567
             major, minor, rel);

    ret = virGetVersion(&libVersion, hvType, &apiVersion);
    if (ret < 0) {
2568
        vshError(ctl, FALSE, _("failed to get the library version"));
2569 2570 2571 2572 2573 2574
        return FALSE;
    }
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
2575
    vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"),
2576
             major, minor, rel);
2577

2578 2579 2580 2581
    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
2582
    vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType,
2583 2584
             major, minor, rel);

2585
    ret = virConnectGetVersion(ctl->conn, &hvVersion);
2586
    if (ret < 0) {
2587
        vshError(ctl, FALSE, _("failed to get the hypervisor version"));
2588 2589 2590
        return FALSE;
    }
    if (hvVersion == 0) {
K
Karel Zak 已提交
2591
        vshPrint(ctl,
2592
                 _("Cannot extract running %s hypervisor version\n"), hvType);
2593
    } else {
2594
        major = hvVersion / 1000000;
2595
        hvVersion %= 1000000;
2596 2597
        minor = hvVersion / 1000;
        rel = hvVersion % 1000;
2598

2599
        vshPrint(ctl, _("Running hypervisor: %s %d.%d.%d\n"),
2600
                 hvType, major, minor, rel);
2601 2602 2603 2604
    }
    return TRUE;
}

2605
/*
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664
 * "hostname" command
 */
static vshCmdInfo info_hostname[] = {
    {"syntax", "hostname"},
    {"help", gettext_noop("print the hypervisor hostname")},
    {NULL, NULL}
};

static int
cmdHostname (vshControl *ctl, vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *hostname;

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

    hostname = virConnectGetHostname (ctl->conn);
    if (hostname == NULL) {
        vshError(ctl, FALSE, _("failed to get hostname"));
        return FALSE;
    }

    vshPrint (ctl, "%s\n", hostname);
    free (hostname);

    return TRUE;
}

/*
 * "uri" command
 */
static vshCmdInfo info_uri[] = {
    {"syntax", "uri"},
    {"help", gettext_noop("print the hypervisor canonical URI")},
    {NULL, NULL}
};

static int
cmdURI (vshControl *ctl, vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *uri;

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

    uri = virConnectGetURI (ctl->conn);
    if (uri == NULL) {
        vshError(ctl, FALSE, _("failed to get URI"));
        return FALSE;
    }

    vshPrint (ctl, "%s\n", uri);
    free (uri);

    return TRUE;
}

/*
 * "vncdisplay" command
2665 2666 2667 2668
 */
static vshCmdInfo info_vncdisplay[] = {
    {"syntax", "vncdisplay <domain>"},
    {"help", gettext_noop("vnc display")},
2669
    {"desc", gettext_noop("Output the IP address and port number for the VNC display.")},
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
    {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)
2697
        goto cleanup;
2698 2699

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
2700 2701
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOWARNING);
2702 2703 2704 2705 2706 2707 2708 2709 2710
    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) ||
2711
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
2712 2713 2714 2715
        goto cleanup;
    }
    port = strtol((const char *)obj->stringval, NULL, 10);
    if (port == -1) {
2716
        goto cleanup;
2717 2718 2719 2720 2721
    }
    xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@listen)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
2722 2723
        (obj->stringval == NULL) || (obj->stringval[0] == 0) ||
        !strcmp((const char*)obj->stringval, "0.0.0.0")) {
2724 2725 2726 2727 2728 2729 2730 2731 2732
        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)
2733
        xmlXPathFreeObject(obj);
2734 2735 2736 2737 2738 2739 2740 2741
    if (ctxt)
        xmlXPathFreeContext(ctxt);
    if (xml)
        xmlFreeDoc(xml);
    virDomainFree(dom);
    return ret;
}

2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
/*
 * "attach-device" command
 */
static vshCmdInfo info_attach_device[] = {
    {"syntax", "attach-device <domain> <file> "},
    {"help", gettext_noop("attach device from an XML file")},
    {"desc", gettext_noop("Attach device from an XML <file>.")},
    {NULL, NULL}
};

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

static int
cmdAttachDevice(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    char *buffer;
    int ret = TRUE;
    int found;

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

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

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

    buffer = readFile (ctl, from);
    if (buffer == NULL) return FALSE;

    ret = virDomainAttachDevice(dom, buffer);
    free (buffer);

    if (ret < 0) {
        vshError(ctl, FALSE, _("Failed to attach device from %s"), from);
        virDomainFree(dom);
        return FALSE;
    }

    virDomainFree(dom);
    return TRUE;
}


/*
 * "detach-device" command
 */
static vshCmdInfo info_detach_device[] = {
    {"syntax", "detach-device <domain> <file> "},
    {"help", gettext_noop("detach device from an XML file")},
    {"desc", gettext_noop("Detach device from an XML <file>")},
    {NULL, NULL}
};

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

static int
cmdDetachDevice(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    char *buffer;
    int ret = TRUE;
    int found;

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

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

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

    buffer = readFile (ctl, from);
    if (buffer == NULL) return FALSE;

    ret = virDomainDetachDevice(dom, buffer);
    free (buffer);

    if (ret < 0) {
        vshError(ctl, FALSE, _("Failed to detach device from %s"), from);
        virDomainFree(dom);
        return FALSE;
    }

    virDomainFree(dom);
    return TRUE;
}

2849

2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
/*
 * "attach-interface" command
 */
static vshCmdInfo info_attach_interface[] = {
    {"syntax", "attach-interface <domain> <type> <source> [--target <target>] [--mac <mac>] [--script <script>] "},
    {"help", gettext_noop("attach network interface")},
    {"desc", gettext_noop("Attach new network interface.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_attach_interface[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"type",   VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network interface type")},
    {"source", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("source of network interface")},
    {"target", VSH_OT_DATA, 0, gettext_noop("target network name")},
    {"mac",    VSH_OT_DATA, 0, gettext_noop("MAC adress")},
    {"script", VSH_OT_DATA, 0, gettext_noop("script used to bridge network interface")},
    {NULL, 0, 0, NULL}
};

static int
cmdAttachInterface(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom = NULL;
    char *mac, *target, *script, *type, *source;
    int typ, ret = FALSE;
    char *buf = NULL, *tmp = NULL;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        goto cleanup;

    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
        goto cleanup;

    if (!(type = vshCommandOptString(cmd, "type", NULL)))
        goto cleanup;

    source = vshCommandOptString(cmd, "source", NULL);
    target = vshCommandOptString(cmd, "target", NULL);
    mac = vshCommandOptString(cmd, "mac", NULL);
    script = vshCommandOptString(cmd, "script", NULL);

    /* check interface type */
    if (strcmp(type, "network") == 0) {
        typ = 1;
    } else if (strcmp(type, "bridge") == 0) {
        typ = 2;
    } else {
        vshError(ctl, FALSE, _("No support %s in command 'attach-interface'"), type);
        goto cleanup;
    }

    /* Make XML of interface */
    tmp = vshMalloc(ctl, 1);
    if (!tmp) goto cleanup;
    buf = vshMalloc(ctl, strlen(type) + 25);
    if (!buf) goto cleanup;
    sprintf(buf, "    <interface type='%s'>\n" , type);

    tmp = vshRealloc(ctl, tmp, strlen(source) + 28);
    if (!tmp) goto cleanup;
    if (typ == 1) {
        sprintf(tmp, "      <source network='%s'/>\n", source);
    } else if (typ == 2) {
        sprintf(tmp, "      <source bridge='%s'/>\n", source);
    }
    buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
    if (!buf) goto cleanup;
    strcat(buf, tmp);

    if (target != NULL) {
        tmp = vshRealloc(ctl, tmp, strlen(target) + 24);
        if (!tmp) goto cleanup;
        sprintf(tmp, "      <target dev='%s'/>\n", target);
        buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
        if (!buf) goto cleanup;
        strcat(buf, tmp);
    }

    if (mac != NULL) {
        tmp = vshRealloc(ctl, tmp, strlen(mac) + 25);
        if (!tmp) goto cleanup;
        sprintf(tmp, "      <mac address='%s'/>\n", mac);
        buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
        if (!buf) goto cleanup;
        strcat(buf, tmp);
    }

    if (script != NULL) {
        tmp = vshRealloc(ctl, tmp, strlen(script) + 25);
        if (!tmp) goto cleanup;
        sprintf(tmp, "      <script path='%s'/>\n", script);
        buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
        if (!buf) goto cleanup;
        strcat(buf, tmp);
    }

    buf = vshRealloc(ctl, buf, strlen(buf) + 19);
    if (!buf) goto cleanup;
    strcat(buf, "    </interface>\n");

    if (virDomainAttachDevice(dom, buf))
        goto cleanup;

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
    if (buf)
        free(buf);
    if (tmp)
        free(tmp);
    return ret;
}

/*
 * "detach-interface" command
 */
static vshCmdInfo info_detach_interface[] = {
    {"syntax", "detach-interface <domain> <type> [--mac <mac>] "},
    {"help", gettext_noop("detach network interface")},
    {"desc", gettext_noop("Detach network interface.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_detach_interface[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"type",   VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network interface type")},
    {"mac",    VSH_OT_DATA, 0, gettext_noop("MAC adress")},
    {NULL, 0, 0, NULL}
};

static int
cmdDetachInterface(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj=NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr cur = NULL;
    xmlChar *tmp_mac = NULL;
    xmlBufferPtr xml_buf = NULL;
    char *doc, *mac =NULL, *type;
    char buf[64];
    int i = 0, diff_mac, ret = FALSE;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        goto cleanup;

    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
        goto cleanup;

    if (!(type = vshCommandOptString(cmd, "type", NULL)))
        goto cleanup;

    mac = vshCommandOptString(cmd, "mac", NULL);

    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) {
        vshError(ctl, FALSE, _("Failed to get interface information"));
        goto cleanup;
    }
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt) {
        vshError(ctl, FALSE, _("Failed to get interface information"));
        goto cleanup;
    }

    sprintf(buf, "/domain/devices/interface[@type='%s']", type);
    obj = xmlXPathEval(BAD_CAST buf, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
        vshError(ctl, FALSE, _("No found interface whose type is %s"), type);
        goto cleanup;
    }

    if (!mac)
        goto hit;

    /* search mac */
    for (; i < obj->nodesetval->nodeNr; i++) {
        cur = obj->nodesetval->nodeTab[i]->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE && xmlStrEqual(cur->name, BAD_CAST "mac")) {
                tmp_mac = xmlGetProp(cur, BAD_CAST "address");
                diff_mac = xmlStrcasecmp(tmp_mac, BAD_CAST mac);
                xmlFree(tmp_mac);
                if (!diff_mac) {
                    goto hit;
                }
            }
            cur = cur->next;
        }
    }
    vshError(ctl, FALSE, _("No found interface whose MAC address is %s"), mac);
    goto cleanup;

 hit:
    xml_buf = xmlBufferCreate();
    if (!xml_buf) {
        vshError(ctl, FALSE, _("Failed to allocate memory"));
        goto cleanup;
    }

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
        vshError(ctl, FALSE, _("Failed to create XML"));
        goto cleanup;
    }

    ret = virDomainDetachDevice(dom, (char *)xmlBufferContent(xml_buf));
    if (ret != 0)
        ret = FALSE;
    else
        ret = TRUE;

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

/*
 * "attach-disk" command
 */
static vshCmdInfo info_attach_disk[] = {
    {"syntax", "attach-disk <domain> <source> <target> [--driver <driver>] [--subdriver <subdriver>] [--type <type>] [--mode <mode>] "},
    {"help", gettext_noop("attach disk device")},
    {"desc", gettext_noop("Attach new disk device.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_attach_disk[] = {
    {"domain",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"source",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("source of disk device")},
    {"target",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("target of disk device")},
    {"driver",    VSH_OT_DATA, 0, gettext_noop("driver of disk device")},
    {"subdriver", VSH_OT_DATA, 0, gettext_noop("subdriver of disk device")},
    {"type",    VSH_OT_DATA, 0, gettext_noop("target device type")},
    {"mode",    VSH_OT_DATA, 0, gettext_noop("mode of device reading and writing")},
    {NULL, 0, 0, NULL}
};

static int
cmdAttachDisk(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom = NULL;
    char *source, *target, *driver, *subdriver, *type, *mode;
    int isFile = 0, ret = FALSE;
    char *buf = NULL, *tmp = NULL;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        goto cleanup;

    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
        goto cleanup;

    if (!(source = vshCommandOptString(cmd, "source", NULL)))
        goto cleanup;

    if (!(target = vshCommandOptString(cmd, "target", NULL)))
        goto cleanup;

    driver = vshCommandOptString(cmd, "driver", NULL);
    subdriver = vshCommandOptString(cmd, "subdriver", NULL);
    type = vshCommandOptString(cmd, "type", NULL);
    mode = vshCommandOptString(cmd, "mode", NULL);

    if (type) {
        if (strcmp(type, "cdrom") && strcmp(type, "disk")) {
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), type);
            goto cleanup;
        }
    }

    if (driver) {
        if (!strcmp(driver, "file") || !strcmp(driver, "tap")) {
            isFile = 1;
        } else if (strcmp(driver, "phy")) {
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), driver);
            goto cleanup;
        }
    }

    if (mode) {
        if (strcmp(mode, "readonly") && strcmp(mode, "shareable")) {
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), mode);
            goto cleanup;
        }
    }

    /* Make XML of disk */
    tmp = vshMalloc(ctl, 1);
    if (!tmp) goto cleanup;
    buf = vshMalloc(ctl, 23);
    if (!buf) goto cleanup;
    if (isFile) {
        sprintf(buf, "    <disk type='file'");
    } else {
        sprintf(buf, "    <disk type='block'");
    }

    if (type) {
        tmp = vshRealloc(ctl, tmp, strlen(type) + 13);
        if (!tmp) goto cleanup;
        sprintf(tmp, " device='%s'>\n", type);
    } else {
        tmp = vshRealloc(ctl, tmp, 3);
        if (!tmp) goto cleanup;
        sprintf(tmp, ">\n");
    }
    buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
    if (!buf) goto cleanup;
    strcat(buf, tmp);

    if (driver) {
        tmp = vshRealloc(ctl, tmp, strlen(driver) + 22);
        if (!tmp) goto cleanup;
        sprintf(tmp, "      <driver name='%s'", driver);
    } else {
        tmp = vshRealloc(ctl, tmp, 25);
        if (!tmp) goto cleanup;
        sprintf(tmp, "      <driver name='phy'");
    }
    buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
    if (!buf) goto cleanup;
    strcat(buf, tmp);

    if (subdriver) {
        tmp = vshRealloc(ctl, tmp, strlen(subdriver) + 12);
        if (!tmp) goto cleanup;
        sprintf(tmp, " type='%s'/>\n", subdriver);
    } else {
        tmp = vshRealloc(ctl, tmp, 4);
        if (!tmp) goto cleanup;
        sprintf(tmp, "/>\n");
    }
    buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
    if (!buf) goto cleanup;
    strcat(buf, tmp);

    tmp = vshRealloc(ctl, tmp, strlen(source) + 25);
    if (!tmp) goto cleanup;
    if (isFile) {
        sprintf(tmp, "      <source file='%s'/>\n", source);
    } else {
        sprintf(tmp, "      <source dev='%s'/>\n", source);
    }
    buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
    if (!buf) goto cleanup;
    strcat(buf, tmp);

    tmp = vshRealloc(ctl, tmp, strlen(target) + 24);
    if (!tmp) goto cleanup;
    sprintf(tmp, "      <target dev='%s'/>\n", target);
    buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
    if (!buf) goto cleanup;
    strcat(buf, tmp);

    if (mode != NULL) {
        tmp = vshRealloc(ctl, tmp, strlen(mode) + 11);
        if (!tmp) goto cleanup;
        sprintf(tmp, "      <%s/>\n", mode);
        buf = vshRealloc(ctl, buf, strlen(buf) + strlen(tmp) + 1);
        if (!buf) goto cleanup;
        strcat(buf, tmp);
    }

    buf = vshRealloc(ctl, buf, strlen(buf) + 13);
    if (!buf) goto cleanup;
    strcat(buf, "    </disk>\n");

    if (virDomainAttachDevice(dom, buf))
        goto cleanup;

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
    if (buf)
        free(buf);
    if (tmp)
        free(tmp);
    return ret;
}

/*
 * "detach-disk" command
 */
static vshCmdInfo info_detach_disk[] = {
    {"syntax", "detach-disk <domain> <target> "},
    {"help", gettext_noop("detach disk device")},
    {"desc", gettext_noop("Detach disk device.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_detach_disk[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"target", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("target of disk device")},
    {NULL, 0, 0, NULL}
};

static int
cmdDetachDisk(vshControl * ctl, vshCmd * cmd)
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj=NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr cur = NULL;
    xmlChar *tmp_tgt = NULL;
    xmlBufferPtr xml_buf = NULL;
    virDomainPtr dom = NULL;
    char *doc, *target;
    int i = 0, diff_tgt, ret = FALSE;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        goto cleanup;

    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
        goto cleanup;

    if (!(target = vshCommandOptString(cmd, "target", NULL)))
        goto cleanup;

    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) {
        vshError(ctl, FALSE, _("Failed to get disk information"));
        goto cleanup;
    }
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt) {
        vshError(ctl, FALSE, _("Failed to get disk information"));
        goto cleanup;
    }

    obj = xmlXPathEval(BAD_CAST "/domain/devices/disk", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
        vshError(ctl, FALSE, _("Failed to get disk information"));
        goto cleanup;
    }

    /* search target */
    for (; i < obj->nodesetval->nodeNr; i++) {
        cur = obj->nodesetval->nodeTab[i]->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE && xmlStrEqual(cur->name, BAD_CAST "target")) {
                tmp_tgt = xmlGetProp(cur, BAD_CAST "dev");
                diff_tgt = xmlStrEqual(tmp_tgt, BAD_CAST target);
                xmlFree(tmp_tgt);
                if (diff_tgt) {
                    goto hit;
                }
            }
            cur = cur->next;
        }
    }
    vshError(ctl, FALSE, _("No found disk whose target is %s"), target);
    goto cleanup;

 hit:
    xml_buf = xmlBufferCreate();
    if (!xml_buf) {
        vshError(ctl, FALSE, _("Failed to allocate memory"));
        goto cleanup;
    }

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
        vshError(ctl, FALSE, _("Failed to create XML"));
        goto cleanup;
    }

    ret = virDomainDetachDevice(dom, (char *)xmlBufferContent(xml_buf));
    if (ret != 0)
        ret = FALSE;
    else
        ret = TRUE;

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

K
Karel Zak 已提交
3365 3366 3367 3368
/*
 * "quit" command
 */
static vshCmdInfo info_quit[] = {
3369
    {"syntax", "quit"},
3370
    {"help", gettext_noop("quit this interactive terminal")},
3371
    {NULL, NULL}
K
Karel Zak 已提交
3372 3373 3374
};

static int
3375 3376
cmdQuit(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
3377 3378 3379 3380 3381 3382 3383 3384
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
static vshCmdDef commands[] = {
3385 3386 3387 3388
    {"help", cmdHelp, opts_help, info_help},
    {"attach-device", cmdAttachDevice, opts_attach_device, info_attach_device},
    {"attach-disk", cmdAttachDisk, opts_attach_disk, info_attach_disk},
    {"attach-interface", cmdAttachInterface, opts_attach_interface, info_attach_interface},
3389
    {"autostart", cmdAutostart, opts_autostart, info_autostart},
3390
    {"capabilities", cmdCapabilities, NULL, info_capabilities},
3391
    {"connect", cmdConnect, opts_connect, info_connect},
3392
    {"console", cmdConsole, opts_console, info_console},
3393
    {"create", cmdCreate, opts_create, info_create},
3394
    {"start", cmdStart, opts_start, info_start},
K
Karel Zak 已提交
3395
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
3396 3397 3398
    {"detach-device", cmdDetachDevice, opts_detach_device, info_detach_device},
    {"detach-disk", cmdDetachDisk, opts_detach_disk, info_detach_disk},
    {"detach-interface", cmdDetachInterface, opts_detach_interface, info_detach_interface},
3399
    {"define", cmdDefine, opts_define, info_define},
K
Karel Zak 已提交
3400
    {"domid", cmdDomid, opts_domid, info_domid},
K
Karel Zak 已提交
3401
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid},
3402
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
3403 3404
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
3405
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
3406
    {"hostname", cmdHostname, NULL, info_hostname},
3407
    {"list", cmdList, opts_list, info_list},
3408
    {"net-autostart", cmdNetworkAutostart, opts_network_autostart, info_network_autostart},
3409 3410 3411 3412 3413 3414 3415 3416 3417
    {"net-create", cmdNetworkCreate, opts_network_create, info_network_create},
    {"net-define", cmdNetworkDefine, opts_network_define, info_network_define},
    {"net-destroy", cmdNetworkDestroy, opts_network_destroy, info_network_destroy},
    {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml, info_network_dumpxml},
    {"net-list", cmdNetworkList, opts_network_list, info_network_list},
    {"net-name", cmdNetworkName, opts_network_name, info_network_name},
    {"net-start", cmdNetworkStart, opts_network_start, info_network_start},
    {"net-undefine", cmdNetworkUndefine, opts_network_undefine, info_network_undefine},
    {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid},
K
Karel Zak 已提交
3418 3419 3420 3421
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
    {"quit", cmdQuit, NULL, info_quit},
    {"reboot", cmdReboot, opts_reboot, info_reboot},
    {"restore", cmdRestore, opts_restore, info_restore},
3422 3423
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
3424
    {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo},
D
Daniel Veillard 已提交
3425
    {"dump", cmdDump, opts_dump, info_dump},
3426
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
3427 3428 3429
    {"setmem", cmdSetmem, opts_setmem, info_setmem},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus},
K
Karel Zak 已提交
3430
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
3431
    {"undefine", cmdUndefine, opts_undefine, info_undefine},
3432
    {"uri", cmdURI, NULL, info_uri},
3433 3434
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
3435
    {"version", cmdVersion, NULL, info_version},
3436
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay},
3437
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
3438 3439 3440 3441 3442 3443
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
3444
static const char *
3445 3446
vshCmddefGetInfo(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
3447
    vshCmdInfo *info;
3448

K
Karel Zak 已提交
3449
    for (info = cmd->info; info && info->name; info++) {
3450
        if (strcmp(info->name, name) == 0)
K
Karel Zak 已提交
3451 3452 3453 3454 3455 3456
            return info->data;
    }
    return NULL;
}

static vshCmdOptDef *
3457 3458
vshCmddefGetOption(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
3459
    vshCmdOptDef *opt;
3460

K
Karel Zak 已提交
3461
    for (opt = cmd->opts; opt && opt->name; opt++)
3462
        if (strcmp(opt->name, name) == 0)
K
Karel Zak 已提交
3463 3464 3465 3466 3467
            return opt;
    return NULL;
}

static vshCmdOptDef *
3468 3469
vshCmddefGetData(vshCmdDef * cmd, int data_ct)
{
K
Karel Zak 已提交
3470 3471
    vshCmdOptDef *opt;

3472
    for (opt = cmd->opts; opt && opt->name; opt++) {
3473 3474
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
3475 3476 3477 3478 3479
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
3480 3481 3482
    return NULL;
}

3483 3484 3485
/*
 * Checks for required options
 */
3486 3487
static int
vshCommandCheckOpts(vshControl * ctl, vshCmd * cmd)
3488 3489 3490
{
    vshCmdDef *def = cmd->def;
    vshCmdOptDef *d;
3491
    int err = 0;
3492 3493 3494 3495

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

            while (o && ok == 0) {
3499
                if (o->def == d)
3500
                    ok = 1;
3501 3502 3503
                o = o->next;
            }
            if (!ok) {
3504 3505
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
3506
                         _("command '%s' requires <%s> option") :
3507
                         _("command '%s' requires --%s option"),
3508
                         def->name, d->name);
3509 3510
                err = 1;
            }
3511

3512 3513 3514 3515 3516
        }
    }
    return !err;
}

K
Karel Zak 已提交
3517
static vshCmdDef *
3518 3519
vshCmddefSearch(const char *cmdname)
{
K
Karel Zak 已提交
3520
    vshCmdDef *c;
3521

K
Karel Zak 已提交
3522
    for (c = commands; c->name; c++)
3523
        if (strcmp(c->name, cmdname) == 0)
K
Karel Zak 已提交
3524 3525 3526 3527 3528
            return c;
    return NULL;
}

static int
3529 3530
vshCmddefHelp(vshControl * ctl, const char *cmdname, int withprog)
{
K
Karel Zak 已提交
3531
    vshCmdDef *def = vshCmddefSearch(cmdname);
3532

K
Karel Zak 已提交
3533
    if (!def) {
3534
        vshError(ctl, FALSE, _("command '%s' doesn't exist"), cmdname);
3535 3536
        return FALSE;
    } else {
K
Karel Zak 已提交
3537
        vshCmdOptDef *opt;
3538 3539
        const char *desc = N_(vshCmddefGetInfo(def, "desc"));
        const char *help = N_(vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
3540
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
3541

3542
        fputs(_("  NAME\n"), stdout);
3543 3544
        fprintf(stdout, "    %s - %s\n", def->name, help);

K
Karel Zak 已提交
3545
        if (syntax) {
3546
            fputs(_("\n  SYNOPSIS\n"), stdout);
K
Karel Zak 已提交
3547 3548 3549 3550 3551 3552
            if (!withprog)
                fprintf(stdout, "    %s\n", syntax);
            else
                fprintf(stdout, "    %s %s\n", progname, syntax);
        }
        if (desc) {
3553
            fputs(_("\n  DESCRIPTION\n"), stdout);
K
Karel Zak 已提交
3554 3555 3556
            fprintf(stdout, "    %s\n", desc);
        }
        if (def->opts) {
3557
            fputs(_("\n  OPTIONS\n"), stdout);
3558
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
3559
                char buf[256];
3560 3561

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
3562
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
3563
                else if (opt->type == VSH_OT_INT)
3564
                    snprintf(buf, sizeof(buf), _("--%s <number>"), opt->name);
3565
                else if (opt->type == VSH_OT_STRING)
3566
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
3567
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
3568
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
3569

3570
                fprintf(stdout, "    %-15s  %s\n", buf, N_(opt->help));
3571
            }
K
Karel Zak 已提交
3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
3582 3583 3584
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
3585 3586
    vshCmdOpt *a = arg;

3587
    while (a) {
K
Karel Zak 已提交
3588
        vshCmdOpt *tmp = a;
3589

K
Karel Zak 已提交
3590 3591 3592 3593 3594 3595 3596 3597 3598
        a = a->next;

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

static void
3599 3600
vshCommandFree(vshCmd * cmd)
{
K
Karel Zak 已提交
3601 3602
    vshCmd *c = cmd;

3603
    while (c) {
K
Karel Zak 已提交
3604
        vshCmd *tmp = c;
3605

K
Karel Zak 已提交
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
3618 3619
vshCommandOpt(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
3620
    vshCmdOpt *opt = cmd->opts;
3621 3622 3623

    while (opt) {
        if (opt->def && strcmp(opt->def->name, name) == 0)
K
Karel Zak 已提交
3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
3634 3635
vshCommandOptInt(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
3636 3637
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
    int res = 0;
3638

K
Karel Zak 已提交
3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
    if (arg)
        res = atoi(arg->data);
    if (found)
        *found = arg ? TRUE : FALSE;
    return res;
}

/*
 * Returns option as STRING
 */
static char *
3650 3651
vshCommandOptString(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
3652
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
3653

K
Karel Zak 已提交
3654 3655
    if (found)
        *found = arg ? TRUE : FALSE;
3656 3657

    return arg && arg->data && *arg->data ? arg->data : NULL;
K
Karel Zak 已提交
3658 3659 3660 3661 3662 3663
}

/*
 * Returns TRUE/FALSE if the option exists
 */
static int
3664 3665
vshCommandOptBool(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
3666 3667 3668
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

3669

K
Karel Zak 已提交
3670
static virDomainPtr
K
Karel Zak 已提交
3671
vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd, const char *optname,
3672
                      char **name, int flag)
3673
{
K
Karel Zak 已提交
3674 3675 3676
    virDomainPtr dom = NULL;
    char *n, *end = NULL;
    int id;
3677

K
Karel Zak 已提交
3678
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
3679
        vshError(ctl, FALSE, _("undefined domain name or id"));
3680
        return NULL;
K
Karel Zak 已提交
3681
    }
3682

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

K
Karel Zak 已提交
3686 3687
    if (name)
        *name = n;
3688

K
Karel Zak 已提交
3689
    /* try it by ID */
3690
    if (flag & VSH_BYID) {
K
Karel Zak 已提交
3691 3692 3693 3694 3695 3696
        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);
        }
3697
    }
K
Karel Zak 已提交
3698
    /* try it by UUID */
3699
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
K
Karel Zak 已提交
3700
        vshDebug(ctl, 5, "%s: <%s> tring as domain UUID\n",
3701
                 cmd->def->name, optname);
K
Karel Zak 已提交
3702
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
3703
    }
K
Karel Zak 已提交
3704
    /* try it by NAME */
3705
    if (dom==NULL && (flag & VSH_BYNAME)) {
K
Karel Zak 已提交
3706
        vshDebug(ctl, 5, "%s: <%s> tring as domain NAME\n",
3707
                 cmd->def->name, optname);
K
Karel Zak 已提交
3708
        dom = virDomainLookupByName(ctl->conn, n);
3709
    }
K
Karel Zak 已提交
3710

3711
    if (!dom)
3712
        vshError(ctl, FALSE, _("failed to get domain '%s'"), n);
3713

K
Karel Zak 已提交
3714 3715 3716
    return dom;
}

3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753
static virNetworkPtr
vshCommandOptNetworkBy(vshControl * ctl, vshCmd * cmd, const char *optname,
		       char **name, int flag)
{
    virNetworkPtr network = NULL;
    char *n;

    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
        vshError(ctl, FALSE, _("undefined network name"));
        return NULL;
    }

    vshDebug(ctl, 5, "%s: found option <%s>: %s\n",
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by UUID */
    if (network==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
        vshDebug(ctl, 5, "%s: <%s> tring as network UUID\n",
		 cmd->def->name, optname);
        network = virNetworkLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (network==NULL && (flag & VSH_BYNAME)) {
        vshDebug(ctl, 5, "%s: <%s> tring as network NAME\n",
                 cmd->def->name, optname);
        network = virNetworkLookupByName(ctl->conn, n);
    }

    if (!network)
        vshError(ctl, FALSE, _("failed to get network '%s'"), n);

    return network;
}

K
Karel Zak 已提交
3754 3755 3756 3757
/*
 * Executes command(s) and returns return code from last command
 */
static int
3758 3759
vshCommandRun(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
3760
    int ret = TRUE;
3761 3762

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

K
Karel Zak 已提交
3765 3766
        if (ctl->timing)
            GETTIMEOFDAY(&before);
3767

K
Karel Zak 已提交
3768 3769 3770 3771
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
3772 3773

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

        if (ctl->timing)
3777
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
3778 3779
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
3780
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
        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

3796 3797 3798
static int
vshCommandGetToken(vshControl * ctl, char *str, char **end, char **res)
{
K
Karel Zak 已提交
3799 3800 3801 3802 3803
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
3804

K
Karel Zak 已提交
3805
    *end = NULL;
3806

3807
    while (p && *p && (*p == ' ' || *p == '\t'))
K
Karel Zak 已提交
3808
        p++;
3809 3810

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
3811
        return VSH_TK_END;
3812 3813
    if (*p == ';') {
        *end = ++p;             /* = \0 or begi of next command */
K
Karel Zak 已提交
3814 3815
        return VSH_TK_END;
    }
3816
    while (*p) {
K
Karel Zak 已提交
3817
        /* end of token is blank space or ';' */
3818
        if ((quote == FALSE && (*p == ' ' || *p == '\t')) || *p == ';')
K
Karel Zak 已提交
3819
            break;
3820

3821
        /* end of option name could be '=' */
3822 3823
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
3824 3825
            break;
        }
3826 3827 3828 3829

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
                && isalnum((unsigned char) *(p + 2))) {
K
Karel Zak 已提交
3830
                tk = VSH_TK_OPTION;
3831
                p += 2;
K
Karel Zak 已提交
3832 3833
            } else {
                tk = VSH_TK_DATA;
3834 3835
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
3836 3837 3838 3839 3840
                    p++;
                } else {
                    quote = FALSE;
                }
            }
3841 3842
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
3843 3844
            quote = FALSE;
            p++;
3845
            break;              /* end of "..." token */
K
Karel Zak 已提交
3846 3847 3848 3849 3850
        }
        p++;
        sz++;
    }
    if (quote) {
3851
        vshError(ctl, FALSE, _("missing \""));
K
Karel Zak 已提交
3852 3853
        return VSH_TK_ERROR;
    }
3854
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
3855
        return VSH_TK_END;
3856
    if (sz == 0)
K
Karel Zak 已提交
3857
        return VSH_TK_END;
3858

3859
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
3860
    memcpy(*res, tkstr, sz);
3861
    *(*res + sz) = '\0';
K
Karel Zak 已提交
3862 3863 3864 3865 3866 3867

    *end = p;
    return tk;
}

static int
3868 3869
vshCommandParse(vshControl * ctl, char *cmdstr)
{
K
Karel Zak 已提交
3870 3871 3872 3873
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
3874

K
Karel Zak 已提交
3875 3876 3877 3878
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
3879 3880

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

K
Karel Zak 已提交
3883
    str = cmdstr;
3884
    while (str && *str) {
K
Karel Zak 已提交
3885 3886 3887
        vshCmdOpt *last = NULL;
        vshCmdDef *cmd = NULL;
        int tk = VSH_TK_NONE;
3888
        int data_ct = 0;
3889

K
Karel Zak 已提交
3890
        first = NULL;
3891 3892

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
3893 3894
            char *end = NULL;
            vshCmdOptDef *opt = NULL;
3895

K
Karel Zak 已提交
3896
            tkdata = NULL;
3897

K
Karel Zak 已提交
3898 3899
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
3900

K
Karel Zak 已提交
3901
            str = end;
3902 3903

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
3904
                break;
3905
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
3906
                goto syntaxError;
3907 3908

            if (cmd == NULL) {
K
Karel Zak 已提交
3909
                /* first token must be command name */
3910 3911
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
3912
                             _("unexpected token (command name): '%s'"),
3913
                             tkdata);
K
Karel Zak 已提交
3914 3915 3916
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
3917
                    vshError(ctl, FALSE, _("unknown command: '%s'"), tkdata);
3918
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
3919 3920
                }
                free(tkdata);
3921
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
3922 3923
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
3924
                             _("command '%s' doesn't support option --%s"),
3925
                             cmd->name, tkdata);
K
Karel Zak 已提交
3926 3927
                    goto syntaxError;
                }
3928
                free(tkdata);   /* option name */
K
Karel Zak 已提交
3929 3930 3931 3932 3933
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
3934 3935
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
3936
                        goto syntaxError;
3937
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
3938
                        vshError(ctl, FALSE,
3939
                                 _("expected syntax: --%s <%s>"),
3940 3941
                                 opt->name,
                                 opt->type ==
3942
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
3943 3944 3945
                        goto syntaxError;
                    }
                }
3946
            } else if (tk == VSH_TK_DATA) {
3947
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
3948
                    vshError(ctl, FALSE, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
3949 3950 3951 3952 3953
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
3954
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
3955

K
Karel Zak 已提交
3956 3957 3958 3959
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
3960

K
Karel Zak 已提交
3961 3962 3963 3964 3965
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
3966

K
Karel Zak 已提交
3967
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
3968 3969
                         cmd->name,
                         opt->name,
3970
                         tk == VSH_TK_OPTION ? _("OPTION") : _("DATA"),
3971
                         arg->data);
K
Karel Zak 已提交
3972 3973 3974 3975
            }
            if (!str)
                break;
        }
3976

K
Karel Zak 已提交
3977 3978
        /* commad parsed -- allocate new struct for the command */
        if (cmd) {
3979
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
3980

K
Karel Zak 已提交
3981 3982 3983 3984
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

3985 3986
            if (!vshCommandCheckOpts(ctl, c)) {
                if(c) free(c);
3987
                goto syntaxError;
3988
            }
3989

K
Karel Zak 已提交
3990 3991 3992 3993 3994 3995 3996
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
3997

K
Karel Zak 已提交
3998 3999
    return TRUE;

4000
 syntaxError:
K
Karel Zak 已提交
4001 4002 4003 4004 4005 4006
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
    if (tkdata)
        free(tkdata);
4007
    return FALSE;
K
Karel Zak 已提交
4008 4009 4010 4011
}


/* ---------------
4012
 * Misc utils
K
Karel Zak 已提交
4013 4014
 * ---------------
 */
K
Karel Zak 已提交
4015
static const char *
4016 4017
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
4018
    switch (state) {
4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032
    case VIR_DOMAIN_RUNNING:
        return gettext_noop("running");
    case VIR_DOMAIN_BLOCKED:
        return gettext_noop("blocked");
    case VIR_DOMAIN_PAUSED:
        return gettext_noop("paused");
    case VIR_DOMAIN_SHUTDOWN:
        return gettext_noop("in shutdown");
    case VIR_DOMAIN_SHUTOFF:
        return gettext_noop("shut off");
    case VIR_DOMAIN_CRASHED:
        return gettext_noop("crashed");
    default:
        return gettext_noop("no state");  /* = dom0 state */
K
Karel Zak 已提交
4033 4034 4035 4036
    }
    return NULL;
}

4037 4038 4039 4040
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
4041 4042 4043 4044 4045 4046 4047 4048
    case VIR_VCPU_OFFLINE:
        return gettext_noop("offline");
    case VIR_VCPU_BLOCKED:
        return gettext_noop("blocked");
    case VIR_VCPU_RUNNING:
        return gettext_noop("running");
    default:
        return gettext_noop("no state");
4049 4050 4051 4052
    }
    return NULL;
}

K
Karel Zak 已提交
4053
static int
4054 4055
vshConnectionUsability(vshControl * ctl, virConnectPtr conn, int showerror)
{
4056 4057
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
4058 4059 4060
     */
    if (!conn) {
        if (showerror)
4061
            vshError(ctl, FALSE, _("no valid connection"));
K
Karel Zak 已提交
4062 4063 4064 4065 4066
        return FALSE;
    }
    return TRUE;
}

K
Karel Zak 已提交
4067 4068
static void
vshDebug(vshControl * ctl, int level, const char *format, ...)
4069
{
K
Karel Zak 已提交
4070 4071
    va_list ap;

4072 4073 4074 4075
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_DEBUG, format, ap);
    va_end(ap);

K
Karel Zak 已提交
4076 4077 4078 4079 4080 4081
    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
4082 4083 4084
}

static void
K
Karel Zak 已提交
4085
vshPrintExtra(vshControl * ctl, const char *format, ...)
4086
{
K
Karel Zak 已提交
4087
    va_list ap;
4088

K
Karel Zak 已提交
4089
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
4090
        return;
4091

K
Karel Zak 已提交
4092
    va_start(ap, format);
4093
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
4094 4095 4096
    va_end(ap);
}

K
Karel Zak 已提交
4097

K
Karel Zak 已提交
4098
static void
4099 4100
vshError(vshControl * ctl, int doexit, const char *format, ...)
{
K
Karel Zak 已提交
4101
    va_list ap;
4102

4103 4104 4105 4106
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
    va_end(ap);

K
Karel Zak 已提交
4107
    if (doexit)
4108
        fprintf(stderr, _("%s: error: "), progname);
K
Karel Zak 已提交
4109
    else
4110
        fputs(_("error: "), stderr);
4111

K
Karel Zak 已提交
4112 4113 4114 4115 4116
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
4117

K
Karel Zak 已提交
4118
    if (doexit) {
4119 4120
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
4121 4122 4123 4124
        exit(EXIT_FAILURE);
    }
}

4125 4126 4127 4128 4129 4130 4131
static void *
_vshMalloc(vshControl * ctl, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = malloc(size)))
        return x;
4132
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
4133
             filename, line, (int) size);
4134 4135 4136 4137 4138 4139 4140 4141 4142 4143
    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;
4144
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
4145
             filename, line, (int) (size*nmemb));
4146 4147 4148
    return NULL;
}

4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161
static void *
_vshRealloc(vshControl * ctl, void *ptr, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = realloc(ptr, size)))
        return x;
    free(ptr);
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) size);
    return NULL;
}

4162 4163 4164 4165 4166
static char *
_vshStrdup(vshControl * ctl, const char *s, const char *filename, int line)
{
    char *x;

4167 4168
    if (s == NULL)
        return(NULL);
4169 4170
    if ((x = strdup(s)))
        return x;
4171 4172
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
4173 4174 4175
    return NULL;
}

K
Karel Zak 已提交
4176
/*
4177
 * Initialize connection.
K
Karel Zak 已提交
4178 4179
 */
static int
4180 4181
vshInit(vshControl * ctl)
{
K
Karel Zak 已提交
4182 4183 4184 4185
    if (ctl->conn)
        return FALSE;

    ctl->uid = getuid();
4186

4187 4188
    vshOpenLogFile(ctl);

4189 4190
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
4191

4192 4193 4194 4195 4196 4197
    /* Force a non-root, Xen connection to readonly */
    if ((ctl->name == NULL ||
         !strcasecmp(ctl->name, "xen")) && ctl->uid != 0)
         ctl->readonly = 1;

    if (!ctl->readonly)
K
Karel Zak 已提交
4198
        ctl->conn = virConnectOpen(ctl->name);
K
Karel Zak 已提交
4199
    else
K
Karel Zak 已提交
4200
        ctl->conn = virConnectOpenReadOnly(ctl->name);
4201

4202 4203 4204 4205
    /* This is not necessarily fatal.  All the individual commands check
     * vshConnectionUsability, except ones which don't need a connection
     * such as "help".
     */
K
Karel Zak 已提交
4206
    if (!ctl->conn)
4207
        vshError(ctl, FALSE, _("failed to connect to the hypervisor"));
K
Karel Zak 已提交
4208 4209 4210 4211

    return TRUE;
}

4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
static void
vshOpenLogFile(vshControl *ctl)
{
    struct stat st;

    if (ctl->logfile == NULL)
        return;

    /* check log file */
    if (stat(ctl->logfile, &st) == -1) {
        switch (errno) {
            case ENOENT:
                break;
            default:
                vshError(ctl, TRUE, _("failed to get the log file information"));
                break;
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
            vshError(ctl, TRUE, _("the log path is not a file"));
        }
    }

    /* log file open */
    if ((ctl->log_fd = open(ctl->logfile, O_WRONLY | O_APPEND | O_CREAT | O_SYNC, FILE_MODE)) < 0) {
        vshError(ctl, TRUE, _("failed to open the log file. check the log file path"));
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
static void
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format, va_list ap)
{
    char msg_buf[MSG_BUFFER];
    const char *lvl = "";
    struct timeval stTimeval;
    struct tm *stTm;

    if (ctl->log_fd == -1)
        return;

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
    gettimeofday(&stTimeval, NULL);
    stTm = localtime(&stTimeval.tv_sec);
    snprintf(msg_buf, sizeof(msg_buf),
             "[%d.%02d.%02d %02d:%02d:%02d ",
             (1900 + stTm->tm_year),
             (1 + stTm->tm_mon),
             (stTm->tm_mday),
             (stTm->tm_hour),
             (stTm->tm_min),
             (stTm->tm_sec));
    snprintf(msg_buf + strlen(msg_buf), sizeof(msg_buf) - strlen(msg_buf),
             "%s] ", SIGN_NAME);
    switch (log_level) {
        case VSH_ERR_DEBUG:
            lvl = LVL_DEBUG;
            break;
        case VSH_ERR_INFO:
            lvl = LVL_INFO;
            break;
        case VSH_ERR_NOTICE:
            lvl = LVL_INFO;
            break;
        case VSH_ERR_WARNING:
            lvl = LVL_WARNING;
            break;
        case VSH_ERR_ERROR:
            lvl = LVL_ERROR;
            break;
        default:
            lvl = LVL_DEBUG;
            break;
    }
    snprintf(msg_buf + strlen(msg_buf), sizeof(msg_buf) - strlen(msg_buf),
             "%s ", lvl);
    vsnprintf(msg_buf + strlen(msg_buf), sizeof(msg_buf) - strlen(msg_buf),
              msg_format, ap);

    if (msg_buf[strlen(msg_buf) - 1] != '\n')
        snprintf(msg_buf + strlen(msg_buf), sizeof(msg_buf) - strlen(msg_buf), "\n");

    /* write log */
    if (write(ctl->log_fd, msg_buf, strlen(msg_buf)) == -1) {
        vshCloseLogFile(ctl);
        vshError(ctl, FALSE, _("failed to write the log file"));
    }
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
    if (ctl->log_fd >= 0) {
        close(ctl->log_fd);
        ctl->log_fd = -1;
    }

    if (ctl->logfile) {
        free(ctl->logfile);
        ctl->logfile = NULL;
    }
}

K
Karel Zak 已提交
4334 4335 4336 4337 4338
/* -----------------
 * Readline stuff
 * -----------------
 */

4339
/*
K
Karel Zak 已提交
4340 4341
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
4342
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
4343 4344
 */
static char *
4345 4346
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
4347
    static int list_index, len;
K
Karel Zak 已提交
4348
    const char *name;
K
Karel Zak 已提交
4349 4350 4351

    /* If this is a new word to complete, initialize now.  This
     * includes saving the length of TEXT for efficiency, and
4352
     * initializing the index variable to 0.
K
Karel Zak 已提交
4353 4354 4355
     */
    if (!state) {
        list_index = 0;
4356
        len = strlen(text);
K
Karel Zak 已提交
4357 4358 4359
    }

    /* Return the next name which partially matches from the
4360
     * command list.
K
Karel Zak 已提交
4361
     */
K
Karel Zak 已提交
4362
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
4363
        list_index++;
4364
        if (strncmp(name, text, len) == 0)
4365
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
4366 4367 4368 4369 4370 4371 4372
    }

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

static char *
4373 4374
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
4375 4376
    static int list_index, len;
    static vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
4377
    const char *name;
K
Karel Zak 已提交
4378 4379 4380 4381 4382 4383 4384 4385 4386

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

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

4387
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
4388
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
4389 4390 4391

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
4392
        len = strlen(text);
K
Karel Zak 已提交
4393 4394 4395 4396 4397
        free(cmdname);
    }

    if (!cmd)
        return NULL;
4398

4399 4400 4401
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
4402
    while ((name = cmd->opts[list_index].name)) {
K
Karel Zak 已提交
4403 4404
        vshCmdOptDef *opt = &cmd->opts[list_index];
        char *res;
4405

K
Karel Zak 已提交
4406
        list_index++;
4407

K
Karel Zak 已提交
4408
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
4409 4410
            /* ignore non --option */
            continue;
4411

K
Karel Zak 已提交
4412
        if (len > 2) {
4413
            if (strncmp(name, text + 2, len - 2))
K
Karel Zak 已提交
4414 4415
                continue;
        }
4416
        res = vshMalloc(NULL, strlen(name) + 3);
4417
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
4418 4419 4420 4421 4422 4423 4424 4425
        return res;
    }

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

static char **
4426 4427 4428
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
4429 4430
    char **matches = (char **) NULL;

4431
    if (start == 0)
K
Karel Zak 已提交
4432
        /* command name generator */
4433
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
4434 4435
    else
        /* commands options */
4436
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
4437 4438 4439 4440 4441
    return matches;
}


static void
4442 4443
vshReadlineInit(void)
{
K
Karel Zak 已提交
4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454
    /* 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
4455 4456
vshDeinit(vshControl * ctl)
{
4457 4458
    vshCloseLogFile(ctl);

K
Karel Zak 已提交
4459
    if (ctl->conn) {
4460 4461 4462 4463
        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 已提交
4464 4465 4466 4467
        }
    }
    return TRUE;
}
4468

K
Karel Zak 已提交
4469 4470 4471 4472
/*
 * Print usage
 */
static void
4473 4474
vshUsage(vshControl * ctl, const char *cmdname)
{
K
Karel Zak 已提交
4475
    vshCmdDef *cmd;
4476

K
Karel Zak 已提交
4477 4478
    /* global help */
    if (!cmdname) {
4479
        fprintf(stdout, _("\n%s [options] [commands]\n\n"
4480 4481
                          "  options:\n"
                          "    -c | --connect <uri>    hypervisor connection URI\n"
4482
                          "    -r | --readonly         connect readonly\n"
4483 4484 4485 4486
                          "    -d | --debug <num>      debug level [0-5]\n"
                          "    -h | --help             this help\n"
                          "    -q | --quiet            quiet mode\n"
                          "    -t | --timing           print timing information\n"
4487
                          "    -l | --log <file>       output logging to file\n"
4488 4489
                          "    -v | --version          program version\n\n"
                          "  commands (non interactive mode):\n"), progname);
4490 4491 4492

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

        fprintf(stdout,
4497
                _("\n  (specify --help <command> for details about the command)\n\n"));
K
Karel Zak 已提交
4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
4509 4510
vshParseArgv(vshControl * ctl, int argc, char **argv)
{
K
Karel Zak 已提交
4511 4512
    char *last = NULL;
    int i, end = 0, help = 0;
4513
    int arg, idx = 0;
K
Karel Zak 已提交
4514
    struct option opt[] = {
4515 4516 4517 4518 4519
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
4520
        {"connect", 1, 0, 'c'},
4521
        {"readonly", 0, 0, 'r'},
4522
        {"log", 1, 0, 'l'},
K
Karel Zak 已提交
4523
        {0, 0, 0, 0}
4524 4525
    };

K
Karel Zak 已提交
4526 4527

    if (argc < 2)
K
Karel Zak 已提交
4528
        return TRUE;
4529

4530
    /* look for begin of the command, for example:
K
Karel Zak 已提交
4531 4532 4533 4534
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
4535
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
4536 4537
        if (*argv[i] != '-') {
            int valid = FALSE;
4538

K
Karel Zak 已提交
4539 4540 4541 4542
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
4543 4544

                for (o = opt; o->name; o++) {
4545 4546 4547 4548 4549 4550 4551 4552
                    if (o->has_arg == 1){
                        if (sz == 2 && *(last + 1) == o->val)
                            /* valid virsh short option */
                            valid = TRUE;
                        else if (sz > 2 && strcmp(o->name, last + 2) == 0)
                            /* valid virsh long option */
                            valid = TRUE;
                    }
K
Karel Zak 已提交
4553 4554 4555 4556 4557 4558 4559 4560 4561 4562
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
    end = end ? : argc;
4563

K
Karel Zak 已提交
4564
    /* standard (non-command) options */
4565
    while ((arg = getopt_long(end, argv, "d:hqtc:vrl:", opt, &idx)) != -1) {
4566
        switch (arg) {
4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584
        case 'd':
            ctl->debug = atoi(optarg);
            break;
        case 'h':
            help = 1;
            break;
        case 'q':
            ctl->quiet = TRUE;
            break;
        case 't':
            ctl->timing = TRUE;
            break;
        case 'c':
            ctl->name = vshStrdup(ctl, optarg);
            break;
        case 'v':
            fprintf(stdout, "%s\n", VERSION);
            exit(EXIT_SUCCESS);
4585 4586 4587
        case 'r':
            ctl->readonly = TRUE;
            break;
4588 4589 4590
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
4591 4592 4593 4594
        default:
            vshError(ctl, TRUE,
                     _("unsupported option '-%c'. See --help."), arg);
            break;
K
Karel Zak 已提交
4595 4596 4597 4598 4599 4600 4601
        }
    }

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

K
Karel Zak 已提交
4604 4605 4606
    if (argc > end) {
        /* parse command */
        char *cmdstr;
4607 4608
        int sz = 0, ret;

K
Karel Zak 已提交
4609 4610
        ctl->imode = FALSE;

4611 4612 4613
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

4614
        cmdstr = vshCalloc(ctl, sz + 1, 1);
4615 4616

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
4617 4618 4619 4620
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
4621
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
4622
        ret = vshCommandParse(ctl, cmdstr);
4623

K
Karel Zak 已提交
4624 4625 4626 4627 4628 4629
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

4630 4631 4632 4633
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
4634
    char *defaultConn;
K
Karel Zak 已提交
4635 4636
    int ret = TRUE;

4637 4638
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
4639
        return -1;
4640 4641 4642
    }
    if (!bindtextdomain(GETTEXT_PACKAGE, LOCALEBASEDIR)) {
        perror("bindtextdomain");
4643
        return -1;
4644 4645 4646
    }
    if (!textdomain(GETTEXT_PACKAGE)) {
        perror("textdomain");
4647
        return -1;
4648 4649
    }

4650
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
4651 4652 4653
        progname = argv[0];
    else
        progname++;
4654

K
Karel Zak 已提交
4655
    memset(ctl, 0, sizeof(vshControl));
4656
    ctl->imode = TRUE;          /* default is interactive mode */
4657
    ctl->log_fd = -1;           /* Initialize log file descriptor */
K
Karel Zak 已提交
4658

4659
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
4660
        ctl->name = strdup(defaultConn);
4661 4662
    }

K
Karel Zak 已提交
4663 4664
    if (!vshParseArgv(ctl, argc, argv))
        exit(EXIT_FAILURE);
4665

K
Karel Zak 已提交
4666 4667
    if (!vshInit(ctl))
        exit(EXIT_FAILURE);
4668

K
Karel Zak 已提交
4669
    if (!ctl->imode) {
4670
        ret = vshCommandRun(ctl, ctl->cmd);
4671
    } else {
K
Karel Zak 已提交
4672 4673
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
4674
            vshPrint(ctl,
4675
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
4676
                     progname);
K
Karel Zak 已提交
4677
            vshPrint(ctl,
4678
                     _("Type:  'help' for help with commands\n"
4679
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
4680
        }
K
Karel Zak 已提交
4681
        vshReadlineInit();
K
Karel Zak 已提交
4682
        do {
4683 4684 4685 4686
            ctl->cmdstr =
                readline(ctl->uid == 0 ? VSH_PROMPT_RW : VSH_PROMPT_RO);
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
4687 4688 4689 4690 4691 4692 4693
            if (*ctl->cmdstr) {
                add_history(ctl->cmdstr);
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
4694
        } while (ctl->imode);
K
Karel Zak 已提交
4695

4696 4697
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
4698
    }
4699

K
Karel Zak 已提交
4700 4701
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
4702
}
K
Karel Zak 已提交
4703 4704 4705 4706 4707 4708

/*
 * vim: set tabstop=4:
 * vim: set shiftwidth=4:
 * vim: set expandtab:
 */
4709 4710 4711 4712 4713 4714 4715 4716
/*
 * Local variables:
 *  indent-tabs-mode: nil
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  tab-width: 4
 * End:
 */