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

40 41 42 43
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

44
#ifdef HAVE_READLINE_READLINE_H
K
Karel Zak 已提交
45 46
#include <readline/readline.h>
#include <readline/history.h>
47
#endif
K
Karel Zak 已提交
48

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

static char *progname;

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

61 62
#define VIRSH_MAX_XML_FILE 10*1024*1024

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

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 96 97
/**
 * 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;

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

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

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

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

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

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

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

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

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

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

220

K
Karel Zak 已提交
221 222
static vshCmdDef commands[];

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

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

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

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

247 248 249
#define VSH_BYID     (1 << 1)
#define VSH_BYUUID   (1 << 2)
#define VSH_BYNAME   (1 << 3)
K
Karel Zak 已提交
250 251

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

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

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

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

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
static virStoragePoolPtr vshCommandOptPoolBy(vshControl * ctl, vshCmd * cmd,
                            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)

static virStorageVolPtr vshCommandOptVolBy(vshControl * ctl, vshCmd * cmd,
                                           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)

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

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

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

298 299 300 301 302 303
static void *_vshMalloc(vshControl * ctl, size_t sz, const char *filename, int line);
#define vshMalloc(_ctl, _sz)    _vshMalloc(_ctl, _sz, __FILE__, __LINE__)

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

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

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

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

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

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

342
    {NULL, NULL}
K
Karel Zak 已提交
343 344 345
};

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

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

    if (!cmdname) {
        vshCmdDef *def;
357

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

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
/*
 * "autostart" command
 */
static vshCmdInfo info_autostart[] = {
    {"syntax", "autostart [--disable] <domain>"},
    {"help", gettext_noop("autostart a domain")},
    {"desc",
     gettext_noop("Configure a domain to be automatically started at boot.")},
    {NULL, NULL}
};

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

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

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

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

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

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

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

415
    virDomainFree(dom);
416 417 418
    return TRUE;
}

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

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

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

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

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

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

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

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

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

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

483 484
#ifndef __MINGW32__

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

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

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

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

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

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

533 534 535 536 537
#else /* __MINGW32__ */

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

#endif /* __MINGW32__ */

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

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

K
Karel Zak 已提交
560 561

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 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 821 822
/* "domblkstat" command
 */
static vshCmdInfo info_domblkstat[] = {
    {"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}
};

static vshCmdOptDef opts_domblkstat[] = {
    {"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
cmdDomblkstat (vshControl *ctl, vshCmd *cmd)
{
    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
 */
static vshCmdInfo info_domifstat[] = {
    {"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}
};

static vshCmdOptDef opts_domifstat[] = {
    {"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
cmdDomIfstat (vshControl *ctl, vshCmd *cmd)
{
    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;
}

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

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

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

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

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

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

858 859 860 861
    virDomainFree(dom);
    return ret;
}

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

static vshCmdOptDef opts_create[] = {
873
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
874 875 876 877 878 879 880 881 882 883
    {NULL, 0, 0, NULL}
};

static int
cmdCreate(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
884
    char *buffer;
885 886 887 888 889 890 891 892

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

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

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

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

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

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

static vshCmdOptDef opts_define[] = {
921
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML domain description")},
922 923 924 925 926 927 928 929 930 931
    {NULL, 0, 0, NULL}
};

static int
cmdDefine(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    char *from;
    int found;
    int ret = TRUE;
932
    char *buffer;
933 934 935 936 937 938 939 940

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

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

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

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

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

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

static vshCmdOptDef opts_undefine[] = {
969
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    {NULL, 0, 0, NULL}
};

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

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

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

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

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


/*
 * "start" command
 */
static vshCmdInfo info_start[] = {
1002
    {"syntax", "start <domain>"},
1003 1004
    {"help", gettext_noop("start a (previously defined) inactive domain")},
    {"desc", gettext_noop("Start a domain.")},
1005 1006 1007 1008
    {NULL, NULL}
};

static vshCmdOptDef opts_start[] = {
1009
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("name of the inactive domain")},
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    {NULL, 0, 0, NULL}
};

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

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

1022
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
1023 1024 1025
        return FALSE;

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

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

1043 1044 1045 1046
/*
 * "save" command
 */
static vshCmdInfo info_save[] = {
1047
    {"syntax", "save <domain> <file>"},
1048 1049
    {"help", gettext_noop("save a domain state to a file")},
    {"desc", gettext_noop("Save a running domain.")},
1050
    {NULL, NULL}
1051 1052 1053
};

static vshCmdOptDef opts_save[] = {
1054 1055
    {"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")},
1056
    {NULL, 0, 0, NULL}
1057 1058 1059
};

static int
1060 1061
cmdSave(vshControl * ctl, vshCmd * cmd)
{
1062 1063 1064 1065
    virDomainPtr dom;
    char *name;
    char *to;
    int ret = TRUE;
1066

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

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

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

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

1083 1084 1085 1086
    virDomainFree(dom);
    return ret;
}

1087 1088 1089 1090
/*
 * "schedinfo" command
 */
static vshCmdInfo info_schedinfo[] = {
1091
    {"syntax", "schedinfo <domain>"},
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    {"help", gettext_noop("show/set scheduler parameters")},
    {"desc", gettext_noop("Show/Set scheduler parameters.")},
    {NULL, NULL}
};

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

static int
cmdSchedinfo(vshControl * ctl, vshCmd * cmd)
{
    char *schedulertype;
    virDomainPtr dom;
1109
    virSchedParameterPtr params = NULL;
1110 1111 1112 1113 1114
    int i, ret;
    int nparams = 0;
    int nr_inputparams = 0;
    int inputparams = 0;
    int weightfound = 0;
1115
    int weight = 0;
1116
    int capfound = 0;
1117
    int cap = 0;
1118 1119
    char str_weight[] = "weight";
    char str_cap[]    = "cap";
1120
    int ret_val = FALSE;
1121 1122 1123 1124 1125 1126 1127 1128

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

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

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

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

    params = vshMalloc(ctl, sizeof (virSchedParameter) * nr_inputparams);
1150
    if (params == NULL) {
1151
        goto cleanup;
1152
    }
1153 1154 1155 1156 1157

    if (weightfound) {
         strncpy(params[inputparams].field,str_weight,sizeof(str_weight));
         params[inputparams].type = VIR_DOMAIN_SCHED_FIELD_UINT;
         params[inputparams].value.ui = weight;
1158
         inputparams++;
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    }

    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);
1174
        if (ret == -1) {
1175
            goto cleanup;
1176
        }
1177 1178
    }
    free(params);
1179
    params = NULL;
1180 1181 1182 1183

    /* Print SchedulerType */
    schedulertype = virDomainGetSchedulerType(dom, &nparams);
    if (schedulertype!= NULL){
1184
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"),
1185 1186 1187
             schedulertype);
        free(schedulertype);
    } else {
1188
        vshPrint(ctl, "%-15s: %s\n", _("Scheduler"), _("Unknown"));
1189
        goto cleanup;
1190 1191 1192 1193
    }

    /* Get SchedulerParameters */
    params = vshMalloc(ctl, sizeof(virSchedParameter)* nparams);
1194 1195 1196
    if (params == NULL) {
        goto cleanup;
    }
1197 1198 1199 1200 1201
    for (i = 0; i < nparams; i++){
        params[i].type = 0;
        memset (params[i].field, 0, sizeof params[i].field);
    }
    ret = virDomainGetSchedulerParameters(dom, params, &nparams);
1202
    if (ret == -1) {
1203
        goto cleanup;
1204
    }
1205
    ret_val = TRUE;
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    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");
            }
        }
    }
1232
 cleanup:
1233
    free(params);
1234
    virDomainFree(dom);
1235
    return ret_val;
1236 1237
}

1238 1239 1240 1241
/*
 * "restore" command
 */
static vshCmdInfo info_restore[] = {
1242
    {"syntax", "restore a domain from <file>"},
1243 1244
    {"help", gettext_noop("restore a domain from a saved state in a file")},
    {"desc", gettext_noop("Restore a domain.")},
1245
    {NULL, NULL}
1246 1247 1248
};

static vshCmdOptDef opts_restore[] = {
1249
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("the state to restore")},
1250
    {NULL, 0, 0, NULL}
1251 1252 1253
};

static int
1254 1255
cmdRestore(vshControl * ctl, vshCmd * cmd)
{
1256 1257 1258
    char *from;
    int found;
    int ret = TRUE;
1259

1260 1261 1262 1263 1264 1265
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainRestore(ctl->conn, from) == 0) {
1268
        vshPrint(ctl, _("Domain restored from %s\n"), from);
1269
    } else {
1270
        vshError(ctl, FALSE, _("Failed to restore domain from %s"), from);
1271 1272 1273 1274 1275
        ret = FALSE;
    }
    return ret;
}

D
Daniel Veillard 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
/*
 * "dump" command
 */
static vshCmdInfo info_dump[] = {
    {"syntax", "dump <domain> <file>"},
    {"help", gettext_noop("dump the core of a domain to a file for analysis")},
    {"desc", gettext_noop("Core dump a domain.")},
    {NULL, NULL}
};

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

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

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

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

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

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

    virDomainFree(dom);
    return ret;
}

1321 1322 1323 1324
/*
 * "resume" command
 */
static vshCmdInfo info_resume[] = {
1325
    {"syntax", "resume <domain>"},
1326 1327
    {"help", gettext_noop("resume a domain")},
    {"desc", gettext_noop("Resume a previously suspended domain.")},
1328
    {NULL, NULL}
1329 1330 1331
};

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

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

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

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

    if (virDomainResume(dom) == 0) {
1350
        vshPrint(ctl, _("Domain %s resumed\n"), name);
1351
    } else {
1352
        vshError(ctl, FALSE, _("Failed to resume domain %s"), name);
1353 1354
        ret = FALSE;
    }
1355

1356 1357 1358 1359
    virDomainFree(dom);
    return ret;
}

1360 1361 1362 1363
/*
 * "shutdown" command
 */
static vshCmdInfo info_shutdown[] = {
1364
    {"syntax", "shutdown <domain>"},
1365 1366
    {"help", gettext_noop("gracefully shutdown a domain")},
    {"desc", gettext_noop("Run shutdown in the target domain.")},
1367
    {NULL, NULL}
1368 1369 1370
};

static vshCmdOptDef opts_shutdown[] = {
1371
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1372
    {NULL, 0, 0, NULL}
1373 1374 1375
};

static int
1376 1377
cmdShutdown(vshControl * ctl, vshCmd * cmd)
{
1378 1379 1380
    virDomainPtr dom;
    int ret = TRUE;
    char *name;
1381

1382 1383 1384 1385 1386
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

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

    if (virDomainShutdown(dom) == 0) {
1389
        vshPrint(ctl, _("Domain %s is being shutdown\n"), name);
1390
    } else {
1391
        vshError(ctl, FALSE, _("Failed to shutdown domain %s"), name);
1392 1393
        ret = FALSE;
    }
1394

1395 1396 1397 1398
    virDomainFree(dom);
    return ret;
}

