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

16
#include <config.h>
17

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

37 38 39 40
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

41
#ifdef HAVE_READLINE_READLINE_H
K
Karel Zak 已提交
42 43
#include <readline/readline.h>
#include <readline/history.h>
44
#endif
K
Karel Zak 已提交
45

46
#include "internal.h"
47
#include "buf.h"
48
#include "console.h"
49
#include "util.h"
50
#include "util-lib.h"
K
Karel Zak 已提交
51 52 53 54 55 56 57 58

static char *progname;

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

59 60
#define VIRSH_MAX_XML_FILE 10*1024*1024

K
Karel Zak 已提交
61 62 63 64 65 66 67 68
#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)

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
/**
 * The log configuration
 */
#define MSG_BUFFER    4096
#define SIGN_NAME     "virsh"
#define DIR_MODE      (S_IWUSR | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)  /* 0755 */
#define FILE_MODE     (S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH)                                /* 0644 */
#define LOCK_MODE     (S_IWUSR | S_IRUSR)                                                    /* 0600 */
#define LVL_DEBUG     "DEBUG"
#define LVL_INFO      "INFO"
#define LVL_NOTICE    "NOTICE"
#define LVL_WARNING   "WARNING"
#define LVL_ERROR     "ERROR"

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

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

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

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

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

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

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

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

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

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

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

218

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

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

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

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

236 237 238
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,
239
                                 int *found);
240
#if 0
241
static int vshCommandOptStringList(const vshCmd *cmd, const char *name, char ***data);
242
#endif
243
static int vshCommandOptBool(const vshCmd *cmd, const char *name);
K
Karel Zak 已提交
244

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

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

/* default is lookup by Id, Name and UUID */
253 254
#define vshCommandOptDomain(_ctl, _cmd, _optname, _name)            \
    vshCommandOptDomainBy(_ctl, _cmd, _optname, _name,              \
255 256
                          VSH_BYID|VSH_BYUUID|VSH_BYNAME)

257
static virNetworkPtr vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd,
258 259 260 261 262 263 264
                            const char *optname, char **name, int flag);

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

265
static virStoragePoolPtr vshCommandOptPoolBy(vshControl *ctl, const vshCmd *cmd,
266 267 268 269 270 271 272
                            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)

273
static virStorageVolPtr vshCommandOptVolBy(vshControl *ctl, const vshCmd *cmd,
274 275 276 277 278 279 280 281 282
                                           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)

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

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

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

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

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

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

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

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

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

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

340
    {NULL, NULL}
K
Karel Zak 已提交
341 342
};

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

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

    if (!cmdname) {
354
        const vshCmdDef *def;
355

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

365 366 367
/*
 * "autostart" command
 */
368
static const vshCmdInfo info_autostart[] = {
369 370 371 372 373 374 375
    {"syntax", "autostart [--disable] <domain>"},
    {"help", gettext_noop("autostart a domain")},
    {"desc",
     gettext_noop("Configure a domain to be automatically started at boot.")},
    {NULL, NULL}
};

376
static const vshCmdOptDef opts_autostart[] = {
377 378 379 380 381 382
    {"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
383
cmdAutostart(vshControl *ctl, const vshCmd *cmd)
384 385 386 387 388 389 390 391 392 393 394 395 396 397
{
    virDomainPtr dom;
    char *name;
    int autostart;

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

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

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

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

408
    if (autostart)
409
        vshPrint(ctl, _("Domain %s marked as autostarted\n"), name);
410
    else
411
        vshPrint(ctl, _("Domain %s unmarked as autostarted\n"), name);
412

413
    virDomainFree(dom);
414 415 416
    return TRUE;
}

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

428
static const vshCmdOptDef opts_connect[] = {
429 430
    {"name",     VSH_OT_DATA, 0, gettext_noop("hypervisor connection URI")},
    {"readonly", VSH_OT_BOOL, 0, gettext_noop("read-only connection")},
431
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
432 433 434
};

static int
435
cmdConnect(vshControl *ctl, const vshCmd *cmd)
436
{
K
Karel Zak 已提交
437
    int ro = vshCommandOptBool(cmd, "readonly");
438

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

448
    free(ctl->name);
449
    ctl->name = vshStrdup(ctl, vshCommandOptString(cmd, "name", NULL));
K
Karel Zak 已提交
450

451
    if (!ro) {
K
Karel Zak 已提交
452
        ctl->conn = virConnectOpen(ctl->name);
453 454
        ctl->readonly = 0;
    } else {
K
Karel Zak 已提交
455
        ctl->conn = virConnectOpenReadOnly(ctl->name);
456 457
        ctl->readonly = 1;
    }
K
Karel Zak 已提交
458 459

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

K
Karel Zak 已提交
462 463 464
    return ctl->conn ? TRUE : FALSE;
}

465
/*
466
 * "console" command
467
 */
468
static const vshCmdInfo info_console[] = {
469 470 471 472 473 474 475
    {"syntax", "console <domain>"},
    {"help", gettext_noop("connect to the guest console")},
    {"desc",
     gettext_noop("Connect the virtual serial console for the guest")},
    {NULL, NULL}
};

476
static const vshCmdOptDef opts_console[] = {
477 478 479 480
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

481 482
#ifndef __MINGW32__

483
static int
484
cmdConsole(vshControl *ctl, const vshCmd *cmd)
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    int ret = FALSE;
    char *doc;

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

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

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

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

 cleanup:
524
    xmlXPathFreeContext(ctxt);
525 526 527 528 529 530
    if (xml)
        xmlFreeDoc(xml);
    virDomainFree(dom);
    return ret;
}

531 532 533
#else /* __MINGW32__ */

static int
534
cmdConsole(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
535
{
J
Jim Meyering 已提交
536
    vshError (ctl, FALSE, "%s", _("console not implemented on this platform"));
537 538 539 540 541
    return FALSE;
}

#endif /* __MINGW32__ */

K
Karel Zak 已提交
542 543 544
/*
 * "list" command
 */
545
static const vshCmdInfo info_list[] = {
546
    {"syntax", "list [--inactive | --all]"},
547 548
    {"help", gettext_noop("list domains")},
    {"desc", gettext_noop("Returns list of domains.")},
549
    {NULL, NULL}
K
Karel Zak 已提交
550 551
};

552
static const vshCmdOptDef opts_list[] = {
553 554
    {"inactive", VSH_OT_BOOL, 0, gettext_noop("list inactive domains")},
    {"all", VSH_OT_BOOL, 0, gettext_noop("list inactive & active domains")},
555 556 557
    {NULL, 0, 0, NULL}
};

K
Karel Zak 已提交
558 559

static int
560
cmdList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
561
{
562 563 564 565
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int *ids = NULL, maxid = 0, i;
566
    char **names = NULL;
567 568
    int maxname = 0;
    inactive |= all;
K
Karel Zak 已提交
569 570 571

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

573
    if (active) {
574 575
        maxid = virConnectNumOfDomains(ctl->conn);
        if (maxid < 0) {
J
Jim Meyering 已提交
576
            vshError(ctl, FALSE, "%s", _("Failed to list active domains"));
577 578 579 580 581 582
            return FALSE;
        }
        if (maxid) {
            ids = vshMalloc(ctl, sizeof(int) * maxid);

            if ((maxid = virConnectListDomains(ctl->conn, &ids[0], maxid)) < 0) {
J
Jim Meyering 已提交
583
                vshError(ctl, FALSE, "%s", _("Failed to list active domains"));
584 585 586 587
                free(ids);
                return FALSE;
            }

588
            qsort(&ids[0], maxid, sizeof(int), idsorter);
589
        }
590 591
    }
    if (inactive) {
592 593
        maxname = virConnectNumOfDefinedDomains(ctl->conn);
        if (maxname < 0) {
J
Jim Meyering 已提交
594
            vshError(ctl, FALSE, "%s", _("Failed to list inactive domains"));
595
            free(ids);
596
            return FALSE;
597
        }
598 599 600 601
        if (maxname) {
            names = vshMalloc(ctl, sizeof(char *) * maxname);

            if ((maxname = virConnectListDefinedDomains(ctl->conn, names, maxname)) < 0) {
J
Jim Meyering 已提交
602
                vshError(ctl, FALSE, "%s", _("Failed to list inactive domains"));
603
                free(ids);
604 605 606
                free(names);
                return FALSE;
            }
607

608
            qsort(&names[0], maxname, sizeof(char*), namesorter);
609
        }
610
    }
611
    vshPrintExtra(ctl, "%3s %-20s %s\n", _("Id"), _("Name"), _("State"));
K
Karel Zak 已提交
612
    vshPrintExtra(ctl, "----------------------------------\n");
613 614

    for (i = 0; i < maxid; i++) {
K
Karel Zak 已提交
615 616
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByID(ctl->conn, ids[i]);
617
        const char *state;
618 619

        /* this kind of work with domains is not atomic operation */
K
Karel Zak 已提交
620 621
        if (!dom)
            continue;
622 623 624 625

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

K
Karel Zak 已提交
628
        vshPrint(ctl, "%3d %-20s %s\n",
629 630
                 virDomainGetID(dom),
                 virDomainGetName(dom),
631
                 state);
632
        virDomainFree(dom);
K
Karel Zak 已提交
633
    }
634 635 636
    for (i = 0; i < maxname; i++) {
        virDomainInfo info;
        virDomainPtr dom = virDomainLookupByName(ctl->conn, names[i]);
637
        const char *state;
638 639

        /* this kind of work with domains is not atomic operation */
640
        if (!dom) {
641
            free(names[i]);
642
            continue;
643
        }
644 645 646 647

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

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

652
        virDomainFree(dom);
653
        free(names[i]);
654
    }
655 656
    free(ids);
    free(names);
K
Karel Zak 已提交
657 658 659 660
    return TRUE;
}

/*
K
Karel Zak 已提交
661
 * "domstate" command
K
Karel Zak 已提交
662
 */
663
static const vshCmdInfo info_domstate[] = {
K
Karel Zak 已提交
664
    {"syntax", "domstate <domain>"},
665
    {"help", gettext_noop("domain state")},
666
    {"desc", gettext_noop("Returns state about a domain.")},
667
    {NULL, NULL}
K
Karel Zak 已提交
668 669
};

670
static const vshCmdOptDef opts_domstate[] = {
671
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
672
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
673 674 675
};

static int
676
cmdDomstate(vshControl *ctl, const vshCmd *cmd)
677
{
678
    virDomainInfo info;
K
Karel Zak 已提交
679
    virDomainPtr dom;
K
Karel Zak 已提交
680
    int ret = TRUE;
681

K
Karel Zak 已提交
682 683
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
684

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

    if (virDomainGetInfo(dom, &info) == 0)
K
Karel Zak 已提交
689
        vshPrint(ctl, "%s\n",
690
                 N_(vshDomainStateToString(info.state)));
K
Karel Zak 已提交
691 692
    else
        ret = FALSE;
693

694 695 696 697
    virDomainFree(dom);
    return ret;
}

698 699
/* "domblkstat" command
 */
700
static const vshCmdInfo info_domblkstat[] = {
701 702 703 704 705 706
    {"syntax", "domblkstat <domain> <dev>"},
    {"help", gettext_noop("get device block stats for a domain")},
    {"desc", gettext_noop("Get device block stats for a running domain.")},
    {NULL,NULL}
};

707
static const vshCmdOptDef opts_domblkstat[] = {
708 709 710 711 712 713
    {"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
714
cmdDomblkstat (vshControl *ctl, const vshCmd *cmd)
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
{
    virDomainPtr dom;
    char *name, *device;
    struct _virDomainBlockStats stats;

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

    if (!(dom = vshCommandOptDomain (ctl, cmd, "domain", &name)))
        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
 */
757
static const vshCmdInfo info_domifstat[] = {
758 759 760 761 762 763
    {"syntax", "domifstat <domain> <dev>"},
    {"help", gettext_noop("get network interface stats for a domain")},
    {"desc", gettext_noop("Get network interface stats for a running domain.")},
    {NULL,NULL}
};

764
static const vshCmdOptDef opts_domifstat[] = {
765 766 767 768 769 770
    {"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
771
cmdDomIfstat (vshControl *ctl, const vshCmd *cmd)
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 811 812 813 814 815 816 817 818 819 820
{
    virDomainPtr dom;
    char *name, *device;
    struct _virDomainInterfaceStats stats;

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

    if (!(dom = vshCommandOptDomain (ctl, cmd, "domain", &name)))
        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;
}

821 822 823
/*
 * "suspend" command
 */
824
static const vshCmdInfo info_suspend[] = {
825
    {"syntax", "suspend <domain>"},
826 827
    {"help", gettext_noop("suspend a domain")},
    {"desc", gettext_noop("Suspend a running domain.")},
828
    {NULL, NULL}
829 830
};

831
static const vshCmdOptDef opts_suspend[] = {
832
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
833
    {NULL, 0, 0, NULL}
834 835 836
};

static int
837
cmdSuspend(vshControl *ctl, const vshCmd *cmd)
838
{
839
    virDomainPtr dom;
K
Karel Zak 已提交
840 841
    char *name;
    int ret = TRUE;
842

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

K
Karel Zak 已提交
846
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
847
        return FALSE;
848 849

    if (virDomainSuspend(dom) == 0) {
850
        vshPrint(ctl, _("Domain %s suspended\n"), name);
851
    } else {
852
        vshError(ctl, FALSE, _("Failed to suspend domain %s"), name);
853 854
        ret = FALSE;
    }
855

856 857 858 859
    virDomainFree(dom);
    return ret;
}

860 861 862
/*
 * "create" command
 */
863
static const vshCmdInfo info_create[] = {
864
    {"syntax", "create a domain from an XML <file>"},
865 866
    {"help", gettext_noop("create a domain from an XML file")},
    {"desc", gettext_noop("Create a domain.")},
867 868 869
    {NULL, NULL}
};

870
static const vshCmdOptDef opts_create[] = {
871
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
872 873 874 875
    {NULL, 0, 0, NULL}
};

static int
876
cmdCreate(vshControl *ctl, const vshCmd *cmd)
877 878 879 880 881
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
882
    char *buffer;
883 884 885 886 887 888 889 890

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

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

891 892
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
893 894 895 896

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

897
    if (dom != NULL) {
898
        vshPrint(ctl, _("Domain %s created from %s\n"),
899
                 virDomainGetName(dom), from);
900
        virDomainFree(dom);
901
    } else {
902
        vshError(ctl, FALSE, _("Failed to create domain from %s"), from);
903 904 905 906 907
        ret = FALSE;
    }
    return ret;
}

908 909 910
/*
 * "define" command
 */
911
static const vshCmdInfo info_define[] = {
912
    {"syntax", "define a domain from an XML <file>"},
913 914
    {"help", gettext_noop("define (but don't start) a domain from an XML file")},
    {"desc", gettext_noop("Define a domain.")},
915 916 917
    {NULL, NULL}
};

918
static const vshCmdOptDef opts_define[] = {
919
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
920 921 922 923
    {NULL, 0, 0, NULL}
};

static int
924
cmdDefine(vshControl *ctl, const vshCmd *cmd)
925 926 927 928 929
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
930
    char *buffer;
931 932 933 934 935 936 937 938

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

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

939 940
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
941 942 943 944

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

945
    if (dom != NULL) {
946
        vshPrint(ctl, _("Domain %s defined from %s\n"),
947
                 virDomainGetName(dom), from);
948
        virDomainFree(dom);
949
    } else {
950
        vshError(ctl, FALSE, _("Failed to define domain from %s"), from);
951 952 953 954 955 956 957 958
        ret = FALSE;
    }
    return ret;
}

/*
 * "undefine" command
 */
959
static const vshCmdInfo info_undefine[] = {
960
    {"syntax", "undefine <domain>"},
961 962
    {"help", gettext_noop("undefine an inactive domain")},
    {"desc", gettext_noop("Undefine the configuration for an inactive domain.")},
963 964 965
    {NULL, NULL}
};

966
static const vshCmdOptDef opts_undefine[] = {
967
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
968 969 970 971
    {NULL, 0, 0, NULL}
};

static int
972
cmdUndefine(vshControl *ctl, const vshCmd *cmd)
973 974 975 976
{
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
977 978
    int found;
    int id;
979 980 981 982

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

983 984 985 986 987 988 989 990 991 992 993 994
    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;
    }
995 996
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", &name,
                                      VSH_BYNAME|VSH_BYUUID)))
997 998 999
        return FALSE;

    if (virDomainUndefine(dom) == 0) {
1000
        vshPrint(ctl, _("Domain %s has been undefined\n"), name);
1001
    } else {
1002
        vshError(ctl, FALSE, _("Failed to undefine domain %s"), name);
1003 1004 1005
        ret = FALSE;
    }

1006
    virDomainFree(dom);
1007 1008 1009 1010 1011 1012 1013
    return ret;
}


/*
 * "start" command
 */
1014
static const vshCmdInfo info_start[] = {
1015
    {"syntax", "start <domain>"},
1016 1017
    {"help", gettext_noop("start a (previously defined) inactive domain")},
    {"desc", gettext_noop("Start a domain.")},
1018 1019 1020
    {NULL, NULL}
};

1021
static const vshCmdOptDef opts_start[] = {
1022
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive domain")},
1023 1024 1025 1026
    {NULL, 0, 0, NULL}
};

static int
1027
cmdStart(vshControl *ctl, const vshCmd *cmd)
1028 1029 1030 1031 1032 1033 1034
{
    virDomainPtr dom;
    int ret = TRUE;

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

1035
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
1036 1037 1038
        return FALSE;

    if (virDomainGetID(dom) != (unsigned int)-1) {
J
Jim Meyering 已提交
1039
        vshError(ctl, FALSE, "%s", _("Domain is already active"));
1040
        virDomainFree(dom);
1041 1042 1043 1044
        return FALSE;
    }

    if (virDomainCreate(dom) == 0) {
1045
        vshPrint(ctl, _("Domain %s started\n"),
1046
                 virDomainGetName(dom));
1047
    } else {
1048 1049
        vshError(ctl, FALSE, _("Failed to start domain %s"),
                 virDomainGetName(dom));
1050 1051
        ret = FALSE;
    }
1052
    virDomainFree(dom);
1053 1054 1055
    return ret;
}

1056 1057 1058
/*
 * "save" command
 */
1059
static const vshCmdInfo info_save[] = {
1060
    {"syntax", "save <domain> <file>"},
1061 1062
    {"help", gettext_noop("save a domain state to a file")},
    {"desc", gettext_noop("Save a running domain.")},
1063
    {NULL, NULL}
1064 1065
};

1066
static const vshCmdOptDef opts_save[] = {
1067 1068
    {"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")},
1069
    {NULL, 0, 0, NULL}
1070 1071 1072
};

static int
1073
cmdSave(vshControl *ctl, const vshCmd *cmd)
1074
{
1075 1076 1077 1078
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
1079

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

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

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

    if (virDomainSave(dom, to) == 0) {
1090
        vshPrint(ctl, _("Domain %s saved to %s\n"), name, to);
1091
    } else {
1092
        vshError(ctl, FALSE, _("Failed to save domain %s to %s"), name, to);
1093 1094
        ret = FALSE;
    }
1095

1096 1097 1098 1099
    virDomainFree(dom);
    return ret;
}

1100 1101 1102
/*
 * "schedinfo" command
 */
1103
static const vshCmdInfo info_schedinfo[] = {
1104
    {"syntax", "schedinfo <domain>"},
1105 1106 1107 1108 1109
    {"help", gettext_noop("show/set scheduler parameters")},
    {"desc", gettext_noop("Show/Set scheduler parameters.")},
    {NULL, NULL}
};

1110
static const vshCmdOptDef opts_schedinfo[] = {
1111 1112 1113 1114 1115 1116 1117
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"weight", VSH_OT_INT, VSH_OFLAG_NONE, gettext_noop("weight for XEN_CREDIT")},
    {"cap", VSH_OT_INT, VSH_OFLAG_NONE, gettext_noop("cap for XEN_CREDIT")},
    {NULL, 0, 0, NULL}
};

static int
1118
cmdSchedinfo(vshControl *ctl, const vshCmd *cmd)
1119 1120 1121
{
    char *schedulertype;
    virDomainPtr dom;
1122
    virSchedParameterPtr params = NULL;
1123 1124 1125 1126 1127
    int i, ret;
    int nparams = 0;
    int nr_inputparams = 0;
    int inputparams = 0;
    int weightfound = 0;
1128
    int weight = 0;
1129
    int capfound = 0;
1130
    int cap = 0;
1131 1132
    char str_weight[] = "weight";
    char str_cap[]    = "cap";
1133
    int ret_val = FALSE;
1134 1135 1136 1137 1138 1139 1140 1141

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

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

    /* Currently supports Xen Credit only */
1142 1143 1144
    if(vshCommandOptBool(cmd, "weight")) {
        weight = vshCommandOptInt(cmd, "weight", &weightfound);
        if (!weightfound) {
J
Jim Meyering 已提交
1145
            vshError(ctl, FALSE, "%s", _("Invalid value of weight"));
1146 1147 1148 1149 1150 1151 1152 1153 1154
            goto cleanup;
        } else {
            nr_inputparams++;
        }
    }

    if(vshCommandOptBool(cmd, "cap")) {
        cap = vshCommandOptInt(cmd, "cap", &capfound);
        if (!capfound) {
J
Jim Meyering 已提交
1155
            vshError(ctl, FALSE, "%s", _("Invalid value of cap"));
1156 1157 1158 1159 1160
            goto cleanup;
        } else {
            nr_inputparams++;
        }
    }
1161 1162

    params = vshMalloc(ctl, sizeof (virSchedParameter) * nr_inputparams);
1163
    if (params == NULL) {
1164
        goto cleanup;
1165
    }
1166 1167 1168 1169 1170

    if (weightfound) {
         strncpy(params[inputparams].field,str_weight,sizeof(str_weight));
         params[inputparams].type = VIR_DOMAIN_SCHED_FIELD_UINT;
         params[inputparams].value.ui = weight;
1171
         inputparams++;
1172 1173 1174 1175 1176 1177 1178 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++;
    }
    /* End Currently supports Xen Credit only */

    assert (inputparams == nr_inputparams);

    /* Set SchedulerParameters */
    if (inputparams > 0) {
        ret = virDomainSetSchedulerParameters(dom, params, inputparams);
1187
        if (ret == -1) {
1188
            goto cleanup;
1189
        }
1190 1191
    }
    free(params);
1192
    params = NULL;
1193 1194 1195 1196

    /* Print SchedulerType */
    schedulertype = virDomainGetSchedulerType(dom, &nparams);
    if (schedulertype!= NULL){
1197
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"),
1198 1199 1200
             schedulertype);
        free(schedulertype);
    } else {
1201
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"), _("Unknown"));
1202
        goto cleanup;
1203 1204 1205 1206
    }

    /* Get SchedulerParameters */
    params = vshMalloc(ctl, sizeof(virSchedParameter)* nparams);
1207 1208 1209
    if (params == NULL) {
        goto cleanup;
    }
1210 1211 1212 1213 1214
    for (i = 0; i < nparams; i++){
        params[i].type = 0;
        memset (params[i].field, 0, sizeof params[i].field);
    }
    ret = virDomainGetSchedulerParameters(dom, params, &nparams);
1215
    if (ret == -1) {
1216
        goto cleanup;
1217
    }
1218
    ret_val = TRUE;
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    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");
            }
        }
    }
