virsh.c 190.5 KB
Newer Older
1
/*
2
 * virsh.c: a Xen shell used to exercise the libvirt API
3
 *
J
Jim Meyering 已提交
4
 * Copyright (C) 2005, 2007-2008 Red Hat, Inc.
5 6 7 8
 *
 * 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
 * Daniel P. Berrange <berrange@redhat.com>
11 12
 */

13
#include <config.h>
14

15
#include <stdio.h>
K
Karel Zak 已提交
16 17 18
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
19
#include <unistd.h>
20
#include <errno.h>
K
Karel Zak 已提交
21
#include <getopt.h>
22
#include <sys/types.h>
K
Karel Zak 已提交
23
#include <sys/time.h>
J
Jim Meyering 已提交
24
#include "c-ctype.h"
25
#include <fcntl.h>
26
#include <locale.h>
27
#include <time.h>
28
#include <limits.h>
29
#include <assert.h>
30 31
#include <errno.h>
#include <sys/stat.h>
32
#include <inttypes.h>
K
Karel Zak 已提交
33

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

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

43
#include "internal.h"
44
#include "buf.h"
45
#include "console.h"
46
#include "util.h"
K
Karel Zak 已提交
47 48 49 50 51 52 53 54

static char *progname;

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

55 56
#define VIRSH_MAX_XML_FILE 10*1024*1024

K
Karel Zak 已提交
57 58 59 60 61 62 63 64
#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)

65 66 67 68 69 70 71 72 73 74 75 76 77 78
/**
 * 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"

A
Atsushi SAKAI 已提交
79 80 81
#ifndef WEXITSTATUS
# define WEXITSTATUS(x) ((x) & 0xff)
#endif
82 83 84 85 86 87 88 89 90 91 92 93 94
/**
 * 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;

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

/*
132
 * vshCmdOptType - command option type
133
 */
K
Karel Zak 已提交
134
typedef enum {
135 136 137 138 139
    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 已提交
140 141 142 143 144
} vshCmdOptType;

/*
 * Command Option Flags
 */
145 146
#define VSH_OFLAG_NONE    0     /* without flags */
#define VSH_OFLAG_REQ    (1 << 1)       /* option required */
K
Karel Zak 已提交
147 148 149 150 151 152 153 154

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

/*
 * vshCmdInfo -- information about command
 */
155 156 157
typedef struct {
    const char *name;           /* name of information */
    const char *data;           /* information */
K
Karel Zak 已提交
158 159 160 161 162
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
163 164 165 166 167
typedef struct {
    const char *name;           /* the name of option */
    vshCmdOptType type;         /* option type */
    int flag;                   /* flags */
    const char *help;           /* help string */
K
Karel Zak 已提交
168 169 170 171 172 173
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
 */
typedef struct vshCmdOpt {
174
    const vshCmdOptDef *def;    /* pointer to relevant option */
175 176
    char *data;                 /* allocated data */
    struct vshCmdOpt *next;
K
Karel Zak 已提交
177 178 179 180 181
} vshCmdOpt;

/*
 * vshCmdDef - command definition
 */
182 183
typedef struct {
    const char *name;
184
    int (*handler) (vshControl *, const vshCmd *);    /* command handler */
185 186
    const vshCmdOptDef *opts;   /* definition of command options */
    const vshCmdInfo *info;     /* details about command */
K
Karel Zak 已提交
187 188 189 190 191 192
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
193
    const vshCmdDef *def;       /* command definition */
194 195
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
196 197 198 199 200 201
} __vshCmd;

/*
 * vshControl
 */
typedef struct __vshControl {
K
Karel Zak 已提交
202
    char *name;                 /* connection name */
203
    virConnectPtr conn;         /* connection to hypervisor (MAY BE NULL) */
204 205 206 207 208 209
    vshCmd *cmd;                /* the current command */
    char *cmdstr;               /* string with command */
    int imode;                  /* interactive mode? */
    int quiet;                  /* quiet mode */
    int debug;                  /* print debug messages? */
    int timing;                 /* print timing info? */
210 211 212
    int readonly;               /* connect readonly (first time only, not
                                 * during explicit connect command)
                                 */
213 214
    char *logfile;              /* log file name */
    int log_fd;                 /* log file descriptor */
K
Karel Zak 已提交
215
} __vshControl;
216

217

218
static const vshCmdDef commands[];
K
Karel Zak 已提交
219

220
static void vshError(vshControl *ctl, int doexit, const char *format, ...)
221
    ATTRIBUTE_FORMAT(printf, 3, 4);
222 223
static int vshInit(vshControl *ctl);
static int vshDeinit(vshControl *ctl);
224
static void vshUsage(void);
225 226 227
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 已提交
228

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

231
static const char *vshCmddefGetInfo(const vshCmdDef *cmd, const char *info);
232
static const vshCmdDef *vshCmddefSearch(const char *cmdname);
233
static int vshCmddefHelp(vshControl *ctl, const char *name);
K
Karel Zak 已提交
234

235 236 237
static vshCmdOpt *vshCommandOpt(const vshCmd *cmd, const char *name);
static int vshCommandOptInt(const vshCmd *cmd, const char *name, int *found);
static char *vshCommandOptString(const vshCmd *cmd, const char *name,
238
                                 int *found);
239
#if 0
240
static int vshCommandOptStringList(const vshCmd *cmd, const char *name, char ***data);
241
#endif
242
static int vshCommandOptBool(const vshCmd *cmd, const char *name);
K
Karel Zak 已提交
243

244 245 246
#define VSH_BYID     (1 << 1)
#define VSH_BYUUID   (1 << 2)
#define VSH_BYNAME   (1 << 3)
K
Karel Zak 已提交
247

248
static virDomainPtr vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
J
Jim Meyering 已提交
249
                                          char **name, int flag);
K
Karel Zak 已提交
250 251

/* default is lookup by Id, Name and UUID */
J
Jim Meyering 已提交
252 253
#define vshCommandOptDomain(_ctl, _cmd, _name)                      \
    vshCommandOptDomainBy(_ctl, _cmd, _name, VSH_BYID|VSH_BYUUID|VSH_BYNAME)
254

255
static virNetworkPtr vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd,
J
Jim Meyering 已提交
256
                                            char **name, int flag);
257 258

/* default is lookup by Name and UUID */
J
Jim Meyering 已提交
259 260
#define vshCommandOptNetwork(_ctl, _cmd, _name)                    \
    vshCommandOptNetworkBy(_ctl, _cmd, _name,                      \
261 262
                           VSH_BYUUID|VSH_BYNAME)

263
static virStoragePoolPtr vshCommandOptPoolBy(vshControl *ctl, const vshCmd *cmd,
264 265 266 267 268 269 270
                            const char *optname, char **name, int flag);

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

271
static virStorageVolPtr vshCommandOptVolBy(vshControl *ctl, const vshCmd *cmd,
272 273 274 275 276 277 278 279 280
                                           const char *optname,
                                           const char *pooloptname,
                                           char **name, int flag);

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

281
static void vshPrintExtra(vshControl *ctl, const char *format, ...)
282
    ATTRIBUTE_FORMAT(printf, 2, 3);
283
static void vshDebug(vshControl *ctl, int level, const char *format, ...)
284
    ATTRIBUTE_FORMAT(printf, 3, 4);
K
Karel Zak 已提交
285 286

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

K
Karel Zak 已提交
289
static const char *vshDomainStateToString(int state);
290
static const char *vshDomainVcpuStateToString(int state);
291
static int vshConnectionUsability(vshControl *ctl, virConnectPtr conn,
292
                                  int showerror);
K
Karel Zak 已提交
293

294
static void *_vshMalloc(vshControl *ctl, size_t sz, const char *filename, int line);
295 296
#define vshMalloc(_ctl, _sz)    _vshMalloc(_ctl, _sz, __FILE__, __LINE__)

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

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

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

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

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 已提交
325 326 327 328 329 330
/* ---------------
 * Commands
 * ---------------
 */

/*
331
 * "help" command
K
Karel Zak 已提交
332
 */
333
static const vshCmdInfo info_help[] = {
334 335 336
    {"help", gettext_noop("print help")},
    {"desc", gettext_noop("Prints global help or command specific help.")},

337
    {NULL, NULL}
K
Karel Zak 已提交
338 339
};

340
static const vshCmdOptDef opts_help[] = {
341
    {"command", VSH_OT_DATA, 0, gettext_noop("name of command")},
342
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
343 344 345
};

static int
346
cmdHelp(vshControl *ctl, const vshCmd *cmd)
347
{
K
Karel Zak 已提交
348
    const char *cmdname = vshCommandOptString(cmd, "command", NULL);
K
Karel Zak 已提交
349 350

    if (!cmdname) {
351
        const vshCmdDef *def;
352

J
Jim Meyering 已提交
353
        vshPrint(ctl, "%s", _("Commands:\n\n"));
354
        for (def = commands; def->name; def++)
K
Karel Zak 已提交
355
            vshPrint(ctl, "    %-15s %s\n", def->name,
356
                     N_(vshCmddefGetInfo(def, "help")));
K
Karel Zak 已提交
357 358
        return TRUE;
    }
359
    return vshCmddefHelp(ctl, cmdname);
K
Karel Zak 已提交
360 361
}

362 363 364
/*
 * "autostart" command
 */
365
static const vshCmdInfo info_autostart[] = {
366 367 368 369 370 371
    {"help", gettext_noop("autostart a domain")},
    {"desc",
     gettext_noop("Configure a domain to be automatically started at boot.")},
    {NULL, NULL}
};

372
static const vshCmdOptDef opts_autostart[] = {
373 374 375 376 377 378
    {"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
379
cmdAutostart(vshControl *ctl, const vshCmd *cmd)
380 381 382 383 384 385 386 387
{
    virDomainPtr dom;
    char *name;
    int autostart;

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

J
Jim Meyering 已提交
388
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
389 390 391 392 393
        return FALSE;

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

    if (virDomainSetAutostart(dom, autostart) < 0) {
394
        if (autostart)
395
            vshError(ctl, FALSE, _("Failed to mark domain %s as autostarted"),
396
                     name);
397 398
        else
            vshError(ctl, FALSE, _("Failed to unmark domain %s as autostarted"),
399
                     name);
400 401 402 403
        virDomainFree(dom);
        return FALSE;
    }

404
    if (autostart)
405
        vshPrint(ctl, _("Domain %s marked as autostarted\n"), name);
406
    else
407
        vshPrint(ctl, _("Domain %s unmarked as autostarted\n"), name);
408

409
    virDomainFree(dom);
410 411 412
    return TRUE;
}

K
Karel Zak 已提交
413
/*
414
 * "connect" command
K
Karel Zak 已提交
415
 */
416
static const vshCmdInfo info_connect[] = {
417
    {"help", gettext_noop("(re)connect to hypervisor")},
418
    {"desc",
419
     gettext_noop("Connect to local hypervisor. This is built-in command after shell start up.")},
420
    {NULL, NULL}
K
Karel Zak 已提交
421 422
};

423
static const vshCmdOptDef opts_connect[] = {
424 425
    {"name",     VSH_OT_DATA, 0, gettext_noop("hypervisor connection URI")},
    {"readonly", VSH_OT_BOOL, 0, gettext_noop("read-only connection")},
426
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
427 428 429
};

static int
430
cmdConnect(vshControl *ctl, const vshCmd *cmd)
431
{
K
Karel Zak 已提交
432
    int ro = vshCommandOptBool(cmd, "readonly");
433

K
Karel Zak 已提交
434
    if (ctl->conn) {
435
        if (virConnectClose(ctl->conn) != 0) {
J
Jim Meyering 已提交
436
            vshError(ctl, FALSE, "%s",
437
                     _("Failed to disconnect from the hypervisor"));
K
Karel Zak 已提交
438 439 440 441
            return FALSE;
        }
        ctl->conn = NULL;
    }
442

443
    free(ctl->name);
444
    ctl->name = vshStrdup(ctl, vshCommandOptString(cmd, "name", NULL));
K
Karel Zak 已提交
445

446
    if (!ro) {
K
Karel Zak 已提交
447
        ctl->conn = virConnectOpen(ctl->name);
448 449
        ctl->readonly = 0;
    } else {
K
Karel Zak 已提交
450
        ctl->conn = virConnectOpenReadOnly(ctl->name);
451 452
        ctl->readonly = 1;
    }
K
Karel Zak 已提交
453 454

    if (!ctl->conn)
J
Jim Meyering 已提交
455
        vshError(ctl, FALSE, "%s", _("Failed to connect to the hypervisor"));
456

K
Karel Zak 已提交
457 458 459
    return ctl->conn ? TRUE : FALSE;
}

460
/*
461
 * "console" command
462
 */
463
static const vshCmdInfo info_console[] = {
464 465 466 467 468 469
    {"help", gettext_noop("connect to the guest console")},
    {"desc",
     gettext_noop("Connect the virtual serial console for the guest")},
    {NULL, NULL}
};

470
static const vshCmdOptDef opts_console[] = {
471 472 473 474
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

475 476
#ifndef __MINGW32__

477
static int
478
cmdConsole(vshControl *ctl, const vshCmd *cmd)
479 480 481 482 483 484 485 486 487 488 489
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    int ret = FALSE;
    char *doc;

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

J
Jim Meyering 已提交
490
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
491 492 493 494
        return FALSE;

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

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
498 499
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOWARNING);
500 501 502 503 504 505 506 507 508
    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) &&
509
                          (obj->stringval != NULL) && (obj->stringval[0] != 0))) {
510
        if (vshRunConsole((const char *)obj->stringval) == 0)
511 512
            ret = TRUE;
    } else {
J
Jim Meyering 已提交
513
        vshPrintExtra(ctl, "%s", _("No console available for domain\n"));
514 515 516 517
    }
    xmlXPathFreeObject(obj);

 cleanup:
518
    xmlXPathFreeContext(ctxt);
519 520 521 522 523 524
    if (xml)
        xmlFreeDoc(xml);
    virDomainFree(dom);
    return ret;
}

525 526 527
#else /* __MINGW32__ */

static int
528
cmdConsole(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
529
{
J
Jim Meyering 已提交
530
    vshError (ctl, FALSE, "%s", _("console not implemented on this platform"));
531 532 533 534 535
    return FALSE;
}

#endif /* __MINGW32__ */

K
Karel Zak 已提交
536 537 538
/*
 * "list" command
 */
539
static const vshCmdInfo info_list[] = {
540 541
    {"help", gettext_noop("list domains")},
    {"desc", gettext_noop("Returns list of domains.")},
542
    {NULL, NULL}
K
Karel Zak 已提交
543 544
};

545
static const vshCmdOptDef opts_list[] = {
546 547
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive domains")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active domains")},
548 549 550
    {NULL, 0, 0, NULL}
};

K
Karel Zak 已提交
551 552

static int
553
cmdList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
554
{
555 556 557 558
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int *ids = NULL, maxid = 0, i;
559
    char **names = NULL;
560 561
    int maxname = 0;
    inactive |= all;
K
Karel Zak 已提交
562 563 564

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

566
    if (active) {
567 568
        maxid = virConnectNumOfDomains(ctl->conn);
        if (maxid < 0) {
J
Jim Meyering 已提交
569
            vshError(ctl, FALSE, "%s", _("Failed to list active domains"));
570 571 572 573 574 575
            return FALSE;
        }
        if (maxid) {
            ids = vshMalloc(ctl, sizeof(int) * maxid);

            if ((maxid = virConnectListDomains(ctl->conn, &ids[0], maxid)) < 0) {
J
Jim Meyering 已提交
576
                vshError(ctl, FALSE, "%s", _("Failed to list active domains"));
577 578 579 580
                free(ids);
                return FALSE;
            }

581
            qsort(&ids[0], maxid, sizeof(int), idsorter);
582
        }
583 584
    }
    if (inactive) {
585 586
        maxname = virConnectNumOfDefinedDomains(ctl->conn);
        if (maxname < 0) {
J
Jim Meyering 已提交
587
            vshError(ctl, FALSE, "%s", _("Failed to list inactive domains"));
588
            free(ids);
589
            return FALSE;
590
        }
591 592 593 594
        if (maxname) {
            names = vshMalloc(ctl, sizeof(char *) * maxname);

            if ((maxname = virConnectListDefinedDomains(ctl->conn, names, maxname)) < 0) {
J
Jim Meyering 已提交
595
                vshError(ctl, FALSE, "%s", _("Failed to list inactive domains"));
596
                free(ids);
597 598 599
                free(names);
                return FALSE;
            }
600

601
            qsort(&names[0], maxname, sizeof(char*), namesorter);
602
        }
603
    }
604
    vshPrintExtra(ctl, "%3s %-20s %s\n", _("Id"), _("Name"), _("State"));
K
Karel Zak 已提交
605
    vshPrintExtra(ctl, "----------------------------------\n");
606 607

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
608 609
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
610
        const char *state;
611 612

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
613 614
        if (!dom)
            continue;
615 616 617 618

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

K
Karel Zak 已提交
621
        vshPrint(ctl, "%3d %-20s %s\n",
622 623
                 virDomainGetID(dom),
                 virDomainGetName(dom),
624
                 state);
625
        virDomainFree(dom);
K
Karel Zak 已提交
626
    }
627 628 629
    for (i = 0; i < maxname; i++) {
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByName(ctl->conn, names[i]);
630
        const char *state;
631 632

        /* this kind of work with domains is not atomic operation */
633
        if (!dom) {
634
            free(names[i]);
635
            continue;
636
        }
637 638 639 640

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

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

645
        virDomainFree(dom);
646
        free(names[i]);
647
    }
648 649
    free(ids);
    free(names);
K
Karel Zak 已提交
650 651 652 653
    return TRUE;
}

/*
K
Karel Zak 已提交
654
 * "domstate" command
K
Karel Zak 已提交
655
 */
656
static const vshCmdInfo info_domstate[] = {
657
    {"help", gettext_noop("domain state")},
658
    {"desc", gettext_noop("Returns state about a domain.")},
659
    {NULL, NULL}
K
Karel Zak 已提交
660 661
};

662
static const vshCmdOptDef opts_domstate[] = {
663
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
664
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
665 666 667
};

static int
668
cmdDomstate(vshControl *ctl, const vshCmd *cmd)
669
{
670
    virDomainInfo info;
K
Karel Zak 已提交
671
    virDomainPtr dom;
K
Karel Zak 已提交
672
    int ret = TRUE;
673

K
Karel Zak 已提交
674 675
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
676

J
Jim Meyering 已提交
677
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
K
Karel Zak 已提交
678
        return FALSE;
679 680

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
681
        vshPrint(ctl, "%s\n",
682
                 N_(vshDomainStateToString(info.state)));
K
Karel Zak 已提交
683 684
    else
        ret = FALSE;
685

686 687 688 689
    virDomainFree(dom);
    return ret;
}

690 691
/* "domblkstat" command
 */
692
static const vshCmdInfo info_domblkstat[] = {
693 694 695 696 697
    {"help", gettext_noop("get device block stats for a domain")},
    {"desc", gettext_noop("Get device block stats for a running domain.")},
    {NULL,NULL}
};

698
static const vshCmdOptDef opts_domblkstat[] = {
699 700 701 702 703 704
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("block device")},
    {NULL, 0, 0, NULL}
};

static int
705
cmdDomblkstat (vshControl *ctl, const vshCmd *cmd)
706 707 708 709 710 711 712 713
{
    virDomainPtr dom;
    char *name, *device;
    struct _virDomainBlockStats stats;

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

J
Jim Meyering 已提交
714
    if (!(dom = vshCommandOptDomain (ctl, cmd, &name)))
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
        return FALSE;

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

    if (virDomainBlockStats (dom, device, &stats, sizeof stats) == -1) {
        vshError (ctl, FALSE, _("Failed to get block stats %s %s"),
                  name, device);
        virDomainFree(dom);
        return FALSE;
    }

    if (stats.rd_req >= 0)
        vshPrint (ctl, "%s rd_req %lld\n", device, stats.rd_req);

    if (stats.rd_bytes >= 0)
        vshPrint (ctl, "%s rd_bytes %lld\n", device, stats.rd_bytes);

    if (stats.wr_req >= 0)
        vshPrint (ctl, "%s wr_req %lld\n", device, stats.wr_req);

    if (stats.wr_bytes >= 0)
        vshPrint (ctl, "%s wr_bytes %lld\n", device, stats.wr_bytes);

    if (stats.errs >= 0)
        vshPrint (ctl, "%s errs %lld\n", device, stats.errs);

    virDomainFree(dom);
    return TRUE;
}

/* "domifstat" command
 */
748
static const vshCmdInfo info_domifstat[] = {
749 750 751 752 753
    {"help", gettext_noop("get network interface stats for a domain")},
    {"desc", gettext_noop("Get network interface stats for a running domain.")},
    {NULL,NULL}
};

754
static const vshCmdOptDef opts_domifstat[] = {
755 756 757 758 759 760
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("interface device")},
    {NULL, 0, 0, NULL}
};

static int
761
cmdDomIfstat (vshControl *ctl, const vshCmd *cmd)
762 763 764 765 766 767 768 769
{
    virDomainPtr dom;
    char *name, *device;
    struct _virDomainInterfaceStats stats;

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

J
Jim Meyering 已提交
770
    if (!(dom = vshCommandOptDomain (ctl, cmd, &name)))
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
        return FALSE;

    if (!(device = vshCommandOptString (cmd, "interface", NULL)))
        return FALSE;

    if (virDomainInterfaceStats (dom, device, &stats, sizeof stats) == -1) {
        vshError (ctl, FALSE, _("Failed to get interface stats %s %s"),
                  name, device);
        virDomainFree(dom);
        return FALSE;
    }

    if (stats.rx_bytes >= 0)
        vshPrint (ctl, "%s rx_bytes %lld\n", device, stats.rx_bytes);

    if (stats.rx_packets >= 0)
        vshPrint (ctl, "%s rx_packets %lld\n", device, stats.rx_packets);

    if (stats.rx_errs >= 0)
        vshPrint (ctl, "%s rx_errs %lld\n", device, stats.rx_errs);

    if (stats.rx_drop >= 0)
        vshPrint (ctl, "%s rx_drop %lld\n", device, stats.rx_drop);

    if (stats.tx_bytes >= 0)
        vshPrint (ctl, "%s tx_bytes %lld\n", device, stats.tx_bytes);

    if (stats.tx_packets >= 0)
        vshPrint (ctl, "%s tx_packets %lld\n", device, stats.tx_packets);

    if (stats.tx_errs >= 0)
        vshPrint (ctl, "%s tx_errs %lld\n", device, stats.tx_errs);

    if (stats.tx_drop >= 0)
        vshPrint (ctl, "%s tx_drop %lld\n", device, stats.tx_drop);

    virDomainFree(dom);
    return TRUE;
}

811 812 813
/*
 * "suspend" command
 */