1399 1400 1401 1402 1403
/*
 * "reboot" command
 */
static vshCmdInfo info_reboot[] = {
    {"syntax", "reboot <domain>"},
1404 1405
    {"help", gettext_noop("reboot a domain")},
    {"desc", gettext_noop("Run a reboot command in the target domain.")},
1406 1407 1408 1409
    {NULL, NULL}
};

static vshCmdOptDef opts_reboot[] = {
1410
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    {NULL, 0, 0, NULL}
};

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

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

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

    if (virDomainReboot(dom, 0) == 0) {
1428
        vshPrint(ctl, _("Domain %s is being rebooted\n"), name);
1429
    } else {
1430
        vshError(ctl, FALSE, _("Failed to reboot domain %s"), name);
1431 1432 1433 1434 1435 1436 1437
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1438 1439 1440 1441
/*
 * "destroy" command
 */
static vshCmdInfo info_destroy[] = {
1442
    {"syntax", "destroy <domain>"},
1443 1444
    {"help", gettext_noop("destroy a domain")},
    {"desc", gettext_noop("Destroy a given domain.")},
1445
    {NULL, NULL}
1446 1447 1448
};

static vshCmdOptDef opts_destroy[] = {
1449
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1450
    {NULL, 0, 0, NULL}
1451 1452 1453
};

static int
1454 1455
cmdDestroy(vshControl * ctl, vshCmd * cmd)
{
1456
    virDomainPtr dom;
K
Karel Zak 已提交
1457 1458
    int ret = TRUE;
    char *name;
1459

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

K
Karel Zak 已提交
1463
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", &name)))
1464
        return FALSE;
1465 1466

    if (virDomainDestroy(dom) == 0) {
1467
        vshPrint(ctl, _("Domain %s destroyed\n"), name);
1468
    } else {
1469
        vshError(ctl, FALSE, _("Failed to destroy domain %s"), name);
1470 1471 1472
        ret = FALSE;
        virDomainFree(dom);
    }
1473

K
Karel Zak 已提交
1474 1475 1476 1477
    return ret;
}

/*
1478
 * "dominfo" command
K
Karel Zak 已提交
1479
 */
1480 1481
static vshCmdInfo info_dominfo[] = {
    {"syntax", "dominfo <domain>"},
1482 1483
    {"help", gettext_noop("domain information")},
    {"desc", gettext_noop("Returns basic information about the domain.")},
1484
    {NULL, NULL}
K
Karel Zak 已提交
1485 1486
};

1487
static vshCmdOptDef opts_dominfo[] = {
1488
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1489
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
1490 1491 1492
};

static int
1493
cmdDominfo(vshControl * ctl, vshCmd * cmd)
1494
{
K
Karel Zak 已提交
1495 1496
    virDomainInfo info;
    virDomainPtr dom;
K
Karel Zak 已提交
1497
    int ret = TRUE;
1498
    unsigned int id;
1499
    char *str, uuid[VIR_UUID_STRING_BUFLEN];
1500

K
Karel Zak 已提交
1501 1502 1503
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

K
Karel Zak 已提交
1504
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
K
Karel Zak 已提交
1505
        return FALSE;
1506

1507 1508
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
1509
        vshPrint(ctl, "%-15s %s\n", _("Id:"), "-");
1510
    else
1511
        vshPrint(ctl, "%-15s %d\n", _("Id:"), id);
1512 1513
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virDomainGetName(dom));

K
Karel Zak 已提交
1514
    if (virDomainGetUUIDString(dom, &uuid[0])==0)
1515
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);
1516 1517

    if ((str = virDomainGetOSType(dom))) {
1518
        vshPrint(ctl, "%-15s %s\n", _("OS Type:"), str);
1519 1520 1521 1522
        free(str);
    }

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

1526
        vshPrint(ctl, "%-15s %d\n", _("CPU(s):"), info.nrVirtCpu);
1527 1528

        if (info.cpuTime != 0) {
1529
            double cpuUsed = info.cpuTime;
1530

1531
            cpuUsed /= 1000000000.0;
1532

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

1536 1537
        if (info.maxMem != UINT_MAX)
            vshPrint(ctl, "%-15s %lu kB\n", _("Max memory:"),
1538
                 info.maxMem);
1539 1540 1541 1542
        else
            vshPrint(ctl, "%-15s %-15s\n", _("Max memory:"),
                 _("no limit"));

1543
        vshPrint(ctl, "%-15s %lu kB\n", _("Used memory:"),
1544 1545
                 info.memory);

K
Karel Zak 已提交
1546 1547 1548
    } else {
        ret = FALSE;
    }
1549

1550
    virDomainFree(dom);
K
Karel Zak 已提交
1551 1552 1553
    return ret;
}

1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
/*
 * "freecell" command
 */
static vshCmdInfo info_freecell[] = {
    {"syntax", "freecell [<cellno>]"},
    {"help", gettext_noop("NUMA free memory")},
    {"desc", gettext_noop("display available free memory for the NUMA cell.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_freecell[] = {
    {"cellno", VSH_OT_DATA, 0, gettext_noop("NUMA cell number")},
    {NULL, 0, 0, NULL}
};

static int
cmdFreecell(vshControl * ctl, vshCmd * cmd)
{
    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) {
1581 1582
        memory = virNodeGetFreeMemory(ctl->conn);
    } else {
1583 1584 1585
        ret = virNodeGetCellsFreeMemory(ctl->conn, &memory, cell, 1);
        if (ret != 1)
            return FALSE;
1586 1587 1588
    }

    if (cell == -1)
1589
        vshPrint(ctl, "%s: %llu kB\n", _("Total"), memory);
1590
    else
1591
        vshPrint(ctl, "%d: %llu kB\n", cell, memory);
1592 1593 1594 1595

    return TRUE;
}

1596 1597 1598 1599 1600
/*
 * "vcpuinfo" command
 */
static vshCmdInfo info_vcpuinfo[] = {
    {"syntax", "vcpuinfo <domain>"},
1601 1602
    {"help", gettext_noop("domain vcpu information")},
    {"desc", gettext_noop("Returns basic information about the domain virtual CPUs.")},
1603 1604 1605 1606
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpuinfo[] = {
1607
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    {NULL, 0, 0, NULL}
};

static int
cmdVcpuinfo(vshControl * ctl, vshCmd * cmd)
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    virVcpuInfoPtr cpuinfo;
    unsigned char *cpumap;
    int ncpus;
    size_t cpumaplen;
    int ret = TRUE;

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

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

    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
1631
        return FALSE;
1632 1633 1634 1635 1636 1637 1638
    }

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

1639
    cpuinfo = vshMalloc(ctl, sizeof(virVcpuInfo)*info.nrVirtCpu);
1640
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1641
    cpumap = vshMalloc(ctl, info.nrVirtCpu * cpumaplen);
1642

1643 1644 1645
    if ((ncpus = virDomainGetVcpus(dom,
                                   cpuinfo, info.nrVirtCpu,
                                   cpumap, cpumaplen)) >= 0) {
1646
        int n;
1647 1648 1649 1650 1651
        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:"),
1652
                     N_(vshDomainVcpuStateToString(cpuinfo[n].state)));
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
            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");
            }
        }
1669
    } else {
1670
        if (info.state == VIR_DOMAIN_SHUTOFF) {
J
Jim Meyering 已提交
1671
            vshError(ctl, FALSE, "%s",
1672 1673
                 _("Domain shut off, virtual CPUs not present."));
        }
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
        ret = FALSE;
    }

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

/*
 * "vcpupin" command
 */
static vshCmdInfo info_vcpupin[] = {
1687
    {"syntax", "vcpupin <domain> <vcpu> <cpulist>"},
1688 1689
    {"help", gettext_noop("control domain vcpu affinity")},
    {"desc", gettext_noop("Pin domain VCPUs to host physical CPUs.")},
1690 1691 1692 1693
    {NULL, NULL}
};

static vshCmdOptDef opts_vcpupin[] = {
1694 1695 1696
    {"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)")},
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    {NULL, 0, 0, NULL}
};

static int
cmdVcpupin(vshControl * ctl, vshCmd * cmd)
{
    virDomainInfo info;
    virDomainPtr dom;
    virNodeInfo nodeinfo;
    int vcpu;
    char *cpulist;
    int ret = TRUE;
    int vcpufound = 0;
    unsigned char *cpumap;
    int cpumaplen;
1712 1713
    int i;
    enum { expect_num, expect_num_or_comma } state;
1714 1715 1716 1717 1718 1719 1720 1721 1722

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

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

    vcpu = vshCommandOptInt(cmd, "vcpu", &vcpufound);
    if (!vcpufound) {
1723 1724
        vshError(ctl, FALSE, "%s",
                 _("vcpupin: Invalid or missing vCPU number."));
1725 1726 1727 1728 1729
        virDomainFree(dom);
        return FALSE;
    }

    if (!(cpulist = vshCommandOptString(cmd, "cpulist", NULL))) {
1730
        vshError(ctl, FALSE, "%s", _("vcpupin: Missing cpulist"));
1731 1732 1733
        virDomainFree(dom);
        return FALSE;
    }
1734

1735 1736 1737 1738 1739 1740
    if (virNodeGetInfo(ctl->conn, &nodeinfo) != 0) {
        virDomainFree(dom);
        return FALSE;
    }

    if (virDomainGetInfo(dom, &info) != 0) {
D
Daniel Veillard 已提交
1741
        vshError(ctl, FALSE, "%s",
1742
                 _("vcpupin: failed to get domain informations."));
1743 1744 1745 1746 1747
        virDomainFree(dom);
        return FALSE;
    }

    if (vcpu >= info.nrVirtCpu) {
J
Jim Meyering 已提交
1748
        vshError(ctl, FALSE, "%s", _("vcpupin: Invalid vCPU number."));
1749 1750 1751 1752
        virDomainFree(dom);
        return FALSE;
    }

1753 1754 1755 1756
    /* 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 已提交
1757
        vshError(ctl, FALSE, "%s", _("cpulist: Invalid format. Empty string."));
1758 1759 1760 1761 1762 1763 1764 1765
        virDomainFree (dom);
        return FALSE;
    }

    state = expect_num;
    for (i = 0; cpulist[i]; i++) {
        switch (state) {
        case expect_num:
1766
          if (!isdigit (to_uchar(cpulist[i]))) {
1767 1768 1769 1770 1771 1772 1773 1774 1775
                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;
1776
            else if (!isdigit (to_uchar(cpulist[i]))) {
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
                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;
    }

1789
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
1790
    cpumap = vshCalloc(ctl, 1, cpumaplen);
1791 1792 1793 1794 1795 1796

    do {
        unsigned int cpu = atoi(cpulist);

        if (cpu < VIR_NODEINFO_MAXCPUS(nodeinfo)) {
            VIR_USE_CPU(cpumap, cpu);
1797 1798 1799 1800 1801
        } else {
            vshError(ctl, FALSE, _("Physical CPU %d doesn't exist."), cpu);
            free(cpumap);
            virDomainFree(dom);
            return FALSE;
1802
        }
1803
        cpulist = strchr(cpulist, ',');
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
        if (cpulist)
            cpulist++;
    } while (cpulist);

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

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

1817 1818 1819 1820 1821
/*
 * "setvcpus" command
 */
static vshCmdInfo info_setvcpus[] = {
    {"syntax", "setvcpus <domain> <count>"},
1822
    {"help", gettext_noop("change number of virtual CPUs")},
1823
    {"desc", gettext_noop("Change the number of virtual CPUs in the guest domain.")},
1824 1825 1826 1827
    {NULL, NULL}
};

static vshCmdOptDef opts_setvcpus[] = {
1828 1829
    {"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")},
1830 1831 1832 1833 1834 1835 1836 1837
    {NULL, 0, 0, NULL}
};