1245
 cleanup:
1246
    free(params);
1247
    virDomainFree(dom);
1248
    return ret_val;
1249 1250
}

1251 1252 1253
/*
 * "restore" command
 */
1254
static const vshCmdInfo info_restore[] = {
1255
    {"syntax", "restore a domain from <file>"},
1256 1257
    {"help", gettext_noop("restore a domain from a saved state in a file")},
    {"desc", gettext_noop("Restore a domain.")},
1258
    {NULL, NULL}
1259 1260
};

1261
static const vshCmdOptDef opts_restore[] = {
1262
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("the state to restore")},
1263
    {NULL, 0, 0, NULL}
1264 1265 1266
};

static int
1267
cmdRestore(vshControl *ctl, const vshCmd *cmd)
1268
{
1269 1270 1271
    char *from;
    int found;
    int ret = TRUE;
1272

1273 1274 1275 1276 1277 1278
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
1281
        vshPrint(ctl, _("Domain restored from %s\n"), from);
1282
    } else {
1283
        vshError(ctl, FALSE, _("Failed to restore domain from %s"), from);
1284 1285 1286 1287 1288
        ret = FALSE;
    }
    return ret;
}

D
Daniel Veillard 已提交
1289 1290 1291
/*
 * "dump" command
 */
1292
static const vshCmdInfo info_dump[] = {
D
Daniel Veillard 已提交
1293 1294 1295 1296 1297 1298
    {"syntax", "dump <domain> <file>"},
    {"help", gettext_noop("dump the core of a domain to a file for analysis")},
    {"desc", gettext_noop("Core dump a domain.")},
    {NULL, NULL}
};