814
static const vshCmdInfo info_suspend[] = {
815 816
    {"help", gettext_noop("suspend a domain")},
    {"desc", gettext_noop("Suspend a running domain.")},
817
    {NULL, NULL}
818 819
};

820
static const vshCmdOptDef opts_suspend[] = {
821
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
822
    {NULL, 0, 0, NULL}
823 824 825
};

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

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

J
Jim Meyering 已提交
835
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
836
        return FALSE;
837 838

    if (virDomainSuspend(dom) == 0) {
839
        vshPrint(ctl, _("Domain %s suspended\n"), name);
840
    } else {
841
        vshError(ctl, FALSE, _("Failed to suspend domain %s"), name);
842 843
        ret = FALSE;
    }
844

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

849 850 851
/*
 * "create" command
 */
852
static const vshCmdInfo info_create[] = {
853 854
    {"help", gettext_noop("create a domain from an XML file")},
    {"desc", gettext_noop("Create a domain.")},
855 856 857
    {NULL, NULL}
};

858
static const vshCmdOptDef opts_create[] = {
859
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
860 861 862 863
    {NULL, 0, 0, NULL}
};

static int
864
cmdCreate(vshControl *ctl, const vshCmd *cmd)
865 866 867 868 869
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
870
    char *buffer;
871 872 873 874 875 876 877 878

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

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

879 880
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
881

882
    dom = virDomainCreateXML(ctl->conn, buffer, 0);
883 884
    free (buffer);

885
    if (dom != NULL) {
886
        vshPrint(ctl, _("Domain %s created from %s\n"),
887
                 virDomainGetName(dom), from);
888
        virDomainFree(dom);
889
    } else {
890
        vshError(ctl, FALSE, _("Failed to create domain from %s"), from);
891 892 893 894 895
        ret = FALSE;
    }
    return ret;
}

896 897 898
/*
 * "define" command
 */
899
static const vshCmdInfo info_define[] = {
900 901
    {"help", gettext_noop("define (but don't start) a domain from an XML file")},
    {"desc", gettext_noop("Define a domain.")},
902 903 904
    {NULL, NULL}
};

905
static const vshCmdOptDef opts_define[] = {
906
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
907 908 909 910
    {NULL, 0, 0, NULL}
};

static int
911
cmdDefine(vshControl *ctl, const vshCmd *cmd)
912 913 914 915 916
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
917
    char *buffer;
918 919 920 921 922 923 924 925

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

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

926 927
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
928 929 930 931

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

932
    if (dom != NULL) {
933
        vshPrint(ctl, _("Domain %s defined from %s\n"),
934
                 virDomainGetName(dom), from);
935
        virDomainFree(dom);
936
    } else {
937
        vshError(ctl, FALSE, _("Failed to define domain from %s"), from);
938 939 940 941 942 943 944 945
        ret = FALSE;
    }
    return ret;
}

/*
 * "undefine" command
 */
946
static const vshCmdInfo info_undefine[] = {
947 948
    {"help", gettext_noop("undefine an inactive domain")},
    {"desc", gettext_noop("Undefine the configuration for an inactive domain.")},
949 950 951
    {NULL, NULL}
};

952
static const vshCmdOptDef opts_undefine[] = {
953
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
954 955 956 957
    {NULL, 0, 0, NULL}
};

static int
958
cmdUndefine(vshControl *ctl, const vshCmd *cmd)
959 960 961 962
{
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
963 964
    int found;
    int id;
965 966 967 968

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

969 970 971 972 973 974 975 976 977 978 979 980
    name = vshCommandOptString(cmd, "domain", &found);
    if (!found)
        return FALSE;

    if (name && virStrToLong_i(name, NULL, 10, &id) == 0
        && id >= 0 && (dom = virDomainLookupByID(ctl->conn, id))) {
        vshError(ctl, FALSE, _("a running domain like %s cannot be undefined;\n"
                               "to undefine, first shutdown then undefine"
                               " using its name or UUID"), name);
        virDomainFree(dom);
        return FALSE;
    }
J
Jim Meyering 已提交
981
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, &name,
982
                                      VSH_BYNAME|VSH_BYUUID)))
983 984 985
        return FALSE;

    if (virDomainUndefine(dom) == 0) {
986
        vshPrint(ctl, _("Domain %s has been undefined\n"), name);
987
    } else {
988
        vshError(ctl, FALSE, _("Failed to undefine domain %s"), name);
989 990 991
        ret = FALSE;
    }

992
    virDomainFree(dom);
993 994 995 996 997 998 999
    return ret;
}


/*
 * "start" command
 */
1000
static const vshCmdInfo info_start[] = {
1001 1002
    {"help", gettext_noop("start a (previously defined) inactive domain")},
    {"desc", gettext_noop("Start a domain.")},
1003 1004 1005
    {NULL, NULL}
};

1006
static const vshCmdOptDef opts_start[] = {
1007
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive domain")},
1008 1009 1010 1011
    {NULL, 0, 0, NULL}
};

static int
1012
cmdStart(vshControl *ctl, const vshCmd *cmd)
1013 1014 1015 1016 1017 1018 1019
{
    virDomainPtr dom;
    int ret = TRUE;

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

J
Jim Meyering 已提交
1020
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL, VSH_BYNAME)))
1021 1022 1023
        return FALSE;

    if (virDomainGetID(dom) != (unsigned int)-1) {
J
Jim Meyering 已提交
1024
        vshError(ctl, FALSE, "%s", _("Domain is already active"));
1025
        virDomainFree(dom);
1026 1027 1028 1029
        return FALSE;
    }

    if (virDomainCreate(dom) == 0) {
1030
        vshPrint(ctl, _("Domain %s started\n"),
1031
                 virDomainGetName(dom));
1032
    } else {
1033 1034
        vshError(ctl, FALSE, _("Failed to start domain %s"),
                 virDomainGetName(dom));
1035 1036
        ret = FALSE;
    }
1037
    virDomainFree(dom);
1038 1039 1040
    return ret;
}

1041 1042 1043
/*
 * "save" command
 */
1044
static const vshCmdInfo info_save[] = {
1045 1046
    {"help", gettext_noop("save a domain state to a file")},
    {"desc", gettext_noop("Save a running domain.")},
1047
    {NULL, NULL}
1048 1049
};

1050
static const vshCmdOptDef opts_save[] = {
1051 1052
    {"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")},
1053
    {NULL, 0, 0, NULL}
1054 1055 1056
};

static int
1057
cmdSave(vshControl *ctl, const vshCmd *cmd)
1058
{
1059 1060 1061 1062
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
1063

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

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

J
Jim Meyering 已提交
1070
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
1071
        return FALSE;
1072 1073

    if (virDomainSave(dom, to) == 0) {
1074
        vshPrint(ctl, _("Domain %s saved to %s\n"), name, to);
1075
    } else {
1076
        vshError(ctl, FALSE, _("Failed to save domain %s to %s"), name, to);
1077 1078
        ret = FALSE;
    }
1079

1080 1081 1082 1083
    virDomainFree(dom);
    return ret;
}

1084 1085 1086
/*
 * "schedinfo" command
 */
1087
static const vshCmdInfo info_schedinfo[] = {
1088 1089 1090 1091 1092
    {"help", gettext_noop("show/set scheduler parameters")},
    {"desc", gettext_noop("Show/Set scheduler parameters.")},
    {NULL, NULL}
};

1093
static const vshCmdOptDef opts_schedinfo[] = {
1094
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1095
    {"set", VSH_OT_STRING, VSH_OFLAG_NONE, gettext_noop("parameter=value")},
1096 1097 1098 1099 1100 1101
    {"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
1102
cmdSchedinfo(vshControl *ctl, const vshCmd *cmd)
1103 1104
{
    char *schedulertype;
1105 1106 1107
    char *set;
    char *param_name = NULL;
    long long int param_value = 0;
1108
    virDomainPtr dom;
1109
    virSchedParameterPtr params = NULL;
1110 1111 1112 1113 1114
    int i, ret;
    int nparams = 0;
    int nr_inputparams = 0;
    int inputparams = 0;
    int weightfound = 0;
1115
    int setfound = 0;
1116
    int weight = 0;
1117
    int capfound = 0;
1118
    int cap = 0;
1119 1120
    char str_weight[] = "weight";
    char str_cap[]    = "cap";
1121
    int ret_val = FALSE;
1122 1123 1124 1125

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

J
Jim Meyering 已提交
1126
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
1127 1128
        return FALSE;

1129
    /* Deprecated Xen-only options */
1130 1131 1132
    if(vshCommandOptBool(cmd, "weight")) {
        weight = vshCommandOptInt(cmd, "weight", &weightfound);
        if (!weightfound) {
J
Jim Meyering 已提交
1133
            vshError(ctl, FALSE, "%s", _("Invalid value of weight"));
1134 1135 1136 1137 1138 1139 1140 1141 1142
            goto cleanup;
        } else {
            nr_inputparams++;
        }
    }

    if(vshCommandOptBool(cmd, "cap")) {
        cap = vshCommandOptInt(cmd, "cap", &capfound);
        if (!capfound) {
J
Jim Meyering 已提交
1143
            vshError(ctl, FALSE, "%s", _("Invalid value of cap"));
1144 1145 1146 1147 1148
            goto cleanup;
        } else {
            nr_inputparams++;
        }
    }
1149

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    if(vshCommandOptBool(cmd, "set")) {
        set = vshCommandOptString(cmd, "set", &setfound);
        if (!setfound) {
            vshError(ctl, FALSE, "%s", _("Error getting param"));
            goto cleanup;
        }

        param_name = vshMalloc(ctl, strlen(set) + 1);
        if (param_name == NULL)
            goto cleanup;

D
Daniel P. Berrange 已提交
1161
        if (sscanf(set, "%[^=]=%lli", param_name, &param_value) != 2) {
1162 1163 1164 1165 1166 1167 1168
            vshError(ctl, FALSE, "%s", _("Invalid value of param"));
            goto cleanup;
        }

        nr_inputparams++;
    }

1169
    params = vshMalloc(ctl, sizeof (virSchedParameter) * nr_inputparams);
1170
    if (params == NULL) {
1171
        goto cleanup;
1172
    }
1173 1174 1175 1176 1177

    if (weightfound) {
         strncpy(params[inputparams].field,str_weight,sizeof(str_weight));
         params[inputparams].type = VIR_DOMAIN_SCHED_FIELD_UINT;
         params[inputparams].value.ui = weight;
1178
         inputparams++;
1179 1180 1181 1182 1183 1184 1185 1186
    }

    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++;
    }
1187 1188 1189 1190 1191 1192 1193 1194
    /* End Deprecated Xen-only options */

    if (setfound) {
        strncpy(params[inputparams].field,param_name,sizeof(params[0].field));
        params[inputparams].type = VIR_DOMAIN_SCHED_FIELD_LLONG;
        params[inputparams].value.l = param_value;
        inputparams++;
    }
1195 1196 1197 1198 1199 1200

    assert (inputparams == nr_inputparams);

    /* Set SchedulerParameters */
    if (inputparams > 0) {
        ret = virDomainSetSchedulerParameters(dom, params, inputparams);
1201
        if (ret == -1) {
1202
            goto cleanup;
1203
        }
1204 1205
    }
    free(params);
1206
    params = NULL;
1207 1208 1209 1210

    /* Print SchedulerType */
    schedulertype = virDomainGetSchedulerType(dom, &nparams);
    if (schedulertype!= NULL){
1211
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"),
1212 1213 1214
             schedulertype);
        free(schedulertype);
    } else {
1215
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"), _("Unknown"));
1216
        goto cleanup;
1217 1218 1219 1220
    }

    /* Get SchedulerParameters */
    params = vshMalloc(ctl, sizeof(virSchedParameter)* nparams);
1221 1222 1223
    if (params == NULL) {
        goto cleanup;
    }
1224 1225 1226 1227 1228
    for (i = 0; i < nparams; i++){
        params[i].type = 0;
        memset (params[i].field, 0, sizeof params[i].field);
    }
    ret = virDomainGetSchedulerParameters(dom, params, &nparams);
1229
    if (ret == -1) {
1230
        goto cleanup;
1231
    }
1232
    ret_val = TRUE;
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    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");
            }
        }
    }
1259
 cleanup:
1260
    free(params);
1261
    free(param_name);
1262
    virDomainFree(dom);
1263
    return ret_val;
1264 1265
}

1266 1267 1268
/*
 * "restore" command
 */
1269
static const vshCmdInfo info_restore[] = {
1270 1271
    {"help", gettext_noop("restore a domain from a saved state in a file")},
    {"desc", gettext_noop("Restore a domain.")},
1272
    {NULL, NULL}
1273 1274
};

1275
static const vshCmdOptDef opts_restore[] = {
1276
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("the state to restore")},
1277
    {NULL, 0, 0, NULL}
1278 1279 1280
};

static int
1281
cmdRestore(vshControl *ctl, const vshCmd *cmd)
1282
{
1283 1284 1285
    char *from;
    int found;
    int ret = TRUE;
1286

1287 1288 1289 1290 1291 1292
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
1295
        vshPrint(ctl, _("Domain restored from %s\n"), from);
1296
    } else {
1297
        vshError(ctl, FALSE, _("Failed to restore domain from %s"), from);
1298 1299 1300 1301 1302
        ret = FALSE;
    }
    return ret;
}

D
Daniel Veillard 已提交
1303 1304 1305
/*
 * "dump" command
 */
1306
static const vshCmdInfo info_dump[] = {
D
Daniel Veillard 已提交
1307 1308 1309 1310 1311
    {"help", gettext_noop("dump the core of a domain to a file for analysis")},
    {"desc", gettext_noop("Core dump a domain.")},
    {NULL, NULL}
};