static int
cmdSetvcpus(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
    int count;
1838
    int maxcpu;
1839 1840 1841 1842 1843 1844 1845 1846 1847
    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);
1848
    if (count <= 0) {
J
Jim Meyering 已提交
1849
        vshError(ctl, FALSE, "%s", _("Invalid number of virtual CPUs."));
1850 1851 1852 1853
        virDomainFree(dom);
        return FALSE;
    }

1854
    maxcpu = virDomainGetMaxVcpus(dom);
1855
    if (maxcpu <= 0) {
1856 1857 1858 1859 1860
        virDomainFree(dom);
        return FALSE;
    }

    if (count > maxcpu) {
J
Jim Meyering 已提交
1861
        vshError(ctl, FALSE, "%s", _("Too many virtual CPUs."));
1862 1863 1864 1865
        virDomainFree(dom);
        return FALSE;
    }

1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
    if (virDomainSetVcpus(dom, count) != 0) {
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmemory" command
 */
static vshCmdInfo info_setmem[] = {
1878
    {"syntax", "setmem <domain> <kilobytes>"},
1879 1880
    {"help", gettext_noop("change memory allocation")},
    {"desc", gettext_noop("Change the current memory allocation in the guest domain.")},
1881 1882 1883 1884
    {NULL, NULL}
};

static vshCmdOptDef opts_setmem[] = {
1885
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1886
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("number of kilobytes of memory")},
1887 1888 1889 1890 1891 1892 1893
    {NULL, 0, 0, NULL}
};

static int
cmdSetmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
1894
    virDomainInfo info;
1895
    int kilobytes;
1896 1897 1898 1899 1900 1901 1902 1903
    int ret = TRUE;

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

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

1904 1905
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1906
        virDomainFree(dom);
1907
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1908 1909 1910
        return FALSE;
    }

1911 1912
    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
J
Jim Meyering 已提交
1913
        vshError(ctl, FALSE, "%s", _("Unable to verify MaxMemorySize"));
1914 1915 1916 1917 1918 1919 1920 1921 1922
        return FALSE;
    }

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

1923
    if (virDomainSetMemory(dom, kilobytes) != 0) {
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

/*
 * "setmaxmem" command
 */
static vshCmdInfo info_setmaxmem[] = {
1935
    {"syntax", "setmaxmem <domain> <kilobytes>"},
1936 1937
    {"help", gettext_noop("change maximum memory limit")},
    {"desc", gettext_noop("Change the maximum memory allocation limit in the guest domain.")},
1938 1939 1940 1941
    {NULL, NULL}
};

static vshCmdOptDef opts_setmaxmem[] = {
1942
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
1943
    {"kilobytes", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("maximum memory limit in kilobytes")},
1944 1945 1946 1947 1948 1949 1950
    {NULL, 0, 0, NULL}
};

static int
cmdSetmaxmem(vshControl * ctl, vshCmd * cmd)
{
    virDomainPtr dom;
1951
    virDomainInfo info;
1952
    int kilobytes;
1953 1954 1955 1956 1957 1958 1959 1960
    int ret = TRUE;

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

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

1961 1962
    kilobytes = vshCommandOptInt(cmd, "kilobytes", &kilobytes);
    if (kilobytes <= 0) {
1963
        virDomainFree(dom);
1964
        vshError(ctl, FALSE, _("Invalid value of %d for memory size"), kilobytes);
1965 1966 1967
        return FALSE;
    }

1968 1969
    if (virDomainGetInfo(dom, &info) != 0) {
        virDomainFree(dom);
J
Jim Meyering 已提交
1970
        vshError(ctl, FALSE, "%s", _("Unable to verify current MemorySize"));
1971 1972 1973 1974 1975 1976
        return FALSE;
    }

    if (kilobytes < info.memory) {
        if (virDomainSetMemory(dom, kilobytes) != 0) {
            virDomainFree(dom);
J
Jim Meyering 已提交
1977
            vshError(ctl, FALSE, "%s", _("Unable to shrink current MemorySize"));
1978 1979 1980 1981
            return FALSE;
        }
    }

1982
    if (virDomainSetMaxMemory(dom, kilobytes) != 0) {
J
Jim Meyering 已提交
1983
        vshError(ctl, FALSE, "%s", _("Unable to change MaxMemorySize"));
1984 1985 1986 1987 1988 1989 1990
        ret = FALSE;
    }

    virDomainFree(dom);
    return ret;
}

1991 1992 1993 1994 1995
/*
 * "nodeinfo" command
 */
static vshCmdInfo info_nodeinfo[] = {
    {"syntax", "nodeinfo"},
1996 1997
    {"help", gettext_noop("node information")},
    {"desc", gettext_noop("Returns basic information about the node.")},
1998 1999 2000 2001 2002 2003 2004
    {NULL, NULL}
};

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

2006 2007 2008 2009
    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;

    if (virNodeGetInfo(ctl->conn, &info) < 0) {
J
Jim Meyering 已提交
2010
        vshError(ctl, FALSE, "%s", _("failed to get node information"));
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
        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);

2022 2023 2024
    return TRUE;
}

2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
/*
 * "capabilities" command
 */
static vshCmdInfo info_capabilities[] = {
    {"syntax", "capabilities"},
    {"help", gettext_noop("capabilities")},
    {"desc", gettext_noop("Returns capabilities of hypervisor/driver.")},
    {NULL, NULL}
};

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

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

    if ((caps = virConnectGetCapabilities (ctl->conn)) == NULL) {
J
Jim Meyering 已提交
2044
        vshError(ctl, FALSE, "%s", _("failed to get capabilities"));
2045 2046 2047
        return FALSE;
    }
    vshPrint (ctl, "%s\n", caps);
2048
    free (caps);
2049 2050 2051 2052

    return TRUE;
}

2053 2054 2055 2056
/*
 * "dumpxml" command
 */
static vshCmdInfo info_dumpxml[] = {
2057
    {"syntax", "dumpxml <domain>"},
2058
    {"help", gettext_noop("domain information in XML")},
2059
    {"desc", gettext_noop("Output the domain information as an XML dump to stdout.")},
2060
    {NULL, NULL}
2061 2062 2063
};

static vshCmdOptDef opts_dumpxml[] = {
2064
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
2065
    {NULL, 0, 0, NULL}
2066 2067 2068
};

static int
2069 2070
cmdDumpXML(vshControl * ctl, vshCmd * cmd)
{
2071
    virDomainPtr dom;
K
Karel Zak 已提交
2072
    int ret = TRUE;
2073
    char *dump;
2074

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

K
Karel Zak 已提交
2078
    if (!(dom = vshCommandOptDomain(ctl, cmd, "domain", NULL)))
2079
        return FALSE;
2080

2081 2082 2083 2084 2085 2086 2087
    dump = virDomainGetXMLDesc(dom, 0);
    if (dump != NULL) {
        printf("%s", dump);
        free(dump);
    } else {
        ret = FALSE;
    }
2088

2089 2090 2091 2092
    virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
2093
/*
K
Karel Zak 已提交
2094
 * "domname" command
K
Karel Zak 已提交
2095
 */
K
Karel Zak 已提交
2096
static vshCmdInfo info_domname[] = {
K
Karel Zak 已提交
2097
    {"syntax", "domname <domain>"},
2098
    {"help", gettext_noop("convert a domain id or UUID to domain name")},
2099
    {NULL, NULL}
K
Karel Zak 已提交
2100 2101
};

K
Karel Zak 已提交
2102
static vshCmdOptDef opts_domname[] = {
2103
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or uuid")},
2104
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
2105 2106 2107
};

static int
K
Karel Zak 已提交
2108
cmdDomname(vshControl * ctl, vshCmd * cmd)
2109
{
K
Karel Zak 已提交
2110 2111 2112 2113
    virDomainPtr dom;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
2114
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
2115
                                      VSH_BYID|VSH_BYUUID)))
K
Karel Zak 已提交
2116
        return FALSE;
2117

K
Karel Zak 已提交
2118 2119
    vshPrint(ctl, "%s\n", virDomainGetName(dom));
    virDomainFree(dom);
K
Karel Zak 已提交
2120 2121 2122 2123
    return TRUE;
}

/*
K
Karel Zak 已提交
2124
 * "domid" command
K
Karel Zak 已提交
2125
 */
K
Karel Zak 已提交
2126
static vshCmdInfo info_domid[] = {
K
Karel Zak 已提交
2127
    {"syntax", "domid <domain>"},
2128
    {"help", gettext_noop("convert a domain name or UUID to domain id")},
2129
    {NULL, NULL}
K
Karel Zak 已提交
2130 2131
};

K
Karel Zak 已提交
2132
static vshCmdOptDef opts_domid[] = {
2133
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name or uuid")},
2134
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
2135 2136 2137
};

static int
K
Karel Zak 已提交
2138
cmdDomid(vshControl * ctl, vshCmd * cmd)
2139
{
2140
    virDomainPtr dom;
2141
    unsigned int id;
K
Karel Zak 已提交
2142 2143 2144

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
2145
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
2146
                                      VSH_BYNAME|VSH_BYUUID)))
K
Karel Zak 已提交
2147
        return FALSE;
2148

2149 2150
    id = virDomainGetID(dom);
    if (id == ((unsigned int)-1))
2151
        vshPrint(ctl, "%s\n", "-");
2152
    else
2153
        vshPrint(ctl, "%d\n", id);
K
Karel Zak 已提交
2154 2155 2156
    virDomainFree(dom);
    return TRUE;
}
2157

K
Karel Zak 已提交
2158 2159 2160 2161 2162
/*
 * "domuuid" command
 */