1299
static const vshCmdOptDef opts_dump[] = {
D
Daniel Veillard 已提交
1300 1301 1302 1303 1304 1305
    {"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
1306
cmdDump(vshControl *ctl, const vshCmd *cmd)
D
Daniel Veillard 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
{
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;

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

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

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

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

    virDomainFree(dom);
    return ret;
}

1334 1335 1336
/*
 * "resume" command
 */
1337
static const vshCmdInfo info_resume[] = {
1338
    {"syntax", "resume <domain>"},
1339 1340
    {"help", gettext_noop("resume a domain")},
    {"desc", gettext_noop("Resume a previously suspended domain.")},
1341
    {NULL, NULL}
1342 1343
};

1344
static const vshCmdOptDef opts_resume[] = {
1345
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1346
    {NULL, 0, 0, NULL}
1347 1348 1349
};

static int
1350
cmdResume(vshControl *ctl, const vshCmd *cmd)
1351
{
1352
    virDomainPtr dom;
K
Karel Zak 已提交
1353 1354
    int ret = TRUE;
    char *name;
1355

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

K
Karel Zak 已提交
1359
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1360
        return FALSE;
1361 1362

    if (virDomainResume(dom) == 0) {
1363
        vshPrint(ctl, _("Domain %s resumed\n"), name);
1364
    } else {
1365
        vshError(ctl, FALSE, _("Failed to resume domain %s"), name);
1366 1367
        ret = FALSE;
    }
1368

1369 1370 1371 1372
    virDomainFree(dom);
    return ret;
}

1373 1374 1375
/*
 * "shutdown" command
 */
1376
static const vshCmdInfo info_shutdown[] = {
1377
    {"syntax", "shutdown <domain>"},
1378 1379
    {"help", gettext_noop("gracefully shutdown a domain")},
    {"desc", gettext_noop("Run shutdown in the target domain.")},
1380
    {NULL, NULL}
1381 1382
};

1383
static const vshCmdOptDef opts_shutdown[] = {
1384
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1385
    {NULL, 0, 0, NULL}
1386 1387 1388
};

static int
1389
cmdShutdown(vshControl *ctl, const vshCmd *cmd)
1390
{
1391 1392 1393
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
1394

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

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

    if (virDomainShutdown(dom) == 0) {
1402
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
1403
    } else {
1404
        vshError(ctl, FALSE, _("Failed to shutdown domain %s"), name);
1405 1406
        ret = FALSE;
    }
1407

1408 1409 1410 1411
    virDomainFree(dom);
    return ret;
}

1412 1413 1414
/*
 * "reboot" command
 */
1415
static const vshCmdInfo info_reboot[] = {
1416
    {"syntax", "reboot <domain>"},
1417 1418
    {"help", gettext_noop("reboot a domain")},
    {"desc", gettext_noop("Run a reboot command in the target domain.")},
1419 1420 1421
    {NULL, NULL}
};

1422
static const vshCmdOptDef opts_reboot[] = {
1423
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1424 1425 1426 1427
    {NULL, 0, 0, NULL}
};

static int
1428
cmdReboot(vshControl *ctl, const vshCmd *cmd)
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
{
    virDomainPtr dom;
    int ret = TRUE;
    char *name;

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

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

    if (virDomainReboot(dom, 0) == 0) {
1441
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
1442
    } else {
1443
        vshError(ctl, FALSE, _("Failed to reboot domain %s"), name);
1444 1445 1446 1447 1448 1449 1450
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1451 1452 1453
/*
 * "destroy" command
 */
1454
static const vshCmdInfo info_destroy[] = {
1455
    {"syntax", "destroy <domain>"},
1456 1457
    {"help", gettext_noop("destroy a domain")},
    {"desc", gettext_noop("Destroy a given domain.")},
1458
    {NULL, NULL}
1459 1460
};

1461
static const vshCmdOptDef opts_destroy[] = {
1462
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1463
    {NULL, 0, 0, NULL}
1464 1465 1466
};

static int
1467
cmdDestroy(vshControl *ctl, const vshCmd *cmd)
1468
{
1469
    virDomainPtr dom;
K
Karel Zak 已提交
1470 1471
    int ret = TRUE;
    char *name;
1472

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

K
Karel Zak 已提交
1476
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1477
        return FALSE;
1478 1479

    if (virDomainDestroy(dom) == 0) {
1480
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
1481
    } else {
1482
        vshError(ctl, FALSE, _("Failed to destroy domain %s"), name);
1483 1484
        ret = FALSE;
    }
1485

1486
    virDomainFree(dom);
K
Karel Zak 已提交
1487 1488 1489 1490
    return ret;
}

/*
1491
 * "dominfo" command
K
Karel Zak 已提交
1492
 */
1493
static const vshCmdInfo info_dominfo[] = {
1494
    {"syntax", "dominfo <domain>"},
1495 1496
    {"help", gettext_noop("domain information")},
    {"desc", gettext_noop("Returns basic information about the domain.")},
1497
    {NULL, NULL}
K
Karel Zak 已提交
1498 1499
};

1500
static const vshCmdOptDef opts_dominfo[] = {
1501
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1502
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1503 1504 1505
};

static int
1506
cmdDominfo(vshControl *ctl, const vshCmd *cmd)
1507
{
K
Karel Zak 已提交
1508 1509
    virDomainInfo info;
    virDomainPtr dom;
1510
    int ret = TRUE, autostart;
1511
    unsigned int id;
1512
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
1513

K
Karel Zak 已提交
1514 1515 1516
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
1517
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
1518
        return FALSE;
1519

1520 1521
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1522
        vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
1523
    else
1524
        vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
1525 1526
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
1527
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
1528
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
1529 1530

    if ((str = virDomainGetOSType(dom))) {
1531
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
1532 1533 1534 1535
        free(str);
    }

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

1539
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
1540 1541

        if (info.cpuTime != 0) {
1542
            double cpuUsed = info.cpuTime;
1543

1544
            cpuUsed /= 1000000000.0;
1545

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

1549 1550
        if (info.maxMem != UINT_MAX)
            vshPrint(ctl, "%-15s %lu kB\n", _("Max memory:"),
1551
                 info.maxMem);
1552
        else
1553
            vshPrint(ctl, "%-15s %s\n", _("Max memory:"),
1554 1555
                 _("no limit"));

1556
        vshPrint(ctl, "%-15s %lu kB\n", _("Used memory:"),
1557 1558
                 info.memory);

K
Karel Zak 已提交
1559 1560 1561
    } else {
        ret = FALSE;
    }
1562

1563
    if (!virDomainGetAutostart(dom, &autostart)) {
1564
        vshPrint(ctl, "%-15s %s\n", _("Autostart:"),
1565 1566 1567
                 autostart ? _("enable") : _("disable") );
    }

1568
    virDomainFree(dom);
K
Karel Zak 已提交
1569 1570 1571
    return ret;
}

1572 1573 1574
/*
 * "freecell" command
 */
1575
static const vshCmdInfo info_freecell[] = {
1576 1577 1578 1579 1580 1581
    {"syntax", "freecell [<cellno>]"},
    {"help", gettext_noop("NUMA free memory")},
    {"desc", gettext_noop("display available free memory for the NUMA cell.")},
    {NULL, NULL}
};

1582
static const vshCmdOptDef opts_freecell[] = {
1583 1584 1585 1586 1587
    {"cellno", VSH_OT_DATA, 0, gettext_noop("NUMA cell number")},
    {NULL, 0, 0, NULL}
};

static int
1588
cmdFreecell(vshControl *ctl, const vshCmd *cmd)
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
{
    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) {
1599 1600
        memory = virNodeGetFreeMemory(ctl->conn);
    } else {
1601 1602 1603
        ret = virNodeGetCellsFreeMemory(ctl->conn, &memory, cell, 1);
        if (ret != 1)
            return FALSE;
1604 1605 1606
    }

    if (cell == -1)
1607
        vshPrint(ctl, "%s: %llu kB\n", _("Total"), memory);
1608
    else
1609
        vshPrint(ctl, "%d: %llu kB\n", cell, memory);
1610 1611 1612 1613

    return TRUE;
}

1614 1615 1616
/*
 * "vcpuinfo" command
 */
1617
static const vshCmdInfo info_vcpuinfo[] = {
1618
    {"syntax", "vcpuinfo <domain>"},
1619 1620
    {"help", gettext_noop("domain vcpu information")},
    {"desc", gettext_noop("Returns basic information about the domain virtual CPUs.")},
1621 1622 1623
    {NULL, NULL}
};

1624
static const vshCmdOptDef opts_vcpuinfo[] = {
1625
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1626 1627 1628 1629
    {NULL, 0, 0, NULL}
};

static int
1630
cmdVcpuinfo(vshControl *ctl, const vshCmd *cmd)
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    virVcpuInfoPtr cpuinfo;
    unsigned char *cpumap;
    int ncpus;
    size_t cpumaplen;
    int ret = TRUE;

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

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

    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
1649
        return FALSE;
1650 1651 1652 1653 1654 1655 1656
    }

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

1657
    cpuinfo = vshMalloc(ctl, sizeof(virVcpuInfo)*info.nrVirtCpu);
1658
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1659
    cpumap = vshMalloc(ctl, info.nrVirtCpu * cpumaplen);
1660

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

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

/*
 * "vcpupin" command
 */
1704
static const vshCmdInfo info_vcpupin[] = {
1705
    {"syntax", "vcpupin <domain> <vcpu> <cpulist>"},
1706 1707
    {"help", gettext_noop("control domain vcpu affinity")},
    {"desc", gettext_noop("Pin domain VCPUs to host physical CPUs.")},
1708 1709 1710
    {NULL, NULL}
};

1711
static const vshCmdOptDef opts_vcpupin[] = {
1712 1713 1714
    {"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)")},
1715 1716 1717 1718
    {NULL, 0, 0, NULL}
};

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

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

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

    vcpu = vshCommandOptInt(cmd, "vcpu", &vcpufound);
    if (!vcpufound) {
1741 1742
        vshError(ctl, FALSE, "%s",
                 _("vcpupin: Invalid or missing vCPU number."));
1743 1744 1745 1746 1747
        virDomainFree(dom);
        return FALSE;
    }

    if (!(cpulist = vshCommandOptString(cmd, "cpulist", NULL))) {
1748
        vshError(ctl, FALSE, "%s", _("vcpupin: Missing cpulist"));
1749 1750 1751
        virDomainFree(dom);
        return FALSE;
    }
1752

1753 1754 1755 1756 1757 1758
    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
        return FALSE;
    }

    if (virDomainGetInfo(dom, &info) != 0) {
D
Daniel Veillard 已提交
1759
        vshError(ctl, FALSE, "%s",
1760
                 _("vcpupin: failed to get domain informations."));
1761 1762 1763 1764 1765
        virDomainFree(dom);
        return FALSE;
    }

    if (vcpu >= info.nrVirtCpu) {
J
Jim Meyering 已提交
1766
        vshError(ctl, FALSE, "%s", _("vcpupin: Invalid vCPU number."));
1767 1768 1769 1770
        virDomainFree(dom);
        return FALSE;
    }

1771 1772 1773 1774
    /* 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 已提交
1775
        vshError(ctl, FALSE, "%s", _("cpulist: Invalid format. Empty string."));
1776 1777 1778 1779 1780 1781 1782 1783
        virDomainFree (dom);
        return FALSE;
    }

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

1807
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1808
    cpumap = vshCalloc(ctl, 1, cpumaplen);
1809 1810 1811 1812 1813 1814

    do {
        unsigned int cpu = atoi(cpulist);

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

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

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

1835 1836 1837
/*
 * "setvcpus" command
 */
1838
static const vshCmdInfo info_setvcpus[] = {
1839
    {"syntax", "setvcpus <domain> <count>"},
1840
    {"help", gettext_noop("change number of virtual CPUs")},
1841
    {"desc", gettext_noop("Change the number of virtual CPUs in the guest domain.")},
1842 1843 1844
    {NULL, NULL}
};

1845
static const vshCmdOptDef opts_setvcpus[] = {
1846 1847
    {"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")},
1848 1849 1850 1851
    {NULL, 0, 0, NULL}
};

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

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

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

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

1872
    maxcpu = virDomainGetMaxVcpus(dom);
1873
    if (maxcpu <= 0) {
1874 1875 1876 1877 1878
        virDomainFree(dom);
        return FALSE;
    }

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

1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
    if (virDomainSetVcpus(dom, count) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmemory" command
 */
1895
static const vshCmdInfo info_setmem[] = {
1896
    {"syntax", "setmem <domain> <kilobytes>"},
1897 1898
    {"help", gettext_noop("change memory allocation")},
    {"desc", gettext_noop("Change the current memory allocation in the guest domain.")},
1899 1900 1901
    {NULL, NULL}
};

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

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

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

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

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

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

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

1941
    if (virDomainSetMemory(dom, kilobytes) != 0) {
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

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

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

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

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

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

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

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

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

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

    virDomainFree(dom);
    return ret;
}

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

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

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

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

2040 2041 2042
    return TRUE;
}

2043 2044 2045
/*
 * "capabilities" command
 */
2046
static const vshCmdInfo info_capabilities[] = {
2047 2048 2049 2050 2051 2052 2053
    {"syntax", "capabilities"},
    {"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
    {"syntax", "dumpxml <domain>"},
2076
    {"help", gettext_noop("domain information in XML")},
2077
    {"desc", gettext_noop("Output the domain information as an XML dump to stdout.")},
2078
    {NULL, NULL}
2079 2080
};

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

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

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

K
Karel Zak 已提交
2096
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
2097
        return FALSE;
2098

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2221
static const vshCmdOptDef opts_migrate[] = {
2222 2223 2224 2225 2226 2227 2228 2229
    {"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")},
    {NULL, 0, 0, NULL}
};

static int
2230
cmdMigrate (vshControl *ctl, const vshCmd *cmd)
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
{
    virDomainPtr dom = NULL;
    const char *desturi;
    const char *migrateuri;
    int flags = 0, found, ret = FALSE;
    virConnectPtr dconn = NULL;
    virDomainPtr ddom = NULL;

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

    if (!(dom = vshCommandOptDomain (ctl, cmd, "domain", NULL)))
        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 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
        goto done;
    }

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

    if (vshCommandOptBool (cmd, "live"))
        flags |= VIR_MIGRATE_LIVE;

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

    /* Migrate. */
    ddom = virDomainMigrate (dom, dconn, flags, NULL, migrateuri, 0);
    if (!ddom) goto done;

    ret = TRUE;

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

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

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

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

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

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

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

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

    return TRUE;
}
K
Karel Zak 已提交
2324

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

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

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

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

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

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

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

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

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 2430
    {"syntax", "net-destroy <network>"},
    {"help", gettext_noop("destroy a network")},
    {"desc", gettext_noop("Destroy a given network.")},
    {NULL, NULL}
};

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

static int
2437
cmdNetworkDestroy(vshControl *ctl, const vshCmd *cmd)
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
{
    virNetworkPtr network;
    int ret = TRUE;
    char *name;

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

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

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

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


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

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

static int
2477
cmdNetworkDumpXML(vshControl *ctl, const vshCmd *cmd)
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
{
    virNetworkPtr network;
    int ret = TRUE;
    char *dump;

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

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

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

    virNetworkFree(network);
    return ret;
}


/*
 * "net-list" command
 */
2505
static const vshCmdInfo info_network_list[] = {
2506 2507 2508 2509 2510 2511
    {"syntax", "net-list [ --inactive | --all ]"},
    {"help", gettext_noop("list networks")},
    {"desc", gettext_noop("Returns list of networks.")},
    {NULL, NULL}
};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        virNetworkFree(network);
        free(inactiveNames[i]);
    }
2620 2621
    free(activeNames);
    free(inactiveNames);
2622 2623 2624 2625 2626 2627 2628
    return TRUE;
}


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

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

static int
2641
cmdNetworkName(vshControl *ctl, const vshCmd *cmd)
2642 2643 2644 2645 2646 2647
{
    virNetworkPtr network;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "network", NULL,
2648
                                           VSH_BYUUID)))
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
        return FALSE;

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


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

2667
static const vshCmdOptDef opts_network_start[] = {
2668 2669 2670 2671 2672
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive network")},
    {NULL, 0, 0, NULL}
};