1312
static const vshCmdOptDef opts_dump[] = {
D
Daniel Veillard 已提交
1313 1314 1315 1316 1317 1318
    {"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
1319
cmdDump(vshControl *ctl, const vshCmd *cmd)
D
Daniel Veillard 已提交
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
{
    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;

J
Jim Meyering 已提交
1332
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
D
Daniel Veillard 已提交
1333 1334 1335
        return FALSE;

    if (virDomainCoreDump(dom, to, 0) == 0) {
1336
        vshPrint(ctl, _("Domain %s dumped to %s\n"), name, to);
D
Daniel Veillard 已提交
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    } else {
        vshError(ctl, FALSE, _("Failed to core dump domain %s to %s"),
                 name, to);
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1347 1348 1349
/*
 * "resume" command
 */
1350
static const vshCmdInfo info_resume[] = {
1351 1352
    {"help", gettext_noop("resume a domain")},
    {"desc", gettext_noop("Resume a previously suspended domain.")},
1353
    {NULL, NULL}
1354 1355
};

1356
static const vshCmdOptDef opts_resume[] = {
1357
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1358
    {NULL, 0, 0, NULL}
1359 1360 1361
};

static int
1362
cmdResume(vshControl *ctl, const vshCmd *cmd)
1363
{
1364
    virDomainPtr dom;
K
Karel Zak 已提交
1365 1366
    int ret = TRUE;
    char *name;
1367

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

J
Jim Meyering 已提交
1371
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
1372
        return FALSE;
1373 1374

    if (virDomainResume(dom) == 0) {
1375
        vshPrint(ctl, _("Domain %s resumed\n"), name);
1376
    } else {
1377
        vshError(ctl, FALSE, _("Failed to resume domain %s"), name);
1378 1379
        ret = FALSE;
    }
1380

1381 1382 1383 1384
    virDomainFree(dom);
    return ret;
}

1385 1386 1387
/*
 * "shutdown" command
 */
1388
static const vshCmdInfo info_shutdown[] = {
1389 1390
    {"help", gettext_noop("gracefully shutdown a domain")},
    {"desc", gettext_noop("Run shutdown in the target domain.")},
1391
    {NULL, NULL}
1392 1393
};

1394
static const vshCmdOptDef opts_shutdown[] = {
1395
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1396
    {NULL, 0, 0, NULL}
1397 1398 1399
};

static int
1400
cmdShutdown(vshControl *ctl, const vshCmd *cmd)
1401
{
1402 1403 1404
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
1405

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

J
Jim Meyering 已提交
1409
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
1410
        return FALSE;
1411 1412

    if (virDomainShutdown(dom) == 0) {
1413
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
1414
    } else {
1415
        vshError(ctl, FALSE, _("Failed to shutdown domain %s"), name);
1416 1417
        ret = FALSE;
    }
1418

1419 1420 1421 1422
    virDomainFree(dom);
    return ret;
}

1423 1424 1425
/*
 * "reboot" command
 */
1426
static const vshCmdInfo info_reboot[] = {
1427 1428
    {"help", gettext_noop("reboot a domain")},
    {"desc", gettext_noop("Run a reboot command in the target domain.")},
1429 1430 1431
    {NULL, NULL}
};

1432
static const vshCmdOptDef opts_reboot[] = {
1433
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1434 1435 1436 1437
    {NULL, 0, 0, NULL}
};

static int
1438
cmdReboot(vshControl *ctl, const vshCmd *cmd)
1439 1440 1441 1442 1443 1444 1445 1446
{
    virDomainPtr dom;
    int ret = TRUE;
    char *name;

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

J
Jim Meyering 已提交
1447
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
1448 1449 1450
        return FALSE;

    if (virDomainReboot(dom, 0) == 0) {
1451
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
1452
    } else {
1453
        vshError(ctl, FALSE, _("Failed to reboot domain %s"), name);
1454 1455 1456 1457 1458 1459 1460
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1461 1462 1463
/*
 * "destroy" command
 */
1464
static const vshCmdInfo info_destroy[] = {
1465 1466
    {"help", gettext_noop("destroy a domain")},
    {"desc", gettext_noop("Destroy a given domain.")},
1467
    {NULL, NULL}
1468 1469
};

1470
static const vshCmdOptDef opts_destroy[] = {
1471
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1472
    {NULL, 0, 0, NULL}
1473 1474 1475
};

static int
1476
cmdDestroy(vshControl *ctl, const vshCmd *cmd)
1477
{
1478
    virDomainPtr dom;
K
Karel Zak 已提交
1479 1480
    int ret = TRUE;
    char *name;
1481

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

J
Jim Meyering 已提交
1485
    if (!(dom = vshCommandOptDomain(ctl, cmd, &name)))
1486
        return FALSE;
1487 1488

    if (virDomainDestroy(dom) == 0) {
1489
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
1490
    } else {
1491
        vshError(ctl, FALSE, _("Failed to destroy domain %s"), name);
1492 1493
        ret = FALSE;
    }
1494

1495
    virDomainFree(dom);
K
Karel Zak 已提交
1496 1497 1498 1499
    return ret;
}

/*
1500
 * "dominfo" command
K
Karel Zak 已提交
1501
 */
1502
static const vshCmdInfo info_dominfo[] = {
1503 1504
    {"help", gettext_noop("domain information")},
    {"desc", gettext_noop("Returns basic information about the domain.")},
1505
    {NULL, NULL}
K
Karel Zak 已提交
1506 1507
};

1508
static const vshCmdOptDef opts_dominfo[] = {
1509
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1510
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1511 1512 1513
};

static int
1514
cmdDominfo(vshControl *ctl, const vshCmd *cmd)
1515
{
K
Karel Zak 已提交
1516 1517
    virDomainInfo info;
    virDomainPtr dom;
1518
    int ret = TRUE, autostart;
1519
    unsigned int id;
1520
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
1521

K
Karel Zak 已提交
1522 1523 1524
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

J
Jim Meyering 已提交
1525
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
K
Karel Zak 已提交
1526
        return FALSE;
1527

1528 1529
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1530
        vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
1531
    else
1532
        vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
1533 1534
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
1535
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
1536
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
1537 1538

    if ((str = virDomainGetOSType(dom))) {
1539
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
1540 1541 1542 1543
        free(str);
    }

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

1547
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
1548 1549

        if (info.cpuTime != 0) {
1550
            double cpuUsed = info.cpuTime;
1551

1552
            cpuUsed /= 1000000000.0;
1553

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

1557 1558
        if (info.maxMem != UINT_MAX)
            vshPrint(ctl, "%-15s %lu kB\n", _("Max memory:"),
1559
                 info.maxMem);
1560
        else
1561
            vshPrint(ctl, "%-15s %s\n", _("Max memory:"),
1562 1563
                 _("no limit"));

1564
        vshPrint(ctl, "%-15s %lu kB\n", _("Used memory:"),
1565 1566
                 info.memory);

K
Karel Zak 已提交
1567 1568 1569
    } else {
        ret = FALSE;
    }
1570

1571
    if (!virDomainGetAutostart(dom, &autostart)) {
1572
        vshPrint(ctl, "%-15s %s\n", _("Autostart:"),
1573 1574 1575
                 autostart ? _("enable") : _("disable") );
    }

1576
    virDomainFree(dom);
K
Karel Zak 已提交
1577 1578 1579
    return ret;
}

1580 1581 1582
/*
 * "freecell" command
 */
1583
static const vshCmdInfo info_freecell[] = {
1584 1585 1586 1587 1588
    {"help", gettext_noop("NUMA free memory")},
    {"desc", gettext_noop("display available free memory for the NUMA cell.")},
    {NULL, NULL}
};

1589
static const vshCmdOptDef opts_freecell[] = {
1590 1591 1592 1593 1594
    {"cellno", VSH_OT_DATA, 0, gettext_noop("NUMA cell number")},
    {NULL, 0, 0, NULL}
};

static int
1595
cmdFreecell(vshControl *ctl, const vshCmd *cmd)
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
{
    int ret;
    int cell, cell_given;
    unsigned long long memory;

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

    cell = vshCommandOptInt(cmd, "cellno", &cell_given);
    if (!cell_given) {
1606 1607
        memory = virNodeGetFreeMemory(ctl->conn);
    } else {
1608 1609 1610
        ret = virNodeGetCellsFreeMemory(ctl->conn, &memory, cell, 1);
        if (ret != 1)
            return FALSE;
1611 1612 1613
    }

    if (cell == -1)
1614
        vshPrint(ctl, "%s: %llu kB\n", _("Total"), memory);
1615
    else
1616
        vshPrint(ctl, "%d: %llu kB\n", cell, memory);
1617 1618 1619 1620

    return TRUE;
}

1621 1622 1623
/*
 * "vcpuinfo" command
 */
1624
static const vshCmdInfo info_vcpuinfo[] = {
1625 1626
    {"help", gettext_noop("domain vcpu information")},
    {"desc", gettext_noop("Returns basic information about the domain virtual CPUs.")},
1627 1628 1629
    {NULL, NULL}
};

1630
static const vshCmdOptDef opts_vcpuinfo[] = {
1631
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1632 1633 1634 1635
    {NULL, 0, 0, NULL}
};

static int
1636
cmdVcpuinfo(vshControl *ctl, const vshCmd *cmd)
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
{
    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;

J
Jim Meyering 已提交
1650
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
1651 1652 1653 1654
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
1655
        return FALSE;
1656 1657 1658 1659 1660 1661 1662
    }

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

1663
    cpuinfo = vshMalloc(ctl, sizeof(virVcpuInfo)*info.nrVirtCpu);
1664
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1665
    cpumap = vshMalloc(ctl, info.nrVirtCpu * cpumaplen);
1666

1667 1668 1669
    if ((ncpus = virDomainGetVcpus(dom,
                                   cpuinfo, info.nrVirtCpu,
                                   cpumap, cpumaplen)) >= 0) {
1670
        int n;
1671 1672 1673 1674 1675
        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:"),
1676
                     N_(vshDomainVcpuStateToString(cpuinfo[n].state)));
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
            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");
            }
        }
1693
    } else {
1694
        if (info.state == VIR_DOMAIN_SHUTOFF) {
J
Jim Meyering 已提交
1695
            vshError(ctl, FALSE, "%s",
1696 1697
                 _("Domain shut off, virtual CPUs not present."));
        }
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
        ret = FALSE;
    }

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

/*
 * "vcpupin" command
 */
1710
static const vshCmdInfo info_vcpupin[] = {
1711 1712
    {"help", gettext_noop("control domain vcpu affinity")},
    {"desc", gettext_noop("Pin domain VCPUs to host physical CPUs.")},
1713 1714 1715
    {NULL, NULL}
};

1716
static const vshCmdOptDef opts_vcpupin[] = {
1717 1718 1719
    {"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)")},
1720 1721 1722 1723
    {NULL, 0, 0, NULL}
};

static int
1724
cmdVcpupin(vshControl *ctl, const vshCmd *cmd)
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    int vcpu;
    char *cpulist;
    int ret = TRUE;
    int vcpufound = 0;
    unsigned char *cpumap;
    int cpumaplen;
1735 1736
    int i;
    enum { expect_num, expect_num_or_comma } state;
1737 1738 1739 1740

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

J
Jim Meyering 已提交
1741
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
1742 1743 1744 1745
        return FALSE;

    vcpu = vshCommandOptInt(cmd, "vcpu", &vcpufound);
    if (!vcpufound) {
1746 1747
        vshError(ctl, FALSE, "%s",
                 _("vcpupin: Invalid or missing vCPU number."));
1748 1749 1750 1751 1752
        virDomainFree(dom);
        return FALSE;
    }

    if (!(cpulist = vshCommandOptString(cmd, "cpulist", NULL))) {
1753
        vshError(ctl, FALSE, "%s", _("vcpupin: Missing cpulist"));
1754 1755 1756
        virDomainFree(dom);
        return FALSE;
    }
1757

1758 1759 1760 1761 1762 1763
    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
        return FALSE;
    }

    if (virDomainGetInfo(dom, &info) != 0) {
D
Daniel Veillard 已提交
1764
        vshError(ctl, FALSE, "%s",
1765
                 _("vcpupin: failed to get domain informations."));
1766 1767 1768 1769 1770
        virDomainFree(dom);
        return FALSE;
    }

    if (vcpu >= info.nrVirtCpu) {
J
Jim Meyering 已提交
1771
        vshError(ctl, FALSE, "%s", _("vcpupin: Invalid vCPU number."));
1772 1773 1774 1775
        virDomainFree(dom);
        return FALSE;
    }

1776 1777 1778 1779
    /* Check that the cpulist parameter is a comma-separated list of
     * numbers and give an intelligent error message if not.
     */
    if (cpulist[0] == '\0') {
J
Jim Meyering 已提交
1780
        vshError(ctl, FALSE, "%s", _("cpulist: Invalid format. Empty string."));
1781 1782 1783 1784 1785 1786 1787 1788
        virDomainFree (dom);
        return FALSE;
    }

    state = expect_num;
    for (i = 0; cpulist[i]; i++) {
        switch (state) {
        case expect_num:
1789
          if (!c_isdigit (cpulist[i])) {
1790 1791 1792 1793 1794 1795 1796 1797 1798
                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;
1799
            else if (!c_isdigit (cpulist[i])) {
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
                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;
    }

1812
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1813
    cpumap = vshCalloc(ctl, 1, cpumaplen);
1814 1815 1816 1817 1818 1819

    do {
        unsigned int cpu = atoi(cpulist);

        if (cpu < VIR_NODEINFO_MAXCPUS(nodeinfo)) {
            VIR_USE_CPU(cpumap, cpu);
1820 1821 1822 1823 1824
        } else {
            vshError(ctl, FALSE, _("Physical CPU %d doesn't exist."), cpu);
            free(cpumap);
            virDomainFree(dom);
            return FALSE;
1825
        }
1826
        cpulist = strchr(cpulist, ',');
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
        if (cpulist)
            cpulist++;
    } while (cpulist);

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

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

1840 1841 1842
/*
 * "setvcpus" command
 */
1843
static const vshCmdInfo info_setvcpus[] = {
1844
    {"help", gettext_noop("change number of virtual CPUs")},
1845
    {"desc", gettext_noop("Change the number of virtual CPUs in the guest domain.")},
1846 1847 1848
    {NULL, NULL}
};

1849
static const vshCmdOptDef opts_setvcpus[] = {
1850 1851
    {"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")},
1852 1853 1854 1855
    {NULL, 0, 0, NULL}
};

static int
1856
cmdSetvcpus(vshControl *ctl, const vshCmd *cmd)
1857 1858 1859
{
    virDomainPtr dom;
    int count;
1860
    int maxcpu;
1861 1862 1863 1864 1865
    int ret = TRUE;

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

J
Jim Meyering 已提交
1866
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
1867 1868 1869
        return FALSE;

    count = vshCommandOptInt(cmd, "count", &count);
1870
    if (count <= 0) {
J
Jim Meyering 已提交
1871
        vshError(ctl, FALSE, "%s", _("Invalid number of virtual CPUs."));
1872 1873 1874 1875
        virDomainFree(dom);
        return FALSE;
    }

1876
    maxcpu = virDomainGetMaxVcpus(dom);
1877
    if (maxcpu <= 0) {
1878 1879 1880 1881 1882
        virDomainFree(dom);
        return FALSE;
    }

    if (count > maxcpu) {
J
Jim Meyering 已提交
1883
        vshError(ctl, FALSE, "%s", _("Too many virtual CPUs."));
1884 1885 1886 1887
        virDomainFree(dom);
        return FALSE;
    }

1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
    if (virDomainSetVcpus(dom, count) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmemory" command
 */
1899
static const vshCmdInfo info_setmem[] = {
1900 1901
    {"help", gettext_noop("change memory allocation")},
    {"desc", gettext_noop("Change the current memory allocation in the guest domain.")},
1902 1903 1904
    {NULL, NULL}
};

1905
static const vshCmdOptDef opts_setmem[] = {
1906
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1907
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("number of kilobytes of memory")},
1908 1909 1910 1911
    {NULL, 0, 0, NULL}
};

static int
1912
cmdSetmem(vshControl *ctl, const vshCmd *cmd)
1913 1914
{
    virDomainPtr dom;
1915
    virDomainInfo info;
1916
    int kilobytes;
1917 1918 1919 1920 1921
    int ret = TRUE;

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

J
Jim Meyering 已提交
1922
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
1923 1924
        return FALSE;

1925 1926
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1927
        virDomainFree(dom);
1928
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1929 1930 1931
        return FALSE;
    }

1932 1933
    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
J
Jim Meyering 已提交
1934
        vshError(ctl, FALSE, "%s", _("Unable to verify MaxMemorySize"));
1935 1936 1937 1938 1939 1940 1941 1942 1943
        return FALSE;
    }

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

1944
    if (virDomainSetMemory(dom, kilobytes) != 0) {
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmaxmem" command
 */
1955
static const vshCmdInfo info_setmaxmem[] = {
1956 1957
    {"help", gettext_noop("change maximum memory limit")},
    {"desc", gettext_noop("Change the maximum memory allocation limit in the guest domain.")},
1958 1959 1960
    {NULL, NULL}
};

1961
static const vshCmdOptDef opts_setmaxmem[] = {
1962
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1963
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("maximum memory limit in kilobytes")},
1964 1965 1966 1967
    {NULL, 0, 0, NULL}
};

static int
1968
cmdSetmaxmem(vshControl *ctl, const vshCmd *cmd)
1969 1970
{
    virDomainPtr dom;
1971
    virDomainInfo info;
1972
    int kilobytes;
1973 1974 1975 1976 1977
    int ret = TRUE;

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

J
Jim Meyering 已提交
1978
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
1979 1980
        return FALSE;

1981 1982
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1983
        virDomainFree(dom);
1984
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1985 1986 1987
        return FALSE;
    }

1988 1989
    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
J
Jim Meyering 已提交
1990
        vshError(ctl, FALSE, "%s", _("Unable to verify current MemorySize"));
1991 1992 1993 1994 1995 1996
        return FALSE;
    }

    if (kilobytes < info.memory) {
        if (virDomainSetMemory(dom, kilobytes) != 0) {
            virDomainFree(dom);
J
Jim Meyering 已提交
1997
            vshError(ctl, FALSE, "%s", _("Unable to shrink current MemorySize"));
1998 1999 2000 2001
            return FALSE;
        }
    }

2002
    if (virDomainSetMaxMemory(dom, kilobytes) != 0) {
J
Jim Meyering 已提交
2003
        vshError(ctl, FALSE, "%s", _("Unable to change MaxMemorySize"));
2004 2005 2006 2007 2008 2009 2010
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

2011 2012 2013
/*
 * "nodeinfo" command
 */
2014
static const vshCmdInfo info_nodeinfo[] = {
2015 2016
    {"help", gettext_noop("node information")},
    {"desc", gettext_noop("Returns basic information about the node.")},
2017 2018 2019 2020
    {NULL, NULL}
};

static int
2021
cmdNodeinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
2022 2023
{
    virNodeInfo info;
2024

2025 2026 2027 2028
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
J
Jim Meyering 已提交
2029
        vshError(ctl, FALSE, "%s", _("failed to get node information"));
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
        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);

2041 2042 2043
    return TRUE;
}

2044 2045 2046
/*
 * "capabilities" command
 */
2047
static const vshCmdInfo info_capabilities[] = {
2048 2049 2050 2051 2052 2053
    {"help", gettext_noop("capabilities")},
    {"desc", gettext_noop("Returns capabilities of hypervisor/driver.")},
    {NULL, NULL}
};

static int
2054
cmdCapabilities (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
2055 2056 2057 2058 2059 2060 2061
{
    char *caps;

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

    if ((caps = virConnectGetCapabilities (ctl->conn)) == NULL) {
J
Jim Meyering 已提交
2062
        vshError(ctl, FALSE, "%s", _("failed to get capabilities"));
2063 2064 2065
        return FALSE;
    }
    vshPrint (ctl, "%s\n", caps);
2066
    free (caps);
2067 2068 2069 2070

    return TRUE;
}

2071 2072 2073
/*
 * "dumpxml" command
 */
2074
static const vshCmdInfo info_dumpxml[] = {
2075
    {"help", gettext_noop("domain information in XML")},
2076
    {"desc", gettext_noop("Output the domain information as an XML dump to stdout.")},
2077
    {NULL, NULL}
2078 2079
};

2080
static const vshCmdOptDef opts_dumpxml[] = {
2081
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
2082
    {NULL, 0, 0, NULL}
2083 2084 2085
};

static int
2086
cmdDumpXML(vshControl *ctl, const vshCmd *cmd)
2087
{
2088
    virDomainPtr dom;
K
Karel Zak 已提交
2089
    int ret = TRUE;
2090
    char *dump;
2091

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

J
Jim Meyering 已提交
2095
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
2096
        return FALSE;
2097

2098 2099 2100 2101 2102 2103 2104
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
2105

2106 2107 2108 2109
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
2110
/*
K
Karel Zak 已提交
2111
 * "domname" command
K
Karel Zak 已提交
2112
 */
2113
static const vshCmdInfo info_domname[] = {
2114
    {"help", gettext_noop("convert a domain id or UUID to domain name")},
2115
    {"desc", gettext_noop("")}, /* FIXME: describe */
2116
    {NULL, NULL}
K
Karel Zak 已提交
2117 2118
};

2119
static const vshCmdOptDef opts_domname[] = {
2120
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or uuid")},
2121
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
2122 2123 2124
};

static int
2125
cmdDomname(vshControl *ctl, const vshCmd *cmd)
2126
{
K
Karel Zak 已提交
2127 2128 2129 2130
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
J
Jim Meyering 已提交
2131
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL,
2132
                                      VSH_BYID|VSH_BYUUID)))
K
Karel Zak 已提交
2133
        return FALSE;
2134

K
Karel Zak 已提交
2135 2136
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
K
Karel Zak 已提交
2137 2138 2139 2140
    return TRUE;
}

/*
K
Karel Zak 已提交
2141
 * "domid" command
K
Karel Zak 已提交
2142
 */
2143
static const vshCmdInfo info_domid[] = {
2144
    {"help", gettext_noop("convert a domain name or UUID to domain id")},
2145
    {"desc", gettext_noop("")}, /* FIXME: describe */
2146
    {NULL, NULL}
K
Karel Zak 已提交
2147 2148
};

2149
static const vshCmdOptDef opts_domid[] = {
2150
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
2151
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
2152 2153 2154
};

static int
2155
cmdDomid(vshControl *ctl, const vshCmd *cmd)
2156
{
2157
    virDomainPtr dom;
2158
    unsigned int id;
K
Karel Zak 已提交
2159 2160 2161

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
J
Jim Meyering 已提交
2162
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL,
2163
                                      VSH_BYNAME|VSH_BYUUID)))
K
Karel Zak 已提交
2164
        return FALSE;
2165

2166 2167
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
2168
        vshPrint(ctl, "%s\n", "-");
2169
    else
2170
        vshPrint(ctl, "%d\n", id);
K
Karel Zak 已提交
2171 2172 2173
    virDomainFree(dom);
    return TRUE;
}
2174

K
Karel Zak 已提交
2175 2176 2177
/*
 * "domuuid" command
 */
2178
static const vshCmdInfo info_domuuid[] = {
2179
    {"help", gettext_noop("convert a domain name or id to domain UUID")},
2180
    {"desc", gettext_noop("")}, /* FIXME: describe */
K
Karel Zak 已提交
2181 2182 2183
    {NULL, NULL}
};

2184
static const vshCmdOptDef opts_domuuid[] = {
2185
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or name")},
K
Karel Zak 已提交
2186 2187 2188 2189
    {NULL, 0, 0, NULL}
};

static int
2190
cmdDomuuid(vshControl *ctl, const vshCmd *cmd)
K
Karel Zak 已提交
2191 2192
{
    virDomainPtr dom;
2193
    char uuid[VIR_UUID_STRING_BUFLEN];
K
Karel Zak 已提交
2194 2195

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
K
Karel Zak 已提交
2196
        return FALSE;
J
Jim Meyering 已提交
2197
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, NULL,
2198
                                      VSH_BYNAME|VSH_BYID)))
K
Karel Zak 已提交
2199
        return FALSE;
2200

K
Karel Zak 已提交
2201 2202 2203
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
J
Jim Meyering 已提交
2204
        vshError(ctl, FALSE, "%s", _("failed to get domain UUID"));
2205

2206
    virDomainFree(dom);
K
Karel Zak 已提交
2207 2208 2209
    return TRUE;
}

2210 2211 2212
/*
 * "migrate" command
 */
2213
static const vshCmdInfo info_migrate[] = {
2214 2215 2216 2217 2218
    {"help", gettext_noop("migrate domain to another host")},
    {"desc", gettext_noop("Migrate domain to another host.  Add --live for live migration.")},
    {NULL, NULL}
};

2219
static const vshCmdOptDef opts_migrate[] = {
2220 2221 2222 2223
    {"live", VSH_OT_BOOL, 0, gettext_noop("live migration")},
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"desturi", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("connection URI of the destination host")},
    {"migrateuri", VSH_OT_DATA, 0, gettext_noop("migration URI, usually can be omitted")},
D
Daniel Veillard 已提交
2224
    {"dname", VSH_OT_DATA, 0, gettext_noop("rename to new name during migration (if supported)")},
2225 2226 2227 2228
    {NULL, 0, 0, NULL}
};

static int
2229
cmdMigrate (vshControl *ctl, const vshCmd *cmd)
2230 2231 2232 2233
{
    virDomainPtr dom = NULL;
    const char *desturi;
    const char *migrateuri;
D
Daniel Veillard 已提交
2234
    const char *dname;
2235 2236 2237 2238 2239 2240 2241
    int flags = 0, found, ret = FALSE;
    virConnectPtr dconn = NULL;
    virDomainPtr ddom = NULL;

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

J
Jim Meyering 已提交
2242
    if (!(dom = vshCommandOptDomain (ctl, cmd, NULL)))
2243 2244 2245 2246
        return FALSE;

    desturi = vshCommandOptString (cmd, "desturi", &found);
    if (!found) {
J
Jim Meyering 已提交
2247
        vshError (ctl, FALSE, "%s", _("migrate: Missing desturi"));
2248 2249 2250 2251 2252 2253
        goto done;
    }

    migrateuri = vshCommandOptString (cmd, "migrateuri", &found);
    if (!found) migrateuri = NULL;

D
Daniel Veillard 已提交
2254 2255 2256
    dname = vshCommandOptString (cmd, "dname", &found);
    if (!found) migrateuri = dname;

2257 2258 2259 2260 2261 2262 2263 2264
    if (vshCommandOptBool (cmd, "live"))
        flags |= VIR_MIGRATE_LIVE;

    /* Temporarily connect to the destination host. */
    dconn = virConnectOpen (desturi);
    if (!dconn) goto done;

    /* Migrate. */
D
Daniel Veillard 已提交
2265
    ddom = virDomainMigrate (dom, dconn, flags, dname, migrateuri, 0);
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
    if (!ddom) goto done;

    ret = TRUE;

 done:
    if (dom) virDomainFree (dom);
    if (ddom) virDomainFree (ddom);
    if (dconn) virConnectClose (dconn);
    return ret;
}

2277 2278 2279
/*
 * "net-autostart" command
 */
2280
static const vshCmdInfo info_network_autostart[] = {
2281 2282 2283 2284 2285 2286
    {"help", gettext_noop("autostart a network")},
    {"desc",
     gettext_noop("Configure a network to be automatically started at boot.")},
    {NULL, NULL}
};

2287
static const vshCmdOptDef opts_network_autostart[] = {
2288 2289 2290 2291 2292 2293
    {"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
2294
cmdNetworkAutostart(vshControl *ctl, const vshCmd *cmd)
2295 2296 2297 2298 2299 2300 2301 2302
{
    virNetworkPtr network;
    char *name;
    int autostart;

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

J
Jim Meyering 已提交
2303
    if (!(network = vshCommandOptNetwork(ctl, cmd, &name)))
2304 2305 2306 2307 2308
        return FALSE;

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

    if (virNetworkSetAutostart(network, autostart) < 0) {
2309
        if (autostart)
2310
            vshError(ctl, FALSE, _("failed to mark network %s as autostarted"),
2311
                                   name);
2312 2313
        else
            vshError(ctl, FALSE,_("failed to unmark network %s as autostarted"),
2314
                                   name);
2315 2316 2317 2318
        virNetworkFree(network);
        return FALSE;
    }

2319
    if (autostart)
2320
        vshPrint(ctl, _("Network %s marked as autostarted\n"), name);
2321
    else
2322
        vshPrint(ctl, _("Network %s unmarked as autostarted\n"), name);
2323 2324 2325

    return TRUE;
}
K
Karel Zak 已提交
2326

2327 2328 2329
/*
 * "net-create" command
 */
2330
static const vshCmdInfo info_network_create[] = {
2331 2332 2333 2334 2335
    {"help", gettext_noop("create a network from an XML file")},
    {"desc", gettext_noop("Create a network.")},
    {NULL, NULL}
};

2336
static const vshCmdOptDef opts_network_create[] = {
2337 2338 2339 2340 2341
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML network description")},
    {NULL, 0, 0, NULL}
};

static int
2342
cmdNetworkCreate(vshControl *ctl, const vshCmd *cmd)
2343 2344 2345 2346 2347
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
2348
    char *buffer;
2349 2350 2351 2352 2353 2354 2355 2356

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

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

2357 2358
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2359 2360 2361 2362

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

2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
    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
 */
2377
static const vshCmdInfo info_network_define[] = {
2378 2379 2380 2381 2382
    {"help", gettext_noop("define (but don't start) a network from an XML file")},
    {"desc", gettext_noop("Define a network.")},
    {NULL, NULL}
};

2383
static const vshCmdOptDef opts_network_define[] = {
2384
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML network description")},
2385 2386 2387 2388
    {NULL, 0, 0, NULL}
};

static int
2389
cmdNetworkDefine(vshControl *ctl, const vshCmd *cmd)
2390 2391 2392 2393 2394
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
2395
    char *buffer;
2396 2397 2398 2399 2400 2401 2402 2403

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

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

2404 2405
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2406 2407 2408 2409

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

2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
    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
 */
2424
static const vshCmdInfo info_network_destroy[] = {
2425 2426 2427 2428 2429
    {"help", gettext_noop("destroy a network")},
    {"desc", gettext_noop("Destroy a given network.")},
    {NULL, NULL}
};

2430
static const vshCmdOptDef opts_network_destroy[] = {
2431 2432 2433 2434 2435
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
2436
cmdNetworkDestroy(vshControl *ctl, const vshCmd *cmd)
2437 2438 2439 2440 2441 2442 2443 2444
{
    virNetworkPtr network;
    int ret = TRUE;
    char *name;

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

J
Jim Meyering 已提交
2445
    if (!(network = vshCommandOptNetwork(ctl, cmd, &name)))
2446 2447 2448 2449 2450 2451 2452 2453 2454
        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;
    }

2455
    virNetworkFree(network);
2456 2457 2458 2459 2460 2461 2462
    return ret;
}


/*
 * "net-dumpxml" command
 */
2463
static const vshCmdInfo info_network_dumpxml[] = {
2464
    {"help", gettext_noop("network information in XML")},
2465
    {"desc", gettext_noop("Output the network information as an XML dump to stdout.")},
2466 2467 2468
    {NULL, NULL}
};

2469
static const vshCmdOptDef opts_network_dumpxml[] = {
2470 2471 2472 2473 2474
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
2475
cmdNetworkDumpXML(vshControl *ctl, const vshCmd *cmd)
2476 2477 2478 2479 2480 2481 2482 2483
{
    virNetworkPtr network;
    int ret = TRUE;
    char *dump;

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

J
Jim Meyering 已提交
2484
    if (!(network = vshCommandOptNetwork(ctl, cmd, NULL)))
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
        return FALSE;

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

    virNetworkFree(network);
    return ret;
}


/*
 * "net-list" command
 */
2503
static const vshCmdInfo info_network_list[] = {
2504 2505 2506 2507 2508
    {"help", gettext_noop("list networks")},
    {"desc", gettext_noop("Returns list of networks.")},
    {NULL, NULL}
};

2509
static const vshCmdOptDef opts_network_list[] = {
2510 2511 2512 2513 2514 2515
    {"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
2516
cmdNetworkList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
2517 2518 2519 2520 2521
{
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int maxactive = 0, maxinactive = 0, i;
2522
    char **activeNames = NULL, **inactiveNames = NULL;
2523 2524 2525 2526 2527 2528
    inactive |= all;

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

    if (active) {
2529 2530
        maxactive = virConnectNumOfNetworks(ctl->conn);
        if (maxactive < 0) {
J
Jim Meyering 已提交
2531
            vshError(ctl, FALSE, "%s", _("Failed to list active networks"));
2532
            return FALSE;
2533
        }
2534
        if (maxactive) {
2535
            activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);
2536

2537
            if ((maxactive = virConnectListNetworks(ctl->conn, activeNames,
2538
                                                    maxactive)) < 0) {
J
Jim Meyering 已提交
2539
                vshError(ctl, FALSE, "%s", _("Failed to list active networks"));
2540 2541 2542
                free(activeNames);
                return FALSE;
            }
2543

2544
            qsort(&activeNames[0], maxactive, sizeof(char *), namesorter);
2545
        }
2546 2547
    }
    if (inactive) {
2548 2549
        maxinactive = virConnectNumOfDefinedNetworks(ctl->conn);
        if (maxinactive < 0) {
J
Jim Meyering 已提交
2550
            vshError(ctl, FALSE, "%s", _("Failed to list inactive networks"));
2551
            free(activeNames);
2552
            return FALSE;
2553
        }
2554 2555 2556 2557
        if (maxinactive) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive);

            if ((maxinactive = virConnectListDefinedNetworks(ctl->conn, inactiveNames, maxinactive)) < 0) {
J
Jim Meyering 已提交
2558
                vshError(ctl, FALSE, "%s", _("Failed to list inactive networks"));
2559
                free(activeNames);
2560 2561 2562
                free(inactiveNames);
                return FALSE;
            }
2563

2564 2565
            qsort(&inactiveNames[0], maxinactive, sizeof(char*), namesorter);
        }
2566
    }
2567 2568
    vshPrintExtra(ctl, "%-20s %-10s %-10s\n", _("Name"), _("State"), _("Autostart"));
    vshPrintExtra(ctl, "-----------------------------------------\n");
2569 2570 2571

    for (i = 0; i < maxactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, activeNames[i]);
2572 2573
        const char *autostartStr;
        int autostart = 0;
2574 2575 2576 2577 2578

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

2581 2582 2583 2584 2585 2586 2587 2588 2589
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %-10s %-10s\n",
                 virNetworkGetName(network),
                 _("active"),
                 autostartStr);
2590 2591 2592 2593 2594
        virNetworkFree(network);
        free(activeNames[i]);
    }
    for (i = 0; i < maxinactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, inactiveNames[i]);
2595 2596
        const char *autostartStr;
        int autostart = 0;
2597 2598 2599 2600 2601

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

2604 2605 2606 2607 2608 2609 2610 2611 2612
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %s %s\n",
                 inactiveNames[i],
                 _("inactive"),
                 autostartStr);