static vshCmdInfo info_domuuid[] = {
    {"syntax", "domuuid <domain>"},
2163
    {"help", gettext_noop("convert a domain name or id to domain UUID")},
K
Karel Zak 已提交
2164 2165 2166 2167
    {NULL, NULL}
};

static vshCmdOptDef opts_domuuid[] = {
2168
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain id or name")},
K
Karel Zak 已提交
2169 2170 2171 2172 2173 2174 2175
    {NULL, 0, 0, NULL}
};

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

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
K
Karel Zak 已提交
2179
        return FALSE;
2180
    if (!(dom = vshCommandOptDomainBy(ctl, cmd, "domain", NULL,
2181
                                      VSH_BYNAME|VSH_BYID)))
K
Karel Zak 已提交
2182
        return FALSE;
2183

K
Karel Zak 已提交
2184 2185 2186
    if (virDomainGetUUIDString(dom, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
J
Jim Meyering 已提交
2187
        vshError(ctl, FALSE, "%s", _("failed to get domain UUID"));
2188

2189
    virDomainFree(dom);
K
Karel Zak 已提交
2190 2191 2192
    return TRUE;
}

2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
/*
 * "migrate" command
 */
static vshCmdInfo info_migrate[] = {
    {"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}
};

static vshCmdOptDef opts_migrate[] = {
    {"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
cmdMigrate (vshControl *ctl, vshCmd *cmd)
{
    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 已提交
2229
        vshError (ctl, FALSE, "%s", _("migrate: Missing desturi"));
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
        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;
}

2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
/*
 * "net-autostart" command
 */
static vshCmdInfo info_network_autostart[] = {
    {"syntax", "net-autostart [--disable] <network>"},
    {"help", gettext_noop("autostart a network")},
    {"desc",
     gettext_noop("Configure a network to be automatically started at boot.")},
    {NULL, NULL}
};

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

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

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

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

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

    if (virNetworkSetAutostart(network, autostart) < 0) {
2289
        if (autostart)
2290
            vshError(ctl, FALSE, _("failed to mark network %s as autostarted"),
2291
                                   name);
2292 2293
        else
            vshError(ctl, FALSE,_("failed to unmark network %s as autostarted"),
2294
                                   name);
2295 2296 2297 2298
        virNetworkFree(network);
        return FALSE;
    }

2299
    if (autostart)
2300
        vshPrint(ctl, _("Network %s marked as autostarted\n"), name);
2301
    else
2302
        vshPrint(ctl, _("Network %s unmarked as autostarted\n"), name);
2303 2304 2305

    return TRUE;
}
K
Karel Zak 已提交
2306

2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
/*
 * "net-create" command
 */
static vshCmdInfo info_network_create[] = {
    {"syntax", "create a network from an XML <file>"},
    {"help", gettext_noop("create a network from an XML file")},
    {"desc", gettext_noop("Create a network.")},
    {NULL, NULL}
};

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

static int
cmdNetworkCreate(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
2329
    char *buffer;
2330 2331 2332 2333 2334 2335 2336 2337

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

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

2338 2339
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2340 2341 2342 2343

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

2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
    if (network != NULL) {
        vshPrint(ctl, _("Network %s created from %s\n"),
                 virNetworkGetName(network), from);
    } else {
        vshError(ctl, FALSE, _("Failed to create network from %s"), from);
        ret = FALSE;
    }
    return ret;
}


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

static vshCmdOptDef opts_network_define[] = {
2366
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML network description")},
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
    {NULL, 0, 0, NULL}
};

static int
cmdNetworkDefine(vshControl * ctl, vshCmd * cmd)
{
    virNetworkPtr network;
    char *from;
    int found;
    int ret = TRUE;
2377
    char *buffer;
2378 2379 2380 2381 2382 2383 2384 2385

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

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

2386 2387
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2388 2389 2390 2391

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

2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
    if (network != NULL) {
        vshPrint(ctl, _("Network %s defined from %s\n"),
                 virNetworkGetName(network), from);
    } else {
        vshError(ctl, FALSE, _("Failed to define network from %s"), from);
        ret = FALSE;
    }
    return ret;
}


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

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

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

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

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

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

    return ret;
}


/*
 * "net-dumpxml" command
 */
static vshCmdInfo info_network_dumpxml[] = {
2447
    {"syntax", "net-dumpxml <network>"},
2448
    {"help", gettext_noop("network information in XML")},
2449
    {"desc", gettext_noop("Output the network information as an XML dump to stdout.")},
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
    {NULL, NULL}
};

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

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

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

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

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

    virNetworkFree(network);
    return ret;
}


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

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

static int
cmdNetworkList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int maxactive = 0, maxinactive = 0, i;
2507
    char **activeNames = NULL, **inactiveNames = NULL;
2508 2509 2510 2511 2512 2513
    inactive |= all;

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

    if (active) {
2514 2515
        maxactive = virConnectNumOfNetworks(ctl->conn);
        if (maxactive < 0) {
J
Jim Meyering 已提交
2516
            vshError(ctl, FALSE, "%s", _("Failed to list active networks"));
2517
            return FALSE;
2518
        }
2519
        if (maxactive) {
2520
            activeNames = vshMalloc(ctl, sizeof(char *) * maxactive);
2521

2522
            if ((maxactive = virConnectListNetworks(ctl->conn, activeNames,
2523
                                                    maxactive)) < 0) {
J
Jim Meyering 已提交
2524
                vshError(ctl, FALSE, "%s", _("Failed to list active networks"));
2525 2526 2527
                free(activeNames);
                return FALSE;
            }
2528

2529
            qsort(&activeNames[0], maxactive, sizeof(char *), namesorter);
2530
        }
2531 2532
    }
    if (inactive) {
2533 2534
        maxinactive = virConnectNumOfDefinedNetworks(ctl->conn);
        if (maxinactive < 0) {
J
Jim Meyering 已提交
2535
            vshError(ctl, FALSE, "%s", _("Failed to list inactive networks"));
2536
            free(activeNames);
2537
            return FALSE;
2538
        }
2539 2540 2541 2542
        if (maxinactive) {
            inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive);

            if ((maxinactive = virConnectListDefinedNetworks(ctl->conn, inactiveNames, maxinactive)) < 0) {
J
Jim Meyering 已提交
2543
                vshError(ctl, FALSE, "%s", _("Failed to list inactive networks"));
2544
                free(activeNames);
2545 2546 2547
                free(inactiveNames);
                return FALSE;
            }
2548

2549 2550
            qsort(&inactiveNames[0], maxinactive, sizeof(char*), namesorter);
        }
2551
    }
2552 2553
    vshPrintExtra(ctl, "%-20s %-10s %-10s\n", _("Name"), _("State"), _("Autostart"));
    vshPrintExtra(ctl, "-----------------------------------------\n");
2554 2555 2556

    for (i = 0; i < maxactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, activeNames[i]);
2557 2558
        const char *autostartStr;
        int autostart = 0;
2559 2560 2561 2562 2563

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

2566 2567 2568 2569 2570 2571 2572 2573 2574
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

        vshPrint(ctl, "%-20s %-10s %-10s\n",
                 virNetworkGetName(network),
                 _("active"),
                 autostartStr);
2575 2576 2577 2578 2579
        virNetworkFree(network);
        free(activeNames[i]);
    }
    for (i = 0; i < maxinactive; i++) {
        virNetworkPtr network = virNetworkLookupByName(ctl->conn, inactiveNames[i]);
2580 2581
        const char *autostartStr;
        int autostart = 0;
2582 2583 2584 2585 2586

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

2589 2590 2591 2592 2593 2594 2595 2596 2597
        if (virNetworkGetAutostart(network, &autostart) < 0)
            autostartStr = _("no autostart");
        else
            autostartStr = autostart ? "yes" : "no";

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

        virNetworkFree(network);
        free(inactiveNames[i]);
    }
2602 2603
    free(activeNames);
    free(inactiveNames);
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
    return TRUE;
}


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

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

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

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "network", NULL,
2630
                                           VSH_BYUUID)))
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
        return FALSE;

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


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

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

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

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

2663 2664
    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "name", NULL, VSH_BYNAME)))
         return FALSE;
2665 2666 2667

    if (virNetworkCreate(network) == 0) {
        vshPrint(ctl, _("Network %s started\n"),
2668
                 virNetworkGetName(network));
2669
    } else {
2670 2671
        vshError(ctl, FALSE, _("Failed to start network %s"),
                 virNetworkGetName(network));
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 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 2738 2739 2740
        ret = FALSE;
    }
    return ret;
}


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

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

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

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

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

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

    return ret;
}


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

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

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

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

    if (!(network = vshCommandOptNetworkBy(ctl, cmd, "network", NULL,
2741
                                           VSH_BYNAME)))
2742 2743 2744 2745 2746
        return FALSE;

    if (virNetworkGetUUIDString(network, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
J
Jim Meyering 已提交
2747
        vshError(ctl, FALSE, "%s", _("failed to get network UUID"));
2748 2749 2750 2751 2752

    return TRUE;
}


2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763











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

2775 2776 2777 2778 2779
static vshCmdOptDef opts_pool_autostart[] = {
    {"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}
};
2780 2781

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

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

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

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

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

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

    return TRUE;
}

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

2825 2826 2827 2828 2829
static vshCmdOptDef opts_pool_create[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML pool description")},
    {NULL, 0, 0, NULL}
};

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

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

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

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

2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
    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;
2860 2861
}

2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
/*
 * "pool-create-as" command
 */
static vshCmdInfo info_pool_create_as[] = {
    {"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}
};

static vshCmdOptDef opts_pool_create_as[] = {
    {"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
cmdPoolCreateAs(vshControl * ctl, vshCmd * cmd)
{
    virStoragePoolPtr pool;
    int found;
2888
    char *xml;
2889
    char *name, *type, *srcHost, *srcPath, *srcDev, *target;
2890
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906

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

2907 2908
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf, "  <name>%s</name>\n", name);
2909
    if (srcHost || srcPath || srcDev) {
2910 2911 2912
        virBufferAddLit(&buf, "  <source>\n");
        if (srcHost)
            virBufferVSprintf(&buf, "    <host name='%s'>\n", srcHost);
2913

2914 2915 2916 2917 2918 2919 2920
        if (srcPath)
            virBufferVSprintf(&buf, "    <dir path='%s'/>\n", srcPath);

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

        virBufferAddLit(&buf, "  </source>\n");
2921 2922
    }
    if (target) {
2923 2924 2925
        virBufferAddLit(&buf, "  <target>\n");
        virBufferVSprintf(&buf, "    <path>%s</path>\n", target);
        virBufferAddLit(&buf, "  </target>\n");
2926
    }
2927 2928 2929 2930 2931 2932 2933
    virBufferAddLit(&buf, "</pool>\n");

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

2935 2936
    pool = virStoragePoolCreateXML(ctl->conn, xml, 0);
    free (xml);
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947

    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:
2948
    free(virBufferContentAndReset(&buf));
2949 2950 2951
    return FALSE;
}

2952

2953
/*
2954
 * "pool-define" command
2955
 */
2956 2957 2958 2959
static vshCmdInfo info_pool_define[] = {
    {"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.")},
2960 2961 2962
    {NULL, NULL}
};

2963 2964 2965 2966 2967
static vshCmdOptDef opts_pool_define[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("file containing an XML pool description")},
    {NULL, 0, 0, NULL}
};