static int
2673
cmdNetworkStart(vshControl *ctl, const vshCmd *cmd)
2674 2675 2676 2677 2678 2679 2680
{
    virNetworkPtr network;
    int ret = TRUE;

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

2681 2682
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
         return FALSE;
2683 2684 2685

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


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

2706
static const vshCmdOptDef opts_network_undefine[] = {
2707 2708 2709 2710 2711
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
2712
cmdNetworkUndefine(vshControl *ctl, const vshCmd *cmd)
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
{
    virNetworkPtr network;
    int ret = TRUE;
    char *name;

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

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

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

    return ret;
}


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

2744
static const vshCmdOptDef opts_network_uuid[] = {
2745 2746 2747 2748 2749
    {"network", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network name")},
    {NULL, 0, 0, NULL}
};

static int
2750
cmdNetworkUuid(vshControl *ctl, const vshCmd *cmd)
2751 2752 2753 2754 2755 2756 2757 2758
{
    virNetworkPtr network;
    char uuid[VIR_UUID_STRING_BUFLEN];

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

    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "network", NULL,
2759
                                           VSH_BYNAME)))
2760 2761 2762 2763 2764
        return FALSE;

    if (virNetworkGetUUIDString(network, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
J
Jim Meyering 已提交
2765
        vshError(ctl, FALSE, "%s", _("failed to get network UUID"));
2766 2767 2768 2769 2770

    return TRUE;
}


2771
/*
2772
 * "pool-autostart" command
2773
 */
2774
static const vshCmdInfo info_pool_autostart[] = {
2775 2776 2777 2778
    {"syntax", "pool-autostart [--disable] <pool>"},
    {"help", gettext_noop("autostart a pool")},
    {"desc",
     gettext_noop("Configure a pool to be automatically started at boot.")},
2779
    {NULL, NULL}
2780 2781
};

2782
static const vshCmdOptDef opts_pool_autostart[] = {
2783 2784 2785 2786
    {"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}
};
2787 2788

static int
2789
cmdPoolAutostart(vshControl *ctl, const vshCmd *cmd)
2790
{
2791 2792 2793
    virStoragePoolPtr pool;
    char *name;
    int autostart;
2794 2795 2796

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

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

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

2803 2804
    if (virStoragePoolSetAutostart(pool, autostart) < 0) {
        if (autostart)
2805
            vshError(ctl, FALSE, _("failed to mark pool %s as autostarted"),
2806
                                   name);
2807 2808
        else
            vshError(ctl, FALSE,_("failed to unmark pool %s as autostarted"),
2809 2810
                                   name);
        virStoragePoolFree(pool);
2811 2812 2813
        return FALSE;
    }

2814
    if (autostart)
2815
        vshPrint(ctl, _("Pool %s marked as autostarted\n"), name);
2816
    else
2817
        vshPrint(ctl, _("Pool %s unmarked as autostarted\n"), name);
2818 2819 2820 2821

    return TRUE;
}

2822
/*
2823
 * "pool-create" command
2824
 */
2825
static const vshCmdInfo info_pool_create[] = {
2826 2827 2828
    {"syntax", "create a pool from an XML <file>"},
    {"help", gettext_noop("create a pool from an XML file")},
    {"desc", gettext_noop("Create a pool.")},
2829 2830 2831
    {NULL, NULL}
};

2832
static const vshCmdOptDef opts_pool_create[] = {
2833 2834 2835 2836
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML pool description")},
    {NULL, 0, 0, NULL}
};

2837
static int
2838
cmdPoolCreate(vshControl *ctl, const vshCmd *cmd)
2839
{
2840 2841 2842 2843 2844
    virStoragePoolPtr pool;
    char *from;
    int found;
    int ret = TRUE;
    char *buffer;
2845 2846 2847 2848

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

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

2853 2854
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2855

2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
    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;
2867 2868
}

2869 2870 2871
/*
 * "pool-create-as" command
 */
2872
static const vshCmdInfo info_pool_create_as[] = {
2873 2874 2875 2876 2877 2878
    {"syntax", "pool-create-as <name> <type>"},
    {"help", gettext_noop("create a pool from a set of args")},
    {"desc", gettext_noop("Create a pool.")},
    {NULL, NULL}
};

2879
static const vshCmdOptDef opts_pool_create_as[] = {
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
    {"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")},
    {"target", VSH_OT_DATA, 0, gettext_noop("target for underlying storage")},
    {NULL, 0, 0, NULL}
};


static int
2891
cmdPoolCreateAs(vshControl *ctl, const vshCmd *cmd)
2892 2893 2894
{
    virStoragePoolPtr pool;
    int found;
2895
    char *xml;
2896
    char *name, *type, *srcHost, *srcPath, *srcDev, *target;
2897
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913

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

    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);
    target = vshCommandOptString(cmd, "target", &found);

2914 2915
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf, "  <name>%s</name>\n", name);
2916
    if (srcHost || srcPath || srcDev) {
2917 2918 2919
        virBufferAddLit(&buf, "  <source>\n");
        if (srcHost)
            virBufferVSprintf(&buf, "    <host name='%s'>\n", srcHost);
2920

2921 2922 2923 2924 2925 2926 2927
        if (srcPath)
            virBufferVSprintf(&buf, "    <dir path='%s'/>\n", srcPath);

        if (srcDev)
            virBufferVSprintf(&buf, "    <device path='%s'/>\n", srcDev);

        virBufferAddLit(&buf, "  </source>\n");
2928 2929
    }
    if (target) {
2930 2931 2932
        virBufferAddLit(&buf, "  <target>\n");
        virBufferVSprintf(&buf, "    <path>%s</path>\n", target);
        virBufferAddLit(&buf, "  </target>\n");
2933
    }
2934 2935 2936 2937 2938 2939 2940
    virBufferAddLit(&buf, "</pool>\n");

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        return FALSE;
    }
    xml = virBufferContentAndReset(&buf);
2941

2942 2943
    pool = virStoragePoolCreateXML(ctl->conn, xml, 0);
    free (xml);
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954

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

 cleanup:
2955
    free(virBufferContentAndReset(&buf));
2956 2957 2958
    return FALSE;
}

2959

2960
/*
2961
 * "pool-define" command
2962
 */
2963
static const vshCmdInfo info_pool_define[] = {
2964 2965 2966
    {"syntax", "define a pool from an XML <file>"},
    {"help", gettext_noop("define (but don't start) a pool from an XML file")},
    {"desc", gettext_noop("Define a pool.")},
2967 2968 2969
    {NULL, NULL}
};

2970
static const vshCmdOptDef opts_pool_define[] = {
2971 2972 2973 2974
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML pool description")},
    {NULL, 0, 0, NULL}
};

2975
static int
2976
cmdPoolDefine(vshControl *ctl, const vshCmd *cmd)
2977
{
2978 2979 2980 2981 2982
    virStoragePoolPtr pool;
    char *from;
    int found;
    int ret = TRUE;
    char *buffer;
2983 2984 2985 2986

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

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

2991 2992
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2993

2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
    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;
3005 3006
}

3007

3008 3009 3010
/*
 * "pool-define-as" command
 */
3011
static const vshCmdInfo info_pool_define_as[] = {
3012 3013 3014 3015 3016 3017
    {"syntax", "pool-define-as <name> <type>"},
    {"help", gettext_noop("define a pool from a set of args")},
    {"desc", gettext_noop("Define a pool.")},
    {NULL, NULL}
};

3018
static const vshCmdOptDef opts_pool_define_as[] = {
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
    {"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")},
    {"target", VSH_OT_DATA, 0, gettext_noop("target for underlying storage")},
    {NULL, 0, 0, NULL}
};


static int
3030
cmdPoolDefineAs(vshControl *ctl, const vshCmd *cmd)
3031 3032 3033
{
    virStoragePoolPtr pool;
    int found;
3034
    char *xml;
3035
    char *name, *type, *srcHost, *srcPath, *srcDev, *target;
3036
    virBuffer buf = VIR_BUFFER_INITIALIZER;
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052

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

    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);
    target = vshCommandOptString(cmd, "target", &found);

3053 3054
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf, "  <name>%s</name>\n", name);
3055
    if (srcHost || srcPath || srcDev) {
3056 3057 3058 3059 3060 3061 3062
        virBufferAddLit(&buf, "  <source>\n");
        if (srcHost)
            virBufferVSprintf(&buf, "    <host>%s</host>\n", srcHost);
        if (srcPath)
            virBufferVSprintf(&buf, "    <path>%s</path>\n", srcPath);
        if (srcDev)
            virBufferVSprintf(&buf, "    <device>%s</device>\n", srcDev);
3063

3064
        virBufferAddLit(&buf, "  </source>\n");
3065 3066
    }
    if (target) {
3067 3068 3069
        virBufferAddLit(&buf, "  <target>\n");
        virBufferVSprintf(&buf, "    <path>%s</path>\n", target);
        virBufferAddLit(&buf, "  </target>\n");
3070
    }
3071
    virBufferAddLit(&buf, "</pool>\n");
3072

3073 3074 3075 3076 3077 3078 3079 3080 3081

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        return FALSE;
    }
    xml = virBufferContentAndReset(&buf);

    pool = virStoragePoolDefineXML(ctl->conn, xml, 0);
    free (xml);
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092

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

 cleanup:
3093
    free(virBufferContentAndReset(&buf));
3094 3095 3096 3097
    return FALSE;
}


3098
/*
3099
 * "pool-build" command
3100
 */
3101
static const vshCmdInfo info_pool_build[] = {
3102 3103 3104
    {"syntax", "pool-build <pool>"},
    {"help", gettext_noop("build a pool")},
    {"desc", gettext_noop("Build a given pool.")},
3105 3106 3107
    {NULL, NULL}
};

3108
static const vshCmdOptDef opts_pool_build[] = {
3109
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
3110 3111 3112 3113
    {NULL, 0, 0, NULL}
};

static int
3114
cmdPoolBuild(vshControl *ctl, const vshCmd *cmd)
3115
{
3116 3117 3118
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *name;
3119 3120 3121 3122

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

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

3126 3127
    if (virStoragePoolBuild(pool, 0) == 0) {
        vshPrint(ctl, _("Pool %s builded\n"), name);
3128
    } else {
3129 3130 3131
        vshError(ctl, FALSE, _("Failed to build pool %s"), name);
        ret = FALSE;
        virStoragePoolFree(pool);
3132 3133 3134 3135 3136
    }

    return ret;
}

3137

3138
/*
3139
 * "pool-destroy" command
3140
 */
3141
static const vshCmdInfo info_pool_destroy[] = {
3142 3143 3144
    {"syntax", "pool-destroy <pool>"},
    {"help", gettext_noop("destroy a pool")},
    {"desc", gettext_noop("Destroy a given pool.")},
3145 3146 3147
    {NULL, NULL}
};

3148
static const vshCmdOptDef opts_pool_destroy[] = {
3149
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
3150 3151 3152 3153
    {NULL, 0, 0, NULL}
};

static int
3154
cmdPoolDestroy(vshControl *ctl, const vshCmd *cmd)
3155
{
3156 3157 3158
    virStoragePoolPtr pool;
    int ret = TRUE;
    char *name;
3159 3160 3161 3162

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

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

3166 3167 3168 3169 3170
    if (virStoragePoolDestroy(pool) == 0) {
        vshPrint(ctl, _("Pool %s destroyed\n"), name);
    } else {
        vshError(ctl, FALSE, _("Failed to destroy pool %s"), name);
        ret = FALSE;
3171 3172
    }

3173
    virStoragePoolFree(pool);
3174 3175 3176
    return ret;
}

3177

3178
/*
3179 3180
 * "pool-delete" command
 */
3181
static const vshCmdInfo info_pool_delete[] = {
3182 3183 3184 3185 3186 3187
    {"syntax", "pool-delete <pool>"},
    {"help", gettext_noop("delete a pool")},
    {"desc", gettext_noop("Delete a given pool.")},
    {NULL, NULL}
};

3188
static const vshCmdOptDef opts_pool_delete[] = {
3189 3190 3191 3192 3193
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3194
cmdPoolDelete(vshControl *ctl, const vshCmd *cmd)
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
{
    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 已提交
3207
        vshPrint(ctl, _("Pool %s deleted\n"), name);
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
    } else {
        vshError(ctl, FALSE, _("Failed to delete pool %s"), name);
        ret = FALSE;
        virStoragePoolFree(pool);
    }

    return ret;
}


/*
 * "pool-refresh" command
 */
3221
static const vshCmdInfo info_pool_refresh[] = {
3222 3223 3224 3225 3226 3227
    {"syntax", "pool-refresh <pool>"},
    {"help", gettext_noop("refresh a pool")},
    {"desc", gettext_noop("Refresh a given pool.")},
    {NULL, NULL}
};