2613 2614 2615 2616

        virNetworkFree(network);
        free(inactiveNames[i]);
    }
2617 2618
    free(activeNames);
    free(inactiveNames);
2619 2620 2621 2622 2623 2624 2625
    return TRUE;
}


/*
 * "net-name" command
 */
2626
static const vshCmdInfo info_network_name[] = {
2627
    {"help", gettext_noop("convert a network UUID to network name")},
2628
    {"desc", gettext_noop("")}, /* FIXME: describe */
2629 2630 2631
    {NULL, NULL}
};

2632
static const vshCmdOptDef opts_network_name[] = {
2633 2634 2635 2636 2637
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network uuid")},
    {NULL, 0, 0, NULL}
};

static int
2638
cmdNetworkName(vshControl *ctl, const vshCmd *cmd)
2639 2640 2641 2642 2643
{
    virNetworkPtr network;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
J
Jim Meyering 已提交
2644
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL,
2645
                                           VSH_BYUUID)))
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656
        return FALSE;

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


/*
 * "net-start" command
 */
2657
static const vshCmdInfo info_network_start[] = {
2658 2659 2660 2661 2662
    {"help", gettext_noop("start a (previously defined) inactive network")},
    {"desc", gettext_noop("Start a network.")},
    {NULL, NULL}
};

2663
static const vshCmdOptDef opts_network_start[] = {
J
Jim Meyering 已提交
2664
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive network")},
2665 2666 2667 2668
    {NULL, 0, 0, NULL}
};

static int
2669
cmdNetworkStart(vshControl *ctl, const vshCmd *cmd)
2670 2671 2672 2673 2674 2675 2676
{
    virNetworkPtr network;
    int ret = TRUE;

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

J
Jim Meyering 已提交
2677
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL, VSH_BYNAME)))
2678
         return FALSE;
2679 2680 2681

    if (virNetworkCreate(network) == 0) {
        vshPrint(ctl, _("Network %s started\n"),
2682
                 virNetworkGetName(network));
2683
    } else {
2684 2685
        vshError(ctl, FALSE, _("Failed to start network %s"),
                 virNetworkGetName(network));
2686 2687 2688 2689 2690 2691 2692 2693 2694
        ret = FALSE;
    }
    return ret;
}


/*
 * "net-undefine" command
 */
2695
static const vshCmdInfo info_network_undefine[] = {
2696 2697 2698 2699 2700
    {"help", gettext_noop("undefine an inactive network")},
    {"desc", gettext_noop("Undefine the configuration for an inactive network.")},
    {NULL, NULL}
};

2701
static const vshCmdOptDef opts_network_undefine[] = {
2702 2703 2704 2705 2706
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
2707
cmdNetworkUndefine(vshControl *ctl, const vshCmd *cmd)
2708 2709 2710 2711 2712 2713 2714 2715
{
    virNetworkPtr network;
    int ret = TRUE;
    char *name;

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

J
Jim Meyering 已提交
2716
    if (!(network = vshCommandOptNetwork(ctl, cmd, &name)))
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
        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
 */
2733
static const vshCmdInfo info_network_uuid[] = {
2734
    {"help", gettext_noop("convert a network name to network UUID")},
2735
    {"desc", gettext_noop("")}, /* FIXME: describe */
2736 2737 2738
    {NULL, NULL}
};

2739
static const vshCmdOptDef opts_network_uuid[] = {
2740 2741 2742 2743 2744
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name")},
    {NULL, 0, 0, NULL}
};

static int
2745
cmdNetworkUuid(vshControl *ctl, const vshCmd *cmd)
2746 2747 2748 2749 2750 2751 2752
{
    virNetworkPtr network;
    char uuid[VIR_UUID_STRING_BUFLEN];

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

J
Jim Meyering 已提交
2753
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL,
2754
                                           VSH_BYNAME)))
2755 2756 2757 2758 2759
        return FALSE;

    if (virNetworkGetUUIDString(network, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
J
Jim Meyering 已提交
2760
        vshError(ctl, FALSE, "%s", _("failed to get network UUID"));
2761 2762 2763 2764 2765

    return TRUE;
}


2766
/*
2767
 * "pool-autostart" command
2768
 */
2769
static const vshCmdInfo info_pool_autostart[] = {
2770 2771 2772
    {"help", gettext_noop("autostart a pool")},
    {"desc",
     gettext_noop("Configure a pool to be automatically started at boot.")},
2773
    {NULL, NULL}
2774 2775
};

2776
static const vshCmdOptDef opts_pool_autostart[] = {
2777 2778 2779 2780
    {"pool",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {"disable", VSH_OT_BOOL, 0, gettext_noop("disable autostarting")},
    {NULL, 0, 0, NULL}
};
2781 2782

static int
2783
cmdPoolAutostart(vshControl *ctl, const vshCmd *cmd)
2784
{
2785 2786 2787
    virStoragePoolPtr pool;
    char *name;
    int autostart;
2788 2789 2790

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

2792
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
2793 2794
        return FALSE;

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

2797 2798
    if (virStoragePoolSetAutostart(pool, autostart) < 0) {
        if (autostart)
2799
            vshError(ctl, FALSE, _("failed to mark pool %s as autostarted"),
2800
                                   name);
2801 2802
        else
            vshError(ctl, FALSE,_("failed to unmark pool %s as autostarted"),
2803 2804
                                   name);
        virStoragePoolFree(pool);
2805 2806 2807
        return FALSE;
    }

2808
    if (autostart)
2809
        vshPrint(ctl, _("Pool %s marked as autostarted\n"), name);
2810
    else
2811
        vshPrint(ctl, _("Pool %s unmarked as autostarted\n"), name);
2812 2813 2814 2815

    return TRUE;
}

2816
/*
2817
 * "pool-create" command
2818
 */
2819
static const vshCmdInfo info_pool_create[] = {
2820 2821
    {"help", gettext_noop("create a pool from an XML file")},
    {"desc", gettext_noop("Create a pool.")},
2822 2823 2824
    {NULL, NULL}
};

2825
static const vshCmdOptDef opts_pool_create[] = {
J
Jim Meyering 已提交
2826 2827
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ,
     gettext_noop("file containing an XML pool description")},
2828 2829 2830
    {NULL, 0, 0, NULL}
};

2831
static int
2832
cmdPoolCreate(vshControl *ctl, const vshCmd *cmd)
2833
{
2834 2835 2836 2837 2838
    virStoragePoolPtr pool;
    char *from;
    int found;
    int ret = TRUE;
    char *buffer;
2839 2840 2841 2842

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

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

2847 2848
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2849

2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
    pool = virStoragePoolCreateXML(ctl->conn, buffer, 0);
    free (buffer);

    if (pool != NULL) {
        vshPrint(ctl, _("Pool %s created from %s\n"),
                 virStoragePoolGetName(pool), from);
    } else {
        vshError(ctl, FALSE, _("Failed to create pool from %s"), from);
        ret = FALSE;
    }
    return ret;
2861 2862
}

2863

2864
/*
2865
 * XML Building helper for pool-define-as and pool-create-as
2866
 */
2867
static const vshCmdOptDef opts_pool_X_as[] = {
2868 2869 2870 2871 2872
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the pool")},
    {"type", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("type of the pool")},
    {"source-host", VSH_OT_DATA, 0, gettext_noop("source-host for underlying storage")},
    {"source-path", VSH_OT_DATA, 0, gettext_noop("source path for underlying storage")},
    {"source-dev", VSH_OT_DATA, 0, gettext_noop("source device for underlying storage")},
2873
    {"source-name", VSH_OT_DATA, 0, gettext_noop("source name for underlying storage")},
2874 2875 2876 2877
    {"target", VSH_OT_DATA, 0, gettext_noop("target for underlying storage")},
    {NULL, 0, 0, NULL}
};

2878
static int buildPoolXML(const vshCmd *cmd, char **retname, char **xml) {
2879 2880

    int found;
2881
    char *name, *type, *srcHost, *srcPath, *srcDev, *srcName, *target;
2882
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893

    name = vshCommandOptString(cmd, "name", &found);
    if (!found)
        goto cleanup;
    type = vshCommandOptString(cmd, "type", &found);
    if (!found)
        goto cleanup;

    srcHost = vshCommandOptString(cmd, "source-host", &found);
    srcPath = vshCommandOptString(cmd, "source-path", &found);
    srcDev = vshCommandOptString(cmd, "source-dev", &found);
2894
    srcName = vshCommandOptString(cmd, "source-name", &found);
2895 2896
    target = vshCommandOptString(cmd, "target", &found);

2897 2898
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf, "  <name>%s</name>\n", name);
2899
    if (srcHost || srcPath || srcDev) {
2900
        virBufferAddLit(&buf, "  <source>\n");
2901

2902 2903
        if (srcHost)
            virBufferVSprintf(&buf, "    <host name='%s'/>\n", srcHost);
2904 2905 2906 2907
        if (srcPath)
            virBufferVSprintf(&buf, "    <dir path='%s'/>\n", srcPath);
        if (srcDev)
            virBufferVSprintf(&buf, "    <device path='%s'/>\n", srcDev);
2908 2909
        if (srcName)
            virBufferVSprintf(&buf, "    <name>%s</name>\n", srcName);
2910 2911

        virBufferAddLit(&buf, "  </source>\n");
2912 2913
    }
    if (target) {
2914 2915 2916
        virBufferAddLit(&buf, "  <target>\n");
        virBufferVSprintf(&buf, "    <path>%s</path>\n", target);
        virBufferAddLit(&buf, "  </target>\n");
2917
    }
2918 2919 2920 2921 2922 2923
    virBufferAddLit(&buf, "</pool>\n");

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        return FALSE;
    }
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

    *xml = virBufferContentAndReset(&buf);
    *retname = name;
    return TRUE;

cleanup:
    free(virBufferContentAndReset(&buf));
    return FALSE;
}

/*
 * "pool-create-as" command
 */
static const vshCmdInfo info_pool_create_as[] = {
    {"help", gettext_noop("create a pool from a set of args")},
    {"desc", gettext_noop("Create a pool.")},
    {NULL, NULL}
};

static int
cmdPoolCreateAs(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    char *xml, *name;

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

    if (!buildPoolXML(cmd, &name, &xml))
        return FALSE;
2954

2955 2956
    pool = virStoragePoolCreateXML(ctl->conn, xml, 0);
    free (xml);
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968

    if (pool != NULL) {
        vshPrint(ctl, _("Pool %s created\n"), name);
        virStoragePoolFree(pool);
        return TRUE;
    } else {
        vshError(ctl, FALSE, _("Failed to create pool %s"), name);
    }

    return FALSE;
}

2969

2970
/*
2971
 * "pool-define" command
2972
 */
2973
static const vshCmdInfo info_pool_define[] = {
2974 2975
    {"help", gettext_noop("define (but don't start) a pool from an XML file")},
    {"desc", gettext_noop("Define a pool.")},
2976 2977 2978
    {NULL, NULL}
};

2979
static const vshCmdOptDef opts_pool_define[] = {
2980 2981 2982 2983
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML pool description")},
    {NULL, 0, 0, NULL}
};

2984
static int
2985
cmdPoolDefine(vshControl *ctl, const vshCmd *cmd)
2986
{
2987 2988 2989 2990 2991
    virStoragePoolPtr pool;
    char *from;
    int found;
    int ret = TRUE;
    char *buffer;
2992 2993 2994 2995

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

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

3000 3001
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
3002

3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
    pool = virStoragePoolDefineXML(ctl->conn, buffer, 0);
    free (buffer);

    if (pool != NULL) {
        vshPrint(ctl, _("Pool %s defined from %s\n"),
                 virStoragePoolGetName(pool), from);
    } else {
        vshError(ctl, FALSE, _("Failed to define pool from %s"), from);
        ret = FALSE;
    }
    return ret;
3014 3015
}

3016

3017 3018 3019
/*
 * "pool-define-as" command
 */
3020
static const vshCmdInfo info_pool_define_as[] = {
3021 3022 3023 3024 3025 3026
    {"help", gettext_noop("define a pool from a set of args")},
    {"desc", gettext_noop("Define a pool.")},
    {NULL, NULL}
};

static int
3027
cmdPoolDefineAs(vshControl *ctl, const vshCmd *cmd)
3028 3029
{
    virStoragePoolPtr pool;
3030
    char *xml, *name;
3031 3032 3033 3034

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

3035
    if (!buildPoolXML(cmd, &name, &xml))
3036 3037 3038 3039
        return FALSE;

    pool = virStoragePoolDefineXML(ctl->conn, xml, 0);
    free (xml);
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052

    if (pool != NULL) {
        vshPrint(ctl, _("Pool %s defined\n"), name);
        virStoragePoolFree(pool);
        return TRUE;
    } else {
        vshError(ctl, FALSE, _("Failed to define pool %s"), name);
    }

    return FALSE;
}


3053
/*
3054
 * "pool-build" command
3055
 */
3056
static const vshCmdInfo info_pool_build[] = {
3057 3058
    {"help", gettext_noop("build a pool")},
    {"desc", gettext_noop("Build a given pool.")},
3059 3060 3061
    {NULL, NULL}
};

3062
static const vshCmdOptDef opts_pool_build[] = {
3063
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
3064 3065 3066 3067
    {NULL, 0, 0, NULL}
};

static int
3068
cmdPoolBuild(vshControl *ctl, const vshCmd *cmd)
3069
{
3070 3071 3072
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *name;
3073 3074 3075 3076

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

3077
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
3078 3079
        return FALSE;

3080
    if (virStoragePoolBuild(pool, 0) == 0) {
3081
        vshPrint(ctl, _("Pool %s built\n"), name);
3082
    } else {
3083 3084 3085
        vshError(ctl, FALSE, _("Failed to build pool %s"), name);
        ret = FALSE;
        virStoragePoolFree(pool);
3086 3087 3088 3089 3090
    }

    return ret;
}

3091

3092
/*
3093
 * "pool-destroy" command
3094
 */
3095
static const vshCmdInfo info_pool_destroy[] = {
3096 3097
    {"help", gettext_noop("destroy a pool")},
    {"desc", gettext_noop("Destroy a given pool.")},
3098 3099 3100
    {NULL, NULL}
};

3101
static const vshCmdOptDef opts_pool_destroy[] = {
3102
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
3103 3104 3105 3106
    {NULL, 0, 0, NULL}
};

static int
3107
cmdPoolDestroy(vshControl *ctl, const vshCmd *cmd)
3108
{
3109 3110 3111
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *name;
3112 3113 3114 3115

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

3116
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
3117 3118
        return FALSE;

3119 3120 3121 3122 3123
    if (virStoragePoolDestroy(pool) == 0) {
        vshPrint(ctl, _("Pool %s destroyed\n"), name);
    } else {
        vshError(ctl, FALSE, _("Failed to destroy pool %s"), name);
        ret = FALSE;
3124 3125
    }

3126
    virStoragePoolFree(pool);
3127 3128 3129
    return ret;
}

3130

3131
/*
3132 3133
 * "pool-delete" command
 */
3134
static const vshCmdInfo info_pool_delete[] = {
3135 3136 3137 3138 3139
    {"help", gettext_noop("delete a pool")},
    {"desc", gettext_noop("Delete a given pool.")},
    {NULL, NULL}
};