2968
static int
2969
cmdPoolDefine(vshControl * ctl, vshCmd * cmd)
2970
{
2971 2972 2973 2974 2975
    virStoragePoolPtr pool;
    char *from;
    int found;
    int ret = TRUE;
    char *buffer;
2976 2977 2978 2979

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

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

2984 2985
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
        return FALSE;
2986

2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
    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;
2998 2999
}

3000

3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026
/*
 * "pool-define-as" command
 */
static vshCmdInfo info_pool_define_as[] = {
    {"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}
};

static vshCmdOptDef opts_pool_define_as[] = {
    {"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
cmdPoolDefineAs(vshControl * ctl, vshCmd * cmd)
{
    virStoragePoolPtr pool;
    int found;
3027
    char *xml;
3028
    char *name, *type, *srcHost, *srcPath, *srcDev, *target;
3029
    virBuffer buf = VIR_BUFFER_INITIALIZER;
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045

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

3046 3047
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf, "  <name>%s</name>\n", name);
3048
    if (srcHost || srcPath || srcDev) {
3049 3050 3051 3052 3053 3054 3055
        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);
3056

3057
        virBufferAddLit(&buf, "  </source>\n");
3058 3059
    }
    if (target) {
3060 3061 3062
        virBufferAddLit(&buf, "  <target>\n");
        virBufferVSprintf(&buf, "    <path>%s</path>\n", target);
        virBufferAddLit(&buf, "  </target>\n");
3063
    }
3064
    virBufferAddLit(&buf, "</pool>\n");
3065

3066 3067 3068 3069 3070 3071 3072 3073 3074

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

    pool = virStoragePoolDefineXML(ctl->conn, xml, 0);
    free (xml);
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085

    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:
3086
    free(virBufferContentAndReset(&buf));
3087 3088 3089 3090
    return FALSE;
}


3091
/*
3092
 * "pool-build" command
3093
 */
3094 3095 3096 3097
static vshCmdInfo info_pool_build[] = {
    {"syntax", "pool-build <pool>"},
    {"help", gettext_noop("build a pool")},
    {"desc", gettext_noop("Build a given pool.")},
3098 3099 3100
    {NULL, NULL}
};

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

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

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

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

3119 3120
    if (virStoragePoolBuild(pool, 0) == 0) {
        vshPrint(ctl, _("Pool %s builded\n"), name);
3121
    } else {
3122 3123 3124
        vshError(ctl, FALSE, _("Failed to build pool %s"), name);
        ret = FALSE;
        virStoragePoolFree(pool);
3125 3126 3127 3128 3129
    }

    return ret;
}

3130

3131
/*
3132
 * "pool-destroy" command
3133
 */
3134 3135 3136 3137
static vshCmdInfo info_pool_destroy[] = {
    {"syntax", "pool-destroy <pool>"},
    {"help", gettext_noop("destroy a pool")},
    {"desc", gettext_noop("Destroy a given pool.")},
3138 3139 3140
    {NULL, NULL}
};

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

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

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

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

3159 3160 3161 3162 3163 3164
    if (virStoragePoolDestroy(pool) == 0) {
        vshPrint(ctl, _("Pool %s destroyed\n"), name);
    } else {
        vshError(ctl, FALSE, _("Failed to destroy pool %s"), name);
        ret = FALSE;
        virStoragePoolFree(pool);
3165 3166 3167 3168 3169
    }

    return ret;
}

3170

3171
/*
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
 * "pool-delete" command
 */
static vshCmdInfo info_pool_delete[] = {
    {"syntax", "pool-delete <pool>"},
    {"help", gettext_noop("delete a pool")},
    {"desc", gettext_noop("Delete a given pool.")},
    {NULL, NULL}
};

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

static int
cmdPoolDelete(vshControl * ctl, vshCmd * cmd)
{
    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 已提交
3200
        vshPrint(ctl, _("Pool %s deleted\n"), name);
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 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 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
    } else {
        vshError(ctl, FALSE, _("Failed to delete pool %s"), name);
        ret = FALSE;
        virStoragePoolFree(pool);
    }

    return ret;
}


/*
 * "pool-refresh" command
 */
static vshCmdInfo info_pool_refresh[] = {
    {"syntax", "pool-refresh <pool>"},
    {"help", gettext_noop("refresh a pool")},
    {"desc", gettext_noop("Refresh a given pool.")},
    {NULL, NULL}
};

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