3228
static const vshCmdOptDef opts_pool_refresh[] = {
3229 3230 3231 3232 3233
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3234
cmdPoolRefresh(vshControl *ctl, const vshCmd *cmd)
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
{
    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
 */
3261
static const vshCmdInfo info_pool_dumpxml[] = {
3262 3263 3264 3265 3266 3267
    {"syntax", "pool-dumpxml <pool>"},
    {"help", gettext_noop("pool information in XML")},
    {"desc", gettext_noop("Output the pool information as an XML dump to stdout.")},
    {NULL, NULL}
};

3268
static const vshCmdOptDef opts_pool_dumpxml[] = {
3269 3270 3271 3272 3273
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3274
cmdPoolDumpXML(vshControl *ctl, const vshCmd *cmd)
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
{
    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
 */
3302
static const vshCmdInfo info_pool_list[] = {
3303 3304 3305 3306 3307 3308
    {"syntax", "pool-list [ --inactive | --all ]"},
    {"help", gettext_noop("list pools")},
    {"desc", gettext_noop("Returns list of pools.")},
    {NULL, NULL}
};

3309
static const vshCmdOptDef opts_pool_list[] = {
3310 3311 3312 3313 3314 3315
    {"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
3316
cmdPoolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
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 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
{
    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;
}

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
 */
3446
static const vshCmdInfo info_pool_info[] = {
3447 3448 3449 3450 3451 3452
    {"syntax", "pool-info <pool>"},
    {"help", gettext_noop("storage pool information")},
    {"desc", gettext_noop("Returns basic information about the storage pool.")},
    {NULL, NULL}
};

3453
static const vshCmdOptDef opts_pool_info[] = {
3454 3455 3456 3457 3458
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3459
cmdPoolInfo(vshControl *ctl, const vshCmd *cmd)
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 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
{
    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
 */
3522
static const vshCmdInfo info_pool_name[] = {
3523 3524 3525 3526 3527
    {"syntax", "pool-name <pool>"},
    {"help", gettext_noop("convert a pool UUID to pool name")},
    {NULL, NULL}
};

3528
static const vshCmdOptDef opts_pool_name[] = {
3529 3530 3531 3532 3533
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool uuid")},
    {NULL, 0, 0, NULL}
};

static int
3534
cmdPoolName(vshControl *ctl, const vshCmd *cmd)
3535 3536 3537 3538 3539 3540
{
    virStoragePoolPtr pool;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
3541
                                           VSH_BYUUID)))
3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552
        return FALSE;

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


/*
 * "pool-start" command
 */
3553
static const vshCmdInfo info_pool_start[] = {
3554 3555 3556 3557 3558 3559
    {"syntax", "start <pool>"},
    {"help", gettext_noop("start a (previously defined) inactive pool")},
    {"desc", gettext_noop("Start a pool.")},
    {NULL, NULL}
};

3560
static const vshCmdOptDef opts_pool_start[] = {
3561 3562 3563 3564 3565
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive pool")},
    {NULL, 0, 0, NULL}
};

static int
3566
cmdPoolStart(vshControl *ctl, const vshCmd *cmd)
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588
{
    virStoragePoolPtr pool;
    int ret = TRUE;

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

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
         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;
}


3589 3590 3591
/*
 * "vol-create-as" command
 */
3592
static const vshCmdInfo info_vol_create_as[] = {
D
Daniel Veillard 已提交
3593 3594
    {"syntax", "vol-create-as <pool> <name> <capacity>"},
    {"help", gettext_noop("create a volume from a set of args")},
3595 3596 3597 3598
    {"desc", gettext_noop("Create a vol.")},
    {NULL, NULL}
};

3599
static const vshCmdOptDef opts_vol_create_as[] = {
3600
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name")},
D
Daniel Veillard 已提交
3601
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the volume")},
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
    {"capacity", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("size of the vol with optional k,M,G,T suffix")},
    {"allocation", VSH_OT_DATA, 0, gettext_noop("initial allocation size with optional k,M,G,T suffix")},
    {"format", VSH_OT_DATA, 0, gettext_noop("file format type raw,bochs,qcow,qcow2,vmdk")},
    {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 已提交
3615
        /* Deliberate fallthrough cases here :-) */
3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636
        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
3637
cmdVolCreateAs(vshControl *ctl, const vshCmd *cmd)
3638 3639 3640 3641
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
    int found;
3642
    char *xml;
3643 3644
    char *name, *capacityStr, *allocationStr, *format;
    unsigned long long capacity, allocation = 0;
3645
    virBuffer buf = VIR_BUFFER_INITIALIZER;
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670

    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);

3671 3672 3673 3674 3675
    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);
3676 3677

    if (format) {
3678
        virBufferAddLit(&buf, "  <target>\n");
3679
        if (format)
3680 3681
            virBufferVSprintf(&buf, "    <format type='%s'/>\n",format);
        virBufferAddLit(&buf, "  </target>\n");
3682
    }
3683 3684
    virBufferAddLit(&buf, "</volume>\n");

3685

3686 3687 3688 3689 3690 3691 3692
    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        return FALSE;
    }
    xml = virBufferContentAndReset(&buf);
    vol = virStorageVolCreateXML(pool, xml, 0);
    free (xml);
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704
    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:
3705
    free(virBufferContentAndReset(&buf));
3706 3707 3708 3709 3710
    virStoragePoolFree(pool);
    return FALSE;
}


3711 3712 3713
/*
 * "pool-undefine" command
 */
3714
static const vshCmdInfo info_pool_undefine[] = {
3715 3716 3717 3718 3719 3720
    {"syntax", "pool-undefine <pool>"},
    {"help", gettext_noop("undefine an inactive pool")},
    {"desc", gettext_noop("Undefine the configuration for an inactive pool.")},
    {NULL, NULL}
};

3721
static const vshCmdOptDef opts_pool_undefine[] = {
3722 3723 3724 3725 3726
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3727
cmdPoolUndefine(vshControl *ctl, const vshCmd *cmd)
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752
{
    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
 */
3753
static const vshCmdInfo info_pool_uuid[] = {
3754 3755 3756 3757 3758
    {"syntax", "pool-uuid <pool>"},
    {"help", gettext_noop("convert a pool name to pool UUID")},
    {NULL, NULL}
};

3759
static const vshCmdOptDef opts_pool_uuid[] = {
3760 3761 3762 3763 3764
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name")},
    {NULL, 0, 0, NULL}
};

static int
3765
cmdPoolUuid(vshControl *ctl, const vshCmd *cmd)
3766 3767 3768 3769 3770 3771 3772 3773
{
    virStoragePoolPtr pool;
    char uuid[VIR_UUID_STRING_BUFLEN];

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

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
3774
                                           VSH_BYNAME)))
3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790
        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
 */
3791
static const vshCmdInfo info_vol_create[] = {
3792 3793 3794 3795 3796 3797
    {"syntax", "create <file>"},
    {"help", gettext_noop("create a vol from an XML file")},
    {"desc", gettext_noop("Create a vol.")},
    {NULL, NULL}
};

3798
static const vshCmdOptDef opts_vol_create[] = {
3799 3800 3801 3802 3803 3804
    {"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
3805
cmdVolCreate(vshControl *ctl, const vshCmd *cmd)
3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817
{
    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,
3818
                                           VSH_BYNAME)))
3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
        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
 */
3850
static const vshCmdInfo info_vol_delete[] = {
3851 3852 3853 3854 3855 3856
    {"syntax", "vol-delete <vol>"},
    {"help", gettext_noop("delete a vol")},
    {"desc", gettext_noop("Delete a given vol.")},
    {NULL, NULL}
};

3857
static const vshCmdOptDef opts_vol_delete[] = {
3858 3859 3860 3861 3862 3863
    {"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
3864
cmdVolDelete(vshControl *ctl, const vshCmd *cmd)
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877
{
    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 已提交
3878
        vshPrint(ctl, _("Vol %s deleted\n"), name);
3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
    } else {
        vshError(ctl, FALSE, _("Failed to delete vol %s"), name);
        ret = FALSE;
        virStorageVolFree(vol);
    }

    return ret;
}


/*
 * "vol-info" command
 */
3892
static const vshCmdInfo info_vol_info[] = {
3893 3894 3895 3896 3897 3898
    {"syntax", "vol-info <vol>"},
    {"help", gettext_noop("storage vol information")},
    {"desc", gettext_noop("Returns basic information about the storage vol.")},
    {NULL, NULL}
};

3899
static const vshCmdOptDef opts_vol_info[] = {
3900 3901 3902 3903 3904 3905
    {"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
3906
cmdVolInfo(vshControl *ctl, const vshCmd *cmd)
3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
{
    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
 */
3944
static const vshCmdInfo info_vol_dumpxml[] = {
3945 3946 3947 3948 3949 3950
    {"syntax", "vol-dumpxml <vol>"},
    {"help", gettext_noop("vol information in XML")},
    {"desc", gettext_noop("Output the vol information as an XML dump to stdout.")},
    {NULL, NULL}
};

3951
static const vshCmdOptDef opts_vol_dumpxml[] = {
3952 3953 3954 3955 3956 3957
    {"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
3958
cmdVolDumpXML(vshControl *ctl, const vshCmd *cmd)
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
{
    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
 */
3986
static const vshCmdInfo info_vol_list[] = {
3987 3988 3989 3990 3991 3992
    {"syntax", "vol-list <pool>"},
    {"help", gettext_noop("list vols")},
    {"desc", gettext_noop("Returns list of vols by pool.")},
    {NULL, NULL}
};

3993
static const vshCmdOptDef opts_vol_list[] = {
3994 3995 3996 3997 3998
    {"pool", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("pool name or uuid")},
    {NULL, 0, 0, NULL}
};

static int
3999
cmdVolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 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 4058 4059 4060 4061 4062 4063 4064
{
    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
 */
4065
static const vshCmdInfo info_vol_name[] = {
4066 4067 4068 4069 4070
    {"syntax", "vol-name <vol>"},
    {"help", gettext_noop("convert a vol UUID to vol name")},
    {NULL, NULL}
};

4071
static const vshCmdOptDef opts_vol_name[] = {
4072 4073 4074 4075 4076
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol key or path")},
    {NULL, 0, 0, NULL}
};

static int
4077
cmdVolName(vshControl *ctl, const vshCmd *cmd)
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
{
    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
 */
4098
static const vshCmdInfo info_vol_key[] = {
4099 4100 4101 4102 4103
    {"syntax", "vol-key <vol>"},
    {"help", gettext_noop("convert a vol UUID to vol key")},
    {NULL, NULL}
};

4104
static const vshCmdOptDef opts_vol_key[] = {
4105 4106 4107 4108 4109
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol uuid")},
    {NULL, 0, 0, NULL}
};

static int
4110
cmdVolKey(vshControl *ctl, const vshCmd *cmd)
4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130
{
    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
 */
4131
static const vshCmdInfo info_vol_path[] = {
4132 4133 4134 4135 4136
    {"syntax", "vol-path <pool> <vol>"},
    {"help", gettext_noop("convert a vol UUID to vol path")},
    {NULL, NULL}
};

4137
static const vshCmdOptDef opts_vol_path[] = {
4138 4139 4140 4141 4142 4143
    {"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
4144
cmdVolPath(vshControl *ctl, const vshCmd *cmd)
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
{
    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
 */
4168
static const vshCmdInfo info_version[] = {
4169 4170 4171 4172 4173 4174 4175 4176
    {"syntax", "version"},
    {"help", gettext_noop("show version")},
    {"desc", gettext_noop("Display the system version information.")},
    {NULL, NULL}
};


static int
4177
cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247
{
    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;
}

/*
 * "hostkey" command
 */
4248
static const vshCmdInfo info_hostname[] = {
4249 4250 4251 4252 4253 4254
    {"syntax", "hostname"},
    {"help", gettext_noop("print the hypervisor hostname")},
    {NULL, NULL}
};

static int
4255
cmdHostname (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276
{
    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
 */
4277
static const vshCmdInfo info_uri[] = {
4278 4279 4280 4281 4282 4283
    {"syntax", "uri"},
    {"help", gettext_noop("print the hypervisor canonical URI")},
    {NULL, NULL}
};

static int
4284
cmdURI (vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305
{
    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
 */
4306
static const vshCmdInfo info_vncdisplay[] = {
4307 4308 4309 4310 4311 4312
    {"syntax", "vncdisplay <domain>"},
    {"help", gettext_noop("vnc display")},
    {"desc", gettext_noop("Output the IP address and port number for the VNC display.")},
    {NULL, NULL}
};

4313
static const vshCmdOptDef opts_vncdisplay[] = {
4314 4315 4316 4317 4318
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
4319
cmdVNCDisplay(vshControl *ctl, const vshCmd *cmd)
4320 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 4359 4360
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    int ret = FALSE;
    int port = 0;
    char *doc;

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

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

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

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

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/graphics[@type='vnc']/@port)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        goto cleanup;
    }
    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) ||
4361
        STREQ((const char*)obj->stringval, "0.0.0.0")) {
4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381
        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
 */
4382
static const vshCmdInfo info_ttyconsole[] = {
4383 4384 4385 4386 4387 4388
    {"syntax", "ttyconsole <domain>"},
    {"help", gettext_noop("tty console")},
    {"desc", gettext_noop("Output the device for the TTY console.")},
    {NULL, NULL}
};

4389
static const vshCmdOptDef opts_ttyconsole[] = {
4390 4391 4392 4393 4394
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {NULL, 0, 0, NULL}
};

static int
4395
cmdTTYConsole(vshControl *ctl, const vshCmd *cmd)
4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlXPathContextPtr ctxt = NULL;
    virDomainPtr dom;
    int ret = FALSE;
    char *doc;

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

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

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

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

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/console/@tty)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        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
4442
 */
4443
static const vshCmdInfo info_attach_device[] = {
4444 4445 4446 4447 4448 4449
    {"syntax", "attach-device <domain> <file> "},
    {"help", gettext_noop("attach device from an XML file")},
    {"desc", gettext_noop("Attach device from an XML <file>.")},
    {NULL, NULL}
};

4450
static const vshCmdOptDef opts_attach_device[] = {
4451 4452 4453 4454 4455 4456
    {"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
4457
cmdAttachDevice(vshControl *ctl, const vshCmd *cmd)
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472
{
    virDomainPtr dom;
    char *from;
    char *buffer;
    int ret = TRUE;
    int found;

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

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

    from = vshCommandOptString(cmd, "file", &found);
    if (!found) {
4473
        vshError(ctl, FALSE, "%s", _("attach-device: Missing <file> option"));
4474 4475 4476 4477
        virDomainFree(dom);
        return FALSE;
    }

4478 4479
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        virDomainFree(dom);
4480
        return FALSE;
4481
    }
4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499

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

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

    virDomainFree(dom);
    return TRUE;
}


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

4507
static const vshCmdOptDef opts_detach_device[] = {
4508 4509 4510 4511 4512 4513
    {"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
4514
cmdDetachDevice(vshControl *ctl, const vshCmd *cmd)
4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529
{
    virDomainPtr dom;
    char *from;
    char *buffer;
    int ret = TRUE;
    int found;

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

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

    from = vshCommandOptString(cmd, "file", &found);
    if (!found) {
4530
        vshError(ctl, FALSE, "%s", _("detach-device: Missing <file> option"));
4531 4532 4533 4534
        virDomainFree(dom);
        return FALSE;
    }

4535 4536
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        virDomainFree(dom);
4537
        return FALSE;
4538
    }
4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552

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

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

    virDomainFree(dom);
    return TRUE;
}

4553

4554 4555 4556
/*
 * "attach-interface" command
 */
4557
static const vshCmdInfo info_attach_interface[] = {
4558 4559 4560 4561 4562 4563
    {"syntax", "attach-interface <domain> <type> <source> [--target <target>] [--mac <mac>] [--script <script>] "},
    {"help", gettext_noop("attach network interface")},
    {"desc", gettext_noop("Attach new network interface.")},
    {NULL, NULL}
};

4564
static const vshCmdOptDef opts_attach_interface[] = {
4565 4566 4567 4568
    {"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")},
4569
    {"mac",    VSH_OT_DATA, 0, gettext_noop("MAC address")},
4570 4571 4572 4573 4574
    {"script", VSH_OT_DATA, 0, gettext_noop("script used to bridge network interface")},
    {NULL, 0, 0, NULL}
};

static int
4575
cmdAttachInterface(vshControl *ctl, const vshCmd *cmd)
4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596
{
    virDomainPtr dom = NULL;
    char *mac, *target, *script, *type, *source;
    int typ, ret = FALSE;
    char *buf = NULL, *tmp = NULL;

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

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

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

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

    /* check interface type */
4597
    if (STREQ(type, "network")) {
4598
        typ = 1;
4599
    } else if (STREQ(type, "bridge")) {
4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662
        typ = 2;
    } else {
        vshError(ctl, FALSE, _("No support %s in command 'attach-interface'"), type);
        goto cleanup;
    }

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

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

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

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

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

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

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

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
4663 4664
    free(buf);
    free(tmp);
4665 4666 4667 4668 4669 4670
    return ret;
}

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

4678
static const vshCmdOptDef opts_detach_interface[] = {
4679 4680
    {"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")},
4681
    {"mac",    VSH_OT_DATA, 0, gettext_noop("MAC address")},
4682 4683 4684 4685
    {NULL, 0, 0, NULL}
};

static int
4686
cmdDetachInterface(vshControl *ctl, const vshCmd *cmd)
4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718
{
    virDomainPtr dom = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj=NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr cur = NULL;
    xmlChar *tmp_mac = NULL;
    xmlBufferPtr xml_buf = NULL;
    char *doc, *mac =NULL, *type;
    char buf[64];
    int i = 0, diff_mac, ret = FALSE;

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

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

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

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

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

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOWARNING);
    free(doc);
    if (!xml) {
J
Jim Meyering 已提交
4719
        vshError(ctl, FALSE, "%s", _("Failed to get interface information"));
4720 4721 4722 4723
        goto cleanup;
    }
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt) {
J
Jim Meyering 已提交
4724
        vshError(ctl, FALSE, "%s", _("Failed to get interface information"));
4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
        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");
4745
                diff_mac = virMacAddrCompare ((char *) tmp_mac, mac);
4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759
                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 已提交
4760
        vshError(ctl, FALSE, "%s", _("Failed to allocate memory"));
4761 4762 4763 4764
        goto cleanup;
    }

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
J
Jim Meyering 已提交
4765
        vshError(ctl, FALSE, "%s", _("Failed to create XML"));
4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777
        goto cleanup;
    }

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

 cleanup:
    if (dom)
        virDomainFree(dom);
4778
    xmlXPathFreeObject(obj);
4779
    xmlXPathFreeContext(ctxt);
4780 4781 4782 4783 4784 4785 4786 4787 4788 4789
    if (xml)
        xmlFreeDoc(xml);
    if (xml_buf)
        xmlBufferFree(xml_buf);
    return ret;
}

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

4797
static const vshCmdOptDef opts_attach_disk[] = {
4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808
    {"domain",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"source",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("source of disk device")},
    {"target",  VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("target of disk device")},
    {"driver",    VSH_OT_DATA, 0, gettext_noop("driver of disk device")},
    {"subdriver", VSH_OT_DATA, 0, gettext_noop("subdriver of disk device")},
    {"type",    VSH_OT_DATA, 0, gettext_noop("target device type")},
    {"mode",    VSH_OT_DATA, 0, gettext_noop("mode of device reading and writing")},
    {NULL, 0, 0, NULL}
};

static int
4809
cmdAttachDisk(vshControl *ctl, const vshCmd *cmd)
4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833
{
    virDomainPtr dom = NULL;
    char *source, *target, *driver, *subdriver, *type, *mode;
    int isFile = 0, ret = FALSE;
    char *buf = NULL, *tmp = NULL;

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

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

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

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

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

    if (type) {
4834
        if (STRNEQ(type, "cdrom") && STRNEQ(type, "disk")) {
4835 4836 4837 4838 4839 4840
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), type);
            goto cleanup;
        }
    }

    if (driver) {
4841
        if (STREQ(driver, "file") || STREQ(driver, "tap")) {
4842
            isFile = 1;
4843
        } else if (STRNEQ(driver, "phy")) {
4844 4845 4846 4847 4848 4849
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), driver);
            goto cleanup;
        }
    }

    if (mode) {
4850
        if (STRNEQ(mode, "readonly") && STRNEQ(mode, "shareable")) {
4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944
            vshError(ctl, FALSE, _("No support %s in command 'attach-disk'"), mode);
            goto cleanup;
        }
    }

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

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

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

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

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

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

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

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

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

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
4945 4946
    free(buf);
    free(tmp);
4947 4948 4949 4950 4951 4952
    return ret;
}

/*
 * "detach-disk" command
 */
4953
static const vshCmdInfo info_detach_disk[] = {
4954 4955 4956 4957 4958 4959
    {"syntax", "detach-disk <domain> <target> "},
    {"help", gettext_noop("detach disk device")},
    {"desc", gettext_noop("Detach disk device.")},
    {NULL, NULL}
};

4960
static const vshCmdOptDef opts_detach_disk[] = {
4961 4962 4963 4964 4965 4966
    {"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
4967
cmdDetachDisk(vshControl *ctl, const vshCmd *cmd)
4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996
{
    xmlDocPtr xml = NULL;
    xmlXPathObjectPtr obj=NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr cur = NULL;
    xmlChar *tmp_tgt = NULL;
    xmlBufferPtr xml_buf = NULL;
    virDomainPtr dom = NULL;
    char *doc, *target;
    int i = 0, diff_tgt, ret = FALSE;

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

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

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

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

    xml = xmlReadDoc((const xmlChar *) doc, "domain.xml", NULL,
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOWARNING);
    free(doc);
    if (!xml) {
J
Jim Meyering 已提交
4997
        vshError(ctl, FALSE, "%s", _("Failed to get disk information"));
4998 4999 5000 5001
        goto cleanup;
    }
    ctxt = xmlXPathNewContext(xml);
    if (!ctxt) {
J
Jim Meyering 已提交
5002
        vshError(ctl, FALSE, "%s", _("Failed to get disk information"));
5003 5004 5005 5006 5007 5008
        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 已提交
5009
        vshError(ctl, FALSE, "%s", _("Failed to get disk information"));
5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033
        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 已提交
5034
        vshError(ctl, FALSE, "%s", _("Failed to allocate memory"));
5035 5036 5037 5038
        goto cleanup;
    }

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
J
Jim Meyering 已提交
5039
        vshError(ctl, FALSE, "%s", _("Failed to create XML"));
5040 5041 5042 5043 5044 5045 5046 5047 5048 5049
        goto cleanup;
    }

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

 cleanup:
5050
    xmlXPathFreeObject(obj);
5051
    xmlXPathFreeContext(ctxt);
5052 5053 5054 5055 5056 5057 5058 5059 5060
    if (xml)
        xmlFreeDoc(xml);
    if (xml_buf)
        xmlBufferFree(xml_buf);
    if (dom)
        virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
5061 5062 5063
/*
 * "quit" command
 */
5064
static const vshCmdInfo info_quit[] = {
5065
    {"syntax", "quit"},
5066
    {"help", gettext_noop("quit this interactive terminal")},
5067
    {NULL, NULL}
K
Karel Zak 已提交
5068 5069 5070
};

static int
5071
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
5072
{
K
Karel Zak 已提交
5073 5074 5075 5076 5077 5078 5079
    ctl->imode = FALSE;
    return TRUE;
}

/*
 * Commands
 */
5080
static const vshCmdDef commands[] = {
5081 5082 5083 5084
    {"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},
5085
    {"autostart", cmdAutostart, opts_autostart, info_autostart},
5086
    {"capabilities", cmdCapabilities, NULL, info_capabilities},
5087
    {"connect", cmdConnect, opts_connect, info_connect},
5088
    {"console", cmdConsole, opts_console, info_console},
5089
    {"create", cmdCreate, opts_create, info_create},
5090
    {"start", cmdStart, opts_start, info_start},
K
Karel Zak 已提交
5091
    {"destroy", cmdDestroy, opts_destroy, info_destroy},
5092 5093 5094
    {"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},
5095
    {"define", cmdDefine, opts_define, info_define},
K
Karel Zak 已提交
5096
    {"domid", cmdDomid, opts_domid, info_domid},
K
Karel Zak 已提交
5097
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid},
5098
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo},
K
Karel Zak 已提交
5099 5100
    {"domname", cmdDomname, opts_domname, info_domname},
    {"domstate", cmdDomstate, opts_domstate, info_domstate},
5101 5102
    {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat},
    {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat},
5103
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml},
5104
    {"freecell", cmdFreecell, opts_freecell, info_freecell},
5105
    {"hostname", cmdHostname, NULL, info_hostname},
5106
    {"list", cmdList, opts_list, info_list},
5107
    {"migrate", cmdMigrate, opts_migrate, info_migrate},
5108

5109
    {"net-autostart", cmdNetworkAutostart, opts_network_autostart, info_network_autostart},
5110 5111 5112 5113 5114 5115 5116 5117 5118
    {"net-create", cmdNetworkCreate, opts_network_create, info_network_create},
    {"net-define", cmdNetworkDefine, opts_network_define, info_network_define},
    {"net-destroy", cmdNetworkDestroy, opts_network_destroy, info_network_destroy},
    {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml, info_network_dumpxml},
    {"net-list", cmdNetworkList, opts_network_list, info_network_list},
    {"net-name", cmdNetworkName, opts_network_name, info_network_name},
    {"net-start", cmdNetworkStart, opts_network_start, info_network_start},
    {"net-undefine", cmdNetworkUndefine, opts_network_undefine, info_network_undefine},
    {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid},
K
Karel Zak 已提交
5119
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
5120 5121 5122 5123

    {"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},
5124
    {"pool-create-as", cmdPoolCreateAs, opts_pool_create_as, info_pool_create_as},
5125
    {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define},
5126
    {"pool-define-as", cmdPoolDefineAs, opts_pool_define_as, info_pool_define_as},
5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137
    {"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},
    {"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 已提交
5138 5139 5140
    {"quit", cmdQuit, NULL, info_quit},
    {"reboot", cmdReboot, opts_reboot, info_reboot},
    {"restore", cmdRestore, opts_restore, info_restore},
5141 5142
    {"resume", cmdResume, opts_resume, info_resume},
    {"save", cmdSave, opts_save, info_save},
5143
    {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo},
D
Daniel Veillard 已提交
5144
    {"dump", cmdDump, opts_dump, info_dump},
5145
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown},
5146 5147 5148
    {"setmem", cmdSetmem, opts_setmem, info_setmem},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus},
K
Karel Zak 已提交
5149
    {"suspend", cmdSuspend, opts_suspend, info_suspend},
5150
    {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole},
5151
    {"undefine", cmdUndefine, opts_undefine, info_undefine},
5152
    {"uri", cmdURI, NULL, info_uri},
5153 5154

    {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create},
5155
    {"vol-create-as", cmdVolCreateAs, opts_vol_create_as, info_vol_create_as},
5156 5157 5158 5159 5160 5161 5162 5163
    {"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},

5164 5165
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
5166
    {"version", cmdVersion, NULL, info_version},
5167
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay},
5168
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
5169 5170 5171 5172 5173 5174
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
5175
static const char *
5176
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
5177
{
5178
    const vshCmdInfo *info;
5179

K
Karel Zak 已提交
5180
    for (info = cmd->info; info && info->name; info++) {
5181
        if (STREQ(info->name, name))
K
Karel Zak 已提交
5182 5183 5184 5185 5186
            return info->data;
    }
    return NULL;
}

5187 5188
static const vshCmdOptDef *
vshCmddefGetOption(const vshCmdDef * cmd, const char *name)
5189
{
5190
    const vshCmdOptDef *opt;
5191

K
Karel Zak 已提交
5192
    for (opt = cmd->opts; opt && opt->name; opt++)
5193
        if (STREQ(opt->name, name))
K
Karel Zak 已提交
5194 5195 5196 5197
            return opt;
    return NULL;
}

5198 5199
static const vshCmdOptDef *
vshCmddefGetData(const vshCmdDef * cmd, int data_ct)
5200
{
5201
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
5202

5203
    for (opt = cmd->opts; opt && opt->name; opt++) {
5204 5205
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
5206 5207 5208 5209 5210
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
5211 5212 5213
    return NULL;
}

5214 5215 5216
/*
 * Checks for required options
 */
5217
static int
5218
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd)
5219
{
5220 5221
    const vshCmdDef *def = cmd->def;
    const vshCmdOptDef *d;
5222
    int err = 0;
5223 5224 5225 5226

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

            while (o && ok == 0) {
5230
                if (o->def == d)
5231
                    ok = 1;
5232 5233 5234
                o = o->next;
            }
            if (!ok) {
5235 5236
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
5237
                         _("command '%s' requires <%s> option") :
5238
                         _("command '%s' requires --%s option"),
5239
                         def->name, d->name);
5240 5241
                err = 1;
            }
5242

5243 5244 5245 5246 5247
        }
    }
    return !err;
}

5248
static const vshCmdDef *
5249 5250
vshCmddefSearch(const char *cmdname)
{
5251
    const vshCmdDef *c;
5252

K
Karel Zak 已提交
5253
    for (c = commands; c->name; c++)
5254
        if (STREQ(c->name, cmdname))
K
Karel Zak 已提交
5255 5256 5257 5258 5259
            return c;
    return NULL;
}

static int
5260
vshCmddefHelp(vshControl *ctl, const char *cmdname, int withprog)
5261
{
5262
    const vshCmdDef *def = vshCmddefSearch(cmdname);
5263

K
Karel Zak 已提交
5264
    if (!def) {
5265
        vshError(ctl, FALSE, _("command '%s' doesn't exist"), cmdname);
5266 5267
        return FALSE;
    } else {
5268
        const vshCmdOptDef *opt;
5269 5270
        const char *desc = N_(vshCmddefGetInfo(def, "desc"));
        const char *help = N_(vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
5271
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
5272

5273
        fputs(_("  NAME\n"), stdout);
5274 5275
        fprintf(stdout, "    %s - %s\n", def->name, help);

K
Karel Zak 已提交
5276
        if (syntax) {
5277
            fputs(_("\n  SYNOPSIS\n"), stdout);
K
Karel Zak 已提交
5278 5279 5280 5281 5282 5283
            if (!withprog)
                fprintf(stdout, "    %s\n", syntax);
            else
                fprintf(stdout, "    %s %s\n", progname, syntax);
        }
        if (desc) {
5284
            fputs(_("\n  DESCRIPTION\n"), stdout);
K
Karel Zak 已提交
5285 5286 5287
            fprintf(stdout, "    %s\n", desc);
        }
        if (def->opts) {
5288
            fputs(_("\n  OPTIONS\n"), stdout);
5289
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
5290
                char buf[256];
5291 5292

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
5293
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
5294
                else if (opt->type == VSH_OT_INT)
5295
                    snprintf(buf, sizeof(buf), _("--%s <number>"), opt->name);
5296
                else if (opt->type == VSH_OT_STRING)
5297
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
5298
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
5299
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
5300

5301
                fprintf(stdout, "    %-15s  %s\n", buf, N_(opt->help));
5302
            }
K
Karel Zak 已提交
5303 5304 5305 5306 5307 5308 5309 5310 5311 5312
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
5313 5314 5315
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
5316 5317
    vshCmdOpt *a = arg;

5318
    while (a) {
K
Karel Zak 已提交
5319
        vshCmdOpt *tmp = a;
5320

K
Karel Zak 已提交
5321 5322
        a = a->next;

5323
        free(tmp->data);
K
Karel Zak 已提交
5324 5325 5326 5327 5328
        free(tmp);
    }
}

static void
5329
vshCommandFree(vshCmd *cmd)
5330
{
K
Karel Zak 已提交
5331 5332
    vshCmd *c = cmd;

5333
    while (c) {
K
Karel Zak 已提交
5334
        vshCmd *tmp = c;
5335

K
Karel Zak 已提交
5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
5348
vshCommandOpt(const vshCmd *cmd, const char *name)
5349
{
K
Karel Zak 已提交
5350
    vshCmdOpt *opt = cmd->opts;
5351 5352

    while (opt) {
5353
        if (opt->def && STREQ(opt->def->name, name))
K
Karel Zak 已提交
5354 5355 5356 5357 5358 5359 5360 5361 5362 5363
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
5364
vshCommandOptInt(const vshCmd *cmd, const char *name, int *found)
5365
{
K
Karel Zak 已提交
5366
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
5367 5368
    int res = 0, num_found = FALSE;
    char *end_p = NULL;
5369

5370 5371
    if ((arg != NULL) && (arg->data != NULL)) {
        res = strtol(arg->data, &end_p, 10);
5372 5373 5374 5375
        if ((arg->data == end_p) || (*end_p!= 0))
            num_found = FALSE;
        else
            num_found = TRUE;
5376
    }
K
Karel Zak 已提交
5377
    if (found)
5378
        *found = num_found;
K
Karel Zak 已提交
5379 5380 5381 5382 5383 5384 5385
    return res;
}

/*
 * Returns option as STRING
 */
static char *
5386
vshCommandOptString(const vshCmd *cmd, const char *name, int *found)
5387
{
K
Karel Zak 已提交
5388
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
5389

K
Karel Zak 已提交
5390 5391
    if (found)
        *found = arg ? TRUE : FALSE;
5392 5393

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

5396 5397
#if 0
static int
5398
vshCommandOptStringList(const vshCmd *cmd, const char *name, char ***data)
5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421
{
    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 已提交
5422 5423 5424 5425
/*
 * Returns TRUE/FALSE if the option exists
 */
static int
5426
vshCommandOptBool(const vshCmd *cmd, const char *name)
5427
{
K
Karel Zak 已提交
5428 5429 5430
    return vshCommandOpt(cmd, name) ? TRUE : FALSE;
}

5431

K
Karel Zak 已提交
5432
static virDomainPtr
5433
vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd, const char *optname,
5434
                      char **name, int flag)
5435
{
K
Karel Zak 已提交
5436
    virDomainPtr dom = NULL;
5437
    char *n;
K
Karel Zak 已提交
5438
    int id;
5439

K
Karel Zak 已提交
5440
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
J
Jim Meyering 已提交
5441
        vshError(ctl, FALSE, "%s", _("undefined domain name or id"));
5442
        return NULL;
K
Karel Zak 已提交
5443
    }
5444

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

K
Karel Zak 已提交
5448 5449
    if (name)
        *name = n;
5450

K
Karel Zak 已提交
5451
    /* try it by ID */
5452
    if (flag & VSH_BYID) {
5453
        if (virStrToLong_i(n, NULL, 10, &id) == 0 && id >= 0) {
K
Karel Zak 已提交
5454 5455 5456 5457
            vshDebug(ctl, 5, "%s: <%s> seems like domain ID\n",
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
5458
    }
K
Karel Zak 已提交
5459
    /* try it by UUID */
5460
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
D
Daniel Veillard 已提交
5461
        vshDebug(ctl, 5, "%s: <%s> trying as domain UUID\n",
5462
                 cmd->def->name, optname);
K
Karel Zak 已提交
5463
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
5464
    }
K
Karel Zak 已提交
5465
    /* try it by NAME */
5466
    if (dom==NULL && (flag & VSH_BYNAME)) {
D
Daniel Veillard 已提交
5467
        vshDebug(ctl, 5, "%s: <%s> trying as domain NAME\n",
5468
                 cmd->def->name, optname);
K
Karel Zak 已提交
5469
        dom = virDomainLookupByName(ctl->conn, n);
5470
    }
K
Karel Zak 已提交
5471

5472
    if (!dom)
5473
        vshError(ctl, FALSE, _("failed to get domain '%s'"), n);
5474

K
Karel Zak 已提交
5475 5476 5477
    return dom;
}

5478
static virNetworkPtr
5479
vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd, const char *optname,
5480
                       char **name, int flag)
5481 5482 5483 5484 5485
{
    virNetworkPtr network = NULL;
    char *n;

    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
J
Jim Meyering 已提交
5486
        vshError(ctl, FALSE, "%s", _("undefined network name"));
5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497
        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 已提交
5498
        vshDebug(ctl, 5, "%s: <%s> trying as network UUID\n",
5499
                 cmd->def->name, optname);
5500 5501 5502 5503
        network = virNetworkLookupByUUIDString(ctl->conn, n);
    }
    /* try it by NAME */
    if (network==NULL && (flag & VSH_BYNAME)) {
D
Daniel Veillard 已提交
5504
        vshDebug(ctl, 5, "%s: <%s> trying as network NAME\n",
5505 5506 5507 5508 5509 5510 5511 5512 5513 5514
                 cmd->def->name, optname);
        network = virNetworkLookupByName(ctl->conn, n);
    }

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

    return network;
}

5515
static virStoragePoolPtr
5516
vshCommandOptPoolBy(vshControl *ctl, const vshCmd *cmd, const char *optname,
5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535
                    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",
5536
                 cmd->def->name, optname);
5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552
        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
5553
vshCommandOptVolBy(vshControl *ctl, const vshCmd *cmd,
5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607
                   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 已提交
5608 5609 5610 5611
/*
 * Executes command(s) and returns return code from last command
 */
static int
5612
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
5613
{
K
Karel Zak 已提交
5614
    int ret = TRUE;
5615 5616

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

K
Karel Zak 已提交
5619 5620
        if (ctl->timing)
            GETTIMEOFDAY(&before);
5621

K
Karel Zak 已提交
5622 5623 5624 5625
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
5626

5627
        if (STREQ(cmd->def->name, "quit"))        /* hack ... */
K
Karel Zak 已提交
5628 5629 5630
            return ret;

        if (ctl->timing)
5631
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
5632 5633
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
5634
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649
        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

5650
static int
5651
vshCommandGetToken(vshControl *ctl, char *str, char **end, char **res)
5652
{
K
Karel Zak 已提交
5653 5654 5655 5656 5657
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
5658

K
Karel Zak 已提交
5659
    *end = NULL;
5660

5661
    while (p && *p && (*p == ' ' || *p == '\t'))
K
Karel Zak 已提交
5662
        p++;
5663 5664

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
5665
        return VSH_TK_END;
5666
    if (*p == ';') {
D
Daniel Veillard 已提交
5667
        *end = ++p;             /* = \0 or begin of next command */
K
Karel Zak 已提交
5668 5669
        return VSH_TK_END;
    }
5670
    while (*p) {
K
Karel Zak 已提交
5671
        /* end of token is blank space or ';' */
5672
        if ((quote == FALSE && (*p == ' ' || *p == '\t')) || *p == ';')
K
Karel Zak 已提交
5673
            break;
5674

5675
        /* end of option name could be '=' */
5676 5677
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
5678 5679
            break;
        }
5680 5681 5682

        if (tk == VSH_TK_NONE) {
            if (*p == '-' && *(p + 1) == '-' && *(p + 2)
5683
                && c_isalnum(*(p + 2))) {
K
Karel Zak 已提交
5684
                tk = VSH_TK_OPTION;
5685
                p += 2;
K
Karel Zak 已提交
5686 5687
            } else {
                tk = VSH_TK_DATA;
5688 5689
                if (*p == '"') {
                    quote = TRUE;
K
Karel Zak 已提交
5690 5691 5692 5693 5694
                    p++;
                } else {
                    quote = FALSE;
                }
            }
5695 5696
            tkstr = p;          /* begin of token */
        } else if (quote && *p == '"') {
K
Karel Zak 已提交
5697 5698
            quote = FALSE;
            p++;
5699
            break;              /* end of "..." token */
K
Karel Zak 已提交
5700 5701 5702 5703 5704
        }
        p++;
        sz++;
    }
    if (quote) {
J
Jim Meyering 已提交
5705
        vshError(ctl, FALSE, "%s", _("missing \""));
K
Karel Zak 已提交
5706 5707
        return VSH_TK_ERROR;
    }
5708
    if (tkstr == NULL || *tkstr == '\0' || p == NULL)
K
Karel Zak 已提交
5709
        return VSH_TK_END;
5710
    if (sz == 0)
K
Karel Zak 已提交
5711
        return VSH_TK_END;
5712

5713
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
5714
    memcpy(*res, tkstr, sz);
5715
    *(*res + sz) = '\0';
K
Karel Zak 已提交
5716 5717 5718 5719 5720 5721

    *end = p;
    return tk;
}

static int
5722
vshCommandParse(vshControl *ctl, char *cmdstr)
5723
{
K
Karel Zak 已提交
5724 5725 5726 5727
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
5728

K
Karel Zak 已提交
5729 5730 5731 5732
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
5733 5734

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

K
Karel Zak 已提交
5737
    str = cmdstr;
5738
    while (str && *str) {
K
Karel Zak 已提交
5739
        vshCmdOpt *last = NULL;
5740
        const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
5741
        int tk = VSH_TK_NONE;
5742
        int data_ct = 0;
5743

K
Karel Zak 已提交
5744
        first = NULL;
5745 5746

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
5747
            char *end = NULL;
5748
            const vshCmdOptDef *opt = NULL;
5749

K
Karel Zak 已提交
5750
            tkdata = NULL;
5751

K
Karel Zak 已提交
5752 5753
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
5754

K
Karel Zak 已提交
5755
            str = end;
5756 5757

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
5758
                break;
5759
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
5760
                goto syntaxError;
5761 5762

            if (cmd == NULL) {
K
Karel Zak 已提交
5763
                /* first token must be command name */
5764 5765
                if (tk != VSH_TK_DATA) {
                    vshError(ctl, FALSE,
5766
                             _("unexpected token (command name): '%s'"),
5767
                             tkdata);
K
Karel Zak 已提交
5768 5769 5770
                    goto syntaxError;
                }
                if (!(cmd = vshCmddefSearch(tkdata))) {
5771
                    vshError(ctl, FALSE, _("unknown command: '%s'"), tkdata);
5772
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
5773 5774
                }
                free(tkdata);
5775
            } else if (tk == VSH_TK_OPTION) {
K
Karel Zak 已提交
5776 5777
                if (!(opt = vshCmddefGetOption(cmd, tkdata))) {
                    vshError(ctl, FALSE,
5778
                             _("command '%s' doesn't support option --%s"),
5779
                             cmd->name, tkdata);
K
Karel Zak 已提交
5780 5781
                    goto syntaxError;
                }
5782
                free(tkdata);   /* option name */
K
Karel Zak 已提交
5783 5784 5785 5786 5787
                tkdata = NULL;

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    tk = vshCommandGetToken(ctl, str, &end, &tkdata);
5788 5789
                    str = end;
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
5790
                        goto syntaxError;
5791
                    if (tk != VSH_TK_DATA) {
K
Karel Zak 已提交
5792
                        vshError(ctl, FALSE,
5793
                                 _("expected syntax: --%s <%s>"),
5794 5795
                                 opt->name,
                                 opt->type ==
5796
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
5797 5798 5799
                        goto syntaxError;
                    }
                }
5800
            } else if (tk == VSH_TK_DATA) {
5801
                if (!(opt = vshCmddefGetData(cmd, data_ct++))) {
5802
                    vshError(ctl, FALSE, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
5803 5804 5805 5806 5807
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
5808
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
5809

K
Karel Zak 已提交
5810 5811 5812 5813
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
5814

K
Karel Zak 已提交
5815 5816 5817 5818 5819
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
5820

K
Karel Zak 已提交
5821
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
5822 5823
                         cmd->name,
                         opt->name,
5824
                         tk == VSH_TK_OPTION ? _("OPTION") : _("DATA"),
5825
                         arg->data);
K
Karel Zak 已提交
5826 5827 5828 5829
            }
            if (!str)
                break;
        }
5830

D
Daniel Veillard 已提交
5831
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
5832
        if (cmd) {
5833
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
5834

K
Karel Zak 已提交
5835 5836 5837 5838
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

5839
            if (!vshCommandCheckOpts(ctl, c)) {
5840
                free(c);
5841
                goto syntaxError;
5842
            }
5843

K
Karel Zak 已提交
5844 5845 5846 5847 5848 5849 5850
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
5851

K
Karel Zak 已提交
5852 5853
    return TRUE;

5854
 syntaxError:
K
Karel Zak 已提交
5855 5856 5857 5858
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
5859
    free(tkdata);
5860
    return FALSE;
K
Karel Zak 已提交
5861 5862 5863 5864
}


/* ---------------
5865
 * Misc utils
K
Karel Zak 已提交
5866 5867
 * ---------------
 */
K
Karel Zak 已提交
5868
static const char *
5869 5870
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
5871
    switch (state) {
5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884
    case VIR_DOMAIN_RUNNING:
        return gettext_noop("running");
    case VIR_DOMAIN_BLOCKED:
        return gettext_noop("blocked");
    case VIR_DOMAIN_PAUSED:
        return gettext_noop("paused");
    case VIR_DOMAIN_SHUTDOWN:
        return gettext_noop("in shutdown");
    case VIR_DOMAIN_SHUTOFF:
        return gettext_noop("shut off");
    case VIR_DOMAIN_CRASHED:
        return gettext_noop("crashed");
    default:
5885
        ;/*FALLTHROUGH*/
K
Karel Zak 已提交
5886
    }
5887
    return gettext_noop("no state");  /* = dom0 state */
K
Karel Zak 已提交
5888 5889
}

5890 5891 5892 5893
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
5894 5895 5896 5897 5898 5899 5900
    case VIR_VCPU_OFFLINE:
        return gettext_noop("offline");
    case VIR_VCPU_BLOCKED:
        return gettext_noop("blocked");
    case VIR_VCPU_RUNNING:
        return gettext_noop("running");
    default:
5901
        ;/*FALLTHROUGH*/
5902
    }
5903
    return gettext_noop("no state");
5904 5905
}

K
Karel Zak 已提交
5906
static int
5907
vshConnectionUsability(vshControl *ctl, virConnectPtr conn, int showerror)
5908
{
5909 5910
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
5911 5912 5913
     */
    if (!conn) {
        if (showerror)
J
Jim Meyering 已提交
5914
            vshError(ctl, FALSE, "%s", _("no valid connection"));
K
Karel Zak 已提交
5915 5916 5917 5918 5919
        return FALSE;
    }
    return TRUE;
}

K
Karel Zak 已提交
5920
static void
5921
vshDebug(vshControl *ctl, int level, const char *format, ...)
5922
{
K
Karel Zak 已提交
5923 5924
    va_list ap;

5925 5926 5927 5928
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_DEBUG, format, ap);
    va_end(ap);

K
Karel Zak 已提交
5929 5930 5931 5932 5933 5934
    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
5935 5936 5937
}

static void
5938
vshPrintExtra(vshControl *ctl, const char *format, ...)
5939
{
K
Karel Zak 已提交
5940
    va_list ap;
5941

K
Karel Zak 已提交
5942
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
5943
        return;
5944

K
Karel Zak 已提交
5945
    va_start(ap, format);
5946
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
5947 5948 5949
    va_end(ap);
}

K
Karel Zak 已提交
5950

K
Karel Zak 已提交
5951
static void
5952
vshError(vshControl *ctl, int doexit, const char *format, ...)
5953
{
K
Karel Zak 已提交
5954
    va_list ap;
5955

5956 5957 5958 5959
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
    va_end(ap);

K
Karel Zak 已提交
5960
    if (doexit)
5961
        fprintf(stderr, _("%s: error: "), progname);
K
Karel Zak 已提交
5962
    else
5963
        fputs(_("error: "), stderr);
5964

K
Karel Zak 已提交
5965 5966 5967 5968 5969
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
5970

K
Karel Zak 已提交
5971
    if (doexit) {
5972 5973
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
5974 5975 5976 5977
        exit(EXIT_FAILURE);
    }
}

5978
static void *
5979
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
5980 5981 5982 5983 5984
{
    void *x;

    if ((x = malloc(size)))
        return x;
5985
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
5986
             filename, line, (int) size);
5987 5988 5989 5990
    return NULL;
}

static void *
5991
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename, int line)
5992 5993 5994 5995 5996
{
    void *x;

    if ((x = calloc(nmemb, size)))
        return x;
5997
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
5998
             filename, line, (int) (size*nmemb));
5999 6000 6001
    return NULL;
}

6002
static void *
6003
_vshRealloc(vshControl *ctl, void *ptr, size_t size, const char *filename, int line)
6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014
{
    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;
}

6015
static char *
6016
_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line)
6017 6018 6019
{
    char *x;

6020 6021
    if (s == NULL)
        return(NULL);
6022 6023
    if ((x = strdup(s)))
        return x;
6024 6025
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
6026 6027 6028
    return NULL;
}

K
Karel Zak 已提交
6029
/*
6030
 * Initialize connection.
K
Karel Zak 已提交
6031 6032
 */
static int
6033
vshInit(vshControl *ctl)
6034
{
K
Karel Zak 已提交
6035 6036 6037
    if (ctl->conn)
        return FALSE;

6038 6039
    vshOpenLogFile(ctl);

6040 6041
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
6042

6043 6044 6045 6046
    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);

6047

6048 6049 6050 6051
    /* This is not necessarily fatal.  All the individual commands check
     * vshConnectionUsability, except ones which don't need a connection
     * such as "help".
     */
6052
    if (!ctl->conn) {
J
Jim Meyering 已提交
6053
        vshError(ctl, FALSE, "%s", _("failed to connect to the hypervisor"));
6054 6055
        return FALSE;
    }
K
Karel Zak 已提交
6056 6057 6058 6059

    return TRUE;
}

6060 6061 6062 6063 6064
#ifndef O_SYNC
#define O_SYNC 0
#endif
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083
/**
 * 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 已提交
6084 6085
                vshError(ctl, TRUE, "%s",
                         _("failed to get the log file information"));
6086 6087 6088 6089
                break;
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
J
Jim Meyering 已提交
6090
            vshError(ctl, TRUE, "%s", _("the log path is not a file"));
6091 6092 6093 6094
        }
    }

    /* log file open */
6095
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
J
Jim Meyering 已提交
6096 6097
        vshError(ctl, TRUE, "%s",
                 _("failed to open the log file. check the log file path"));
6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162
    }
}

/**
 * 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 */
6163
    if (safewrite(ctl->log_fd, msg_buf, strlen(msg_buf)) < 0) {
6164
        vshCloseLogFile(ctl);
J
Jim Meyering 已提交
6165
        vshError(ctl, FALSE, "%s", _("failed to write the log file"));
6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178
    }
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
    if (ctl->log_fd >= 0) {
6179
        if (close(ctl->log_fd) < 0)
6180
            vshError(ctl, FALSE, _("%s: failed to write log file: %s"),
6181
                     ctl->logfile ? ctl->logfile : "?", strerror (errno));
6182 6183 6184 6185 6186 6187 6188 6189 6190
        ctl->log_fd = -1;
    }

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

6191
#ifdef USE_READLINE
6192

K
Karel Zak 已提交
6193 6194 6195 6196 6197
/* -----------------
 * Readline stuff
 * -----------------
 */

6198
/*
K
Karel Zak 已提交
6199 6200
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
6201
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
6202 6203
 */
static char *
6204 6205
vshReadlineCommandGenerator(const char *text, int state)
{
K
Karel Zak 已提交
6206
    static int list_index, len;
K
Karel Zak 已提交
6207
    const char *name;
K
Karel Zak 已提交
6208 6209 6210

    /* If this is a new word to complete, initialize now.  This
     * includes saving the length of TEXT for efficiency, and
6211
     * initializing the index variable to 0.
K
Karel Zak 已提交
6212 6213 6214
     */
    if (!state) {
        list_index = 0;
6215
        len = strlen(text);
K
Karel Zak 已提交
6216 6217 6218
    }

    /* Return the next name which partially matches from the
6219
     * command list.
K
Karel Zak 已提交
6220
     */
K
Karel Zak 已提交
6221
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
6222
        list_index++;
6223
        if (STREQLEN(name, text, len))
6224
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
6225 6226 6227 6228 6229 6230 6231
    }

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

static char *
6232 6233
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
6234
    static int list_index, len;
6235
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
6236
    const char *name;
K
Karel Zak 已提交
6237 6238 6239 6240 6241 6242 6243 6244 6245

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

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

6246
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
6247
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
6248 6249 6250

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
6251
        len = strlen(text);
K
Karel Zak 已提交
6252 6253 6254 6255 6256
        free(cmdname);
    }

    if (!cmd)
        return NULL;
6257

6258 6259 6260
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
6261
    while ((name = cmd->opts[list_index].name)) {
6262
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
6263
        char *res;
6264

K
Karel Zak 已提交
6265
        list_index++;
6266

K
Karel Zak 已提交
6267
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
6268 6269
            /* ignore non --option */
            continue;
6270

K
Karel Zak 已提交
6271
        if (len > 2) {
6272
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
6273 6274
                continue;
        }
6275
        res = vshMalloc(NULL, strlen(name) + 3);
6276
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
6277 6278 6279 6280 6281 6282 6283 6284
        return res;
    }

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

static char **
6285 6286 6287
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
6288 6289
    char **matches = (char **) NULL;

6290
    if (start == 0)
K
Karel Zak 已提交
6291
        /* command name generator */
6292
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
6293 6294
    else
        /* commands options */
6295
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
6296 6297 6298 6299 6300
    return matches;
}


static void
6301 6302
vshReadlineInit(void)
{
K
Karel Zak 已提交
6303 6304 6305 6306 6307 6308 6309
    /* 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;
}

6310 6311 6312 6313 6314 6315
static char *
vshReadline (vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
{
    return readline (prompt);
}

6316
#else /* !USE_READLINE */
6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342

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

6343
#endif /* !USE_READLINE */
6344

K
Karel Zak 已提交
6345
/*
J
Jim Meyering 已提交
6346
 * Deinitialize virsh
K
Karel Zak 已提交
6347 6348
 */
static int
6349
vshDeinit(vshControl *ctl)
6350
{
6351
    vshCloseLogFile(ctl);
6352
    free(ctl->name);
K
Karel Zak 已提交
6353
    if (ctl->conn) {
6354 6355
        if (virConnectClose(ctl->conn) != 0) {
            ctl->conn = NULL;   /* prevent recursive call from vshError() */
J
Jim Meyering 已提交
6356 6357
            vshError(ctl, TRUE, "%s",
                     _("failed to disconnect from the hypervisor"));
K
Karel Zak 已提交
6358 6359
        }
    }
D
Daniel P. Berrange 已提交
6360 6361
    virResetLastError();

K
Karel Zak 已提交
6362 6363
    return TRUE;
}
6364

K
Karel Zak 已提交
6365 6366 6367 6368
/*
 * Print usage
 */
static void
6369
vshUsage(vshControl *ctl, const char *cmdname)
6370
{
6371
    const vshCmdDef *cmd;
6372

K
Karel Zak 已提交
6373 6374
    /* global help */
    if (!cmdname) {
6375
        fprintf(stdout, _("\n%s [options] [commands]\n\n"
6376 6377
                          "  options:\n"
                          "    -c | --connect <uri>    hypervisor connection URI\n"
6378
                          "    -r | --readonly         connect readonly\n"
6379 6380 6381 6382
                          "    -d | --debug <num>      debug level [0-5]\n"
                          "    -h | --help             this help\n"
                          "    -q | --quiet            quiet mode\n"
                          "    -t | --timing           print timing information\n"
6383
                          "    -l | --log <file>       output logging to file\n"
6384 6385
                          "    -v | --version          program version\n\n"
                          "  commands (non interactive mode):\n"), progname);
6386 6387 6388

        for (cmd = commands; cmd->name; cmd++)
            fprintf(stdout,
6389
                    "    %-15s %s\n", cmd->name, N_(vshCmddefGetInfo(cmd,
6390
                                                                     "help")));
6391

J
Jim Meyering 已提交
6392
        fprintf(stdout, "%s",
6393
                _("\n  (specify help <command> for details about the command)\n\n"));
K
Karel Zak 已提交
6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static int
6405
vshParseArgv(vshControl *ctl, int argc, char **argv)
6406
{
K
Karel Zak 已提交
6407 6408
    char *last = NULL;
    int i, end = 0, help = 0;
6409
    int arg, idx = 0;
K
Karel Zak 已提交
6410
    struct option opt[] = {
6411 6412 6413 6414 6415
        {"debug", 1, 0, 'd'},
        {"help", 0, 0, 'h'},
        {"quiet", 0, 0, 'q'},
        {"timing", 0, 0, 't'},
        {"version", 0, 0, 'v'},
K
Karel Zak 已提交
6416
        {"connect", 1, 0, 'c'},
6417
        {"readonly", 0, 0, 'r'},
6418
        {"log", 1, 0, 'l'},
K
Karel Zak 已提交
6419
        {0, 0, 0, 0}
6420 6421
    };

K
Karel Zak 已提交
6422 6423

    if (argc < 2)
K
Karel Zak 已提交
6424
        return TRUE;
6425

6426
    /* look for begin of the command, for example:
K
Karel Zak 已提交
6427 6428 6429 6430
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
6431
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
6432 6433
        if (*argv[i] != '-') {
            int valid = FALSE;
6434

K
Karel Zak 已提交
6435 6436 6437 6438
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
6439 6440

                for (o = opt; o->name; o++) {
6441 6442 6443 6444
                    if (o->has_arg == 1){
                        if (sz == 2 && *(last + 1) == o->val)
                            /* valid virsh short option */
                            valid = TRUE;
6445
                        else if (sz > 2 && STREQ(o->name, last + 2))
6446 6447 6448
                            /* valid virsh long option */
                            valid = TRUE;
                    }
K
Karel Zak 已提交
6449 6450 6451 6452 6453 6454 6455 6456 6457
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
6458
    end = end ? end : argc;
6459

K
Karel Zak 已提交
6460
    /* standard (non-command) options */
6461
    while ((arg = getopt_long(end, argv, "d:hqtc:vrl:", opt, &idx)) != -1) {
6462
        switch (arg) {
6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480
        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);
6481 6482 6483
        case 'r':
            ctl->readonly = TRUE;
            break;
6484 6485 6486
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
6487 6488 6489 6490
        default:
            vshError(ctl, TRUE,
                     _("unsupported option '-%c'. See --help."), arg);
            break;
K
Karel Zak 已提交
6491 6492 6493 6494 6495 6496 6497
        }
    }

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

K
Karel Zak 已提交
6500 6501 6502
    if (argc > end) {
        /* parse command */
        char *cmdstr;
6503 6504
        int sz = 0, ret;

K
Karel Zak 已提交
6505 6506
        ctl->imode = FALSE;

6507 6508 6509
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

6510
        cmdstr = vshCalloc(ctl, sz + 1, 1);
6511 6512

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
6513 6514 6515 6516
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
6517
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
6518
        ret = vshCommandParse(ctl, cmdstr);
6519

K
Karel Zak 已提交
6520 6521 6522 6523 6524 6525
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

6526 6527 6528 6529
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
6530
    char *defaultConn;
K
Karel Zak 已提交
6531 6532
    int ret = TRUE;

6533 6534
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
6535
        return -1;
6536 6537 6538
    }
    if (!bindtextdomain(GETTEXT_PACKAGE, LOCALEBASEDIR)) {
        perror("bindtextdomain");
6539
        return -1;
6540 6541 6542
    }
    if (!textdomain(GETTEXT_PACKAGE)) {
        perror("textdomain");
6543
        return -1;
6544 6545
    }

6546
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
6547 6548 6549
        progname = argv[0];
    else
        progname++;
6550

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

6555
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
6556
        ctl->name = strdup(defaultConn);
6557 6558
    }

D
Daniel P. Berrange 已提交
6559 6560
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
6561
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
6562
    }
6563

D
Daniel P. Berrange 已提交
6564 6565
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
6566
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
6567
    }
6568

K
Karel Zak 已提交
6569
    if (!ctl->imode) {
6570
        ret = vshCommandRun(ctl, ctl->cmd);
6571
    } else {
K
Karel Zak 已提交
6572 6573
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
6574
            vshPrint(ctl,
6575
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
6576
                     progname);
J
Jim Meyering 已提交
6577
            vshPrint(ctl, "%s",
6578
                     _("Type:  'help' for help with commands\n"
6579
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
6580
        }
K
Karel Zak 已提交
6581
        vshReadlineInit();
K
Karel Zak 已提交
6582
        do {
6583
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
6584
            ctl->cmdstr =
6585
                vshReadline(ctl, prompt);
6586 6587
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
6588
            if (*ctl->cmdstr) {
6589
#if USE_READLINE
K
Karel Zak 已提交
6590
                add_history(ctl->cmdstr);
6591
#endif
K
Karel Zak 已提交
6592 6593 6594 6595 6596
                if (vshCommandParse(ctl, ctl->cmdstr))
                    vshCommandRun(ctl, ctl->cmd);
            }
            free(ctl->cmdstr);
            ctl->cmdstr = NULL;
6597
        } while (ctl->imode);
K
Karel Zak 已提交
6598

6599 6600
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
6601
    }
6602

K
Karel Zak 已提交
6603 6604
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
6605
}