3140
static const vshCmdOptDef opts_pool_delete[] = {
3141 3142 3143 3144 3145
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3146
cmdPoolDelete(vshControl *ctl, const vshCmd *cmd)
3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
{
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *name;

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

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
        return FALSE;

    if (virStoragePoolDelete(pool, 0) == 0) {
D
Daniel Veillard 已提交
3159
        vshPrint(ctl, _("Pool %s deleted\n"), name);
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172
    } else {
        vshError(ctl, FALSE, _("Failed to delete pool %s"), name);
        ret = FALSE;
        virStoragePoolFree(pool);
    }

    return ret;
}


/*
 * "pool-refresh" command
 */
3173
static const vshCmdInfo info_pool_refresh[] = {
3174 3175 3176 3177 3178
    {"help", gettext_noop("refresh a pool")},
    {"desc", gettext_noop("Refresh a given pool.")},
    {NULL, NULL}
};

3179
static const vshCmdOptDef opts_pool_refresh[] = {
3180 3181 3182 3183 3184
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3185
cmdPoolRefresh(vshControl *ctl, const vshCmd *cmd)
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
{
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *name;

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

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
        return FALSE;

    if (virStoragePoolRefresh(pool, 0) == 0) {
        vshPrint(ctl, _("Pool %s refreshed\n"), name);
    } else {
        vshError(ctl, FALSE, _("Failed to refresh pool %s"), name);
        ret = FALSE;
    }
    virStoragePoolFree(pool);

    return ret;
}


/*
 * "pool-dumpxml" command
 */
3212
static const vshCmdInfo info_pool_dumpxml[] = {
3213 3214 3215 3216 3217
    {"help", gettext_noop("pool information in XML")},
    {"desc", gettext_noop("Output the pool information as an XML dump to stdout.")},
    {NULL, NULL}
};

3218
static const vshCmdOptDef opts_pool_dumpxml[] = {
3219 3220 3221 3222 3223
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3224
cmdPoolDumpXML(vshControl *ctl, const vshCmd *cmd)
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
{
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *dump;

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

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
        return FALSE;

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

    virStoragePoolFree(pool);
    return ret;
}


/*
 * "pool-list" command
 */
3252
static const vshCmdInfo info_pool_list[] = {
3253 3254 3255 3256 3257
    {"help", gettext_noop("list pools")},
    {"desc", gettext_noop("Returns list of pools.")},
    {NULL, NULL}
};

3258
static const vshCmdOptDef opts_pool_list[] = {
3259 3260 3261 3262 3263 3264
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive pools")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active pools")},
    {NULL, 0, 0, NULL}
};

static int
3265
cmdPoolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
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 3365 3366 3367 3368 3369 3370
{
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int maxactive = 0, maxinactive = 0, i;
    char **activeNames = NULL, **inactiveNames = NULL;
    inactive |= all;

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

    if (active) {
        maxactive = virConnectNumOfStoragePools(ctl->conn);
        if (maxactive < 0) {
            vshError(ctl, FALSE, "%s", _("Failed to list active pools"));
            return FALSE;
        }
        if (maxactive) {
            activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);

            if ((maxactive = virConnectListStoragePools(ctl->conn, activeNames,
                                                        maxactive)) < 0) {
                vshError(ctl, FALSE, "%s", _("Failed to list active pools"));
                free(activeNames);
                return FALSE;
            }

            qsort(&activeNames[0], maxactive, sizeof(char *), namesorter);
        }
    }
    if (inactive) {
        maxinactive = virConnectNumOfDefinedStoragePools(ctl->conn);
        if (maxinactive < 0) {
            vshError(ctl, FALSE, "%s", _("Failed to list inactive pools"));
            free(activeNames);
            return FALSE;
        }
        if (maxinactive) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive);

            if ((maxinactive = virConnectListDefinedStoragePools(ctl->conn, inactiveNames, maxinactive)) < 0) {
                vshError(ctl, FALSE, "%s", _("Failed to list inactive pools"));
                free(activeNames);
                free(inactiveNames);
                return FALSE;
            }

            qsort(&inactiveNames[0], maxinactive, sizeof(char*), namesorter);
        }
    }
    vshPrintExtra(ctl, "%-20s %-10s %-10s\n", _("Name"), _("State"), _("Autostart"));
    vshPrintExtra(ctl, "-----------------------------------------\n");

    for (i = 0; i < maxactive; i++) {
        virStoragePoolPtr pool = virStoragePoolLookupByName(ctl->conn, activeNames[i]);
        const char *autostartStr;
        int autostart = 0;

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

        if (virStoragePoolGetAutostart(pool, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %-10s %-10s\n",
                 virStoragePoolGetName(pool),
                 _("active"),
                 autostartStr);
        virStoragePoolFree(pool);
        free(activeNames[i]);
    }
    for (i = 0; i < maxinactive; i++) {
        virStoragePoolPtr pool = virStoragePoolLookupByName(ctl->conn, inactiveNames[i]);
        const char *autostartStr;
        int autostart = 0;

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

        if (virStoragePoolGetAutostart(pool, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %-10s %-10s\n",
                 inactiveNames[i],
                 _("inactive"),
                 autostartStr);

        virStoragePoolFree(pool);
        free(inactiveNames[i]);
    }
    free(activeNames);
    free(inactiveNames);
    return TRUE;
}

3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
/*
 * "find-storage-pool-sources-as" command
 */
static const vshCmdInfo info_find_storage_pool_sources_as[] = {
    {"help", gettext_noop("find potential storage pool sources")},
    {"desc", gettext_noop("Returns XML <sources> document.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_find_storage_pool_sources_as[] = {
    {"type", VSH_OT_DATA, VSH_OFLAG_REQ,
     gettext_noop("type of storage pool sources to find")},
    {"host", VSH_OT_DATA, VSH_OFLAG_NONE, gettext_noop("optional host to query")},
    {"port", VSH_OT_DATA, VSH_OFLAG_NONE, gettext_noop("optional port to query")},
    {NULL, 0, 0, NULL}
};

static int
cmdPoolDiscoverSourcesAs(vshControl * ctl, const vshCmd * cmd ATTRIBUTE_UNUSED)
{
    char *type, *host;
    char *srcSpec = NULL;
    char *srcList;
    int found;

    type = vshCommandOptString(cmd, "type", &found);
    if (!found)
        return FALSE;
    host = vshCommandOptString(cmd, "host", &found);
    if (!found)
        host = NULL;

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

    if (host) {
        size_t hostlen = strlen(host);
        char *port = vshCommandOptString(cmd, "port", &found);
        int ret;
        if (!found) {
            port = strrchr(host, ':');
            if (port) {
                if (*(++port))
                    hostlen = port - host - 1;
                else
                    port = NULL;
            }
        }
        ret = port ?
            asprintf(&srcSpec,
                     "<source><host name='%.*s' port='%s'/></source>",
                     (int)hostlen, host, port) :
            asprintf(&srcSpec,
                     "<source><host name='%.*s'/></source>",
                     (int)hostlen, host);
        if (ret < 0) {
            switch (errno) {
            case ENOMEM:
                vshError(ctl, FALSE, "%s", _("Out of memory"));
                break;
            default:
                vshError(ctl, FALSE, _("asprintf failed (errno %d)"), errno);
            }
            return FALSE;
        }
    }

    srcList = virConnectFindStoragePoolSources(ctl->conn, type, srcSpec, 0);
    free(srcSpec);
    if (srcList == NULL) {
        vshError(ctl, FALSE, _("Failed to find any %s pool sources"), type);
        return FALSE;
    }
    vshPrint(ctl, "%s", srcList);
    free(srcList);

    return TRUE;
}


/*
 * "find-storage-pool-sources" command
 */
static const vshCmdInfo info_find_storage_pool_sources[] = {
    {"help", gettext_noop("discover potential storage pool sources")},
    {"desc", gettext_noop("Returns XML <sources> document.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_find_storage_pool_sources[] = {
    {"type", VSH_OT_DATA, VSH_OFLAG_REQ,
     gettext_noop("type of storage pool sources to discover")},
    {"srcSpec", VSH_OT_DATA, VSH_OFLAG_NONE,
     gettext_noop("optional file of source xml to query for pools")},
    {NULL, 0, 0, NULL}
};

static int
cmdPoolDiscoverSources(vshControl * ctl, const vshCmd * cmd ATTRIBUTE_UNUSED)
{
    char *type, *srcSpec, *srcSpecFile, *srcList;
    int found;

    type = vshCommandOptString(cmd, "type", &found);
    if (!found)
        return FALSE;
    srcSpecFile = vshCommandOptString(cmd, "srcSpec", &found);
    if (!found) {
        srcSpecFile = NULL;
        srcSpec = NULL;
    }

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

    if (srcSpecFile && virFileReadAll(srcSpecFile, VIRSH_MAX_XML_FILE, &srcSpec) < 0)
        return FALSE;

    srcList = virConnectFindStoragePoolSources(ctl->conn, type, srcSpec, 0);
    free(srcSpec);
    if (srcList == NULL) {
        vshError(ctl, FALSE, _("Failed to find any %s pool sources"), type);
        return FALSE;
    }
    vshPrint(ctl, "%s", srcList);
    free(srcList);

    return TRUE;
}


3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
static double
prettyCapacity(unsigned long long val,
               const char **unit) {
    if (val < 1024) {
        *unit = "";
        return (double)val;
    } else if (val < (1024.0l * 1024.0l)) {
        *unit = "KB";
        return (((double)val / 1024.0l));
    } else if (val < (1024.0l * 1024.0l * 1024.0l)) {
        *unit = "MB";
        return ((double)val / (1024.0l * 1024.0l));
    } else if (val < (1024.0l * 1024.0l * 1024.0l * 1024.0l)) {
        *unit = "GB";
        return ((double)val / (1024.0l * 1024.0l * 1024.0l));
    } else {
        *unit = "TB";
        return ((double)val / (1024.0l * 1024.0l * 1024.0l * 1024.0l));
    }
}

/*
 * "pool-info" command
 */
3526
static const vshCmdInfo info_pool_info[] = {
3527 3528 3529 3530 3531
    {"help", gettext_noop("storage pool information")},
    {"desc", gettext_noop("Returns basic information about the storage pool.")},
    {NULL, NULL}
};

3532
static const vshCmdOptDef opts_pool_info[] = {
3533 3534 3535 3536 3537
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3538
cmdPoolInfo(vshControl *ctl, const vshCmd *cmd)
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600
{
    virStoragePoolInfo info;
    virStoragePoolPtr pool;
    int ret = TRUE;
    char uuid[VIR_UUID_STRING_BUFLEN];

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

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
        return FALSE;

    vshPrint(ctl, "%-15s %s\n", _("Name:"), virStoragePoolGetName(pool));

    if (virStoragePoolGetUUIDString(pool, &uuid[0])==0)
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);

    if (virStoragePoolGetInfo(pool, &info) == 0) {
        double val;
        const char *unit;
        switch (info.state) {
        case VIR_STORAGE_POOL_INACTIVE:
            vshPrint(ctl, "%-15s %s\n", _("State:"),
                     _("inactive"));
            break;
        case VIR_STORAGE_POOL_BUILDING:
            vshPrint(ctl, "%-15s %s\n", _("State:"),
                     _("building"));
            break;
        case VIR_STORAGE_POOL_RUNNING:
            vshPrint(ctl, "%-15s %s\n", _("State:"),
                     _("running"));
            break;
        case VIR_STORAGE_POOL_DEGRADED:
            vshPrint(ctl, "%-15s %s\n", _("State:"),
                     _("degraded"));
            break;
        }

        if (info.state == VIR_STORAGE_POOL_RUNNING ||
            info.state == VIR_STORAGE_POOL_DEGRADED) {
            val = prettyCapacity(info.capacity, &unit);
            vshPrint(ctl, "%-15s %2.2lf %s\n", _("Capacity:"), val, unit);

            val = prettyCapacity(info.allocation, &unit);
            vshPrint(ctl, "%-15s %2.2lf %s\n", _("Allocation:"), val, unit);

            val = prettyCapacity(info.available, &unit);
            vshPrint(ctl, "%-15s %2.2lf %s\n", _("Available:"), val, unit);
        }
    } else {
        ret = FALSE;
    }

    virStoragePoolFree(pool);
    return ret;
}


/*
 * "pool-name" command
 */
3601
static const vshCmdInfo info_pool_name[] = {
3602
    {"help", gettext_noop("convert a pool UUID to pool name")},
3603
    {"desc", gettext_noop("")}, /* FIXME: describe */
3604 3605 3606
    {NULL, NULL}
};

3607
static const vshCmdOptDef opts_pool_name[] = {
3608 3609 3610 3611 3612
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool uuid")},
    {NULL, 0, 0, NULL}
};

static int
3613
cmdPoolName(vshControl *ctl, const vshCmd *cmd)
3614 3615 3616 3617 3618 3619
{
    virStoragePoolPtr pool;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
3620
                                           VSH_BYUUID)))
3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631
        return FALSE;

    vshPrint(ctl, "%s\n", virStoragePoolGetName(pool));
    virStoragePoolFree(pool);
    return TRUE;
}


/*
 * "pool-start" command
 */
3632
static const vshCmdInfo info_pool_start[] = {
3633 3634 3635 3636 3637
    {"help", gettext_noop("start a (previously defined) inactive pool")},
    {"desc", gettext_noop("Start a pool.")},
    {NULL, NULL}
};

3638
static const vshCmdOptDef opts_pool_start[] = {
3639
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive pool")},
3640 3641 3642 3643
    {NULL, 0, 0, NULL}
};

static int
3644
cmdPoolStart(vshControl *ctl, const vshCmd *cmd)
3645 3646 3647 3648 3649 3650 3651
{
    virStoragePoolPtr pool;
    int ret = TRUE;

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

3652
    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL, VSH_BYNAME)))
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666
         return FALSE;

    if (virStoragePoolCreate(pool, 0) == 0) {
        vshPrint(ctl, _("Pool %s started\n"),
                 virStoragePoolGetName(pool));
    } else {
        vshError(ctl, FALSE, _("Failed to start pool %s"),
                 virStoragePoolGetName(pool));
        ret = FALSE;
    }
    return ret;
}


3667 3668 3669
/*
 * "vol-create-as" command
 */
3670
static const vshCmdInfo info_vol_create_as[] = {
D
Daniel Veillard 已提交
3671
    {"help", gettext_noop("create a volume from a set of args")},
3672 3673 3674 3675
    {"desc", gettext_noop("Create a vol.")},
    {NULL, NULL}
};

3676
static const vshCmdOptDef opts_vol_create_as[] = {
3677
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name")},
D
Daniel Veillard 已提交
3678
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the volume")},
3679
    {"capacity", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("size of the vol with optional k,M,G,T suffix")},
3680 3681
    {"allocation", VSH_OT_STRING, 0, gettext_noop("initial allocation size with optional k,M,G,T suffix")},
    {"format", VSH_OT_STRING, 0, gettext_noop("file format type raw,bochs,qcow,qcow2,vmdk")},
3682 3683 3684 3685 3686 3687 3688 3689 3690 3691
    {NULL, 0, 0, NULL}
};

static int cmdVolSize(const char *data, unsigned long long *val)
{
    char *end;
    if (virStrToLong_ull(data, &end, 10, val) < 0)
        return -1;

    if (end && *end) {
D
Daniel Veillard 已提交
3692
        /* Deliberate fallthrough cases here :-) */
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
        switch (*end) {
        case 'T':
            *val *= 1024;
        case 'G':
            *val *= 1024;
        case 'M':
            *val *= 1024;
        case 'k':
            *val *= 1024;
            break;
        default:
            return -1;
        }
        end++;
        if (*end)
            return -1;
    }
    return 0;
}

static int
3714
cmdVolCreateAs(vshControl *ctl, const vshCmd *cmd)
3715 3716 3717 3718
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
    int found;
3719
    char *xml;
3720 3721
    char *name, *capacityStr, *allocationStr, *format;
    unsigned long long capacity, allocation = 0;
3722
    virBuffer buf = VIR_BUFFER_INITIALIZER;
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

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

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
                                     VSH_BYNAME)))
        return FALSE;

    name = vshCommandOptString(cmd, "name", &found);
    if (!found)
        goto cleanup;

    capacityStr = vshCommandOptString(cmd, "capacity", &found);
    if (!found)
        goto cleanup;
    if (cmdVolSize(capacityStr, &capacity) < 0)
        vshError(ctl, FALSE, _("Malformed size %s"), capacityStr);

    allocationStr = vshCommandOptString(cmd, "allocation", &found);
    if (allocationStr &&
        cmdVolSize(allocationStr, &allocation) < 0)
        vshError(ctl, FALSE, _("Malformed size %s"), allocationStr);

    format = vshCommandOptString(cmd, "format", &found);

3748 3749 3750 3751 3752
    virBufferAddLit(&buf, "<volume>\n");
    virBufferVSprintf(&buf, "  <name>%s</name>\n", name);
    virBufferVSprintf(&buf, "  <capacity>%llu</capacity>\n", capacity);
    if (allocationStr)
        virBufferVSprintf(&buf, "  <allocation>%llu</allocation>\n", allocation);
3753 3754

    if (format) {
3755
        virBufferAddLit(&buf, "  <target>\n");
3756
        if (format)
3757 3758
            virBufferVSprintf(&buf, "    <format type='%s'/>\n",format);
        virBufferAddLit(&buf, "  </target>\n");
3759
    }
3760 3761
    virBufferAddLit(&buf, "</volume>\n");

3762

3763 3764 3765 3766 3767 3768 3769
    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        return FALSE;
    }
    xml = virBufferContentAndReset(&buf);
    vol = virStorageVolCreateXML(pool, xml, 0);
    free (xml);
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
    virStoragePoolFree(pool);

    if (vol != NULL) {
        vshPrint(ctl, _("Vol %s created\n"), name);
        virStorageVolFree(vol);
        return TRUE;
    } else {
        vshError(ctl, FALSE, _("Failed to create vol %s"), name);
        return FALSE;
    }

 cleanup:
3782
    free(virBufferContentAndReset(&buf));
3783 3784 3785 3786 3787
    virStoragePoolFree(pool);
    return FALSE;
}


3788 3789 3790
/*
 * "pool-undefine" command
 */
3791
static const vshCmdInfo info_pool_undefine[] = {
3792 3793 3794 3795 3796
    {"help", gettext_noop("undefine an inactive pool")},
    {"desc", gettext_noop("Undefine the configuration for an inactive pool.")},
    {NULL, NULL}
};

3797
static const vshCmdOptDef opts_pool_undefine[] = {
3798 3799 3800 3801 3802
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3803
cmdPoolUndefine(vshControl *ctl, const vshCmd *cmd)
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828
{
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *name;

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

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", &name)))
        return FALSE;

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

    return ret;
}


/*
 * "pool-uuid" command
 */
3829
static const vshCmdInfo info_pool_uuid[] = {
3830
    {"help", gettext_noop("convert a pool name to pool UUID")},
3831
    {"desc", gettext_noop("")}, /* FIXME: describe */
3832 3833 3834
    {NULL, NULL}
};

3835
static const vshCmdOptDef opts_pool_uuid[] = {
3836 3837 3838 3839 3840
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name")},
    {NULL, 0, 0, NULL}
};

static int
3841
cmdPoolUuid(vshControl *ctl, const vshCmd *cmd)
3842 3843 3844 3845 3846 3847 3848 3849
{
    virStoragePoolPtr pool;
    char uuid[VIR_UUID_STRING_BUFLEN];

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

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
3850
                                           VSH_BYNAME)))
3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866
        return FALSE;

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

    return TRUE;
}




/*
 * "vol-create" command
 */
3867
static const vshCmdInfo info_vol_create[] = {
3868 3869 3870 3871 3872
    {"help", gettext_noop("create a vol from an XML file")},
    {"desc", gettext_noop("Create a vol.")},
    {NULL, NULL}
};

3873
static const vshCmdOptDef opts_vol_create[] = {
3874 3875 3876 3877 3878 3879
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name")},
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML vol description")},
    {NULL, 0, 0, NULL}
};

static int
3880
cmdVolCreate(vshControl *ctl, const vshCmd *cmd)
3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
    char *from;
    int found;
    int ret = TRUE;
    char *buffer;

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

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
3893
                                           VSH_BYNAME)))
3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924
        return FALSE;

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

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        virStoragePoolFree(pool);
        return FALSE;
    }

    vol = virStorageVolCreateXML(pool, buffer, 0);
    free (buffer);
    virStoragePoolFree(pool);

    if (vol != NULL) {
        vshPrint(ctl, _("Vol %s created from %s\n"),
                 virStorageVolGetName(vol), from);
        virStorageVolFree(vol);
    } else {
        vshError(ctl, FALSE, _("Failed to create vol from %s"), from);
        ret = FALSE;
    }
    return ret;
}

/*
 * "vol-delete" command
 */
3925
static const vshCmdInfo info_vol_delete[] = {
3926 3927 3928 3929 3930
    {"help", gettext_noop("delete a vol")},
    {"desc", gettext_noop("Delete a given vol.")},
    {NULL, NULL}
};

3931
static const vshCmdOptDef opts_vol_delete[] = {
3932 3933 3934 3935 3936 3937
    {"pool", VSH_OT_STRING, 0, gettext_noop("pool name or uuid")},
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol name, key or path")},
    {NULL, 0, 0, NULL}
};

static int
3938
cmdVolDelete(vshControl *ctl, const vshCmd *cmd)
3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
{
    virStorageVolPtr vol;
    int ret = TRUE;
    char *name;

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

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name))) {
        return FALSE;
    }

    if (virStorageVolDelete(vol, 0) == 0) {
D
Daniel Veillard 已提交
3952
        vshPrint(ctl, _("Vol %s deleted\n"), name);
3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
    } else {
        vshError(ctl, FALSE, _("Failed to delete vol %s"), name);
        ret = FALSE;
        virStorageVolFree(vol);
    }

    return ret;
}


/*
 * "vol-info" command
 */
3966
static const vshCmdInfo info_vol_info[] = {
3967 3968 3969 3970 3971
    {"help", gettext_noop("storage vol information")},
    {"desc", gettext_noop("Returns basic information about the storage vol.")},
    {NULL, NULL}
};

3972
static const vshCmdOptDef opts_vol_info[] = {
3973 3974 3975 3976 3977 3978
    {"pool", VSH_OT_STRING, 0, gettext_noop("pool name or uuid")},
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol name, key or path")},
    {NULL, 0, 0, NULL}
};

static int
3979
cmdVolInfo(vshControl *ctl, const vshCmd *cmd)
3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
{
    virStorageVolInfo info;
    virStorageVolPtr vol;
    int ret = TRUE;

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

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        return FALSE;

    vshPrint(ctl, "%-15s %s\n", _("Name:"), virStorageVolGetName(vol));

    if (virStorageVolGetInfo(vol, &info) == 0) {
        double val;
        const char *unit;
        vshPrint(ctl, "%-15s %s\n", _("Type:"),
                 info.type == VIR_STORAGE_VOL_FILE ?
                 _("file") : _("block"));

        val = prettyCapacity(info.capacity, &unit);
        vshPrint(ctl, "%-15s %2.2lf %s\n", _("Capacity:"), val, unit);

        val = prettyCapacity(info.allocation, &unit);
        vshPrint(ctl, "%-15s %2.2lf %s\n", _("Allocation:"), val, unit);
    } else {
        ret = FALSE;
    }

    virStorageVolFree(vol);
    return ret;
}


/*
 * "vol-dumpxml" command
 */
4017
static const vshCmdInfo info_vol_dumpxml[] = {
4018 4019 4020 4021 4022
    {"help", gettext_noop("vol information in XML")},
    {"desc", gettext_noop("Output the vol information as an XML dump to stdout.")},
    {NULL, NULL}
};

4023
static const vshCmdOptDef opts_vol_dumpxml[] = {
4024 4025 4026 4027 4028 4029
    {"pool", VSH_OT_STRING, 0, gettext_noop("pool name or uuid")},
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol name, key or path")},
    {NULL, 0, 0, NULL}
};

static int
4030
cmdVolDumpXML(vshControl *ctl, const vshCmd *cmd)
4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057
{
    virStorageVolPtr vol;
    int ret = TRUE;
    char *dump;

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

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        return FALSE;

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

    virStorageVolFree(vol);
    return ret;
}


/*
 * "vol-list" command
 */
4058
static const vshCmdInfo info_vol_list[] = {
4059 4060 4061 4062 4063
    {"help", gettext_noop("list vols")},
    {"desc", gettext_noop("Returns list of vols by pool.")},
    {NULL, NULL}
};

4064
static const vshCmdOptDef opts_vol_list[] = {
4065 4066 4067 4068 4069
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
4070
cmdVolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135
{
    virStoragePoolPtr pool;
    int maxactive = 0, i;
    char **activeNames = NULL;

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

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
        return FALSE;

    maxactive = virStoragePoolNumOfVolumes(pool);
    if (maxactive < 0) {
        virStoragePoolFree(pool);
        vshError(ctl, FALSE, "%s", _("Failed to list active vols"));
        return FALSE;
    }
    if (maxactive) {
        activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);

        if ((maxactive = virStoragePoolListVolumes(pool, activeNames,
                                                   maxactive)) < 0) {
            vshError(ctl, FALSE, "%s", _("Failed to list active vols"));
            free(activeNames);
            virStoragePoolFree(pool);
            return FALSE;
        }

        qsort(&activeNames[0], maxactive, sizeof(char *), namesorter);
    }
    vshPrintExtra(ctl, "%-20s %-40s\n", _("Name"), _("Path"));
    vshPrintExtra(ctl, "-----------------------------------------\n");

    for (i = 0; i < maxactive; i++) {
        virStorageVolPtr vol = virStorageVolLookupByName(pool, activeNames[i]);
        char *path;

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

        if ((path = virStorageVolGetPath(vol)) == NULL) {
            virStorageVolFree(vol);
            continue;
        }


        vshPrint(ctl, "%-20s %-40s\n",
                 virStorageVolGetName(vol),
                 path);
        free(path);
        virStorageVolFree(vol);
        free(activeNames[i]);
    }
    free(activeNames);
    virStoragePoolFree(pool);
    return TRUE;
}


/*
 * "vol-name" command
 */
4136
static const vshCmdInfo info_vol_name[] = {
4137
    {"help", gettext_noop("convert a vol UUID to vol name")},
4138
    {"desc", gettext_noop("")}, /* FIXME: describe */
4139 4140 4141
    {NULL, NULL}
};

4142
static const vshCmdOptDef opts_vol_name[] = {
4143 4144 4145 4146 4147
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol key or path")},
    {NULL, 0, 0, NULL}
};

static int
4148
cmdVolName(vshControl *ctl, const vshCmd *cmd)
4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
{
    virStorageVolPtr vol;

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

    if (!(vol = vshCommandOptVolBy(ctl, cmd, "vol", "pool", NULL,
                                   VSH_BYUUID)))
        return FALSE;

    vshPrint(ctl, "%s\n", virStorageVolGetName(vol));
    virStorageVolFree(vol);
    return TRUE;
}



/*
 * "vol-key" command
 */