static int
cmdPoolRefresh(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_pool_dumpxml[] = {
    {"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}
};

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

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

static vshCmdOptDef opts_pool_list[] = {
    {"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
cmdPoolList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    int inactive = vshCommandOptBool(cmd, "inactive");
    int all = vshCommandOptBool(cmd, "all");
    int active = !inactive || all ? 1 : 0;
    int maxactive = 0, maxinactive = 0, i;
    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
 */
static vshCmdInfo info_pool_info[] = {
    {"syntax", "pool-info <pool>"},
    {"help", gettext_noop("storage pool information")},
    {"desc", gettext_noop("Returns basic information about the storage pool.")},
    {NULL, NULL}
};

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

static int
cmdPoolInfo(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_pool_name[] = {
    {"syntax", "pool-name <pool>"},
    {"help", gettext_noop("convert a pool UUID to pool name")},
    {NULL, NULL}
};

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

static int
cmdPoolName(vshControl * ctl, vshCmd * cmd)
{
    virStoragePoolPtr pool;

    if (!vshConnectionUsability(ctl, ctl->conn, TRUE))
        return FALSE;
    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
3534
                                           VSH_BYUUID)))
3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
        return FALSE;

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


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

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

static int
cmdPoolStart(vshControl * ctl, vshCmd * cmd)
{
    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;
}


3582 3583 3584 3585
/*
 * "vol-create-as" command
 */
static vshCmdInfo info_vol_create_as[] = {
D
Daniel Veillard 已提交
3586 3587
    {"syntax", "vol-create-as <pool> <name> <capacity>"},
    {"help", gettext_noop("create a volume from a set of args")},
3588 3589 3590 3591 3592 3593
    {"desc", gettext_noop("Create a vol.")},
    {NULL, NULL}
};

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

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

3664 3665 3666 3667 3668
    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);
3669 3670

    if (format) {
3671
        virBufferAddLit(&buf, "  <target>\n");
3672
        if (format)
3673 3674
            virBufferVSprintf(&buf, "    <format type='%s'/>\n",format);
        virBufferAddLit(&buf, "  </target>\n");
3675
    }
3676 3677
    virBufferAddLit(&buf, "</volume>\n");

3678

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


3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766
/*
 * "pool-undefine" command
 */
static vshCmdInfo info_pool_undefine[] = {
    {"syntax", "pool-undefine <pool>"},
    {"help", gettext_noop("undefine an inactive pool")},
    {"desc", gettext_noop("Undefine the configuration for an inactive pool.")},
    {NULL, NULL}
};

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

static int
cmdPoolUndefine(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_pool_uuid[] = {
    {"syntax", "pool-uuid <pool>"},
    {"help", gettext_noop("convert a pool name to pool UUID")},
    {NULL, NULL}
};

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

static int
cmdPoolUuid(vshControl * ctl, vshCmd * cmd)
{
    virStoragePoolPtr pool;
    char uuid[VIR_UUID_STRING_BUFLEN];

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

    if (!(pool = vshCommandOptPoolBy(ctl, cmd, "pool", NULL,
3767
                                           VSH_BYNAME)))
3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810
        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
 */
static vshCmdInfo info_vol_create[] = {
    {"syntax", "create <file>"},
    {"help", gettext_noop("create a vol from an XML file")},
    {"desc", gettext_noop("Create a vol.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_vol_create[] = {
    {"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
cmdVolCreate(vshControl * ctl, vshCmd * cmd)
{
    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,
3811
                                           VSH_BYNAME)))
3812 3813 3814 3815 3816 3817 3818 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 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870
        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
 */
static vshCmdInfo info_vol_delete[] = {
    {"syntax", "vol-delete <vol>"},
    {"help", gettext_noop("delete a vol")},
    {"desc", gettext_noop("Delete a given vol.")},
    {NULL, NULL}
};

static vshCmdOptDef opts_vol_delete[] = {
    {"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
cmdVolDelete(vshControl * ctl, vshCmd * cmd)
{
    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 已提交
3871
        vshPrint(ctl, _("Vol %s deleted\n"), name);
3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 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 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 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 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 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 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 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 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 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
    } else {
        vshError(ctl, FALSE, _("Failed to delete vol %s"), name);
        ret = FALSE;
        virStorageVolFree(vol);
    }

    return ret;
}


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

static vshCmdOptDef opts_vol_info[] = {
    {"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
cmdVolInfo(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_vol_dumpxml[] = {
    {"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}
};

static vshCmdOptDef opts_vol_dumpxml[] = {
    {"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
cmdVolDumpXML(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_vol_list[] = {
    {"syntax", "vol-list <pool>"},
    {"help", gettext_noop("list vols")},
    {"desc", gettext_noop("Returns list of vols by pool.")},
    {NULL, NULL}
};

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

static int
cmdVolList(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    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
 */
static vshCmdInfo info_vol_name[] = {
    {"syntax", "vol-name <vol>"},
    {"help", gettext_noop("convert a vol UUID to vol name")},
    {NULL, NULL}
};

static vshCmdOptDef opts_vol_name[] = {
    {"vol", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("vol key or path")},
    {NULL, 0, 0, NULL}
};

static int
cmdVolName(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_vol_key[] = {
    {"syntax", "vol-key <vol>"},
    {"help", gettext_noop("convert a vol UUID to vol key")},
    {NULL, NULL}
};

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

static int
cmdVolKey(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_vol_path[] = {
    {"syntax", "vol-path <pool> <vol>"},
    {"help", gettext_noop("convert a vol UUID to vol path")},
    {NULL, NULL}
};

static vshCmdOptDef opts_vol_path[] = {
    {"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
cmdVolPath(vshControl * ctl, vshCmd * cmd)
{
    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
 */
static vshCmdInfo info_version[] = {
    {"syntax", "version"},
    {"help", gettext_noop("show version")},
    {"desc", gettext_noop("Display the system version information.")},
    {NULL, NULL}
};


static int
cmdVersion(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
    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
 */
static vshCmdInfo info_hostname[] = {
    {"syntax", "hostname"},
    {"help", gettext_noop("print the hypervisor hostname")},
    {NULL, NULL}
};

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

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

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

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

    return TRUE;
}

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

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

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

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

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

    return TRUE;
}

/*
 * "vncdisplay" command
 */
static vshCmdInfo info_vncdisplay[] = {
    {"syntax", "vncdisplay <domain>"},
    {"help", gettext_noop("vnc display")},
    {"desc", gettext_noop("Output the IP address and port number for the VNC display.")},
    {NULL, NULL}
};

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

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

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

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

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

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

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

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

/*
 * "ttyconsole" command
 */
static vshCmdInfo info_ttyconsole[] = {
    {"syntax", "ttyconsole <domain>"},
    {"help", gettext_noop("tty console")},
    {"desc", gettext_noop("Output the device for the TTY console.")},
    {NULL, NULL}
};

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

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

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

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

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

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

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/console/@tty)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        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
4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465
 */
static vshCmdInfo info_attach_device[] = {
    {"syntax", "attach-device <domain> <file> "},
    {"help", gettext_noop("attach device from an XML file")},
    {"desc", gettext_noop("Attach device from an XML <file>.")},
    {NULL, NULL}
};

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

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

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

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

    from = vshCommandOptString(cmd, "file", &found);
    if (!found) {
4466
        vshError(ctl, FALSE, "%s", _("attach-device: Missing <file> option"));
4467 4468 4469 4470
        virDomainFree(dom);
        return FALSE;
    }

4471 4472
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        virDomainFree(dom);
4473
        return FALSE;
4474
    }
4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522

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

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

    virDomainFree(dom);
    return TRUE;
}


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

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

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

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

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

    from = vshCommandOptString(cmd, "file", &found);
    if (!found) {
4523
        vshError(ctl, FALSE, "%s", _("detach-device: Missing <file> option"));
4524 4525 4526 4527
        virDomainFree(dom);
        return FALSE;
    }

4528 4529
    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) {
        virDomainFree(dom);
4530
        return FALSE;
4531
    }
4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545

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

4546

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

static vshCmdOptDef opts_attach_interface[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"type",   VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network interface type")},
    {"source", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("source of network interface")},
    {"target", VSH_OT_DATA, 0, gettext_noop("target network name")},
4562
    {"mac",    VSH_OT_DATA, 0, gettext_noop("MAC address")},
4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 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
    {"script", VSH_OT_DATA, 0, gettext_noop("script used to bridge network interface")},
    {NULL, 0, 0, NULL}
};

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

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

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

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

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

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

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

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

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

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

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

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

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

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
4656 4657
    free(buf);
    free(tmp);
4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673
    return ret;
}

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

static vshCmdOptDef opts_detach_interface[] = {
    {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("domain name, id or uuid")},
    {"type",   VSH_OT_DATA, VSH_OFLAG_REQ, gettext_noop("network interface type")},
4674
    {"mac",    VSH_OT_DATA, 0, gettext_noop("MAC address")},
4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 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
    {NULL, 0, 0, NULL}
};

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

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

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

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

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

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

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

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
J
Jim Meyering 已提交
4758
        vshError(ctl, FALSE, "%s", _("Failed to create XML"));
4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770
        goto cleanup;
    }

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

 cleanup:
    if (dom)
        virDomainFree(dom);
4771
    xmlXPathFreeObject(obj);
4772
    xmlXPathFreeContext(ctxt);
4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 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
    if (xml)
        xmlFreeDoc(xml);
    if (xml_buf)
        xmlBufferFree(xml_buf);
    return ret;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ret = TRUE;

 cleanup:
    if (dom)
        virDomainFree(dom);
4938 4939
    free(buf);
    free(tmp);
4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989
    return ret;
}

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

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

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

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

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

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

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

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

    if(xmlNodeDump(xml_buf, xml, obj->nodesetval->nodeTab[i], 0, 0) < 0){
J
Jim Meyering 已提交
5032
        vshError(ctl, FALSE, "%s", _("Failed to create XML"));
5033 5034 5035 5036 5037 5038 5039 5040 5041 5042
        goto cleanup;
    }

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

 cleanup:
5043
    xmlXPathFreeObject(obj);
5044
    xmlXPathFreeContext(ctxt);
5045 5046 5047 5048 5049 5050 5051 5052 5053
    if (xml)
        xmlFreeDoc(xml);
    if (xml_buf)
        xmlBufferFree(xml_buf);
    if (dom)
        virDomainFree(dom);
    return ret;
}

K
Karel Zak 已提交
5054 5055 5056 5057
/*
 * "quit" command
 */
static vshCmdInfo info_quit[] = {
5058
    {"syntax", "quit"},
5059
    {"help", gettext_noop("quit this interactive terminal")},
5060
    {NULL, NULL}
K
Karel Zak 已提交
5061 5062 5063
};

static int
5064 5065
cmdQuit(vshControl * ctl, vshCmd * cmd ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
5066 5067 5068 5069 5070 5071 5072 5073
    ctl->imode = FALSE;
    return TRUE;
}

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

5102
    {"net-autostart", cmdNetworkAutostart, opts_network_autostart, info_network_autostart},
5103 5104 5105 5106 5107 5108 5109 5110 5111
    {"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 已提交
5112
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo},
5113 5114 5115 5116

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

    {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create},
5148
    {"vol-create-as", cmdVolCreateAs, opts_vol_create_as, info_vol_create_as},
5149 5150 5151 5152 5153 5154 5155 5156
    {"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},

5157 5158
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo},
    {"vcpupin", cmdVcpupin, opts_vcpupin, info_vcpupin},
5159
    {"version", cmdVersion, NULL, info_version},
5160
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay},
5161
    {NULL, NULL, NULL, NULL}
K
Karel Zak 已提交
5162 5163 5164 5165 5166 5167
};

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
K
Karel Zak 已提交
5168
static const char *
5169 5170
vshCmddefGetInfo(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
5171
    vshCmdInfo *info;
5172

K
Karel Zak 已提交
5173
    for (info = cmd->info; info && info->name; info++) {
5174
        if (strcmp(info->name, name) == 0)
K
Karel Zak 已提交
5175 5176 5177 5178 5179 5180
            return info->data;
    }
    return NULL;
}

static vshCmdOptDef *
5181 5182
vshCmddefGetOption(vshCmdDef * cmd, const char *name)
{
K
Karel Zak 已提交
5183
    vshCmdOptDef *opt;
5184

K
Karel Zak 已提交
5185
    for (opt = cmd->opts; opt && opt->name; opt++)
5186
        if (strcmp(opt->name, name) == 0)
K
Karel Zak 已提交
5187 5188 5189 5190 5191
            return opt;
    return NULL;
}

static vshCmdOptDef *
5192 5193
vshCmddefGetData(vshCmdDef * cmd, int data_ct)
{
K
Karel Zak 已提交
5194 5195
    vshCmdOptDef *opt;

5196
    for (opt = cmd->opts; opt && opt->name; opt++) {
5197 5198
        if (opt->type == VSH_OT_DATA) {
            if (data_ct == 0)
5199 5200 5201 5202 5203
                return opt;
            else
                data_ct--;
        }
    }
K
Karel Zak 已提交
5204 5205 5206
    return NULL;
}

5207 5208 5209
/*
 * Checks for required options
 */
5210 5211
static int
vshCommandCheckOpts(vshControl * ctl, vshCmd * cmd)
5212 5213 5214
{
    vshCmdDef *def = cmd->def;
    vshCmdOptDef *d;
5215
    int err = 0;
5216 5217 5218 5219

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

            while (o && ok == 0) {
5223
                if (o->def == d)
5224
                    ok = 1;
5225 5226 5227
                o = o->next;
            }
            if (!ok) {
5228 5229
                vshError(ctl, FALSE,
                         d->type == VSH_OT_DATA ?
5230
                         _("command '%s' requires <%s> option") :
5231
                         _("command '%s' requires --%s option"),
5232
                         def->name, d->name);
5233 5234
                err = 1;
            }
5235

5236 5237 5238 5239 5240
        }
    }
    return !err;
}

K
Karel Zak 已提交
5241
static vshCmdDef *
5242 5243
vshCmddefSearch(const char *cmdname)
{
K
Karel Zak 已提交
5244
    vshCmdDef *c;
5245

K
Karel Zak 已提交
5246
    for (c = commands; c->name; c++)
5247
        if (strcmp(c->name, cmdname) == 0)
K
Karel Zak 已提交
5248 5249 5250 5251 5252
            return c;
    return NULL;
}

static int
5253 5254
vshCmddefHelp(vshControl * ctl, const char *cmdname, int withprog)
{
K
Karel Zak 已提交
5255
    vshCmdDef *def = vshCmddefSearch(cmdname);
5256

K
Karel Zak 已提交
5257
    if (!def) {
5258
        vshError(ctl, FALSE, _("command '%s' doesn't exist"), cmdname);
5259 5260
        return FALSE;
    } else {
K
Karel Zak 已提交
5261
        vshCmdOptDef *opt;
5262 5263
        const char *desc = N_(vshCmddefGetInfo(def, "desc"));
        const char *help = N_(vshCmddefGetInfo(def, "help"));
K
Karel Zak 已提交
5264
        const char *syntax = vshCmddefGetInfo(def, "syntax");
K
Karel Zak 已提交
5265

5266
        fputs(_("  NAME\n"), stdout);
5267 5268
        fprintf(stdout, "    %s - %s\n", def->name, help);

K
Karel Zak 已提交
5269
        if (syntax) {
5270
            fputs(_("\n  SYNOPSIS\n"), stdout);
K
Karel Zak 已提交
5271 5272 5273 5274 5275 5276
            if (!withprog)
                fprintf(stdout, "    %s\n", syntax);
            else
                fprintf(stdout, "    %s %s\n", progname, syntax);
        }
        if (desc) {
5277
            fputs(_("\n  DESCRIPTION\n"), stdout);
K
Karel Zak 已提交
5278 5279 5280
            fprintf(stdout, "    %s\n", desc);
        }
        if (def->opts) {
5281
            fputs(_("\n  OPTIONS\n"), stdout);
5282
            for (opt = def->opts; opt->name; opt++) {
K
Karel Zak 已提交
5283
                char buf[256];
5284 5285

                if (opt->type == VSH_OT_BOOL)
K
Karel Zak 已提交
5286
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
5287
                else if (opt->type == VSH_OT_INT)
5288
                    snprintf(buf, sizeof(buf), _("--%s <number>"), opt->name);
5289
                else if (opt->type == VSH_OT_STRING)
5290
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
5291
                else if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
5292
                    snprintf(buf, sizeof(buf), "<%s>", opt->name);
5293

5294
                fprintf(stdout, "    %-15s  %s\n", buf, N_(opt->help));
5295
            }
K
Karel Zak 已提交
5296 5297 5298 5299 5300 5301 5302 5303 5304 5305
        }
        fputc('\n', stdout);
    }
    return TRUE;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
5306 5307 5308
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
5309 5310
    vshCmdOpt *a = arg;

5311
    while (a) {
K
Karel Zak 已提交
5312
        vshCmdOpt *tmp = a;
5313

K
Karel Zak 已提交
5314 5315
        a = a->next;

5316
        free(tmp->data);
K
Karel Zak 已提交
5317 5318 5319 5320 5321
        free(tmp);
    }
}

static void
5322 5323
vshCommandFree(vshCmd * cmd)
{
K
Karel Zak 已提交
5324 5325
    vshCmd *c = cmd;

5326
    while (c) {
K
Karel Zak 已提交
5327
        vshCmd *tmp = c;
5328

K
Karel Zak 已提交
5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340
        c = c->next;

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

/*
 * Returns option by name
 */
static vshCmdOpt *
5341 5342
vshCommandOpt(vshCmd * cmd, const char *name)
{
K
Karel Zak 已提交
5343
    vshCmdOpt *opt = cmd->opts;
5344 5345 5346

    while (opt) {
        if (opt->def && strcmp(opt->def->name, name) == 0)
K
Karel Zak 已提交
5347 5348 5349 5350 5351 5352 5353 5354 5355 5356
            return opt;
        opt = opt->next;
    }
    return NULL;
}

/*
 * Returns option as INT
 */
static int
5357 5358
vshCommandOptInt(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
5359
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
5360 5361
    int res = 0, num_found = FALSE;
    char *end_p = NULL;
5362

5363 5364
    if ((arg != NULL) && (arg->data != NULL)) {
        res = strtol(arg->data, &end_p, 10);
5365 5366 5367 5368
        if ((arg->data == end_p) || (*end_p!= 0))
            num_found = FALSE;
        else
            num_found = TRUE;
5369
    }
K
Karel Zak 已提交
5370
    if (found)
5371
        *found = num_found;
K
Karel Zak 已提交
5372 5373 5374 5375 5376 5377 5378
    return res;
}

/*
 * Returns option as STRING
 */
static char *
5379 5380
vshCommandOptString(vshCmd * cmd, const char *name, int *found)
{
K
Karel Zak 已提交
5381
    vshCmdOpt *arg = vshCommandOpt(cmd, name);
5382

K
Karel Zak 已提交
5383 5384
    if (found)
        *found = arg ? TRUE : FALSE;
5385 5386

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

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

5424

K
Karel Zak 已提交
5425
static virDomainPtr
K
Karel Zak 已提交
5426
vshCommandOptDomainBy(vshControl * ctl, vshCmd * cmd, const char *optname,
5427
                      char **name, int flag)
5428
{
K
Karel Zak 已提交
5429
    virDomainPtr dom = NULL;
5430
    char *n;
K
Karel Zak 已提交
5431
    int id;
5432

K
Karel Zak 已提交
5433
    if (!(n = vshCommandOptString(cmd, optname, NULL))) {
J
Jim Meyering 已提交
5434
        vshError(ctl, FALSE, "%s", _("undefined domain name or id"));
5435
        return NULL;
K
Karel Zak 已提交
5436
    }
5437

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

K
Karel Zak 已提交
5441 5442
    if (name)
        *name = n;
5443

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

5465
    if (!dom)
5466
        vshError(ctl, FALSE, _("failed to get domain '%s'"), n);
5467

K
Karel Zak 已提交
5468 5469 5470
    return dom;
}

5471 5472
static virNetworkPtr
vshCommandOptNetworkBy(vshControl * ctl, vshCmd * cmd, const char *optname,
5473
                       char **name, int flag)
5474 5475 5476 5477 5478
{
    virNetworkPtr network = NULL;
    char *n;

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

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

    return network;
}

5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528
static virStoragePoolPtr
vshCommandOptPoolBy(vshControl * ctl, vshCmd * cmd, const char *optname,
                    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",
5529
                 cmd->def->name, optname);
5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 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
        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
vshCommandOptVolBy(vshControl * ctl, vshCmd * cmd,
                   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 已提交
5601 5602 5603 5604
/*
 * Executes command(s) and returns return code from last command
 */
static int
5605 5606
vshCommandRun(vshControl * ctl, vshCmd * cmd)
{
K
Karel Zak 已提交
5607
    int ret = TRUE;
5608 5609

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

K
Karel Zak 已提交
5612 5613
        if (ctl->timing)
            GETTIMEOFDAY(&before);
5614

K
Karel Zak 已提交
5615 5616 5617 5618
        ret = cmd->def->handler(ctl, cmd);

        if (ctl->timing)
            GETTIMEOFDAY(&after);
5619 5620

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

        if (ctl->timing)
5624
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
5625 5626
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
5627
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642
        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

5643 5644 5645
static int
vshCommandGetToken(vshControl * ctl, char *str, char **end, char **res)
{
K
Karel Zak 已提交
5646 5647 5648 5649 5650
    int tk = VSH_TK_NONE;
    int quote = FALSE;
    int sz = 0;
    char *p = str;
    char *tkstr = NULL;
5651

K
Karel Zak 已提交
5652
    *end = NULL;
5653

5654
    while (p && *p && (*p == ' ' || *p == '\t'))
K
Karel Zak 已提交
5655
        p++;
5656 5657

    if (p == NULL || *p == '\0')
K
Karel Zak 已提交
5658
        return VSH_TK_END;
5659
    if (*p == ';') {
D
Daniel Veillard 已提交
5660
        *end = ++p;             /* = \0 or begin of next command */
K
Karel Zak 已提交
5661 5662
        return VSH_TK_END;
    }
5663
    while (*p) {
K
Karel Zak 已提交
5664
        /* end of token is blank space or ';' */
5665
        if ((quote == FALSE && (*p == ' ' || *p == '\t')) || *p == ';')
K
Karel Zak 已提交
5666
            break;
5667

5668
        /* end of option name could be '=' */
5669 5670
        if (tk == VSH_TK_OPTION && *p == '=') {
            p++;                /* skip '=' */
5671 5672
            break;
        }
5673 5674 5675

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

5706
    *res = vshMalloc(ctl, sz + 1);
K
Karel Zak 已提交
5707
    memcpy(*res, tkstr, sz);
5708
    *(*res + sz) = '\0';
K
Karel Zak 已提交
5709 5710 5711 5712 5713 5714

    *end = p;
    return tk;
}

static int
5715 5716
vshCommandParse(vshControl * ctl, char *cmdstr)
{
K
Karel Zak 已提交
5717 5718 5719 5720
    char *str;
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
5721

K
Karel Zak 已提交
5722 5723 5724 5725
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
5726 5727

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

K
Karel Zak 已提交
5730
    str = cmdstr;
5731
    while (str && *str) {
K
Karel Zak 已提交
5732 5733 5734
        vshCmdOpt *last = NULL;
        vshCmdDef *cmd = NULL;
        int tk = VSH_TK_NONE;
5735
        int data_ct = 0;
5736

K
Karel Zak 已提交
5737
        first = NULL;
5738 5739

        while (tk != VSH_TK_END) {
K
Karel Zak 已提交
5740 5741
            char *end = NULL;
            vshCmdOptDef *opt = NULL;
5742

K
Karel Zak 已提交
5743
            tkdata = NULL;
5744

K
Karel Zak 已提交
5745 5746
            /* get token */
            tk = vshCommandGetToken(ctl, str, &end, &tkdata);
5747

K
Karel Zak 已提交
5748
            str = end;
5749 5750

            if (tk == VSH_TK_END)
K
Karel Zak 已提交
5751
                break;
5752
            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
5753
                goto syntaxError;
5754 5755

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

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

K
Karel Zak 已提交
5803 5804 5805 5806
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
5807

K
Karel Zak 已提交
5808 5809 5810 5811 5812
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
5813

K
Karel Zak 已提交
5814
                vshDebug(ctl, 4, "%s: %s(%s): %s\n",
5815 5816
                         cmd->name,
                         opt->name,
5817
                         tk == VSH_TK_OPTION ? _("OPTION") : _("DATA"),
5818
                         arg->data);
K
Karel Zak 已提交
5819 5820 5821 5822
            }
            if (!str)
                break;
        }
5823

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

K
Karel Zak 已提交
5828 5829 5830 5831
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

5832
            if (!vshCommandCheckOpts(ctl, c)) {
5833
                free(c);
5834
                goto syntaxError;
5835
            }
5836

K
Karel Zak 已提交
5837 5838 5839 5840 5841 5842 5843
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
    }
5844

K
Karel Zak 已提交
5845 5846
    return TRUE;

5847
 syntaxError:
K
Karel Zak 已提交
5848 5849 5850 5851
    if (ctl->cmd)
        vshCommandFree(ctl->cmd);
    if (first)
        vshCommandOptFree(first);
5852
    free(tkdata);
5853
    return FALSE;
K
Karel Zak 已提交
5854 5855 5856 5857
}


/* ---------------
5858
 * Misc utils
K
Karel Zak 已提交
5859 5860
 * ---------------
 */
K
Karel Zak 已提交
5861
static const char *
5862 5863
vshDomainStateToString(int state)
{
K
Karel Zak 已提交
5864
    switch (state) {
5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877
    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:
5878
        ;/*FALLTHROUGH*/
K
Karel Zak 已提交
5879
    }
5880
    return gettext_noop("no state");  /* = dom0 state */
K
Karel Zak 已提交
5881 5882
}

5883 5884 5885 5886
static const char *
vshDomainVcpuStateToString(int state)
{
    switch (state) {
5887 5888 5889 5890 5891 5892 5893
    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:
5894
        ;/*FALLTHROUGH*/
5895
    }
5896
    return gettext_noop("no state");
5897 5898
}

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

K
Karel Zak 已提交
5913 5914
static void
vshDebug(vshControl * ctl, int level, const char *format, ...)
5915
{
K
Karel Zak 已提交
5916 5917
    va_list ap;

5918 5919 5920 5921
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_DEBUG, format, ap);
    va_end(ap);

K
Karel Zak 已提交
5922 5923 5924 5925 5926 5927
    if (level > ctl->debug)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
K
Karel Zak 已提交
5928 5929 5930
}

static void
K
Karel Zak 已提交
5931
vshPrintExtra(vshControl * ctl, const char *format, ...)
5932
{
K
Karel Zak 已提交
5933
    va_list ap;
5934

K
Karel Zak 已提交
5935
    if (ctl->quiet == TRUE)
K
Karel Zak 已提交
5936
        return;
5937

K
Karel Zak 已提交
5938
    va_start(ap, format);
5939
    vfprintf(stdout, format, ap);
K
Karel Zak 已提交
5940 5941 5942
    va_end(ap);
}

K
Karel Zak 已提交
5943

K
Karel Zak 已提交
5944
static void
5945 5946
vshError(vshControl * ctl, int doexit, const char *format, ...)
{
K
Karel Zak 已提交
5947
    va_list ap;
5948

5949 5950 5951 5952
    va_start(ap, format);
    vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
    va_end(ap);

K
Karel Zak 已提交
5953
    if (doexit)
5954
        fprintf(stderr, _("%s: error: "), progname);
K
Karel Zak 已提交
5955
    else
5956
        fputs(_("error: "), stderr);
5957

K
Karel Zak 已提交
5958 5959 5960 5961 5962
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);

    fputc('\n', stderr);
5963

K
Karel Zak 已提交
5964
    if (doexit) {
5965 5966
        if (ctl)
            vshDeinit(ctl);
K
Karel Zak 已提交
5967 5968 5969 5970
        exit(EXIT_FAILURE);
    }
}

5971 5972 5973 5974 5975 5976 5977
static void *
_vshMalloc(vshControl * ctl, size_t size, const char *filename, int line)
{
    void *x;

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

static void *
_vshCalloc(vshControl * ctl, size_t nmemb, size_t size, const char *filename, int line)
{
    void *x;

    if ((x = calloc(nmemb, size)))
        return x;
5990
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %d bytes"),
5991
             filename, line, (int) (size*nmemb));
5992 5993 5994
    return NULL;
}

5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007
static void *
_vshRealloc(vshControl * ctl, void *ptr, size_t size, const char *filename, int line)
{
    void *x;

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

6008 6009 6010 6011 6012
static char *
_vshStrdup(vshControl * ctl, const char *s, const char *filename, int line)
{
    char *x;

6013 6014
    if (s == NULL)
        return(NULL);
6015 6016
    if ((x = strdup(s)))
        return x;
6017 6018
    vshError(ctl, TRUE, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
6019 6020 6021
    return NULL;
}

K
Karel Zak 已提交
6022
/*
6023
 * Initialize connection.
K
Karel Zak 已提交
6024 6025
 */
static int
6026 6027
vshInit(vshControl * ctl)
{
K
Karel Zak 已提交
6028 6029 6030
    if (ctl->conn)
        return FALSE;

6031 6032
    vshOpenLogFile(ctl);

6033 6034
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
6035

6036 6037 6038 6039
    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);

6040

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

    return TRUE;
}

6053 6054 6055 6056 6057
#ifndef O_SYNC
#define O_SYNC 0
#endif
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

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

    /* log file open */
6088
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
J
Jim Meyering 已提交
6089 6090
        vshError(ctl, TRUE, "%s",
                 _("failed to open the log file. check the log file path"));
6091 6092 6093 6094 6095 6096 6097 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
    }
}

/**
 * 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 */
6156
    if (safewrite(ctl->log_fd, msg_buf, strlen(msg_buf)) < 0) {
6157
        vshCloseLogFile(ctl);
J
Jim Meyering 已提交
6158
        vshError(ctl, FALSE, "%s", _("failed to write the log file"));
6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171
    }
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
    if (ctl->log_fd >= 0) {
6172
        if (close(ctl->log_fd) < 0)
6173
            vshError(ctl, FALSE, _("%s: failed to write log file: %s"),
6174
                     ctl->logfile ? ctl->logfile : "?", strerror (errno));
6175 6176 6177 6178 6179 6180 6181 6182 6183
        ctl->log_fd = -1;
    }

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

6184
#ifdef USE_READLINE
6185

K
Karel Zak 已提交
6186 6187 6188 6189 6190
/* -----------------
 * Readline stuff
 * -----------------
 */

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

    /* If this is a new word to complete, initialize now.  This
     * includes saving the length of TEXT for efficiency, and
6204
     * initializing the index variable to 0.
K
Karel Zak 已提交
6205 6206 6207
     */
    if (!state) {
        list_index = 0;
6208
        len = strlen(text);
K
Karel Zak 已提交
6209 6210 6211
    }

    /* Return the next name which partially matches from the
6212
     * command list.
K
Karel Zak 已提交
6213
     */
K
Karel Zak 已提交
6214
    while ((name = commands[list_index].name)) {
K
Karel Zak 已提交
6215
        list_index++;
6216
        if (strncmp(name, text, len) == 0)
6217
            return vshStrdup(NULL, name);
K
Karel Zak 已提交
6218 6219 6220 6221 6222 6223 6224
    }

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

static char *
6225 6226
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
6227 6228
    static int list_index, len;
    static vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
6229
    const char *name;
K
Karel Zak 已提交
6230 6231 6232 6233 6234 6235 6236 6237 6238

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

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

6239
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
6240
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
6241 6242 6243

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
6244
        len = strlen(text);
K
Karel Zak 已提交
6245 6246 6247 6248 6249
        free(cmdname);
    }

    if (!cmd)
        return NULL;
6250

6251 6252 6253
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
6254
    while ((name = cmd->opts[list_index].name)) {
K
Karel Zak 已提交
6255 6256
        vshCmdOptDef *opt = &cmd->opts[list_index];
        char *res;
6257

K
Karel Zak 已提交
6258
        list_index++;
6259

K
Karel Zak 已提交
6260
        if (opt->type == VSH_OT_DATA)
K
Karel Zak 已提交
6261 6262
            /* ignore non --option */
            continue;
6263

K
Karel Zak 已提交
6264
        if (len > 2) {
6265
            if (strncmp(name, text + 2, len - 2))
K
Karel Zak 已提交
6266 6267
                continue;
        }
6268
        res = vshMalloc(NULL, strlen(name) + 3);
6269
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
6270 6271 6272 6273 6274 6275 6276 6277
        return res;
    }

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

static char **
6278 6279 6280
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
6281 6282
    char **matches = (char **) NULL;

6283
    if (start == 0)
K
Karel Zak 已提交
6284
        /* command name generator */
6285
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
6286 6287
    else
        /* commands options */
6288
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
6289 6290 6291 6292 6293
    return matches;
}


static void
6294 6295
vshReadlineInit(void)
{
K
Karel Zak 已提交
6296 6297 6298 6299 6300 6301 6302
    /* 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;
}

6303 6304 6305 6306 6307 6308
static char *
vshReadline (vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
{
    return readline (prompt);
}

6309
#else /* !USE_READLINE */
6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335

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

6336
#endif /* !USE_READLINE */
6337

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

K
Karel Zak 已提交
6355 6356
    return TRUE;
}
6357

K
Karel Zak 已提交
6358 6359 6360 6361
/*
 * Print usage
 */
static void
6362 6363
vshUsage(vshControl * ctl, const char *cmdname)
{
K
Karel Zak 已提交
6364
    vshCmdDef *cmd;
6365

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

        for (cmd = commands; cmd->name; cmd++)
            fprintf(stdout,
6382
                    "    %-15s %s\n", cmd->name, N_(vshCmddefGetInfo(cmd,
6383
                                                                     "help")));
6384

J
Jim Meyering 已提交
6385
        fprintf(stdout, "%s",
6386
                _("\n  (specify help <command> for details about the command)\n\n"));
K
Karel Zak 已提交
6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397
        return;
    }
    if (!vshCmddefHelp(ctl, cmdname, TRUE))
        exit(EXIT_FAILURE);
}

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

K
Karel Zak 已提交
6415 6416

    if (argc < 2)
K
Karel Zak 已提交
6417
        return TRUE;
6418

6419
    /* look for begin of the command, for example:
K
Karel Zak 已提交
6420 6421 6422 6423
     *   ./virsh --debug 5 -q command --cmdoption
     *                  <--- ^ --->
     *        getopt() stuff | command suff
     */
6424
    for (i = 1; i < argc; i++) {
K
Karel Zak 已提交
6425 6426
        if (*argv[i] != '-') {
            int valid = FALSE;
6427

K
Karel Zak 已提交
6428 6429 6430 6431
            /* non "--option" argv, is it command? */
            if (last) {
                struct option *o;
                int sz = strlen(last);
6432 6433

                for (o = opt; o->name; o++) {
6434 6435 6436 6437 6438 6439 6440 6441
                    if (o->has_arg == 1){
                        if (sz == 2 && *(last + 1) == o->val)
                            /* valid virsh short option */
                            valid = TRUE;
                        else if (sz > 2 && strcmp(o->name, last + 2) == 0)
                            /* valid virsh long option */
                            valid = TRUE;
                    }
K
Karel Zak 已提交
6442 6443 6444 6445 6446 6447 6448 6449 6450
                }
            }
            if (!valid) {
                end = i;
                break;
            }
        }
        last = argv[i];
    }
6451
    end = end ? end : argc;
6452

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

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

K
Karel Zak 已提交
6493 6494 6495
    if (argc > end) {
        /* parse command */
        char *cmdstr;
6496 6497
        int sz = 0, ret;

K
Karel Zak 已提交
6498 6499
        ctl->imode = FALSE;

6500 6501 6502
        for (i = end; i < argc; i++)
            sz += strlen(argv[i]) + 1;  /* +1 is for blank space between items */

6503
        cmdstr = vshCalloc(ctl, sz + 1, 1);
6504 6505

        for (i = end; i < argc; i++) {
K
Karel Zak 已提交
6506 6507 6508 6509
            strncat(cmdstr, argv[i], sz);
            sz -= strlen(argv[i]);
            strncat(cmdstr, " ", sz--);
        }
K
Karel Zak 已提交
6510
        vshDebug(ctl, 2, "command: \"%s\"\n", cmdstr);
K
Karel Zak 已提交
6511
        ret = vshCommandParse(ctl, cmdstr);
6512

K
Karel Zak 已提交
6513 6514 6515 6516 6517 6518
        free(cmdstr);
        return ret;
    }
    return TRUE;
}

6519 6520 6521 6522
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
6523
    char *defaultConn;
K
Karel Zak 已提交
6524 6525
    int ret = TRUE;

6526 6527
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
6528
        return -1;
6529 6530 6531
    }
    if (!bindtextdomain(GETTEXT_PACKAGE, LOCALEBASEDIR)) {
        perror("bindtextdomain");
6532
        return -1;
6533 6534 6535
    }
    if (!textdomain(GETTEXT_PACKAGE)) {
        perror("textdomain");
6536
        return -1;
6537 6538
    }

6539
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
6540 6541 6542
        progname = argv[0];
    else
        progname++;
6543

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

6548
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
6549
        ctl->name = strdup(defaultConn);
6550 6551
    }

D
Daniel P. Berrange 已提交
6552 6553
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
6554
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
6555
    }
6556

D
Daniel P. Berrange 已提交
6557 6558
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
6559
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
6560
    }
6561

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

6592 6593
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
6594
    }
6595

K
Karel Zak 已提交
6596 6597
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
6598
}