4169
static const vshCmdInfo info_vol_key[] = {
4170
    {"help", gettext_noop("convert a vol UUID to vol key")},
4171
    {"desc", gettext_noop("")}, /* FIXME: describe */
4172 4173 4174
    {NULL, NULL}
};

4175
static const vshCmdOptDef opts_vol_key[] = {
4176 4177 4178 4179 4180
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol uuid")},
    {NULL, 0, 0, NULL}
};

static int
4181
cmdVolKey(vshControl *ctl, const vshCmd *cmd)
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201
{
    virStorageVolPtr vol;

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

    if (!(vol = vshCommandOptVolBy(ctl, cmd, "vol", NULL, NULL,
                                   VSH_BYUUID)))
        return FALSE;

    vshPrint(ctl, "%s\n", virStorageVolGetKey(vol));
    virStorageVolFree(vol);
    return TRUE;
}



/*
 * "vol-path" command
 */
4202
static const vshCmdInfo info_vol_path[] = {
4203
    {"help", gettext_noop("convert a vol UUID to vol path")},
4204
    {"desc", gettext_noop("")}, /* FIXME: describe */
4205 4206 4207
    {NULL, NULL}
};

4208
static const vshCmdOptDef opts_vol_path[] = {
4209 4210 4211 4212 4213 4214
    {"pool", VSH_OT_STRING, 0, gettext_noop("pool name or uuid")},
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol name or key")},
    {NULL, 0, 0, NULL}
};

static int
4215
cmdVolPath(vshControl *ctl, const vshCmd *cmd)
4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238
{
    virStorageVolPtr vol;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(vol = vshCommandOptVolBy(ctl, cmd, "vol", "pool", NULL,
                                   VSH_BYUUID)))
        return FALSE;

    vshPrint(ctl, "%s\n", virStorageVolGetPath(vol));
    virStorageVolFree(vol);
    return TRUE;
}







/*
 * "version" command
 */
4239
static const vshCmdInfo info_version[] = {
4240 4241 4242 4243 4244 4245 4246
    {"help", gettext_noop("show version")},
    {"desc", gettext_noop("Display the system version information.")},
    {NULL, NULL}
};


static int
4247
cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
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
{
    unsigned long hvVersion;
    const char *hvType;
    unsigned long libVersion;
    unsigned long includeVersion;
    unsigned long apiVersion;
    int ret;
    unsigned int major;
    unsigned int minor;
    unsigned int rel;

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

    hvType = virConnectGetType(ctl->conn);
    if (hvType == NULL) {
        vshError(ctl, FALSE, "%s", _("failed to get hypervisor type"));
        return FALSE;
    }

    includeVersion = LIBVIR_VERSION_NUMBER;
    major = includeVersion / 1000000;
    includeVersion %= 1000000;
    minor = includeVersion / 1000;
    rel = includeVersion % 1000;
    vshPrint(ctl, _("Compiled against library: libvir %d.%d.%d\n"),
             major, minor, rel);

    ret = virGetVersion(&libVersion, hvType, &apiVersion);
    if (ret < 0) {
        vshError(ctl, FALSE, "%s", _("failed to get the library version"));
        return FALSE;
    }
    major = libVersion / 1000000;
    libVersion %= 1000000;
    minor = libVersion / 1000;
    rel = libVersion % 1000;
    vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"),
             major, minor, rel);

    major = apiVersion / 1000000;
    apiVersion %= 1000000;
    minor = apiVersion / 1000;
    rel = apiVersion % 1000;
    vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType,
             major, minor, rel);

    ret = virConnectGetVersion(ctl->conn, &hvVersion);
    if (ret < 0) {
        vshError(ctl, FALSE, "%s", _("failed to get the hypervisor version"));
        return FALSE;
    }
    if (hvVersion == 0) {
        vshPrint(ctl,
                 _("Cannot extract running %s hypervisor version\n"), hvType);
    } else {
        major = hvVersion / 1000000;
        hvVersion %= 1000000;
        minor = hvVersion / 1000;
        rel = hvVersion % 1000;

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

4315 4316 4317 4318 4319
/*
 * "nodedev-list" command
 */
static const vshCmdInfo info_node_list_devices[] = {
    {"help", gettext_noop("enumerate devices on this host")},
4320
    {"desc", gettext_noop("")}, /* FIXME: describe */
4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358
    {NULL, NULL}
};

static const vshCmdOptDef opts_node_list_devices[] = {
    {"cap", VSH_OT_STRING, VSH_OFLAG_NONE, gettext_noop("capability name")},
    {NULL, 0, 0, NULL}
};

static int
cmdNodeListDevices (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cap;
    char **devices;
    int found, num_devices, i;

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

    cap = vshCommandOptString(cmd, "cap", &found);
    if (!found)
        cap = NULL;

    num_devices = virNodeNumOfDevices(ctl->conn, cap, 0);
    if (num_devices < 0) {
        vshError(ctl, FALSE, "%s", _("Failed to count node devices"));
        return FALSE;
    } else if (num_devices == 0) {
        return TRUE;
    }

    devices = vshMalloc(ctl, sizeof(char *) * num_devices);
    num_devices =
        virNodeListDevices(ctl->conn, cap, devices, num_devices, 0);
    if (num_devices < 0) {
        vshError(ctl, FALSE, "%s", _("Failed to list node devices"));
        free(devices);
        return FALSE;
    }
4359
    qsort(&devices[0], num_devices, sizeof(char*), namesorter);
4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402
    for (i = 0; i < num_devices; i++) {
        vshPrint(ctl, "%s\n", devices[i]);
        free(devices[i]);
    }
    free(devices);
    return TRUE;
}

/*
 * "nodedev-dumpxml" command
 */
static const vshCmdInfo info_node_device_dumpxml[] = {
    {"help", gettext_noop("node device details in XML")},
    {"desc", gettext_noop("Output the node device details as an XML dump to stdout.")},
    {NULL, NULL}
};


static const vshCmdOptDef opts_node_device_dumpxml[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("device key")},
    {NULL, 0, 0, NULL}
};

static int
cmdNodeDeviceDumpXML (vshControl *ctl, const vshCmd *cmd)
{
    const char *name;
    virNodeDevicePtr device;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(name = vshCommandOptString(cmd, "device", NULL)))
        return FALSE;
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, FALSE, "%s '%s'", _("Could not find matching device"), name);
        return FALSE;
    }

    vshPrint(ctl, "%s\n", virNodeDeviceGetXMLDesc(device, 0));
    virNodeDeviceFree(device);
    return TRUE;
}

4403 4404 4405
/*
 * "hostkey" command
 */
4406
static const vshCmdInfo info_hostname[] = {
4407
    {"help", gettext_noop("print the hypervisor hostname")},
4408
    {"desc", gettext_noop("")}, /* FIXME: describe */
4409 4410 4411 4412
    {NULL, NULL}
};

static int
4413
cmdHostname (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434
{
    char *hostname;

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

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

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

    return TRUE;
}

/*
 * "uri" command
 */
4435
static const vshCmdInfo info_uri[] = {
4436
    {"help", gettext_noop("print the hypervisor canonical URI")},
4437
    {"desc", gettext_noop("")}, /* FIXME: describe */
4438 4439 4440 4441
    {NULL, NULL}
};

static int
4442
cmdURI (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463
{
    char *uri;

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

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

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

    return TRUE;
}

/*
 * "vncdisplay" command
 */
4464
static const vshCmdInfo info_vncdisplay[] = {
4465 4466 4467 4468 4469
    {"help", gettext_noop("vnc display")},
    {"desc", gettext_noop("Output the IP address and port number for the VNC display.")},
    {NULL, NULL}
};

4470
static const vshCmdOptDef opts_vncdisplay[] = {
4471 4472 4473 4474 4475
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
4476
cmdVNCDisplay(vshControl *ctl, const vshCmd *cmd)
4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488
{
    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;

J
Jim Meyering 已提交
4489
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
        return FALSE;

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

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

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

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@listen)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0) ||
4518
        STREQ((const char*)obj->stringval, "0.0.0.0")) {
4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538
        vshPrint(ctl, ":%d\n", port-5900);
    } else {
        vshPrint(ctl, "%s:%d\n", (const char *)obj->stringval, port-5900);
    }
    xmlXPathFreeObject(obj);
    obj = NULL;
    ret = TRUE;

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

/*
 * "ttyconsole" command
 */
4539
static const vshCmdInfo info_ttyconsole[] = {
4540 4541 4542 4543 4544
    {"help", gettext_noop("tty console")},
    {"desc", gettext_noop("Output the device for the TTY console.")},
    {NULL, NULL}
};

4545
static const vshCmdOptDef opts_ttyconsole[] = {
4546 4547 4548 4549 4550
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
4551
cmdTTYConsole(vshControl *ctl, const vshCmd *cmd)
4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    int ret = FALSE;
    char *doc;

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

J
Jim Meyering 已提交
4563
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597
        return FALSE;

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

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

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/console/@tty)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        goto cleanup;
    }
    vshPrint(ctl, "%s\n", (const char *)obj->stringval);

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

/*
 * "attach-device" command
4598
 */
4599
static const vshCmdInfo info_attach_device[] = {
4600 4601 4602 4603 4604
    {"help", gettext_noop("attach device from an XML file")},
    {"desc", gettext_noop("Attach device from an XML <file>.")},
    {NULL, NULL}
};

4605
static const vshCmdOptDef opts_attach_device[] = {
4606 4607 4608 4609 4610 4611
    {"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
4612
cmdAttachDevice(vshControl *ctl, const vshCmd *cmd)
4613 4614 4615 4616 4617 4618 4619 4620 4621 4622
{
    virDomainPtr dom;
    char *from;
    char *buffer;
    int ret = TRUE;
    int found;

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

J
Jim Meyering 已提交
4623
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
4624 4625 4626 4627
        return FALSE;

    from = vshCommandOptString(cmd, "file", &found);
    if (!found) {
4628
        vshError(ctl, FALSE, "%s", _("attach-device: Missing <file> option"));
4629 4630 4631 4632
        virDomainFree(dom);
        return FALSE;
    }

4633 4634
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        virDomainFree(dom);
4635
        return FALSE;
4636
    }
4637 4638 4639 4640 4641 4642 4643 4644

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

    if (ret < 0) {
        vshError(ctl, FALSE, _("Failed to attach device from %s"), from);
        virDomainFree(dom);
        return FALSE;
4645
    } else {
J
Jim Meyering 已提交
4646
        vshPrint(ctl, "%s", _("Device attached successfully\n"));
4647 4648 4649 4650 4651 4652 4653 4654 4655 4656
    }

    virDomainFree(dom);
    return TRUE;
}


/*
 * "detach-device" command
 */
4657
static const vshCmdInfo info_detach_device[] = {
4658 4659 4660 4661 4662
    {"help", gettext_noop("detach device from an XML file")},
    {"desc", gettext_noop("Detach device from an XML <file>")},
    {NULL, NULL}
};

4663
static const vshCmdOptDef opts_detach_device[] = {
4664 4665 4666 4667 4668 4669
    {"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
4670
cmdDetachDevice(vshControl *ctl, const vshCmd *cmd)
4671 4672 4673 4674 4675 4676 4677 4678 4679 4680
{
    virDomainPtr dom;
    char *from;
    char *buffer;
    int ret = TRUE;
    int found;

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

J
Jim Meyering 已提交
4681
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
4682 4683 4684 4685
        return FALSE;

    from = vshCommandOptString(cmd, "file", &found);
    if (!found) {
4686
        vshError(ctl, FALSE, "%s", _("detach-device: Missing <file> option"));
4687 4688 4689 4690
        virDomainFree(dom);
        return FALSE;
    }

4691 4692
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        virDomainFree(dom);
4693
        return FALSE;
4694
    }
4695 4696 4697 4698 4699 4700 4701 4702

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

    if (ret < 0) {
        vshError(ctl, FALSE, _("Failed to detach device from %s"), from);
        virDomainFree(dom);
        return FALSE;
4703
    } else {
J
Jim Meyering 已提交
4704
        vshPrint(ctl, "%s", _("Device detached successfully\n"));
4705 4706 4707 4708 4709 4710
    }

    virDomainFree(dom);
    return TRUE;
}

4711

4712 4713 4714
/*
 * "attach-interface" command
 */
4715
static const vshCmdInfo info_attach_interface[] = {
4716 4717 4718 4719 4720
    {"help", gettext_noop("attach network interface")},
    {"desc", gettext_noop("Attach new network interface.")},
    {NULL, NULL}
};

4721
static const vshCmdOptDef opts_attach_interface[] = {
4722 4723 4724 4725
    {"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")},
4726
    {"mac",    VSH_OT_DATA, 0, gettext_noop("MAC address")},
4727 4728 4729 4730 4731
    {"script", VSH_OT_DATA, 0, gettext_noop("script used to bridge network interface")},
    {NULL, 0, 0, NULL}
};

static int
4732
cmdAttachInterface(vshControl *ctl, const vshCmd *cmd)
4733 4734 4735 4736 4737 4738 4739 4740 4741
{
    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;

J
Jim Meyering 已提交
4742
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753
        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 */
4754
    if (STREQ(type, "network")) {
4755
        typ = 1;
4756
    } else if (STREQ(type, "bridge")) {
4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811
        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");

4812
    if (virDomainAttachDevice(dom, buf)) {
4813
        goto cleanup;
4814
    } else {
J
Jim Meyering 已提交
4815
        vshPrint(ctl, "%s", _("Interface attached successfully\n"));
4816
    }
4817 4818 4819 4820 4821 4822

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
4823 4824
    free(buf);
    free(tmp);
4825 4826 4827 4828 4829 4830
    return ret;
}

/*
 * "detach-interface" command
 */
4831
static const vshCmdInfo info_detach_interface[] = {
4832 4833 4834 4835 4836
    {"help", gettext_noop("detach network interface")},
    {"desc", gettext_noop("Detach network interface.")},
    {NULL, NULL}
};

4837
static const vshCmdOptDef opts_detach_interface[] = {
4838 4839
    {"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")},
4840
    {"mac",    VSH_OT_STRING, 0, gettext_noop("MAC address")},
4841 4842 4843 4844
    {NULL, 0, 0, NULL}
};

static int
4845
cmdDetachInterface(vshControl *ctl, const vshCmd *cmd)
4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860
{
    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;

J
Jim Meyering 已提交
4861
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877
        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) {
J
Jim Meyering 已提交
4878
        vshError(ctl, FALSE, "%s", _("Failed to get interface information"));
4879 4880 4881 4882
        goto cleanup;
    }
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt) {
J
Jim Meyering 已提交
4883
        vshError(ctl, FALSE, "%s", _("Failed to get interface information"));
4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903
        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");
4904
                diff_mac = virMacAddrCompare ((char *) tmp_mac, mac);
4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918
                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) {
J
Jim Meyering 已提交
4919
        vshError(ctl, FALSE, "%s", _("Failed to allocate memory"));
4920 4921 4922 4923
        goto cleanup;
    }

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
J
Jim Meyering 已提交
4924
        vshError(ctl, FALSE, "%s", _("Failed to create XML"));
4925 4926 4927 4928 4929 4930
        goto cleanup;
    }

    ret = virDomainDetachDevice(dom, (char *)xmlBufferContent(xml_buf));
    if (ret != 0)
        ret = FALSE;
4931
    else {
J
Jim Meyering 已提交
4932
        vshPrint(ctl, "%s", _("Interface detached successfully\n"));
4933
        ret = TRUE;
4934
    }
4935 4936 4937 4938

 cleanup:
    if (dom)
        virDomainFree(dom);
4939
    xmlXPathFreeObject(obj);
4940
    xmlXPathFreeContext(ctxt);
4941 4942 4943 4944 4945 4946 4947 4948 4949 4950
    if (xml)
        xmlFreeDoc(xml);
    if (xml_buf)
        xmlBufferFree(xml_buf);
    return ret;
}

/*
 * "attach-disk" command
 */
4951
static const vshCmdInfo info_attach_disk[] = {
4952 4953 4954 4955 4956
    {"help", gettext_noop("attach disk device")},
    {"desc", gettext_noop("Attach new disk device.")},
    {NULL, NULL}
};

4957
static const vshCmdOptDef opts_attach_disk[] = {
4958 4959 4960
    {"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")},
4961 4962 4963 4964
    {"driver",    VSH_OT_STRING, 0, gettext_noop("driver of disk device")},
    {"subdriver", VSH_OT_STRING, 0, gettext_noop("subdriver of disk device")},
    {"type",    VSH_OT_STRING, 0, gettext_noop("target device type")},
    {"mode",    VSH_OT_STRING, 0, gettext_noop("mode of device reading and writing")},
4965 4966 4967 4968
    {NULL, 0, 0, NULL}
};

static int
4969
cmdAttachDisk(vshControl *ctl, const vshCmd *cmd)
4970 4971 4972 4973 4974 4975 4976 4977 4978
{
    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;

J
Jim Meyering 已提交
4979
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
        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) {
4994
        if (STRNEQ(type, "cdrom") && STRNEQ(type, "disk")) {
4995 4996 4997 4998 4999 5000
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), type);
            goto cleanup;
        }
    }

    if (driver) {
5001
        if (STREQ(driver, "file") || STREQ(driver, "tap")) {
5002
            isFile = 1;
5003
        } else if (STRNEQ(driver, "phy")) {
5004 5005 5006 5007 5008 5009
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), driver);
            goto cleanup;
        }
    }

    if (mode) {
5010
        if (STRNEQ(mode, "readonly") && STRNEQ(mode, "shareable")) {
5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098
            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;
5099
    else
J
Jim Meyering 已提交
5100
        vshPrint(ctl, "%s", _("Disk attached successfully\n"));
5101 5102 5103 5104 5105 5106

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
5107 5108
    free(buf);
    free(tmp);
5109 5110 5111 5112 5113 5114
    return ret;
}

/*
 * "detach-disk" command
 */
5115
static const vshCmdInfo info_detach_disk[] = {
5116 5117 5118 5119 5120
    {"help", gettext_noop("detach disk device")},
    {"desc", gettext_noop("Detach disk device.")},
    {NULL, NULL}
};

5121
static const vshCmdOptDef opts_detach_disk[] = {
5122 5123 5124 5125 5126 5127
    {"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
5128
cmdDetachDisk(vshControl *ctl, const vshCmd *cmd)
5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142
{
    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;

J
Jim Meyering 已提交
5143
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157
        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) {
J
Jim Meyering 已提交
5158
        vshError(ctl, FALSE, "%s", _("Failed to get disk information"));
5159 5160 5161 5162
        goto cleanup;
    }
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt) {
J
Jim Meyering 已提交
5163
        vshError(ctl, FALSE, "%s", _("Failed to get disk information"));
5164 5165 5166 5167 5168 5169
        goto cleanup;
    }

    obj = xmlXPathEval(BAD_CAST "/domain/devices/disk", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
J
Jim Meyering 已提交
5170
        vshError(ctl, FALSE, "%s", _("Failed to get disk information"));
5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194
        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) {
J
Jim Meyering 已提交
5195
        vshError(ctl, FALSE, "%s", _("Failed to allocate memory"));
5196 5197 5198 5199
        goto cleanup;
    }

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
J
Jim Meyering 已提交
5200
        vshError(ctl, FALSE, "%s", _("Failed to create XML"));
5201 5202 5203 5204 5205 5206
        goto cleanup;
    }

    ret = virDomainDetachDevice(dom, (char *)xmlBufferContent(xml_buf));
    if (ret != 0)
        ret = FALSE;
5207
    else {
J
Jim Meyering 已提交
5208
        vshPrint(ctl, "%s", _("Disk detached successfully\n"));
5209
        ret = TRUE;
5210
    }
5211 5212

 cleanup:
5213
    xmlXPathFreeObject(obj);
5214
    xmlXPathFreeContext(ctxt);
5215 5216 5217 5218 5219 5220 5221 5222 5223
    if (xml)
        xmlFreeDoc(xml);
    if (xml_buf)
        xmlBufferFree(xml_buf);
    if (dom)
        virDomainFree(dom);
    return ret;
}

5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371
/* Common code for the edit / net-edit / pool-edit functions which follow. */
static char *
editWriteToTempFile (vshControl *ctl, const char *doc)
{
    char *ret;
    const char *tmpdir;
    int fd;

    ret = malloc (PATH_MAX);
    if (!ret) {
        vshError(ctl, FALSE,
                 _("malloc: failed to allocate temporary file name: %s"),
                 strerror (errno));
        return NULL;
    }

    tmpdir = getenv ("TMPDIR");
    if (!tmpdir) tmpdir = "/tmp";
    snprintf (ret, PATH_MAX, "%s/virshXXXXXX", tmpdir);
    fd = mkstemp (ret);
    if (fd == -1) {
        vshError(ctl, FALSE,
                 _("mkstemp: failed to create temporary file: %s"),
                 strerror (errno));
        return NULL;
    }

    if (safewrite (fd, doc, strlen (doc)) == -1) {
        vshError(ctl, FALSE,
                 _("write: %s: failed to write to temporary file: %s"),
                 ret, strerror (errno));
        close (fd);
        unlink (ret);
        free (ret);
        return NULL;
    }
    if (close (fd) == -1) {
        vshError(ctl, FALSE,
                 _("close: %s: failed to write or close temporary file: %s"),
                 ret, strerror (errno));
        unlink (ret);
        free (ret);
        return NULL;
    }

    /* Temporary filename: caller frees. */
    return ret;
}

/* Characters permitted in $EDITOR environment variable and temp filename. */
#define ACCEPTED_CHARS \
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-/_.:@"

static int
editFile (vshControl *ctl, const char *filename)
{
    const char *editor;
    char *command;
    int command_ret;

    editor = getenv ("EDITOR");
    if (!editor) editor = "vi"; /* could be cruel & default to ed(1) here */

    /* Check the editor doesn't contain shell meta-characters, and if
     * it does, refuse to run.
     */
    if (strspn (editor, ACCEPTED_CHARS) != strlen (editor)) {
        vshError(ctl, FALSE,
                 _("%s: $EDITOR environment variable contains shell meta or other unacceptable characters"),
                 editor);
        return -1;
    }
    /* Same for the filename. */
    if (strspn (filename, ACCEPTED_CHARS) != strlen (filename)) {
        vshError(ctl, FALSE,
                 _("%s: temporary filename contains shell meta or other unacceptable characters (is $TMPDIR wrong?)"),
                 filename);
        return -1;
    }

    if (asprintf (&command, "%s %s", editor, filename) == -1) {
        vshError(ctl, FALSE,
                 _("asprintf: could not create editing command: %s"),
                 strerror (errno));
        return -1;
    }

    command_ret = system (command);
    if (command_ret == -1) {
        vshError(ctl, FALSE,
                 _("%s: edit command failed: %s"), command, strerror (errno));
        free (command);
        return -1;
    }
    if (command_ret != WEXITSTATUS (0)) {
        vshError(ctl, FALSE,
                 _("%s: command exited with non-zero status"), command);
        free (command);
        return -1;
    }
    free (command);
    return 0;
}

static char *
editReadBackFile (vshControl *ctl, const char *filename)
{
    char *ret;

    if (virFileReadAll (filename, VIRSH_MAX_XML_FILE, &ret) == -1) {
        vshError(ctl, FALSE,
                 _("%s: failed to read temporary file: %s"),
                 filename, strerror (errno));
        return NULL;
    }
    return ret;
}

/*
 * "edit" command
 */
static const vshCmdInfo info_edit[] = {
    {"help", gettext_noop("edit XML configuration for a domain")},
    {"desc", gettext_noop("Edit the XML configuration for a domain.")},
    {NULL, NULL}
};

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

/* This function also acts as a template to generate cmdNetworkEdit
 * and cmdPoolEdit functions (below) using a sed script in the Makefile.
 */
static int
cmdEdit (vshControl *ctl, const vshCmd *cmd)
{
    int ret = FALSE;
    virDomainPtr dom = NULL;
    char *tmp = NULL;
    char *doc = NULL;
    char *doc_edited = NULL;
    char *doc_reread = NULL;

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

J
Jim Meyering 已提交
5372
    dom = vshCommandOptDomain (ctl, cmd, NULL);
5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412
    if (dom == NULL)
        goto cleanup;

    /* Get the XML configuration of the domain. */
    doc = virDomainGetXMLDesc (dom, 0);
    if (!doc)
        goto cleanup;

    /* Create and open the temporary file. */
    tmp = editWriteToTempFile (ctl, doc);
    if (!tmp) goto cleanup;

    /* Start the editor. */
    if (editFile (ctl, tmp) == -1) goto cleanup;

    /* Read back the edited file. */
    doc_edited = editReadBackFile (ctl, tmp);
    if (!doc_edited) goto cleanup;

    unlink (tmp);
    tmp = NULL;

    /* Compare original XML with edited.  Has it changed at all? */
    if (STREQ (doc, doc_edited)) {
        vshPrint (ctl, _("Domain %s XML configuration not changed.\n"),
                  virDomainGetName (dom));
        ret = TRUE;
        goto cleanup;
    }

    /* Now re-read the domain XML.  Did someone else change it while
     * it was being edited?  This also catches problems such as us
     * losing a connection or the domain going away.
     */
    doc_reread = virDomainGetXMLDesc (dom, 0);
    if (!doc_reread)
        goto cleanup;

    if (STRNEQ (doc, doc_reread)) {
        vshError (ctl, FALSE,
J
Jim Meyering 已提交
5413
                  "%s", _("ERROR: the XML configuration was changed by another user"));
5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477
        goto cleanup;
    }

    /* Everything checks out, so redefine the domain. */
    virDomainFree (dom);
    dom = virDomainDefineXML (ctl->conn, doc_edited);
    if (!dom)
        goto cleanup;

    vshPrint (ctl, _("Domain %s XML configuration edited.\n"),
              virDomainGetName(dom));

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree (dom);

    free (doc);
    free (doc_edited);
    free (doc_reread);

    if (tmp) {
        unlink (tmp);
        free (tmp);
    }

    return ret;
}

/*
 * "net-edit" command
 */
static const vshCmdInfo info_network_edit[] = {
    {"help", gettext_noop("edit XML configuration for a network")},
    {"desc", gettext_noop("Edit the XML configuration for a network.")},
    {NULL, NULL}
};

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

/* This is generated from this file by a sed script in the Makefile. */
#include "virsh-net-edit.c"

/*
 * "pool-edit" command
 */
static const vshCmdInfo info_pool_edit[] = {
    {"help", gettext_noop("edit XML configuration for a storage pool")},
    {"desc", gettext_noop("Edit the XML configuration for a storage pool.")},
    {NULL, NULL}
};

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

/* This is generated from this file by a sed script in the Makefile. */
#include "virsh-pool-edit.c"

K
Karel Zak 已提交
5478 5479 5480
/*
 * "quit" command
 */
5481
static const vshCmdInfo info_quit[] = {
5482
    {"help", gettext_noop("quit this interactive terminal")},
5483
    {"desc", gettext_noop("")}, /* FIXME: describe */
5484
    {NULL, NULL}
K
Karel Zak 已提交
5485 5486 5487
};

static int
5488
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
5489
{
K
Karel Zak 已提交
5490 5491 5492 5493 5494 5495 5496
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
5497
static const vshCmdDef commands[] = {
5498 5499 5500 5501
    {"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},
5502
    {"autostart", cmdAutostart, opts_autostart, info_autostart},
5503
    {"capabilities", cmdCapabilities, NULL, info_capabilities},
5504
    {"connect", cmdConnect, opts_connect, info_connect},
5505
    {"console", cmdConsole, opts_console, info_console},
5506
    {"create", cmdCreate, opts_create, info_create},
5507
    {"start", cmdStart, opts_start, info_start},
K
Karel Zak 已提交
5508
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
5509 5510 5511
    {"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},
5512
    {"define", cmdDefine, opts_define, info_define},
K
Karel Zak 已提交
5513
    {"domid", cmdDomid, opts_domid, info_domid},
K
Karel Zak 已提交
5514
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid},
5515
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
5516 5517
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
5518 5519
    {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat},
    {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat},
5520
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
5521
    {"edit", cmdEdit, opts_edit, info_edit},
5522 5523 5524 5525
    {"find-storage-pool-sources", cmdPoolDiscoverSources,
     opts_find_storage_pool_sources, info_find_storage_pool_sources},
    {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs,
     opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as},
5526
    {"freecell", cmdFreecell, opts_freecell, info_freecell},
5527
    {"hostname", cmdHostname, NULL, info_hostname},
5528
    {"list", cmdList, opts_list, info_list},
5529
    {"migrate", cmdMigrate, opts_migrate, info_migrate},
5530

5531
    {"net-autostart", cmdNetworkAutostart, opts_network_autostart, info_network_autostart},
5532 5533 5534 5535
    {"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},
5536
    {"net-edit", cmdNetworkEdit, opts_network_edit, info_network_edit},
5537 5538 5539 5540 5541
    {"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 已提交
5542
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
5543

5544 5545 5546
    {"nodedev-list", cmdNodeListDevices, opts_node_list_devices, info_node_list_devices},
    {"nodedev-dumpxml", cmdNodeDeviceDumpXML, opts_node_device_dumpxml, info_node_device_dumpxml},

5547 5548 5549
    {"pool-autostart", cmdPoolAutostart, opts_pool_autostart, info_pool_autostart},
    {"pool-build", cmdPoolBuild, opts_pool_build, info_pool_build},
    {"pool-create", cmdPoolCreate, opts_pool_create, info_pool_create},
5550
    {"pool-create-as", cmdPoolCreateAs, opts_pool_X_as, info_pool_create_as},
5551
    {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define},
5552
    {"pool-define-as", cmdPoolDefineAs, opts_pool_X_as, info_pool_define_as},
5553 5554 5555
    {"pool-destroy", cmdPoolDestroy, opts_pool_destroy, info_pool_destroy},
    {"pool-delete", cmdPoolDelete, opts_pool_delete, info_pool_delete},
    {"pool-dumpxml", cmdPoolDumpXML, opts_pool_dumpxml, info_pool_dumpxml},
5556
    {"pool-edit", cmdPoolEdit, opts_pool_edit, info_pool_edit},
5557 5558 5559 5560 5561 5562 5563 5564
    {"pool-info", cmdPoolInfo, opts_pool_info, info_pool_info},
    {"pool-list", cmdPoolList, opts_pool_list, info_pool_list},
    {"pool-name", cmdPoolName, opts_pool_name, info_pool_name},
    {"pool-refresh", cmdPoolRefresh, opts_pool_refresh, info_pool_refresh},
    {"pool-start", cmdPoolStart, opts_pool_start, info_pool_start},
    {"pool-undefine", cmdPoolUndefine, opts_pool_undefine, info_pool_undefine},
    {"pool-uuid", cmdPoolUuid, opts_pool_uuid, info_pool_uuid},

K
Karel Zak 已提交
5565 5566 5567
    {"quit", cmdQuit, NULL, info_quit},
    {"reboot", cmdReboot, opts_reboot, info_reboot},
    {"restore", cmdRestore, opts_restore, info_restore},
5568 5569
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
5570
    {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo},
D
Daniel Veillard 已提交
5571
    {"dump", cmdDump, opts_dump, info_dump},
5572
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
5573 5574 5575
    {"setmem", cmdSetmem, opts_setmem, info_setmem},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus},
K
Karel Zak 已提交
5576
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
5577
    {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole},
5578
    {"undefine", cmdUndefine, opts_undefine, info_undefine},
5579
    {"uri", cmdURI, NULL, info_uri},
5580 5581

    {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create},
5582
    {"vol-create-as", cmdVolCreateAs, opts_vol_create_as, info_vol_create_as},
5583 5584 5585 5586 5587 5588 5589 5590
    {"vol-delete", cmdVolDelete, opts_vol_delete, info_vol_delete},
    {"vol-dumpxml", cmdVolDumpXML, opts_vol_dumpxml, info_vol_dumpxml},
    {"vol-info", cmdVolInfo, opts_vol_info, info_vol_info},
    {"vol-list", cmdVolList, opts_vol_list, info_vol_list},
    {"vol-path", cmdVolPath, opts_vol_path, info_vol_path},
    {"vol-name", cmdVolName, opts_vol_name, info_vol_name},
    {"vol-key", cmdVolKey, opts_vol_key, info_vol_key},

5591 5592
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
5593
    {"version", cmdVersion, NULL, info_version},
5594
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay},
5595
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
5596 5597 5598 5599 5600 5601
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
5602
static const char *
5603
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
5604
{
5605
    const vshCmdInfo *info;
5606

K
Karel Zak 已提交
5607
    for (info = cmd->info; info && info->name; info++) {
5608
        if (STREQ(info->name, name))
K
Karel Zak 已提交
5609 5610 5611 5612 5613
            return info->data;
    }
    return NULL;
}

5614 5615
static const vshCmdOptDef *
vshCmddefGetOption(const vshCmdDef * cmd, const char *name)
5616
{
5617
    const vshCmdOptDef *opt;
5618

K
Karel Zak 已提交
5619
    for (opt = cmd->opts; opt && opt->name; opt++)
5620
        if (STREQ(opt->name, name))
K
Karel Zak 已提交
5621 5622 5623 5624
            return opt;
    return NULL;
}

5625 5626
static const vshCmdOptDef *
vshCmddefGetData(const vshCmdDef * cmd, int data_ct)
5627
{
5628
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
5629

5630
    for (opt = cmd->opts; opt && opt->name; opt++) {
5631 5632
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
5633 5634 5635 5636 5637
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
5638 5639 5640
    return NULL;
}

5641 5642 5643
/*
 * Checks for required options
 */
5644
static int
5645
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd)
5646
{
5647 5648
    const vshCmdDef *def = cmd->def;
    const vshCmdOptDef *d;
5649
    int err = 0;
5650 5651 5652 5653

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

            while (o && ok == 0) {
5657
                if (o->def == d)
5658
                    ok = 1;
5659 5660 5661
                o = o->next;
            }
            if (!ok) {
5662 5663
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
5664
                         _("command '%s' requires <%s> option") :
5665
                         _("command '%s' requires --%s option"),
5666
                         def->name, d->name);
5667 5668
                err = 1;
            }
5669

5670 5671 5672 5673 5674
        }
    }
    return !err;
}

5675
static const vshCmdDef *
5676 5677
vshCmddefSearch(const char *cmdname)
{
5678
    const vshCmdDef *c;
5679

K
Karel Zak 已提交
5680
    for (c = commands; c->name; c++)
5681
        if (STREQ(c->name, cmdname))
K
Karel Zak 已提交
5682 5683 5684 5685 5686
            return c;
    return NULL;
}

static int
5687
vshCmddefHelp(vshControl *ctl, const char *cmdname)
5688
{
5689
    const vshCmdDef *def = vshCmddefSearch(cmdname);
5690

K
Karel Zak 已提交
5691
    if (!def) {
5692
        vshError(ctl, FALSE, _("command '%s' doesn't exist"), cmdname);
5693 5694
        return FALSE;
    } else {
5695 5696
        const char *desc = N_(vshCmddefGetInfo(def, "desc"));
        const char *help = N_(vshCmddefGetInfo(def, "help"));
5697
        char buf[256];
K
Karel Zak 已提交
5698

5699
        fputs(_("  NAME\n"), stdout);
5700 5701
        fprintf(stdout, "    %s - %s\n", def->name, help);

5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
                const char *fmt;
                if (opt->type == VSH_OT_BOOL)
                    fmt = "[--%s]";
                else if (opt->type == VSH_OT_INT)
                    fmt = N_("[--%s <number>]");
                else if (opt->type == VSH_OT_STRING)
                    fmt = N_("[--%s <string>]");
                else if (opt->type == VSH_OT_DATA)
                    fmt = ((opt->flag & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
                else
                    assert(0);
                fputc(' ', stdout);
                fprintf(stdout, _(fmt), opt->name);
            }
K
Karel Zak 已提交
5721
        }
5722 5723 5724 5725 5726
        fputc('\n', stdout);

        if (desc[0]) {
            /* FIXME: remove this test once all of the empty descriptions
               have been removed; see `FIXME: describe' lines.  */
5727
            fputs(_("\n  DESCRIPTION\n"), stdout);
K
Karel Zak 已提交
5728 5729
            fprintf(stdout, "    %s\n", desc);
        }
5730

K
Karel Zak 已提交
5731
        if (def->opts) {
5732
            const vshCmdOptDef *opt;
5733
            fputs(_("\n  OPTIONS\n"), stdout);
5734 5735
            for (opt = def->opts; opt->name; opt++) {
                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
5736
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
5737
                else if (opt->type == VSH_OT_INT)
5738
                    snprintf(buf, sizeof(buf), _("--%s <number>"), opt->name);
5739
                else if (opt->type == VSH_OT_STRING)
5740
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
5741
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
5742
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
5743

5744
                fprintf(stdout, "    %-15s  %s\n", buf, N_(opt->help));
5745
            }
K
Karel Zak 已提交
5746 5747 5748 5749 5750 5751 5752 5753 5754 5755
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
5756 5757 5758
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
5759 5760
    vshCmdOpt *a = arg;

5761
    while (a) {
K
Karel Zak 已提交
5762
        vshCmdOpt *tmp = a;
5763

K
Karel Zak 已提交
5764 5765
        a = a->next;

5766
        free(tmp->data);
K
Karel Zak 已提交
5767 5768 5769 5770 5771
        free(tmp);
    }
}

static void
5772
vshCommandFree(vshCmd *cmd)
5773
{
K
Karel Zak 已提交
5774 5775
    vshCmd *c = cmd;

5776
    while (c) {
K
Karel Zak 已提交
5777
        vshCmd *tmp = c;
5778

K
Karel Zak 已提交
5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
5791
vshCommandOpt(const vshCmd *cmd, const char *name)
5792
{
K
Karel Zak 已提交
5793
    vshCmdOpt *opt = cmd->opts;
5794 5795

    while (opt) {
5796
        if (opt->def && STREQ(opt->def->name, name))
K
Karel Zak 已提交
5797 5798 5799 5800 5801 5802 5803 5804 5805 5806
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
5807
vshCommandOptInt(const vshCmd *cmd, const char *name, int *found)
5808
{
K
Karel Zak 已提交
5809
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
5810 5811
    int res = 0, num_found = FALSE;
    char *end_p = NULL;
5812

5813 5814
    if ((arg != NULL) && (arg->data != NULL)) {
        res = strtol(arg->data, &end_p, 10);
5815 5816 5817 5818
        if ((arg->data == end_p) || (*end_p!= 0))
            num_found = FALSE;
        else
            num_found = TRUE;
5819
    }
K
Karel Zak 已提交
5820
    if (found)
5821
        *found = num_found;
K
Karel Zak 已提交
5822 5823 5824 5825 5826 5827 5828
    return res;
}

/*
 * Returns option as STRING
 */
static char *
5829
vshCommandOptString(const vshCmd *cmd, const char *name, int *found)
5830
{
K
Karel Zak 已提交
5831
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
5832

K
Karel Zak 已提交
5833 5834
    if (found)
        *found = arg ? TRUE : FALSE;
5835 5836

    return arg && arg->data && *arg->data ? arg->data : NULL;
K
Karel Zak 已提交
5837 5838
}

5839 5840
#if 0
static int
5841
vshCommandOptStringList(const vshCmd *cmd, const char *name, char ***data)
5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864
{
    vshCmdOpt *arg = cmd->opts;
    char **val = NULL;
    int nval = 0;

    while (arg) {
        if (arg->def && STREQ(arg->def->name, name)) {
            char **tmp = realloc(val, sizeof(*tmp) * (nval+1));
            if (!tmp) {
                free(val);
                return -1;
            }
            val = tmp;
            val[nval++] = arg->data;
        }
        arg = arg->next;
    }

    *data = val;
    return nval;
}
#endif

K
Karel Zak 已提交
5865 5866 5867 5868
/*
 * Returns TRUE/FALSE if the option exists
 */
static int
5869
vshCommandOptBool(const vshCmd *cmd, const char *name)
5870
{
K
Karel Zak 已提交
5871 5872 5873
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

J
Jim Meyering 已提交
5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
static bool
cmd_has_option (vshControl *ctl, const vshCmd *cmd, const char *optname)
{
    /* Iterate through cmd->opts, to ensure that there is an entry
       with name OPTNAME and type VSH_OT_DATA. */
    bool found = false;
    const vshCmdOpt *opt;
    for (opt = cmd->opts; opt; opt = opt->next) {
        if (STREQ (opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
            found = true;
            break;
        }
    }

    if (!found)
        vshError(ctl, FALSE,
                 _("internal error: virsh %s: no %s VSH_OT_DATA option"),
                 cmd->def->name, optname);
    return found;
}
5897

K
Karel Zak 已提交
5898
static virDomainPtr
J
Jim Meyering 已提交
5899
vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
5900
                      char **name, int flag)
5901
{
K
Karel Zak 已提交
5902
    virDomainPtr dom = NULL;
5903
    char *n;
K
Karel Zak 已提交
5904
    int id;
J
Jim Meyering 已提交
5905 5906 5907
    const char *optname = "domain";
    if (!cmd_has_option (ctl, cmd, optname))
        return NULL;
5908

K
Karel Zak 已提交
5909
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
J
Jim Meyering 已提交
5910
        vshError(ctl, FALSE, "%s", _("undefined domain name or id"));
5911
        return NULL;
K
Karel Zak 已提交
5912
    }
5913

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

K
Karel Zak 已提交
5917 5918
    if (name)
        *name = n;
5919

K
Karel Zak 已提交
5920
    /* try it by ID */
5921
    if (flag & VSH_BYID) {
5922
        if (virStrToLong_i(n, NULL, 10, &id) == 0 && id >= 0) {
K
Karel Zak 已提交
5923 5924 5925 5926
            vshDebug(ctl, 5, "%s: <%s> seems like domain ID\n",
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
5927
    }
K
Karel Zak 已提交
5928
    /* try it by UUID */
5929
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
D
Daniel Veillard 已提交
5930
        vshDebug(ctl, 5, "%s: <%s> trying as domain UUID\n",
5931
                 cmd->def->name, optname);
K
Karel Zak 已提交
5932
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
5933
    }
K
Karel Zak 已提交
5934
    /* try it by NAME */
5935
    if (dom==NULL && (flag & VSH_BYNAME)) {
D
Daniel Veillard 已提交
5936
        vshDebug(ctl, 5, "%s: <%s> trying as domain NAME\n",
5937
                 cmd->def->name, optname);
K
Karel Zak 已提交
5938
        dom = virDomainLookupByName(ctl->conn, n);
5939
    }
K
Karel Zak 已提交
5940

5941
    if (!dom)
5942
        vshError(ctl, FALSE, _("failed to get domain '%s'"), n);
5943

K
Karel Zak 已提交
5944 5945 5946
    return dom;
}

5947
static virNetworkPtr
J
Jim Meyering 已提交
5948
vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd,
5949
                       char **name, int flag)
5950 5951 5952
{
    virNetworkPtr network = NULL;
    char *n;
J
Jim Meyering 已提交
5953 5954 5955
    const char *optname = "network";
    if (!cmd_has_option (ctl, cmd, optname))
        return NULL;
5956 5957

    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
J
Jim Meyering 已提交
5958
        vshError(ctl, FALSE, "%s", _("undefined network name"));
5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969
        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) {
D
Daniel Veillard 已提交
5970
        vshDebug(ctl, 5, "%s: <%s> trying as network UUID\n",
5971
                 cmd->def->name, optname);
5972 5973 5974 5975
        network = virNetworkLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (network==NULL && (flag & VSH_BYNAME)) {
D
Daniel Veillard 已提交
5976
        vshDebug(ctl, 5, "%s: <%s> trying as network NAME\n",
5977 5978 5979 5980 5981 5982 5983 5984 5985 5986
                 cmd->def->name, optname);
        network = virNetworkLookupByName(ctl->conn, n);
    }

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

    return network;
}

5987
static virStoragePoolPtr
5988
vshCommandOptPoolBy(vshControl *ctl, const vshCmd *cmd, const char *optname,
5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007
                    char **name, int flag)
{
    virStoragePoolPtr pool = NULL;
    char *n;

    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
        vshError(ctl, FALSE, "%s", _("undefined pool 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 (pool==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
        vshDebug(ctl, 5, "%s: <%s> trying as pool UUID\n",
6008
                 cmd->def->name, optname);
6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024
        pool = virStoragePoolLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (pool==NULL && (flag & VSH_BYNAME)) {
        vshDebug(ctl, 5, "%s: <%s> trying as pool NAME\n",
                 cmd->def->name, optname);
        pool = virStoragePoolLookupByName(ctl->conn, n);
    }

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

    return pool;
}

static virStorageVolPtr
6025
vshCommandOptVolBy(vshControl *ctl, const vshCmd *cmd,
6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079
                   const char *optname,
                   const char *pooloptname,
                   char **name, int flag)
{
    virStorageVolPtr vol = NULL;
    virStoragePoolPtr pool = NULL;
    char *n, *p;
    int found;

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

    if (!(p = vshCommandOptString(cmd, pooloptname, &found)) && found) {
        vshError(ctl, FALSE, "%s", _("undefined pool name"));
        return NULL;
    }

    if (p)
        pool = vshCommandOptPoolBy(ctl, cmd, pooloptname, name, flag);

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

    if (name)
        *name = n;

    /* try it by PATH */
    if (pool && (flag & VSH_BYNAME)) {
        vshDebug(ctl, 5, "%s: <%s> trying as vol UUID\n",
                 cmd->def->name, optname);
        vol = virStorageVolLookupByName(pool, n);
    }
    if (vol == NULL && (flag & VSH_BYUUID)) {
        vshDebug(ctl, 5, "%s: <%s> trying as vol key\n",
                 cmd->def->name, optname);
        vol = virStorageVolLookupByKey(ctl->conn, n);
    }
    if (vol == NULL && (flag & VSH_BYUUID)) {
        vshDebug(ctl, 5, "%s: <%s> trying as vol path\n",
                 cmd->def->name, optname);
        vol = virStorageVolLookupByPath(ctl->conn, n);
    }

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

    if (pool)
        virStoragePoolFree(pool);

    return vol;
}

K
Karel Zak 已提交
6080 6081 6082 6083
/*
 * Executes command(s) and returns return code from last command
 */
static int
6084
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
6085
{
K
Karel Zak 已提交
6086
    int ret = TRUE;
6087 6088

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

K
Karel Zak 已提交
6091 6092
        if (ctl->timing)
            GETTIMEOFDAY(&before);
6093

K
Karel Zak 已提交
6094 6095 6096 6097
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
6098

6099
        if (STREQ(cmd->def->name, "quit"))        /* hack ... */
K
Karel Zak 已提交
6100 6101 6102
            return ret;

        if (ctl->timing)
6103
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
6104 6105
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
6106
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121
        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

6122
static int
6123
vshCommandGetToken(vshControl *ctl, char *str, char **end, char **res)
6124
{
K
Karel Zak 已提交
6125 6126 6127 6128 6129
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
6130

K
Karel Zak 已提交
6131
    *end = NULL;
6132

6133
    while (p && *p && (*p == ' ' || *p == '\t'))
K
Karel Zak 已提交
6134
        p++;
6135 6136

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
6137
        return VSH_TK_END;
6138
    if (*p == ';') {
D
Daniel Veillard 已提交
6139
        *end = ++p;             /* = \0 or begin of next command */
K
Karel Zak 已提交
6140 6141
        return VSH_TK_END;
    }
6142
    while (*p) {
K
Karel Zak 已提交
6143
        /* end of token is blank space or ';' */
6144
        if ((quote == FALSE && (*p == ' ' || *p == '\t')) || *p == ';')
K
Karel Zak 已提交
6145
            break;
6146

6147
        /* end of option name could be '=' */
6148 6149
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
6150 6151
            break;
        }
6152 6153 6154

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
6155
                && c_isalnum(*(p + 2))) {
K
Karel Zak 已提交
6156
                tk = VSH_TK_OPTION;
6157
                p += 2;
K
Karel Zak 已提交
6158 6159
            } else {
                tk = VSH_TK_DATA;
6160 6161
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
6162 6163 6164 6165 6166
                    p++;
                } else {
                    quote = FALSE;
                }
            }
6167 6168
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
6169 6170
            quote = FALSE;
            p++;
6171
            break;              /* end of "..." token */
K
Karel Zak 已提交
6172 6173 6174 6175 6176
        }
        p++;
        sz++;
    }
    if (quote) {
J
Jim Meyering 已提交
6177
        vshError(ctl, FALSE, "%s", _("missing \""));
K
Karel Zak 已提交
6178 6179
        return VSH_TK_ERROR;
    }
6180
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
6181
        return VSH_TK_END;
6182
    if (sz == 0)
K
Karel Zak 已提交
6183
        return VSH_TK_END;
6184

6185
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
6186
    memcpy(*res, tkstr, sz);
6187
    *(*res + sz) = '\0';
K
Karel Zak 已提交
6188 6189 6190 6191 6192 6193

    *end = p;
    return tk;
}

static int
6194
vshCommandParse(vshControl *ctl, char *cmdstr)
6195
{
K
Karel Zak 已提交
6196 6197 6198 6199
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
6200

K
Karel Zak 已提交
6201 6202 6203 6204
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
6205 6206

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

K
Karel Zak 已提交
6209
    str = cmdstr;
6210
    while (str && *str) {
K
Karel Zak 已提交
6211
        vshCmdOpt *last = NULL;
6212
        const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
6213
        int tk = VSH_TK_NONE;
6214
        int data_ct = 0;
6215

K
Karel Zak 已提交
6216
        first = NULL;
6217 6218

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
6219
            char *end = NULL;
6220
            const vshCmdOptDef *opt = NULL;
6221

K
Karel Zak 已提交
6222
            tkdata = NULL;
6223

K
Karel Zak 已提交
6224 6225
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
6226

K
Karel Zak 已提交
6227
            str = end;
6228 6229

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
6230
                break;
6231
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
6232
                goto syntaxError;
6233 6234

            if (cmd == NULL) {
K
Karel Zak 已提交
6235
                /* first token must be command name */
6236 6237
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
6238
                             _("unexpected token (command name): '%s'"),
6239
                             tkdata);
K
Karel Zak 已提交
6240 6241 6242
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
6243
                    vshError(ctl, FALSE, _("unknown command: '%s'"), tkdata);
6244
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
6245 6246
                }
                free(tkdata);
6247
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
6248 6249
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
6250
                             _("command '%s' doesn't support option --%s"),
6251
                             cmd->name, tkdata);
K
Karel Zak 已提交
6252 6253
                    goto syntaxError;
                }
6254
                free(tkdata);   /* option name */
K
Karel Zak 已提交
6255 6256 6257 6258 6259
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
6260 6261
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
6262
                        goto syntaxError;
6263
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
6264
                        vshError(ctl, FALSE,
6265
                                 _("expected syntax: --%s <%s>"),
6266 6267
                                 opt->name,
                                 opt->type ==
6268
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
6269 6270 6271
                        goto syntaxError;
                    }
                }
6272
            } else if (tk == VSH_TK_DATA) {
6273
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
6274
                    vshError(ctl, FALSE, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
6275 6276 6277 6278 6279
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
6280
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
6281

K
Karel Zak 已提交
6282 6283 6284 6285
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
6286

K
Karel Zak 已提交
6287 6288 6289 6290 6291
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
6292

K
Karel Zak 已提交
6293
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
6294 6295
                         cmd->name,
                         opt->name,
6296
                         tk == VSH_TK_OPTION ? _("OPTION") : _("DATA"),
6297
                         arg->data);
K
Karel Zak 已提交
6298 6299 6300 6301
            }
            if (!str)
                break;
        }
6302

D
Daniel Veillard 已提交
6303
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
6304
        if (cmd) {
6305
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
6306

K
Karel Zak 已提交
6307 6308 6309 6310
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

6311
            if (!vshCommandCheckOpts(ctl, c)) {
6312
                free(c);
6313
                goto syntaxError;
6314
            }
6315

K
Karel Zak 已提交
6316 6317 6318 6319 6320 6321 6322
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
6323

K
Karel Zak 已提交
6324 6325
    return TRUE;

6326
 syntaxError:
K
Karel Zak 已提交
6327 6328 6329 6330
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
6331
    free(tkdata);
6332
    return FALSE;
K
Karel Zak 已提交
6333 6334 6335 6336
}


/* ---------------
6337
 * Misc utils
K
Karel Zak 已提交
6338 6339
 * ---------------
 */
K
Karel Zak 已提交
6340
static const char *
6341 6342
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
6343
    switch (state) {
6344 6345 6346
    case VIR_DOMAIN_RUNNING:
        return gettext_noop("running");
    case VIR_DOMAIN_BLOCKED:
6347
        return gettext_noop("idle");
6348 6349 6350 6351 6352 6353 6354 6355 6356
    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:
6357
        ;/*FALLTHROUGH*/
K
Karel Zak 已提交
6358
    }
6359
    return gettext_noop("no state");  /* = dom0 state */
K
Karel Zak 已提交
6360 6361
}

6362 6363 6364 6365
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
6366 6367 6368
    case VIR_VCPU_OFFLINE:
        return gettext_noop("offline");
    case VIR_VCPU_BLOCKED:
6369
        return gettext_noop("idle");
6370 6371 6372
    case VIR_VCPU_RUNNING:
        return gettext_noop("running");
    default:
6373
        ;/*FALLTHROUGH*/
6374
    }
6375
    return gettext_noop("no state");
6376 6377
}

K
Karel Zak 已提交
6378
static int
6379
vshConnectionUsability(vshControl *ctl, virConnectPtr conn, int showerror)
6380
{
6381 6382
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
6383 6384 6385
     */
    if (!conn) {
        if (showerror)
J
Jim Meyering 已提交
6386
            vshError(ctl, FALSE, "%s", _("no valid connection"));
K
Karel Zak 已提交
6387 6388 6389 6390 6391
        return FALSE;
    }
    return TRUE;
}

K
Karel Zak 已提交
6392
static void
6393
vshDebug(vshControl *ctl, int level, const char *format, ...)
6394
{
K
Karel Zak 已提交
6395 6396
    va_list ap;

6397 6398 6399 6400
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_DEBUG, format, ap);
    va_end(ap);

K
Karel Zak 已提交
6401 6402 6403 6404 6405 6406
    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
6407 6408 6409
}

static void
6410
vshPrintExtra(vshControl *ctl, const char *format, ...)
6411
{
K
Karel Zak 已提交
6412
    va_list ap;
6413

K
Karel Zak 已提交
6414
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
6415
        return;
6416

K
Karel Zak 已提交
6417
    va_start(ap, format);
6418
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
6419 6420 6421
    va_end(ap);
}

K
Karel Zak 已提交
6422

K
Karel Zak 已提交
6423
static void
6424
vshError(vshControl *ctl, int doexit, const char *format, ...)
6425
{
K
Karel Zak 已提交
6426
    va_list ap;
6427

6428 6429 6430 6431
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
    va_end(ap);

K
Karel Zak 已提交
6432
    if (doexit)
6433
        fprintf(stderr, _("%s: error: "), progname);
K
Karel Zak 已提交
6434
    else
6435
        fputs(_("error: "), stderr);
6436

K
Karel Zak 已提交
6437 6438 6439 6440 6441
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
6442

K
Karel Zak 已提交
6443
    if (doexit) {
6444 6445
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
6446 6447 6448 6449
        exit(EXIT_FAILURE);
    }
}

6450
static void *
6451
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
6452 6453 6454 6455 6456
{
    void *x;

    if ((x = malloc(size)))
        return x;
6457
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
6458
             filename, line, (int) size);
6459 6460 6461 6462
    return NULL;
}

static void *
6463
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename, int line)
6464 6465 6466 6467 6468
{
    void *x;

    if ((x = calloc(nmemb, size)))
        return x;
6469
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
6470
             filename, line, (int) (size*nmemb));
6471 6472 6473
    return NULL;
}

6474
static void *
6475
_vshRealloc(vshControl *ctl, void *ptr, size_t size, const char *filename, int line)
6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486
{
    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;
}

6487
static char *
6488
_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line)
6489 6490 6491
{
    char *x;

6492 6493
    if (s == NULL)
        return(NULL);
6494 6495
    if ((x = strdup(s)))
        return x;
6496 6497
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
6498 6499 6500
    return NULL;
}

K
Karel Zak 已提交
6501
/*
6502
 * Initialize connection.
K
Karel Zak 已提交
6503 6504
 */
static int
6505
vshInit(vshControl *ctl)
6506
{
K
Karel Zak 已提交
6507 6508 6509
    if (ctl->conn)
        return FALSE;

6510 6511
    vshOpenLogFile(ctl);

6512 6513
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
6514

6515 6516 6517 6518
    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);

6519

6520 6521 6522 6523
    /* This is not necessarily fatal.  All the individual commands check
     * vshConnectionUsability, except ones which don't need a connection
     * such as "help".
     */
6524
    if (!ctl->conn) {
J
Jim Meyering 已提交
6525
        vshError(ctl, FALSE, "%s", _("failed to connect to the hypervisor"));
6526 6527
        return FALSE;
    }
K
Karel Zak 已提交
6528 6529 6530 6531

    return TRUE;
}

6532 6533 6534 6535 6536
#ifndef O_SYNC
#define O_SYNC 0
#endif
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555
/**
 * 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:
J
Jim Meyering 已提交
6556 6557
                vshError(ctl, TRUE, "%s",
                         _("failed to get the log file information"));
6558 6559 6560 6561
                break;
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
J
Jim Meyering 已提交
6562
            vshError(ctl, TRUE, "%s", _("the log path is not a file"));
6563 6564 6565 6566
        }
    }

    /* log file open */
6567
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
J
Jim Meyering 已提交
6568 6569
        vshError(ctl, TRUE, "%s",
                 _("failed to open the log file. check the log file path"));
6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634
    }
}

/**
 * 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 */
6635
    if (safewrite(ctl->log_fd, msg_buf, strlen(msg_buf)) < 0) {
6636
        vshCloseLogFile(ctl);
J
Jim Meyering 已提交
6637
        vshError(ctl, FALSE, "%s", _("failed to write the log file"));
6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650
    }
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
    if (ctl->log_fd >= 0) {
6651
        if (close(ctl->log_fd) < 0)
6652
            vshError(ctl, FALSE, _("%s: failed to write log file: %s"),
6653
                     ctl->logfile ? ctl->logfile : "?", strerror (errno));
6654 6655 6656 6657 6658 6659 6660 6661 6662
        ctl->log_fd = -1;
    }

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

6663
#ifdef USE_READLINE
6664

K
Karel Zak 已提交
6665 6666 6667 6668 6669
/* -----------------
 * Readline stuff
 * -----------------
 */

6670
/*
K
Karel Zak 已提交
6671 6672
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
6673
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
6674 6675
 */
static char *
6676 6677
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
6678
    static int list_index, len;
K
Karel Zak 已提交
6679
    const char *name;
K
Karel Zak 已提交
6680 6681 6682

    /* If this is a new word to complete, initialize now.  This
     * includes saving the length of TEXT for efficiency, and
6683
     * initializing the index variable to 0.
K
Karel Zak 已提交
6684 6685 6686
     */
    if (!state) {
        list_index = 0;
6687
        len = strlen(text);
K
Karel Zak 已提交
6688 6689 6690
    }

    /* Return the next name which partially matches from the
6691
     * command list.
K
Karel Zak 已提交
6692
     */
K
Karel Zak 已提交
6693
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
6694
        list_index++;
6695
        if (STREQLEN(name, text, len))
6696
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
6697 6698 6699 6700 6701 6702 6703
    }

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

static char *
6704 6705
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
6706
    static int list_index, len;
6707
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
6708
    const char *name;
K
Karel Zak 已提交
6709 6710 6711 6712 6713 6714 6715 6716 6717

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

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

6718
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
6719
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
6720 6721 6722

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
6723
        len = strlen(text);
K
Karel Zak 已提交
6724 6725 6726 6727 6728
        free(cmdname);
    }

    if (!cmd)
        return NULL;
6729

6730 6731 6732
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
6733
    while ((name = cmd->opts[list_index].name)) {
6734
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
6735
        char *res;
6736

K
Karel Zak 已提交
6737
        list_index++;
6738

K
Karel Zak 已提交
6739
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
6740 6741
            /* ignore non --option */
            continue;
6742

K
Karel Zak 已提交
6743
        if (len > 2) {
6744
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
6745 6746
                continue;
        }
6747
        res = vshMalloc(NULL, strlen(name) + 3);
6748
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
6749 6750 6751 6752 6753 6754 6755 6756
        return res;
    }

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

static char **
6757 6758 6759
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
6760 6761
    char **matches = (char **) NULL;

6762
    if (start == 0)
K
Karel Zak 已提交
6763
        /* command name generator */
6764
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
6765 6766
    else
        /* commands options */
6767
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
6768 6769 6770 6771 6772
    return matches;
}


static void
6773 6774
vshReadlineInit(void)
{
K
Karel Zak 已提交
6775 6776 6777 6778 6779 6780 6781
    /* 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;
}

6782 6783 6784 6785 6786 6787
static char *
vshReadline (vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
{
    return readline (prompt);
}

6788
#else /* !USE_READLINE */
6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814

static void
vshReadlineInit (void)
{
    /* empty */
}

static char *
vshReadline (vshControl *ctl, const char *prompt)
{
    char line[1024];
    char *r;
    int len;

    fputs (prompt, stdout);
    r = fgets (line, sizeof line, stdin);
    if (r == NULL) return NULL; /* EOF */

    /* Chomp trailing \n */
    len = strlen (r);
    if (len > 0 && r[len-1] == '\n')
        r[len-1] = '\0';

    return vshStrdup (ctl, r);
}

6815
#endif /* !USE_READLINE */
6816

K
Karel Zak 已提交
6817
/*
J
Jim Meyering 已提交
6818
 * Deinitialize virsh
K
Karel Zak 已提交
6819 6820
 */
static int
6821
vshDeinit(vshControl *ctl)
6822
{
6823
    vshCloseLogFile(ctl);
6824
    free(ctl->name);
K
Karel Zak 已提交
6825
    if (ctl->conn) {
6826 6827
        if (virConnectClose(ctl->conn) != 0) {
            ctl->conn = NULL;   /* prevent recursive call from vshError() */
J
Jim Meyering 已提交
6828 6829
            vshError(ctl, TRUE, "%s",
                     _("failed to disconnect from the hypervisor"));
K
Karel Zak 已提交
6830 6831
        }
    }
D
Daniel P. Berrange 已提交
6832 6833
    virResetLastError();

K
Karel Zak 已提交
6834 6835
    return TRUE;
}
6836

K
Karel Zak 已提交
6837 6838 6839 6840
/*
 * Print usage
 */
static void
6841
vshUsage(void)
6842
{
6843
    const vshCmdDef *cmd;
6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863
    fprintf(stdout, _("\n%s [options] [commands]\n\n"
                      "  options:\n"
                      "    -c | --connect <uri>    hypervisor connection URI\n"
                      "    -r | --readonly         connect readonly\n"
                      "    -d | --debug <num>      debug level [0-5]\n"
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
                      "    -l | --log <file>       output logging to file\n"
                      "    -v | --version          program version\n\n"
                      "  commands (non interactive mode):\n"), progname);

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

    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
6864 6865 6866 6867 6868 6869 6870
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
6871
vshParseArgv(vshControl *ctl, int argc, char **argv)
6872
{
K
Karel Zak 已提交
6873 6874
    char *last = NULL;
    int i, end = 0, help = 0;
6875
    int arg, idx = 0;
K
Karel Zak 已提交
6876
    struct option opt[] = {
6877 6878 6879 6880 6881
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
6882
        {"connect", 1, 0, 'c'},
6883
        {"readonly", 0, 0, 'r'},
6884
        {"log", 1, 0, 'l'},
K
Karel Zak 已提交
6885
        {0, 0, 0, 0}
6886 6887
    };

K
Karel Zak 已提交
6888 6889

    if (argc < 2)
K
Karel Zak 已提交
6890
        return TRUE;
6891

6892
    /* look for begin of the command, for example:
K
Karel Zak 已提交
6893 6894 6895 6896
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
6897
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
6898 6899
        if (*argv[i] != '-') {
            int valid = FALSE;
6900

K
Karel Zak 已提交
6901 6902 6903 6904
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
6905 6906

                for (o = opt; o->name; o++) {
6907 6908 6909 6910
                    if (o->has_arg == 1){
                        if (sz == 2 && *(last + 1) == o->val)
                            /* valid virsh short option */
                            valid = TRUE;
6911
                        else if (sz > 2 && STREQ(o->name, last + 2))
6912 6913 6914
                            /* valid virsh long option */
                            valid = TRUE;
                    }
K
Karel Zak 已提交
6915 6916 6917 6918 6919 6920 6921 6922 6923
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
6924
    end = end ? end : argc;
6925

K
Karel Zak 已提交
6926
    /* standard (non-command) options */
6927
    while ((arg = getopt_long(end, argv, "d:hqtc:vrl:", opt, &idx)) != -1) {
6928
        switch (arg) {
6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946
        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);
6947 6948 6949
        case 'r':
            ctl->readonly = TRUE;
            break;
6950 6951 6952
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
6953 6954 6955 6956
        default:
            vshError(ctl, TRUE,
                     _("unsupported option '-%c'. See --help."), arg);
            break;
K
Karel Zak 已提交
6957 6958 6959 6960
        }
    }

    if (help) {
6961 6962 6963 6964 6965 6966
        if (end < argc)
            vshError(ctl, TRUE,
                     _("extra argument '%s'. See --help."), argv[end]);

        /* list all command */
        vshUsage();
K
Karel Zak 已提交
6967
        exit(EXIT_SUCCESS);
6968 6969
    }

K
Karel Zak 已提交
6970 6971 6972
    if (argc > end) {
        /* parse command */
        char *cmdstr;
6973 6974
        int sz = 0, ret;

K
Karel Zak 已提交
6975 6976
        ctl->imode = FALSE;

6977 6978 6979
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

6980
        cmdstr = vshCalloc(ctl, sz + 1, 1);
6981 6982

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
6983 6984 6985 6986
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
6987
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
6988
        ret = vshCommandParse(ctl, cmdstr);
6989

K
Karel Zak 已提交
6990 6991 6992 6993 6994 6995
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

6996 6997 6998 6999
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
7000
    char *defaultConn;
K
Karel Zak 已提交
7001 7002
    int ret = TRUE;

7003 7004
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
7005
        return -1;
7006 7007 7008
    }
    if (!bindtextdomain(GETTEXT_PACKAGE, LOCALEBASEDIR)) {
        perror("bindtextdomain");
7009
        return -1;
7010 7011 7012
    }
    if (!textdomain(GETTEXT_PACKAGE)) {
        perror("textdomain");
7013
        return -1;
7014 7015
    }

7016
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
7017 7018 7019
        progname = argv[0];
    else
        progname++;
7020

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

7025
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
7026
        ctl->name = strdup(defaultConn);
7027 7028
    }

D
Daniel P. Berrange 已提交
7029 7030
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
7031
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
7032
    }
7033

D
Daniel P. Berrange 已提交
7034 7035
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
7036
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
7037
    }
7038

K
Karel Zak 已提交
7039
    if (!ctl->imode) {
7040
        ret = vshCommandRun(ctl, ctl->cmd);
7041
    } else {
K
Karel Zak 已提交
7042 7043
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
7044
            vshPrint(ctl,
7045
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
7046
                     progname);
J
Jim Meyering 已提交
7047
            vshPrint(ctl, "%s",
7048
                     _("Type:  'help' for help with commands\n"
7049
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
7050
        }
K
Karel Zak 已提交
7051
        vshReadlineInit();
K
Karel Zak 已提交
7052
        do {
7053
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
7054
            ctl->cmdstr =
7055
                vshReadline(ctl, prompt);
7056 7057
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
7058
            if (*ctl->cmdstr) {
7059
#if USE_READLINE
K
Karel Zak 已提交
7060
                add_history(ctl->cmdstr);
7061
#endif
K
Karel Zak 已提交
7062 7063 7064 7065 7066
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
7067
        } while (ctl->imode);
K
Karel Zak 已提交
7068

7069 7070
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
7071
    }
7072

K
Karel Zak 已提交
7073 7074
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
7075
}